/*! p5.js v1.2.0 December 19, 2020 */
(function(f) {
if (typeof exports === 'object' && typeof module !== 'undefined') {
module.exports = f();
} else if (typeof define === 'function' && define.amd) {
define([], f);
} else {
var g;
if (typeof window !== 'undefined') {
g = window;
} else if (typeof global !== 'undefined') {
g = global;
} else if (typeof self !== 'undefined') {
g = self;
} else {
g = this;
}
g.p5 = f();
}
})(function() {
var define, module, exports;
return (function() {
function r(e, n, t) {
function o(i, f) {
if (!n[i]) {
if (!e[i]) {
var c = 'function' == typeof require && require;
if (!f && c) return c(i, !0);
if (u) return u(i, !0);
var a = new Error("Cannot find module '" + i + "'");
throw ((a.code = 'MODULE_NOT_FOUND'), a);
}
var p = (n[i] = { exports: {} });
e[i][0].call(
p.exports,
function(r) {
var n = e[i][1][r];
return o(n || r);
},
p,
p.exports,
r,
e,
n,
t
);
}
return n[i].exports;
}
for (var u = 'function' == typeof require && require, i = 0; i < t.length; i++)
o(t[i]);
return o;
}
return r;
})()(
{
1: [
function(_dereq_, module, exports) {
module.exports = {
p5: {
describe: {
name: 'describe',
params: [
{
name: 'text',
description: '<p>description of the canvas</p>\n',
type: 'String'
},
{
name: 'display',
description: '<p>either LABEL or FALLBACK (Optional)</p>\n',
type: 'Constant',
optional: true
}
],
class: 'p5',
module: 'Environment'
},
describeElement: {
name: 'describeElement',
params: [
{
name: 'name',
description: '<p>name of the element</p>\n',
type: 'String'
},
{
name: 'text',
description: '<p>description of the element</p>\n',
type: 'String'
},
{
name: 'display',
description: '<p>either LABEL or FALLBACK (Optional)</p>\n',
type: 'Constant',
optional: true
}
],
class: 'p5',
module: 'Environment'
},
textOutput: {
name: 'textOutput',
params: [
{
name: 'display',
description: '<p>either FALLBACK or LABEL (Optional)</p>\n',
type: 'Constant',
optional: true
}
],
class: 'p5',
module: 'Environment'
},
gridOutput: {
name: 'gridOutput',
params: [
{
name: 'display',
description: '<p>either FALLBACK or LABEL (Optional)</p>\n',
type: 'Constant',
optional: true
}
],
class: 'p5',
module: 'Environment'
},
alpha: {
name: 'alpha',
params: [
{
name: 'color',
description:
'<p><a href="#/p5.Color">p5.Color</a> object, color components,\n or CSS color</p>\n',
type: 'p5.Color|Number[]|String'
}
],
class: 'p5',
module: 'Color'
},
blue: {
name: 'blue',
params: [
{
name: 'color',
description:
'<p><a href="#/p5.Color">p5.Color</a> object, color components,\n or CSS color</p>\n',
type: 'p5.Color|Number[]|String'
}
],
class: 'p5',
module: 'Color'
},
brightness: {
name: 'brightness',
params: [
{
name: 'color',
description:
'<p><a href="#/p5.Color">p5.Color</a> object, color components,\n or CSS color</p>\n',
type: 'p5.Color|Number[]|String'
}
],
class: 'p5',
module: 'Color'
},
color: {
name: 'color',
class: 'p5',
module: 'Color',
overloads: [
{
params: [
{
name: 'gray',
description:
'<p>number specifying value between white and black.</p>\n',
type: 'Number'
},
{
name: 'alpha',
description:
'<p>alpha value relative to current color range\n (default is 0-255)</p>\n',
type: 'Number',
optional: true
}
]
},
{
params: [
{
name: 'v1',
description:
'<p>red or hue value relative to\n the current color range</p>\n',
type: 'Number'
},
{
name: 'v2',
description:
'<p>green or saturation value\n relative to the current color range</p>\n',
type: 'Number'
},
{
name: 'v3',
description:
'<p>blue or brightness value\n relative to the current color range</p>\n',
type: 'Number'
},
{
name: 'alpha',
description: '',
type: 'Number',
optional: true
}
]
},
{
params: [
{
name: 'value',
description: '<p>a color string</p>\n',
type: 'String'
}
]
},
{
params: [
{
name: 'values',
description:
'<p>an array containing the red,green,blue &\n and alpha components of the color</p>\n',
type: 'Number[]'
}
]
},
{
params: [
{
name: 'color',
description: '',
type: 'p5.Color'
}
]
}
]
},
green: {
name: 'green',
params: [
{
name: 'color',
description:
'<p><a href="#/p5.Color">p5.Color</a> object, color components,\n or CSS color</p>\n',
type: 'p5.Color|Number[]|String'
}
],
class: 'p5',
module: 'Color'
},
hue: {
name: 'hue',
params: [
{
name: 'color',
description:
'<p><a href="#/p5.Color">p5.Color</a> object, color components,\n or CSS color</p>\n',
type: 'p5.Color|Number[]|String'
}
],
class: 'p5',
module: 'Color'
},
lerpColor: {
name: 'lerpColor',
params: [
{
name: 'c1',
description: '<p>interpolate from this color</p>\n',
type: 'p5.Color'
},
{
name: 'c2',
description: '<p>interpolate to this color</p>\n',
type: 'p5.Color'
},
{
name: 'amt',
description: '<p>number between 0 and 1</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Color'
},
lightness: {
name: 'lightness',
params: [
{
name: 'color',
description:
'<p><a href="#/p5.Color">p5.Color</a> object, color components,\n or CSS color</p>\n',
type: 'p5.Color|Number[]|String'
}
],
class: 'p5',
module: 'Color'
},
red: {
name: 'red',
params: [
{
name: 'color',
description:
'<p><a href="#/p5.Color">p5.Color</a> object, color components,\n or CSS color</p>\n',
type: 'p5.Color|Number[]|String'
}
],
class: 'p5',
module: 'Color'
},
saturation: {
name: 'saturation',
params: [
{
name: 'color',
description:
'<p><a href="#/p5.Color">p5.Color</a> object, color components,\n or CSS color</p>\n',
type: 'p5.Color|Number[]|String'
}
],
class: 'p5',
module: 'Color'
},
background: {
name: 'background',
class: 'p5',
module: 'Color',
overloads: [
{
params: [
{
name: 'color',
description:
'<p>any value created by the <a href="#/p5/color">color()</a> function</p>\n',
type: 'p5.Color'
}
],
chainable: 1
},
{
params: [
{
name: 'colorstring',
description:
'<p>color string, possible formats include: integer\n rgb() or rgba(), percentage rgb() or rgba(),\n 3-digit hex, 6-digit hex</p>\n',
type: 'String'
},
{
name: 'a',
description:
'<p>opacity of the background relative to current\n color range (default is 0-255)</p>\n',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'gray',
description: '<p>specifies a value between white and black</p>\n',
type: 'Number'
},
{
name: 'a',
description: '',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'v1',
description:
'<p>red or hue value (depending on the current color\n mode)</p>\n',
type: 'Number'
},
{
name: 'v2',
description:
'<p>green or saturation value (depending on the current\n color mode)</p>\n',
type: 'Number'
},
{
name: 'v3',
description:
'<p>blue or brightness value (depending on the current\n color mode)</p>\n',
type: 'Number'
},
{
name: 'a',
description: '',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'values',
description:
'<p>an array containing the red, green, blue\n and alpha components of the color</p>\n',
type: 'Number[]'
}
],
chainable: 1
},
{
params: [
{
name: 'image',
description:
'<p>image created with <a href="#/p5/loadImage">loadImage()</a> or <a href="#/p5/createImage">createImage()</a>,\n to set as background\n (must be same size as the sketch window)</p>\n',
type: 'p5.Image'
},
{
name: 'a',
description: '',
type: 'Number',
optional: true
}
],
chainable: 1
}
]
},
clear: {
name: 'clear',
class: 'p5',
module: 'Color'
},
colorMode: {
name: 'colorMode',
class: 'p5',
module: 'Color',
overloads: [
{
params: [
{
name: 'mode',
description:
'<p>either RGB, HSB or HSL, corresponding to\n Red/Green/Blue and Hue/Saturation/Brightness\n (or Lightness)</p>\n',
type: 'Constant'
},
{
name: 'max',
description: '<p>range for all values</p>\n',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'mode',
description: '',
type: 'Constant'
},
{
name: 'max1',
description:
'<p>range for the red or hue depending on the\n current color mode</p>\n',
type: 'Number'
},
{
name: 'max2',
description:
'<p>range for the green or saturation depending\n on the current color mode</p>\n',
type: 'Number'
},
{
name: 'max3',
description:
'<p>range for the blue or brightness/lightness\n depending on the current color mode</p>\n',
type: 'Number'
},
{
name: 'maxA',
description: '<p>range for the alpha</p>\n',
type: 'Number',
optional: true
}
],
chainable: 1
}
]
},
fill: {
name: 'fill',
class: 'p5',
module: 'Color',
overloads: [
{
params: [
{
name: 'v1',
description:
'<p>red or hue value relative to\n the current color range</p>\n',
type: 'Number'
},
{
name: 'v2',
description:
'<p>green or saturation value\n relative to the current color range</p>\n',
type: 'Number'
},
{
name: 'v3',
description:
'<p>blue or brightness value\n relative to the current color range</p>\n',
type: 'Number'
},
{
name: 'alpha',
description: '',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'value',
description: '<p>a color string</p>\n',
type: 'String'
}
],
chainable: 1
},
{
params: [
{
name: 'gray',
description: '<p>a gray value</p>\n',
type: 'Number'
},
{
name: 'alpha',
description: '',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'values',
description:
'<p>an array containing the red,green,blue &\n and alpha components of the color</p>\n',
type: 'Number[]'
}
],
chainable: 1
},
{
params: [
{
name: 'color',
description: '<p>the fill color</p>\n',
type: 'p5.Color'
}
],
chainable: 1
}
]
},
noFill: {
name: 'noFill',
class: 'p5',
module: 'Color'
},
noStroke: {
name: 'noStroke',
class: 'p5',
module: 'Color'
},
stroke: {
name: 'stroke',
class: 'p5',
module: 'Color',
overloads: [
{
params: [
{
name: 'v1',
description:
'<p>red or hue value relative to\n the current color range</p>\n',
type: 'Number'
},
{
name: 'v2',
description:
'<p>green or saturation value\n relative to the current color range</p>\n',
type: 'Number'
},
{
name: 'v3',
description:
'<p>blue or brightness value\n relative to the current color range</p>\n',
type: 'Number'
},
{
name: 'alpha',
description: '',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'value',
description: '<p>a color string</p>\n',
type: 'String'
}
],
chainable: 1
},
{
params: [
{
name: 'gray',
description: '<p>a gray value</p>\n',
type: 'Number'
},
{
name: 'alpha',
description: '',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'values',
description:
'<p>an array containing the red,green,blue &\n and alpha components of the color</p>\n',
type: 'Number[]'
}
],
chainable: 1
},
{
params: [
{
name: 'color',
description: '<p>the stroke color</p>\n',
type: 'p5.Color'
}
],
chainable: 1
}
]
},
erase: {
name: 'erase',
params: [
{
name: 'strengthFill',
description:
"<p>A number (0-255) for the strength of erasing for a shape's fill.\n This will default to 255 when no argument is given, which\n is full strength.</p>\n",
type: 'Number',
optional: true
},
{
name: 'strengthStroke',
description:
"<p>A number (0-255) for the strength of erasing for a shape's stroke.\n This will default to 255 when no argument is given, which\n is full strength.</p>\n",
type: 'Number',
optional: true
}
],
class: 'p5',
module: 'Color'
},
noErase: {
name: 'noErase',
class: 'p5',
module: 'Color'
},
arc: {
name: 'arc',
params: [
{
name: 'x',
description: "<p>x-coordinate of the arc's ellipse</p>\n",
type: 'Number'
},
{
name: 'y',
description: "<p>y-coordinate of the arc's ellipse</p>\n",
type: 'Number'
},
{
name: 'w',
description: "<p>width of the arc's ellipse by default</p>\n",
type: 'Number'
},
{
name: 'h',
description: "<p>height of the arc's ellipse by default</p>\n",
type: 'Number'
},
{
name: 'start',
description: '<p>angle to start the arc, specified in radians</p>\n',
type: 'Number'
},
{
name: 'stop',
description: '<p>angle to stop the arc, specified in radians</p>\n',
type: 'Number'
},
{
name: 'mode',
description:
'<p>optional parameter to determine the way of drawing\n the arc. either CHORD, PIE or OPEN</p>\n',
type: 'Constant',
optional: true
},
{
name: 'detail',
description:
'<p>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.</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5',
module: 'Shape'
},
ellipse: {
name: 'ellipse',
class: 'p5',
module: 'Shape',
overloads: [
{
params: [
{
name: 'x',
description: '<p>x-coordinate of the center of ellipse.</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>y-coordinate of the center of ellipse.</p>\n',
type: 'Number'
},
{
name: 'w',
description: '<p>width of the ellipse.</p>\n',
type: 'Number'
},
{
name: 'h',
description: '<p>height of the ellipse.</p>\n',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'x',
description: '',
type: 'Number'
},
{
name: 'y',
description: '',
type: 'Number'
},
{
name: 'w',
description: '',
type: 'Number'
},
{
name: 'h',
description: '',
type: 'Number'
},
{
name: 'detail',
description:
'<p>number of radial sectors to draw (for WebGL mode)</p>\n',
type: 'Integer'
}
]
}
]
},
circle: {
name: 'circle',
params: [
{
name: 'x',
description: '<p>x-coordinate of the centre of the circle.</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>y-coordinate of the centre of the circle.</p>\n',
type: 'Number'
},
{
name: 'd',
description: '<p>diameter of the circle.</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Shape'
},
line: {
name: 'line',
class: 'p5',
module: 'Shape',
overloads: [
{
params: [
{
name: 'x1',
description: '<p>the x-coordinate of the first point</p>\n',
type: 'Number'
},
{
name: 'y1',
description: '<p>the y-coordinate of the first point</p>\n',
type: 'Number'
},
{
name: 'x2',
description: '<p>the x-coordinate of the second point</p>\n',
type: 'Number'
},
{
name: 'y2',
description: '<p>the y-coordinate of the second point</p>\n',
type: 'Number'
}
],
chainable: 1
},
{
params: [
{
name: 'x1',
description: '',
type: 'Number'
},
{
name: 'y1',
description: '',
type: 'Number'
},
{
name: 'z1',
description: '<p>the z-coordinate of the first point</p>\n',
type: 'Number'
},
{
name: 'x2',
description: '',
type: 'Number'
},
{
name: 'y2',
description: '',
type: 'Number'
},
{
name: 'z2',
description: '<p>the z-coordinate of the second point</p>\n',
type: 'Number'
}
],
chainable: 1
}
]
},
point: {
name: 'point',
class: 'p5',
module: 'Shape',
overloads: [
{
params: [
{
name: 'x',
description: '<p>the x-coordinate</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>the y-coordinate</p>\n',
type: 'Number'
},
{
name: 'z',
description: '<p>the z-coordinate (for WebGL mode)</p>\n',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'coordinate_vector',
description: '<p>the coordinate vector</p>\n',
type: 'p5.Vector'
}
],
chainable: 1
}
]
},
quad: {
name: 'quad',
class: 'p5',
module: 'Shape',
overloads: [
{
params: [
{
name: 'x1',
description: '<p>the x-coordinate of the first point</p>\n',
type: 'Number'
},
{
name: 'y1',
description: '<p>the y-coordinate of the first point</p>\n',
type: 'Number'
},
{
name: 'x2',
description: '<p>the x-coordinate of the second point</p>\n',
type: 'Number'
},
{
name: 'y2',
description: '<p>the y-coordinate of the second point</p>\n',
type: 'Number'
},
{
name: 'x3',
description: '<p>the x-coordinate of the third point</p>\n',
type: 'Number'
},
{
name: 'y3',
description: '<p>the y-coordinate of the third point</p>\n',
type: 'Number'
},
{
name: 'x4',
description: '<p>the x-coordinate of the fourth point</p>\n',
type: 'Number'
},
{
name: 'y4',
description: '<p>the y-coordinate of the fourth point</p>\n',
type: 'Number'
}
],
chainable: 1
},
{
params: [
{
name: 'x1',
description: '',
type: 'Number'
},
{
name: 'y1',
description: '',
type: 'Number'
},
{
name: 'z1',
description: '<p>the z-coordinate of the first point</p>\n',
type: 'Number'
},
{
name: 'x2',
description: '',
type: 'Number'
},
{
name: 'y2',
description: '',
type: 'Number'
},
{
name: 'z2',
description: '<p>the z-coordinate of the second point</p>\n',
type: 'Number'
},
{
name: 'x3',
description: '',
type: 'Number'
},
{
name: 'y3',
description: '',
type: 'Number'
},
{
name: 'z3',
description: '<p>the z-coordinate of the third point</p>\n',
type: 'Number'
},
{
name: 'x4',
description: '',
type: 'Number'
},
{
name: 'y4',
description: '',
type: 'Number'
},
{
name: 'z4',
description: '<p>the z-coordinate of the fourth point</p>\n',
type: 'Number'
}
],
chainable: 1
}
]
},
rect: {
name: 'rect',
class: 'p5',
module: 'Shape',
overloads: [
{
params: [
{
name: 'x',
description: '<p>x-coordinate of the rectangle.</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>y-coordinate of the rectangle.</p>\n',
type: 'Number'
},
{
name: 'w',
description: '<p>width of the rectangle.</p>\n',
type: 'Number'
},
{
name: 'h',
description: '<p>height of the rectangle.</p>\n',
type: 'Number',
optional: true
},
{
name: 'tl',
description: '<p>optional radius of top-left corner.</p>\n',
type: 'Number',
optional: true
},
{
name: 'tr',
description: '<p>optional radius of top-right corner.</p>\n',
type: 'Number',
optional: true
},
{
name: 'br',
description: '<p>optional radius of bottom-right corner.</p>\n',
type: 'Number',
optional: true
},
{
name: 'bl',
description: '<p>optional radius of bottom-left corner.</p>\n',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'x',
description: '',
type: 'Number'
},
{
name: 'y',
description: '',
type: 'Number'
},
{
name: 'w',
description: '',
type: 'Number'
},
{
name: 'h',
description: '',
type: 'Number'
},
{
name: 'detailX',
description:
'<p>number of segments in the x-direction (for WebGL mode)</p>\n',
type: 'Integer',
optional: true
},
{
name: 'detailY',
description:
'<p>number of segments in the y-direction (for WebGL mode)</p>\n',
type: 'Integer',
optional: true
}
],
chainable: 1
}
]
},
square: {
name: 'square',
params: [
{
name: 'x',
description: '<p>x-coordinate of the square.</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>y-coordinate of the square.</p>\n',
type: 'Number'
},
{
name: 's',
description: '<p>side size of the square.</p>\n',
type: 'Number'
},
{
name: 'tl',
description: '<p>optional radius of top-left corner.</p>\n',
type: 'Number',
optional: true
},
{
name: 'tr',
description: '<p>optional radius of top-right corner.</p>\n',
type: 'Number',
optional: true
},
{
name: 'br',
description: '<p>optional radius of bottom-right corner.</p>\n',
type: 'Number',
optional: true
},
{
name: 'bl',
description: '<p>optional radius of bottom-left corner.</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5',
module: 'Shape'
},
triangle: {
name: 'triangle',
params: [
{
name: 'x1',
description: '<p>x-coordinate of the first point</p>\n',
type: 'Number'
},
{
name: 'y1',
description: '<p>y-coordinate of the first point</p>\n',
type: 'Number'
},
{
name: 'x2',
description: '<p>x-coordinate of the second point</p>\n',
type: 'Number'
},
{
name: 'y2',
description: '<p>y-coordinate of the second point</p>\n',
type: 'Number'
},
{
name: 'x3',
description: '<p>x-coordinate of the third point</p>\n',
type: 'Number'
},
{
name: 'y3',
description: '<p>y-coordinate of the third point</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Shape'
},
ellipseMode: {
name: 'ellipseMode',
params: [
{
name: 'mode',
description: '<p>either CENTER, RADIUS, CORNER, or CORNERS</p>\n',
type: 'Constant'
}
],
class: 'p5',
module: 'Shape'
},
noSmooth: {
name: 'noSmooth',
class: 'p5',
module: 'Shape'
},
rectMode: {
name: 'rectMode',
params: [
{
name: 'mode',
description: '<p>either CORNER, CORNERS, CENTER, or RADIUS</p>\n',
type: 'Constant'
}
],
class: 'p5',
module: 'Shape'
},
smooth: {
name: 'smooth',
class: 'p5',
module: 'Shape'
},
strokeCap: {
name: 'strokeCap',
params: [
{
name: 'cap',
description: '<p>either ROUND, SQUARE or PROJECT</p>\n',
type: 'Constant'
}
],
class: 'p5',
module: 'Shape'
},
strokeJoin: {
name: 'strokeJoin',
params: [
{
name: 'join',
description: '<p>either MITER, BEVEL, ROUND</p>\n',
type: 'Constant'
}
],
class: 'p5',
module: 'Shape'
},
strokeWeight: {
name: 'strokeWeight',
params: [
{
name: 'weight',
description: '<p>the weight of the stroke (in pixels)</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Shape'
},
bezier: {
name: 'bezier',
class: 'p5',
module: 'Shape',
overloads: [
{
params: [
{
name: 'x1',
description: '<p>x-coordinate for the first anchor point</p>\n',
type: 'Number'
},
{
name: 'y1',
description: '<p>y-coordinate for the first anchor point</p>\n',
type: 'Number'
},
{
name: 'x2',
description: '<p>x-coordinate for the first control point</p>\n',
type: 'Number'
},
{
name: 'y2',
description: '<p>y-coordinate for the first control point</p>\n',
type: 'Number'
},
{
name: 'x3',
description: '<p>x-coordinate for the second control point</p>\n',
type: 'Number'
},
{
name: 'y3',
description: '<p>y-coordinate for the second control point</p>\n',
type: 'Number'
},
{
name: 'x4',
description: '<p>x-coordinate for the second anchor point</p>\n',
type: 'Number'
},
{
name: 'y4',
description: '<p>y-coordinate for the second anchor point</p>\n',
type: 'Number'
}
],
chainable: 1
},
{
params: [
{
name: 'x1',
description: '',
type: 'Number'
},
{
name: 'y1',
description: '',
type: 'Number'
},
{
name: 'z1',
description: '<p>z-coordinate for the first anchor point</p>\n',
type: 'Number'
},
{
name: 'x2',
description: '',
type: 'Number'
},
{
name: 'y2',
description: '',
type: 'Number'
},
{
name: 'z2',
description: '<p>z-coordinate for the first control point</p>\n',
type: 'Number'
},
{
name: 'x3',
description: '',
type: 'Number'
},
{
name: 'y3',
description: '',
type: 'Number'
},
{
name: 'z3',
description: '<p>z-coordinate for the second control point</p>\n',
type: 'Number'
},
{
name: 'x4',
description: '',
type: 'Number'
},
{
name: 'y4',
description: '',
type: 'Number'
},
{
name: 'z4',
description: '<p>z-coordinate for the second anchor point</p>\n',
type: 'Number'
}
],
chainable: 1
}
]
},
bezierDetail: {
name: 'bezierDetail',
params: [
{
name: 'detail',
description: '<p>resolution of the curves</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Shape'
},
bezierPoint: {
name: 'bezierPoint',
params: [
{
name: 'a',
description: '<p>coordinate of first point on the curve</p>\n',
type: 'Number'
},
{
name: 'b',
description: '<p>coordinate of first control point</p>\n',
type: 'Number'
},
{
name: 'c',
description: '<p>coordinate of second control point</p>\n',
type: 'Number'
},
{
name: 'd',
description: '<p>coordinate of second point on the curve</p>\n',
type: 'Number'
},
{
name: 't',
description: '<p>value between 0 and 1</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Shape'
},
bezierTangent: {
name: 'bezierTangent',
params: [
{
name: 'a',
description: '<p>coordinate of first point on the curve</p>\n',
type: 'Number'
},
{
name: 'b',
description: '<p>coordinate of first control point</p>\n',
type: 'Number'
},
{
name: 'c',
description: '<p>coordinate of second control point</p>\n',
type: 'Number'
},
{
name: 'd',
description: '<p>coordinate of second point on the curve</p>\n',
type: 'Number'
},
{
name: 't',
description: '<p>value between 0 and 1</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Shape'
},
curve: {
name: 'curve',
class: 'p5',
module: 'Shape',
overloads: [
{
params: [
{
name: 'x1',
description:
'<p>x-coordinate for the beginning control point</p>\n',
type: 'Number'
},
{
name: 'y1',
description:
'<p>y-coordinate for the beginning control point</p>\n',
type: 'Number'
},
{
name: 'x2',
description: '<p>x-coordinate for the first point</p>\n',
type: 'Number'
},
{
name: 'y2',
description: '<p>y-coordinate for the first point</p>\n',
type: 'Number'
},
{
name: 'x3',
description: '<p>x-coordinate for the second point</p>\n',
type: 'Number'
},
{
name: 'y3',
description: '<p>y-coordinate for the second point</p>\n',
type: 'Number'
},
{
name: 'x4',
description: '<p>x-coordinate for the ending control point</p>\n',
type: 'Number'
},
{
name: 'y4',
description: '<p>y-coordinate for the ending control point</p>\n',
type: 'Number'
}
],
chainable: 1
},
{
params: [
{
name: 'x1',
description: '',
type: 'Number'
},
{
name: 'y1',
description: '',
type: 'Number'
},
{
name: 'z1',
description:
'<p>z-coordinate for the beginning control point</p>\n',
type: 'Number'
},
{
name: 'x2',
description: '',
type: 'Number'
},
{
name: 'y2',
description: '',
type: 'Number'
},
{
name: 'z2',
description: '<p>z-coordinate for the first point</p>\n',
type: 'Number'
},
{
name: 'x3',
description: '',
type: 'Number'
},
{
name: 'y3',
description: '',
type: 'Number'
},
{
name: 'z3',
description: '<p>z-coordinate for the second point</p>\n',
type: 'Number'
},
{
name: 'x4',
description: '',
type: 'Number'
},
{
name: 'y4',
description: '',
type: 'Number'
},
{
name: 'z4',
description: '<p>z-coordinate for the ending control point</p>\n',
type: 'Number'
}
],
chainable: 1
}
]
},
curveDetail: {
name: 'curveDetail',
params: [
{
name: 'resolution',
description: '<p>resolution of the curves</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Shape'
},
curveTightness: {
name: 'curveTightness',
params: [
{
name: 'amount',
description:
'<p>amount of deformation from the original vertices</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Shape'
},
curvePoint: {
name: 'curvePoint',
params: [
{
name: 'a',
description: '<p>coordinate of first control point of the curve</p>\n',
type: 'Number'
},
{
name: 'b',
description: '<p>coordinate of first point</p>\n',
type: 'Number'
},
{
name: 'c',
description: '<p>coordinate of second point</p>\n',
type: 'Number'
},
{
name: 'd',
description: '<p>coordinate of second control point</p>\n',
type: 'Number'
},
{
name: 't',
description: '<p>value between 0 and 1</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Shape'
},
curveTangent: {
name: 'curveTangent',
params: [
{
name: 'a',
description: '<p>coordinate of first control point</p>\n',
type: 'Number'
},
{
name: 'b',
description: '<p>coordinate of first point on the curve</p>\n',
type: 'Number'
},
{
name: 'c',
description: '<p>coordinate of second point on the curve</p>\n',
type: 'Number'
},
{
name: 'd',
description: '<p>coordinate of second conrol point</p>\n',
type: 'Number'
},
{
name: 't',
description: '<p>value between 0 and 1</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Shape'
},
beginContour: {
name: 'beginContour',
class: 'p5',
module: 'Shape'
},
beginShape: {
name: 'beginShape',
params: [
{
name: 'kind',
description:
'<p>either POINTS, LINES, TRIANGLES, TRIANGLE_FAN\n TRIANGLE_STRIP, QUADS, QUAD_STRIP or TESS</p>\n',
type: 'Constant',
optional: true
}
],
class: 'p5',
module: 'Shape'
},
bezierVertex: {
name: 'bezierVertex',
class: 'p5',
module: 'Shape',
overloads: [
{
params: [
{
name: 'x2',
description: '<p>x-coordinate for the first control point</p>\n',
type: 'Number'
},
{
name: 'y2',
description: '<p>y-coordinate for the first control point</p>\n',
type: 'Number'
},
{
name: 'x3',
description: '<p>x-coordinate for the second control point</p>\n',
type: 'Number'
},
{
name: 'y3',
description: '<p>y-coordinate for the second control point</p>\n',
type: 'Number'
},
{
name: 'x4',
description: '<p>x-coordinate for the anchor point</p>\n',
type: 'Number'
},
{
name: 'y4',
description: '<p>y-coordinate for the anchor point</p>\n',
type: 'Number'
}
],
chainable: 1
},
{
params: [
{
name: 'x2',
description: '',
type: 'Number'
},
{
name: 'y2',
description: '',
type: 'Number'
},
{
name: 'z2',
description:
'<p>z-coordinate for the first control point (for WebGL mode)</p>\n',
type: 'Number'
},
{
name: 'x3',
description: '',
type: 'Number'
},
{
name: 'y3',
description: '',
type: 'Number'
},
{
name: 'z3',
description:
'<p>z-coordinate for the second control point (for WebGL mode)</p>\n',
type: 'Number'
},
{
name: 'x4',
description: '',
type: 'Number'
},
{
name: 'y4',
description: '',
type: 'Number'
},
{
name: 'z4',
description:
'<p>z-coordinate for the anchor point (for WebGL mode)</p>\n',
type: 'Number'
}
],
chainable: 1
}
]
},
curveVertex: {
name: 'curveVertex',
class: 'p5',
module: 'Shape',
overloads: [
{
params: [
{
name: 'x',
description: '<p>x-coordinate of the vertex</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>y-coordinate of the vertex</p>\n',
type: 'Number'
}
],
chainable: 1
},
{
params: [
{
name: 'x',
description: '',
type: 'Number'
},
{
name: 'y',
description: '',
type: 'Number'
},
{
name: 'z',
description: '<p>z-coordinate of the vertex (for WebGL mode)</p>\n',
type: 'Number',
optional: true
}
],
chainable: 1
}
]
},
endContour: {
name: 'endContour',
class: 'p5',
module: 'Shape'
},
endShape: {
name: 'endShape',
params: [
{
name: 'mode',
description: '<p>use CLOSE to close the shape</p>\n',
type: 'Constant',
optional: true
}
],
class: 'p5',
module: 'Shape'
},
quadraticVertex: {
name: 'quadraticVertex',
class: 'p5',
module: 'Shape',
overloads: [
{
params: [
{
name: 'cx',
description: '<p>x-coordinate for the control point</p>\n',
type: 'Number'
},
{
name: 'cy',
description: '<p>y-coordinate for the control point</p>\n',
type: 'Number'
},
{
name: 'x3',
description: '<p>x-coordinate for the anchor point</p>\n',
type: 'Number'
},
{
name: 'y3',
description: '<p>y-coordinate for the anchor point</p>\n',
type: 'Number'
}
],
chainable: 1
},
{
params: [
{
name: 'cx',
description: '',
type: 'Number'
},
{
name: 'cy',
description: '',
type: 'Number'
},
{
name: 'cz',
description:
'<p>z-coordinate for the control point (for WebGL mode)</p>\n',
type: 'Number'
},
{
name: 'x3',
description: '',
type: 'Number'
},
{
name: 'y3',
description: '',
type: 'Number'
},
{
name: 'z3',
description:
'<p>z-coordinate for the anchor point (for WebGL mode)</p>\n',
type: 'Number'
}
],
chainable: 1
}
]
},
vertex: {
name: 'vertex',
class: 'p5',
module: 'Shape',
overloads: [
{
params: [
{
name: 'x',
description: '<p>x-coordinate of the vertex</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>y-coordinate of the vertex</p>\n',
type: 'Number'
}
],
chainable: 1
},
{
params: [
{
name: 'x',
description: '',
type: 'Number'
},
{
name: 'y',
description: '',
type: 'Number'
},
{
name: 'z',
description: '<p>z-coordinate of the vertex</p>\n',
type: 'Number'
},
{
name: 'u',
description: "<p>the vertex's texture u-coordinate</p>\n",
type: 'Number',
optional: true
},
{
name: 'v',
description: "<p>the vertex's texture v-coordinate</p>\n",
type: 'Number',
optional: true
}
],
chainable: 1
}
]
},
P2D: {
name: 'P2D',
class: 'p5',
module: 'Constants'
},
WEBGL: {
name: 'WEBGL',
class: 'p5',
module: 'Constants'
},
ARROW: {
name: 'ARROW',
class: 'p5',
module: 'Constants'
},
CROSS: {
name: 'CROSS',
class: 'p5',
module: 'Constants'
},
HAND: {
name: 'HAND',
class: 'p5',
module: 'Constants'
},
MOVE: {
name: 'MOVE',
class: 'p5',
module: 'Constants'
},
TEXT: {
name: 'TEXT',
class: 'p5',
module: 'Constants'
},
WAIT: {
name: 'WAIT',
class: 'p5',
module: 'Constants'
},
HALF_PI: {
name: 'HALF_PI',
class: 'p5',
module: 'Constants'
},
PI: {
name: 'PI',
class: 'p5',
module: 'Constants'
},
QUARTER_PI: {
name: 'QUARTER_PI',
class: 'p5',
module: 'Constants'
},
TAU: {
name: 'TAU',
class: 'p5',
module: 'Constants'
},
TWO_PI: {
name: 'TWO_PI',
class: 'p5',
module: 'Constants'
},
DEGREES: {
name: 'DEGREES',
class: 'p5',
module: 'Constants'
},
RADIANS: {
name: 'RADIANS',
class: 'p5',
module: 'Constants'
},
CORNER: {
name: 'CORNER',
class: 'p5',
module: 'Constants'
},
CORNERS: {
name: 'CORNERS',
class: 'p5',
module: 'Constants'
},
RADIUS: {
name: 'RADIUS',
class: 'p5',
module: 'Constants'
},
RIGHT: {
name: 'RIGHT',
class: 'p5',
module: 'Constants'
},
LEFT: {
name: 'LEFT',
class: 'p5',
module: 'Constants'
},
CENTER: {
name: 'CENTER',
class: 'p5',
module: 'Constants'
},
TOP: {
name: 'TOP',
class: 'p5',
module: 'Constants'
},
BOTTOM: {
name: 'BOTTOM',
class: 'p5',
module: 'Constants'
},
BASELINE: {
name: 'BASELINE',
class: 'p5',
module: 'Constants'
},
POINTS: {
name: 'POINTS',
class: 'p5',
module: 'Constants'
},
LINES: {
name: 'LINES',
class: 'p5',
module: 'Constants'
},
LINE_STRIP: {
name: 'LINE_STRIP',
class: 'p5',
module: 'Constants'
},
LINE_LOOP: {
name: 'LINE_LOOP',
class: 'p5',
module: 'Constants'
},
TRIANGLES: {
name: 'TRIANGLES',
class: 'p5',
module: 'Constants'
},
TRIANGLE_FAN: {
name: 'TRIANGLE_FAN',
class: 'p5',
module: 'Constants'
},
TRIANGLE_STRIP: {
name: 'TRIANGLE_STRIP',
class: 'p5',
module: 'Constants'
},
QUADS: {
name: 'QUADS',
class: 'p5',
module: 'Constants'
},
QUAD_STRIP: {
name: 'QUAD_STRIP',
class: 'p5',
module: 'Constants'
},
TESS: {
name: 'TESS',
class: 'p5',
module: 'Constants'
},
CLOSE: {
name: 'CLOSE',
class: 'p5',
module: 'Constants'
},
OPEN: {
name: 'OPEN',
class: 'p5',
module: 'Constants'
},
CHORD: {
name: 'CHORD',
class: 'p5',
module: 'Constants'
},
PIE: {
name: 'PIE',
class: 'p5',
module: 'Constants'
},
PROJECT: {
name: 'PROJECT',
class: 'p5',
module: 'Constants'
},
SQUARE: {
name: 'SQUARE',
class: 'p5',
module: 'Constants'
},
ROUND: {
name: 'ROUND',
class: 'p5',
module: 'Constants'
},
BEVEL: {
name: 'BEVEL',
class: 'p5',
module: 'Constants'
},
MITER: {
name: 'MITER',
class: 'p5',
module: 'Constants'
},
RGB: {
name: 'RGB',
class: 'p5',
module: 'Constants'
},
HSB: {
name: 'HSB',
class: 'p5',
module: 'Constants'
},
HSL: {
name: 'HSL',
class: 'p5',
module: 'Constants'
},
AUTO: {
name: 'AUTO',
class: 'p5',
module: 'Constants'
},
ALT: {
name: 'ALT',
class: 'p5',
module: 'Constants'
},
BACKSPACE: {
name: 'BACKSPACE',
class: 'p5',
module: 'Constants'
},
CONTROL: {
name: 'CONTROL',
class: 'p5',
module: 'Constants'
},
DELETE: {
name: 'DELETE',
class: 'p5',
module: 'Constants'
},
DOWN_ARROW: {
name: 'DOWN_ARROW',
class: 'p5',
module: 'Constants'
},
ENTER: {
name: 'ENTER',
class: 'p5',
module: 'Constants'
},
ESCAPE: {
name: 'ESCAPE',
class: 'p5',
module: 'Constants'
},
LEFT_ARROW: {
name: 'LEFT_ARROW',
class: 'p5',
module: 'Constants'
},
OPTION: {
name: 'OPTION',
class: 'p5',
module: 'Constants'
},
RETURN: {
name: 'RETURN',
class: 'p5',
module: 'Constants'
},
RIGHT_ARROW: {
name: 'RIGHT_ARROW',
class: 'p5',
module: 'Constants'
},
SHIFT: {
name: 'SHIFT',
class: 'p5',
module: 'Constants'
},
TAB: {
name: 'TAB',
class: 'p5',
module: 'Constants'
},
UP_ARROW: {
name: 'UP_ARROW',
class: 'p5',
module: 'Constants'
},
BLEND: {
name: 'BLEND',
class: 'p5',
module: 'Constants'
},
REMOVE: {
name: 'REMOVE',
class: 'p5',
module: 'Constants'
},
ADD: {
name: 'ADD',
class: 'p5',
module: 'Constants'
},
DARKEST: {
name: 'DARKEST',
class: 'p5',
module: 'Constants'
},
LIGHTEST: {
name: 'LIGHTEST',
class: 'p5',
module: 'Constants'
},
DIFFERENCE: {
name: 'DIFFERENCE',
class: 'p5',
module: 'Constants'
},
SUBTRACT: {
name: 'SUBTRACT',
class: 'p5',
module: 'Constants'
},
EXCLUSION: {
name: 'EXCLUSION',
class: 'p5',
module: 'Constants'
},
MULTIPLY: {
name: 'MULTIPLY',
class: 'p5',
module: 'Constants'
},
SCREEN: {
name: 'SCREEN',
class: 'p5',
module: 'Constants'
},
REPLACE: {
name: 'REPLACE',
class: 'p5',
module: 'Constants'
},
OVERLAY: {
name: 'OVERLAY',
class: 'p5',
module: 'Constants'
},
HARD_LIGHT: {
name: 'HARD_LIGHT',
class: 'p5',
module: 'Constants'
},
SOFT_LIGHT: {
name: 'SOFT_LIGHT',
class: 'p5',
module: 'Constants'
},
DODGE: {
name: 'DODGE',
class: 'p5',
module: 'Constants'
},
BURN: {
name: 'BURN',
class: 'p5',
module: 'Constants'
},
THRESHOLD: {
name: 'THRESHOLD',
class: 'p5',
module: 'Constants'
},
GRAY: {
name: 'GRAY',
class: 'p5',
module: 'Constants'
},
OPAQUE: {
name: 'OPAQUE',
class: 'p5',
module: 'Constants'
},
INVERT: {
name: 'INVERT',
class: 'p5',
module: 'Constants'
},
POSTERIZE: {
name: 'POSTERIZE',
class: 'p5',
module: 'Constants'
},
DILATE: {
name: 'DILATE',
class: 'p5',
module: 'Constants'
},
ERODE: {
name: 'ERODE',
class: 'p5',
module: 'Constants'
},
BLUR: {
name: 'BLUR',
class: 'p5',
module: 'Constants'
},
NORMAL: {
name: 'NORMAL',
class: 'p5',
module: 'Constants'
},
ITALIC: {
name: 'ITALIC',
class: 'p5',
module: 'Constants'
},
BOLD: {
name: 'BOLD',
class: 'p5',
module: 'Constants'
},
BOLDITALIC: {
name: 'BOLDITALIC',
class: 'p5',
module: 'Constants'
},
LINEAR: {
name: 'LINEAR',
class: 'p5',
module: 'Constants'
},
QUADRATIC: {
name: 'QUADRATIC',
class: 'p5',
module: 'Constants'
},
BEZIER: {
name: 'BEZIER',
class: 'p5',
module: 'Constants'
},
CURVE: {
name: 'CURVE',
class: 'p5',
module: 'Constants'
},
STROKE: {
name: 'STROKE',
class: 'p5',
module: 'Constants'
},
FILL: {
name: 'FILL',
class: 'p5',
module: 'Constants'
},
TEXTURE: {
name: 'TEXTURE',
class: 'p5',
module: 'Constants'
},
IMMEDIATE: {
name: 'IMMEDIATE',
class: 'p5',
module: 'Constants'
},
IMAGE: {
name: 'IMAGE',
class: 'p5',
module: 'Constants'
},
NEAREST: {
name: 'NEAREST',
class: 'p5',
module: 'Constants'
},
REPEAT: {
name: 'REPEAT',
class: 'p5',
module: 'Constants'
},
CLAMP: {
name: 'CLAMP',
class: 'p5',
module: 'Constants'
},
MIRROR: {
name: 'MIRROR',
class: 'p5',
module: 'Constants'
},
LANDSCAPE: {
name: 'LANDSCAPE',
class: 'p5',
module: 'Constants'
},
PORTRAIT: {
name: 'PORTRAIT',
class: 'p5',
module: 'Constants'
},
GRID: {
name: 'GRID',
class: 'p5',
module: 'Constants'
},
AXES: {
name: 'AXES',
class: 'p5',
module: 'Constants'
},
LABEL: {
name: 'LABEL',
class: 'p5',
module: 'Constants'
},
FALLBACK: {
name: 'FALLBACK',
class: 'p5',
module: 'Constants'
},
print: {
name: 'print',
params: [
{
name: 'contents',
description:
'<p>any combination of Number, String, Object, Boolean,\n Array to print</p>\n',
type: 'Any'
}
],
class: 'p5',
module: 'Environment'
},
frameCount: {
name: 'frameCount',
class: 'p5',
module: 'Environment'
},
deltaTime: {
name: 'deltaTime',
class: 'p5',
module: 'Environment'
},
focused: {
name: 'focused',
class: 'p5',
module: 'Environment'
},
cursor: {
name: 'cursor',
params: [
{
name: 'type',
description:
"<p>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 <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/cursor\">https://developer.mozilla.org/en-US/docs/Web/CSS/cursor</a></p>\n",
type: 'String|Constant'
},
{
name: 'x',
description:
'<p>the horizontal active spot of the cursor (must be less than 32)</p>\n',
type: 'Number',
optional: true
},
{
name: 'y',
description:
'<p>the vertical active spot of the cursor (must be less than 32)</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5',
module: 'Environment'
},
frameRate: {
name: 'frameRate',
class: 'p5',
module: 'Environment',
overloads: [
{
params: [
{
name: 'fps',
description:
'<p>number of frames to be displayed every second</p>\n',
type: 'Number'
}
],
chainable: 1
},
{
params: []
}
]
},
noCursor: {
name: 'noCursor',
class: 'p5',
module: 'Environment'
},
displayWidth: {
name: 'displayWidth',
class: 'p5',
module: 'Environment'
},
displayHeight: {
name: 'displayHeight',
class: 'p5',
module: 'Environment'
},
windowWidth: {
name: 'windowWidth',
class: 'p5',
module: 'Environment'
},
windowHeight: {
name: 'windowHeight',
class: 'p5',
module: 'Environment'
},
windowResized: {
name: 'windowResized',
class: 'p5',
module: 'Environment'
},
width: {
name: 'width',
class: 'p5',
module: 'Environment'
},
height: {
name: 'height',
class: 'p5',
module: 'Environment'
},
fullscreen: {
name: 'fullscreen',
params: [
{
name: 'val',
description:
'<p>whether the sketch should be in fullscreen mode\nor not</p>\n',
type: 'Boolean',
optional: true
}
],
class: 'p5',
module: 'Environment'
},
pixelDensity: {
name: 'pixelDensity',
class: 'p5',
module: 'Environment',
overloads: [
{
params: [
{
name: 'val',
description: '<p>whether or how much the sketch should scale</p>\n',
type: 'Number'
}
],
chainable: 1
},
{
params: []
}
]
},
displayDensity: {
name: 'displayDensity',
class: 'p5',
module: 'Environment'
},
getURL: {
name: 'getURL',
class: 'p5',
module: 'Environment'
},
getURLPath: {
name: 'getURLPath',
class: 'p5',
module: 'Environment'
},
getURLParams: {
name: 'getURLParams',
class: 'p5',
module: 'Environment'
},
preload: {
name: 'preload',
class: 'p5',
module: 'Structure'
},
setup: {
name: 'setup',
class: 'p5',
module: 'Structure'
},
draw: {
name: 'draw',
class: 'p5',
module: 'Structure'
},
remove: {
name: 'remove',
class: 'p5',
module: 'Structure'
},
disableFriendlyErrors: {
name: 'disableFriendlyErrors',
class: 'p5',
module: 'Structure'
},
let: {
name: 'let',
class: 'p5',
module: 'Foundation'
},
const: {
name: 'const',
class: 'p5',
module: 'Foundation'
},
'===': {
name: '===',
class: 'p5',
module: 'Foundation'
},
'>': {
name: '>',
class: 'p5',
module: 'Foundation'
},
'>=': {
name: '>=',
class: 'p5',
module: 'Foundation'
},
'<': {
name: '<',
class: 'p5',
module: 'Foundation'
},
'<=': {
name: '<=',
class: 'p5',
module: 'Foundation'
},
'if-else': {
name: 'if-else',
class: 'p5',
module: 'Foundation'
},
function: {
name: 'function',
class: 'p5',
module: 'Foundation'
},
return: {
name: 'return',
class: 'p5',
module: 'Foundation'
},
boolean: {
name: 'boolean',
params: [
{
name: 'n',
description: '<p>value to parse</p>\n',
type: 'String|Boolean|Number|Array'
}
],
class: 'p5',
module: 'Data'
},
string: {
name: 'string',
class: 'p5',
module: 'Foundation'
},
number: {
name: 'number',
class: 'p5',
module: 'Foundation'
},
object: {
name: 'object',
class: 'p5',
module: 'Foundation'
},
class: {
name: 'class',
class: 'p5',
module: 'Foundation'
},
for: {
name: 'for',
class: 'p5',
module: 'Foundation'
},
while: {
name: 'while',
class: 'p5',
module: 'Foundation'
},
createCanvas: {
name: 'createCanvas',
params: [
{
name: 'w',
description: '<p>width of the canvas</p>\n',
type: 'Number'
},
{
name: 'h',
description: '<p>height of the canvas</p>\n',
type: 'Number'
},
{
name: 'renderer',
description: '<p>either P2D or WEBGL</p>\n',
type: 'Constant',
optional: true
}
],
class: 'p5',
module: 'Rendering'
},
resizeCanvas: {
name: 'resizeCanvas',
params: [
{
name: 'w',
description: '<p>width of the canvas</p>\n',
type: 'Number'
},
{
name: 'h',
description: '<p>height of the canvas</p>\n',
type: 'Number'
},
{
name: 'noRedraw',
description: "<p>don't redraw the canvas immediately</p>\n",
type: 'Boolean',
optional: true
}
],
class: 'p5',
module: 'Rendering'
},
noCanvas: {
name: 'noCanvas',
class: 'p5',
module: 'Rendering'
},
createGraphics: {
name: 'createGraphics',
params: [
{
name: 'w',
description: '<p>width of the offscreen graphics buffer</p>\n',
type: 'Number'
},
{
name: 'h',
description: '<p>height of the offscreen graphics buffer</p>\n',
type: 'Number'
},
{
name: 'renderer',
description:
'<p>either P2D or WEBGL\n undefined defaults to p2d</p>\n',
type: 'Constant',
optional: true
}
],
class: 'p5',
module: 'Rendering'
},
blendMode: {
name: 'blendMode',
params: [
{
name: 'mode',
description:
'<p>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</p>\n',
type: 'Constant'
}
],
class: 'p5',
module: 'Rendering'
},
drawingContext: {
name: 'drawingContext',
class: 'p5',
module: 'Rendering'
},
noLoop: {
name: 'noLoop',
class: 'p5',
module: 'Structure'
},
loop: {
name: 'loop',
class: 'p5',
module: 'Structure'
},
isLooping: {
name: 'isLooping',
class: 'p5',
module: 'Structure'
},
push: {
name: 'push',
class: 'p5',
module: 'Structure'
},
pop: {
name: 'pop',
class: 'p5',
module: 'Structure'
},
redraw: {
name: 'redraw',
params: [
{
name: 'n',
description: '<p>Redraw for n-times. The default value is 1.</p>\n',
type: 'Integer',
optional: true
}
],
class: 'p5',
module: 'Structure'
},
p5: {
name: 'p5',
params: [
{
name: 'sketch',
description: '<p>a function containing a p5.js sketch</p>\n',
type: 'Object'
},
{
name: 'node',
description:
'<p>ID or pointer to HTML DOM node to contain sketch in</p>\n',
type: 'String|Object'
}
],
class: 'p5',
module: 'Structure'
},
applyMatrix: {
name: 'applyMatrix',
params: [
{
name: 'a',
description:
'<p>numbers which define the 2x3 matrix to be multiplied</p>\n',
type: 'Number'
},
{
name: 'b',
description:
'<p>numbers which define the 2x3 matrix to be multiplied</p>\n',
type: 'Number'
},
{
name: 'c',
description:
'<p>numbers which define the 2x3 matrix to be multiplied</p>\n',
type: 'Number'
},
{
name: 'd',
description:
'<p>numbers which define the 2x3 matrix to be multiplied</p>\n',
type: 'Number'
},
{
name: 'e',
description:
'<p>numbers which define the 2x3 matrix to be multiplied</p>\n',
type: 'Number'
},
{
name: 'f',
description:
'<p>numbers which define the 2x3 matrix to be multiplied</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Transform'
},
resetMatrix: {
name: 'resetMatrix',
class: 'p5',
module: 'Transform'
},
rotate: {
name: 'rotate',
params: [
{
name: 'angle',
description:
'<p>the angle of rotation, specified in radians\n or degrees, depending on current angleMode</p>\n',
type: 'Number'
},
{
name: 'axis',
description: '<p>(in 3d) the axis to rotate around</p>\n',
type: 'p5.Vector|Number[]',
optional: true
}
],
class: 'p5',
module: 'Transform'
},
rotateX: {
name: 'rotateX',
params: [
{
name: 'angle',
description:
'<p>the angle of rotation, specified in radians\n or degrees, depending on current angleMode</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Transform'
},
rotateY: {
name: 'rotateY',
params: [
{
name: 'angle',
description:
'<p>the angle of rotation, specified in radians\n or degrees, depending on current angleMode</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Transform'
},
rotateZ: {
name: 'rotateZ',
params: [
{
name: 'angle',
description:
'<p>the angle of rotation, specified in radians\n or degrees, depending on current angleMode</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Transform'
},
scale: {
name: 'scale',
class: 'p5',
module: 'Transform',
overloads: [
{
params: [
{
name: 's',
description:
'<p>percent to scale the object, or percentage to\n scale the object in the x-axis if multiple arguments\n are given</p>\n',
type: 'Number|p5.Vector|Number[]'
},
{
name: 'y',
description: '<p>percent to scale the object in the y-axis</p>\n',
type: 'Number',
optional: true
},
{
name: 'z',
description:
'<p>percent to scale the object in the z-axis (webgl only)</p>\n',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'scales',
description: '<p>per-axis percents to scale the object</p>\n',
type: 'p5.Vector|Number[]'
}
],
chainable: 1
}
]
},
shearX: {
name: 'shearX',
params: [
{
name: 'angle',
description:
'<p>angle of shear specified in radians or degrees,\n depending on current angleMode</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Transform'
},
shearY: {
name: 'shearY',
params: [
{
name: 'angle',
description:
'<p>angle of shear specified in radians or degrees,\n depending on current angleMode</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Transform'
},
translate: {
name: 'translate',
class: 'p5',
module: 'Transform',
overloads: [
{
params: [
{
name: 'x',
description: '<p>left/right translation</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>up/down translation</p>\n',
type: 'Number'
},
{
name: 'z',
description: '<p>forward/backward translation (webgl only)</p>\n',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'vector',
description: '<p>the vector to translate by</p>\n',
type: 'p5.Vector'
}
],
chainable: 1
}
]
},
storeItem: {
name: 'storeItem',
params: [
{
name: 'key',
description: '',
type: 'String'
},
{
name: 'value',
description: '',
type: 'String|Number|Object|Boolean|p5.Color|p5.Vector'
}
],
class: 'p5',
module: 'Data'
},
getItem: {
name: 'getItem',
params: [
{
name: 'key',
description:
'<p>name that you wish to use to store in local storage</p>\n',
type: 'String'
}
],
class: 'p5',
module: 'Data'
},
clearStorage: {
name: 'clearStorage',
class: 'p5',
module: 'Data'
},
removeItem: {
name: 'removeItem',
params: [
{
name: 'key',
description: '',
type: 'String'
}
],
class: 'p5',
module: 'Data'
},
createStringDict: {
name: 'createStringDict',
class: 'p5',
module: 'Data',
overloads: [
{
params: [
{
name: 'key',
description: '',
type: 'String'
},
{
name: 'value',
description: '',
type: 'String'
}
]
},
{
params: [
{
name: 'object',
description: '<p>object</p>\n',
type: 'Object'
}
]
}
]
},
createNumberDict: {
name: 'createNumberDict',
class: 'p5',
module: 'Data',
overloads: [
{
params: [
{
name: 'key',
description: '',
type: 'Number'
},
{
name: 'value',
description: '',
type: 'Number'
}
]
},
{
params: [
{
name: 'object',
description: '<p>object</p>\n',
type: 'Object'
}
]
}
]
},
select: {
name: 'select',
params: [
{
name: 'selectors',
description: '<p>CSS selector string of element to search for</p>\n',
type: 'String'
},
{
name: 'container',
description:
'<p>CSS selector string, <a href="#/p5.Element">p5.Element</a>, or\n HTML element to search within</p>\n',
type: 'String|p5.Element|HTMLElement',
optional: true
}
],
class: 'p5',
module: 'DOM'
},
selectAll: {
name: 'selectAll',
params: [
{
name: 'selectors',
description: '<p>CSS selector string of elements to search for</p>\n',
type: 'String'
},
{
name: 'container',
description:
'<p>CSS selector string, <a href="#/p5.Element">p5.Element</a>\n , or HTML element to search within</p>\n',
type: 'String|p5.Element|HTMLElement',
optional: true
}
],
class: 'p5',
module: 'DOM'
},
removeElements: {
name: 'removeElements',
class: 'p5',
module: 'DOM'
},
changed: {
name: 'changed',
params: [
{
name: 'fxn',
description:
'<p>function to be fired when the value of\n an element changes.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n',
type: 'Function|Boolean'
}
],
class: 'p5',
module: 'DOM'
},
input: {
name: 'input',
params: [
{
name: 'fxn',
description:
'<p>function to be fired when any user input is\n detected within the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n',
type: 'Function|Boolean'
}
],
class: 'p5',
module: 'DOM'
},
createDiv: {
name: 'createDiv',
params: [
{
name: 'html',
description: '<p>inner HTML for element created</p>\n',
type: 'String',
optional: true
}
],
class: 'p5',
module: 'DOM'
},
createP: {
name: 'createP',
params: [
{
name: 'html',
description: '<p>inner HTML for element created</p>\n',
type: 'String',
optional: true
}
],
class: 'p5',
module: 'DOM'
},
createSpan: {
name: 'createSpan',
params: [
{
name: 'html',
description: '<p>inner HTML for element created</p>\n',
type: 'String',
optional: true
}
],
class: 'p5',
module: 'DOM'
},
createImg: {
name: 'createImg',
class: 'p5',
module: 'DOM',
overloads: [
{
params: [
{
name: 'src',
description: '<p>src path or url for image</p>\n',
type: 'String'
},
{
name: 'alt',
description:
'<p><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Img#Attributes">alternate text</a> to be used if image does not load. You can use also an empty string (<code>""</code>) if that an image is not intended to be viewed.</p>\n',
type: 'String'
}
]
},
{
params: [
{
name: 'src',
description: '',
type: 'String'
},
{
name: 'alt',
description: '',
type: 'String'
},
{
name: 'crossOrigin',
description:
'<p><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes">crossOrigin property</a> of the <code>img</code> element; use either \'anonymous\' or \'use-credentials\' to retrieve the image with cross-origin access (for later use with <code>canvas</code>. if an empty string(<code>""</code>) is passed, CORS is not used</p>\n',
type: 'String'
},
{
name: 'successCallback',
description:
'<p>callback to be called once image data is loaded with the <a href="#/p5.Element">p5.Element</a> as argument</p>\n',
type: 'Function',
optional: true
}
]
}
]
},
createA: {
name: 'createA',
params: [
{
name: 'href',
description: '<p>url of page to link to</p>\n',
type: 'String'
},
{
name: 'html',
description: '<p>inner html of link element to display</p>\n',
type: 'String'
},
{
name: 'target',
description:
'<p>target where new link should open,\n could be _blank, _self, _parent, _top.</p>\n',
type: 'String',
optional: true
}
],
class: 'p5',
module: 'DOM'
},
createSlider: {
name: 'createSlider',
params: [
{
name: 'min',
description: '<p>minimum value of the slider</p>\n',
type: 'Number'
},
{
name: 'max',
description: '<p>maximum value of the slider</p>\n',
type: 'Number'
},
{
name: 'value',
description: '<p>default value of the slider</p>\n',
type: 'Number',
optional: true
},
{
name: 'step',
description:
'<p>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)</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5',
module: 'DOM'
},
createButton: {
name: 'createButton',
params: [
{
name: 'label',
description: '<p>label displayed on the button</p>\n',
type: 'String'
},
{
name: 'value',
description: '<p>value of the button</p>\n',
type: 'String',
optional: true
}
],
class: 'p5',
module: 'DOM'
},
createCheckbox: {
name: 'createCheckbox',
params: [
{
name: 'label',
description: '<p>label displayed after checkbox</p>\n',
type: 'String',
optional: true
},
{
name: 'value',
description:
'<p>value of the checkbox; checked is true, unchecked is false</p>\n',
type: 'Boolean',
optional: true
}
],
class: 'p5',
module: 'DOM'
},
createSelect: {
name: 'createSelect',
class: 'p5',
module: 'DOM',
overloads: [
{
params: [
{
name: 'multiple',
description:
'<p>true if dropdown should support multiple selections</p>\n',
type: 'Boolean',
optional: true
}
]
},
{
params: [
{
name: 'existing',
description: '<p>DOM select element</p>\n',
type: 'Object'
}
]
}
]
},
createRadio: {
name: 'createRadio',
class: 'p5',
module: 'DOM',
overloads: [
{
params: [
{
name: 'containerElement',
description:
'<p>An container HTML Element either a div\nor span inside which all existing radio inputs will be considered as options.</p>\n',
type: 'Object'
},
{
name: 'name',
description: '<p>A name parameter for each Input Element.</p>\n',
type: 'String',
optional: true
}
]
},
{
params: [
{
name: 'name',
description: '',
type: 'String'
}
]
},
{
params: []
}
]
},
createColorPicker: {
name: 'createColorPicker',
params: [
{
name: 'value',
description: '<p>default color of element</p>\n',
type: 'String|p5.Color',
optional: true
}
],
class: 'p5',
module: 'DOM'
},
createInput: {
name: 'createInput',
class: 'p5',
module: 'DOM',
overloads: [
{
params: [
{
name: 'value',
description: '<p>default value of the input box</p>\n',
type: 'String'
},
{
name: 'type',
description:
'<p>type of text, ie text, password etc. Defaults to text.\n Needs a value to be specified first.</p>\n',
type: 'String',
optional: true
}
]
},
{
params: [
{
name: 'value',
description: '',
type: 'String',
optional: true
}
]
}
]
},
createFileInput: {
name: 'createFileInput',
params: [
{
name: 'callback',
description: '<p>callback function for when a file is loaded</p>\n',
type: 'Function'
},
{
name: 'multiple',
description:
'<p>optional, to allow multiple files to be selected</p>\n',
type: 'Boolean',
optional: true
}
],
class: 'p5',
module: 'DOM'
},
createVideo: {
name: 'createVideo',
params: [
{
name: 'src',
description:
'<p>path to a video file, or array of paths for\n supporting different browsers</p>\n',
type: 'String|String[]'
},
{
name: 'callback',
description:
"<p>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</p>\n",
type: 'Function',
optional: true
}
],
class: 'p5',
module: 'DOM'
},
createAudio: {
name: 'createAudio',
params: [
{
name: 'src',
description:
'<p>path to an audio file, or array of paths\n for supporting different browsers</p>\n',
type: 'String|String[]',
optional: true
},
{
name: 'callback',
description:
"<p>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</p>\n",
type: 'Function',
optional: true
}
],
class: 'p5',
module: 'DOM'
},
VIDEO: {
name: 'VIDEO',
class: 'p5',
module: 'DOM'
},
AUDIO: {
name: 'AUDIO',
class: 'p5',
module: 'DOM'
},
createCapture: {
name: 'createCapture',
params: [
{
name: 'type',
description:
'<p>type of capture, either VIDEO or\n AUDIO if none specified, default both,\n or a Constraints object</p>\n',
type: 'String|Constant|Object'
},
{
name: 'callback',
description:
'<p>function to be called once\n stream has loaded</p>\n',
type: 'Function',
optional: true
}
],
class: 'p5',
module: 'DOM'
},
createElement: {
name: 'createElement',
params: [
{
name: 'tag',
description: '<p>tag for the new element</p>\n',
type: 'String'
},
{
name: 'content',
description: '<p>html content to be inserted into the element</p>\n',
type: 'String',
optional: true
}
],
class: 'p5',
module: 'DOM'
},
deviceOrientation: {
name: 'deviceOrientation',
class: 'p5',
module: 'Events'
},
accelerationX: {
name: 'accelerationX',
class: 'p5',
module: 'Events'
},
accelerationY: {
name: 'accelerationY',
class: 'p5',
module: 'Events'
},
accelerationZ: {
name: 'accelerationZ',
class: 'p5',
module: 'Events'
},
pAccelerationX: {
name: 'pAccelerationX',
class: 'p5',
module: 'Events'
},
pAccelerationY: {
name: 'pAccelerationY',
class: 'p5',
module: 'Events'
},
pAccelerationZ: {
name: 'pAccelerationZ',
class: 'p5',
module: 'Events'
},
rotationX: {
name: 'rotationX',
class: 'p5',
module: 'Events'
},
rotationY: {
name: 'rotationY',
class: 'p5',
module: 'Events'
},
rotationZ: {
name: 'rotationZ',
class: 'p5',
module: 'Events'
},
pRotationX: {
name: 'pRotationX',
class: 'p5',
module: 'Events'
},
pRotationY: {
name: 'pRotationY',
class: 'p5',
module: 'Events'
},
pRotationZ: {
name: 'pRotationZ',
class: 'p5',
module: 'Events'
},
turnAxis: {
name: 'turnAxis',
class: 'p5',
module: 'Events'
},
setMoveThreshold: {
name: 'setMoveThreshold',
params: [
{
name: 'value',
description: '<p>The threshold value</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Events'
},
setShakeThreshold: {
name: 'setShakeThreshold',
params: [
{
name: 'value',
description: '<p>The threshold value</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Events'
},
deviceMoved: {
name: 'deviceMoved',
class: 'p5',
module: 'Events'
},
deviceTurned: {
name: 'deviceTurned',
class: 'p5',
module: 'Events'
},
deviceShaken: {
name: 'deviceShaken',
class: 'p5',
module: 'Events'
},
keyIsPressed: {
name: 'keyIsPressed',
class: 'p5',
module: 'Events'
},
key: {
name: 'key',
class: 'p5',
module: 'Events'
},
keyCode: {
name: 'keyCode',
class: 'p5',
module: 'Events'
},
keyPressed: {
name: 'keyPressed',
class: 'p5',
module: 'Events'
},
keyReleased: {
name: 'keyReleased',
class: 'p5',
module: 'Events'
},
keyTyped: {
name: 'keyTyped',
class: 'p5',
module: 'Events'
},
keyIsDown: {
name: 'keyIsDown',
params: [
{
name: 'code',
description: '<p>The key to check for.</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Events'
},
movedX: {
name: 'movedX',
class: 'p5',
module: 'Events'
},
movedY: {
name: 'movedY',
class: 'p5',
module: 'Events'
},
mouseX: {
name: 'mouseX',
class: 'p5',
module: 'Events'
},
mouseY: {
name: 'mouseY',
class: 'p5',
module: 'Events'
},
pmouseX: {
name: 'pmouseX',
class: 'p5',
module: 'Events'
},
pmouseY: {
name: 'pmouseY',
class: 'p5',
module: 'Events'
},
winMouseX: {
name: 'winMouseX',
class: 'p5',
module: 'Events'
},
winMouseY: {
name: 'winMouseY',
class: 'p5',
module: 'Events'
},
pwinMouseX: {
name: 'pwinMouseX',
class: 'p5',
module: 'Events'
},
pwinMouseY: {
name: 'pwinMouseY',
class: 'p5',
module: 'Events'
},
mouseButton: {
name: 'mouseButton',
class: 'p5',
module: 'Events'
},
mouseIsPressed: {
name: 'mouseIsPressed',
class: 'p5',
module: 'Events'
},
mouseMoved: {
name: 'mouseMoved',
params: [
{
name: 'event',
description: '<p>optional MouseEvent callback argument.</p>\n',
type: 'Object',
optional: true
}
],
class: 'p5',
module: 'Events'
},
mouseDragged: {
name: 'mouseDragged',
params: [
{
name: 'event',
description: '<p>optional MouseEvent callback argument.</p>\n',
type: 'Object',
optional: true
}
],
class: 'p5',
module: 'Events'
},
mousePressed: {
name: 'mousePressed',
params: [
{
name: 'event',
description: '<p>optional MouseEvent callback argument.</p>\n',
type: 'Object',
optional: true
}
],
class: 'p5',
module: 'Events'
},
mouseReleased: {
name: 'mouseReleased',
params: [
{
name: 'event',
description: '<p>optional MouseEvent callback argument.</p>\n',
type: 'Object',
optional: true
}
],
class: 'p5',
module: 'Events'
},
mouseClicked: {
name: 'mouseClicked',
params: [
{
name: 'event',
description: '<p>optional MouseEvent callback argument.</p>\n',
type: 'Object',
optional: true
}
],
class: 'p5',
module: 'Events'
},
doubleClicked: {
name: 'doubleClicked',
params: [
{
name: 'event',
description: '<p>optional MouseEvent callback argument.</p>\n',
type: 'Object',
optional: true
}
],
class: 'p5',
module: 'Events'
},
mouseWheel: {
name: 'mouseWheel',
params: [
{
name: 'event',
description: '<p>optional WheelEvent callback argument.</p>\n',
type: 'Object',
optional: true
}
],
class: 'p5',
module: 'Events'
},
requestPointerLock: {
name: 'requestPointerLock',
class: 'p5',
module: 'Events'
},
exitPointerLock: {
name: 'exitPointerLock',
class: 'p5',
module: 'Events'
},
touches: {
name: 'touches',
class: 'p5',
module: 'Events'
},
touchStarted: {
name: 'touchStarted',
params: [
{
name: 'event',
description: '<p>optional TouchEvent callback argument.</p>\n',
type: 'Object',
optional: true
}
],
class: 'p5',
module: 'Events'
},
touchMoved: {
name: 'touchMoved',
params: [
{
name: 'event',
description: '<p>optional TouchEvent callback argument.</p>\n',
type: 'Object',
optional: true
}
],
class: 'p5',
module: 'Events'
},
touchEnded: {
name: 'touchEnded',
params: [
{
name: 'event',
description: '<p>optional TouchEvent callback argument.</p>\n',
type: 'Object',
optional: true
}
],
class: 'p5',
module: 'Events'
},
createImage: {
name: 'createImage',
params: [
{
name: 'width',
description: '<p>width in pixels</p>\n',
type: 'Integer'
},
{
name: 'height',
description: '<p>height in pixels</p>\n',
type: 'Integer'
}
],
class: 'p5',
module: 'Image'
},
saveCanvas: {
name: 'saveCanvas',
class: 'p5',
module: 'Image',
overloads: [
{
params: [
{
name: 'selectedCanvas',
description:
'<p>a variable\n representing a specific html5 canvas (optional)</p>\n',
type: 'p5.Element|HTMLCanvasElement'
},
{
name: 'filename',
description: '',
type: 'String',
optional: true
},
{
name: 'extension',
description: "<p>'jpg' or 'png'</p>\n",
type: 'String',
optional: true
}
]
},
{
params: [
{
name: 'filename',
description: '',
type: 'String',
optional: true
},
{
name: 'extension',
description: '',
type: 'String',
optional: true
}
]
}
]
},
saveFrames: {
name: 'saveFrames',
params: [
{
name: 'filename',
description: '',
type: 'String'
},
{
name: 'extension',
description: "<p>'jpg' or 'png'</p>\n",
type: 'String'
},
{
name: 'duration',
description: '<p>Duration in seconds to save the frames for.</p>\n',
type: 'Number'
},
{
name: 'framerate',
description: '<p>Framerate to save the frames in.</p>\n',
type: 'Number'
},
{
name: 'callback',
description:
'<p>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.</p>\n',
type: 'Function(Array)',
optional: true
}
],
class: 'p5',
module: 'Image'
},
loadImage: {
name: 'loadImage',
params: [
{
name: 'path',
description: '<p>Path of the image to be loaded</p>\n',
type: 'String'
},
{
name: 'successCallback',
description:
'<p>Function to be called once\n the image is loaded. Will be passed the\n <a href="#/p5.Image">p5.Image</a>.</p>\n',
type: 'function(p5.Image)',
optional: true
},
{
name: 'failureCallback',
description:
'<p>called with event error if\n the image fails to load.</p>\n',
type: 'Function(Event)',
optional: true
}
],
class: 'p5',
module: 'Image'
},
image: {
name: 'image',
class: 'p5',
module: 'Image',
overloads: [
{
params: [
{
name: 'img',
description: '<p>the image to display</p>\n',
type: 'p5.Image|p5.Element'
},
{
name: 'x',
description:
'<p>the x-coordinate of the top-left corner of the image</p>\n',
type: 'Number'
},
{
name: 'y',
description:
'<p>the y-coordinate of the top-left corner of the image</p>\n',
type: 'Number'
},
{
name: 'width',
description: '<p>the width to draw the image</p>\n',
type: 'Number',
optional: true
},
{
name: 'height',
description: '<p>the height to draw the image</p>\n',
type: 'Number',
optional: true
}
]
},
{
params: [
{
name: 'img',
description: '',
type: 'p5.Image|p5.Element'
},
{
name: 'dx',
description:
'<p>the x-coordinate of the destination\n rectangle in which to draw the source image</p>\n',
type: 'Number'
},
{
name: 'dy',
description:
'<p>the y-coordinate of the destination\n rectangle in which to draw the source image</p>\n',
type: 'Number'
},
{
name: 'dWidth',
description: '<p>the width of the destination rectangle</p>\n',
type: 'Number'
},
{
name: 'dHeight',
description: '<p>the height of the destination rectangle</p>\n',
type: 'Number'
},
{
name: 'sx',
description:
'<p>the x-coordinate of the subsection of the source\nimage to draw into the destination rectangle</p>\n',
type: 'Number'
},
{
name: 'sy',
description:
'<p>the y-coordinate of the subsection of the source\nimage to draw into the destination rectangle</p>\n',
type: 'Number'
},
{
name: 'sWidth',
description:
'<p>the width of the subsection of the\n source image to draw into the destination\n rectangle</p>\n',
type: 'Number',
optional: true
},
{
name: 'sHeight',
description:
'<p>the height of the subsection of the\n source image to draw into the destination rectangle</p>\n',
type: 'Number',
optional: true
}
]
}
]
},
tint: {
name: 'tint',
class: 'p5',
module: 'Image',
overloads: [
{
params: [
{
name: 'v1',
description:
'<p>red or hue value relative to\n the current color range</p>\n',
type: 'Number'
},
{
name: 'v2',
description:
'<p>green or saturation value\n relative to the current color range</p>\n',
type: 'Number'
},
{
name: 'v3',
description:
'<p>blue or brightness value\n relative to the current color range</p>\n',
type: 'Number'
},
{
name: 'alpha',
description: '',
type: 'Number',
optional: true
}
]
},
{
params: [
{
name: 'value',
description: '<p>a color string</p>\n',
type: 'String'
}
]
},
{
params: [
{
name: 'gray',
description: '<p>a gray value</p>\n',
type: 'Number'
},
{
name: 'alpha',
description: '',
type: 'Number',
optional: true
}
]
},
{
params: [
{
name: 'values',
description:
'<p>an array containing the red,green,blue &\n and alpha components of the color</p>\n',
type: 'Number[]'
}
]
},
{
params: [
{
name: 'color',
description: '<p>the tint color</p>\n',
type: 'p5.Color'
}
]
}
]
},
noTint: {
name: 'noTint',
class: 'p5',
module: 'Image'
},
imageMode: {
name: 'imageMode',
params: [
{
name: 'mode',
description: '<p>either CORNER, CORNERS, or CENTER</p>\n',
type: 'Constant'
}
],
class: 'p5',
module: 'Image'
},
pixels: {
name: 'pixels',
class: 'p5',
module: 'Image'
},
blend: {
name: 'blend',
class: 'p5',
module: 'Image',
overloads: [
{
params: [
{
name: 'srcImage',
description: '<p>source image</p>\n',
type: 'p5.Image'
},
{
name: 'sx',
description:
"<p>X coordinate of the source's upper left corner</p>\n",
type: 'Integer'
},
{
name: 'sy',
description:
"<p>Y coordinate of the source's upper left corner</p>\n",
type: 'Integer'
},
{
name: 'sw',
description: '<p>source image width</p>\n',
type: 'Integer'
},
{
name: 'sh',
description: '<p>source image height</p>\n',
type: 'Integer'
},
{
name: 'dx',
description:
"<p>X coordinate of the destination's upper left corner</p>\n",
type: 'Integer'
},
{
name: 'dy',
description:
"<p>Y coordinate of the destination's upper left corner</p>\n",
type: 'Integer'
},
{
name: 'dw',
description: '<p>destination image width</p>\n',
type: 'Integer'
},
{
name: 'dh',
description: '<p>destination image height</p>\n',
type: 'Integer'
},
{
name: 'blendMode',
description:
'<p>the blend mode. either\n BLEND, DARKEST, LIGHTEST, DIFFERENCE,\n MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.</p>\n',
type: 'Constant'
}
]
},
{
params: [
{
name: 'sx',
description: '',
type: 'Integer'
},
{
name: 'sy',
description: '',
type: 'Integer'
},
{
name: 'sw',
description: '',
type: 'Integer'
},
{
name: 'sh',
description: '',
type: 'Integer'
},
{
name: 'dx',
description: '',
type: 'Integer'
},
{
name: 'dy',
description: '',
type: 'Integer'
},
{
name: 'dw',
description: '',
type: 'Integer'
},
{
name: 'dh',
description: '',
type: 'Integer'
},
{
name: 'blendMode',
description: '',
type: 'Constant'
}
]
}
]
},
copy: {
name: 'copy',
class: 'p5',
module: 'Image',
overloads: [
{
params: [
{
name: 'srcImage',
description: '<p>source image</p>\n',
type: 'p5.Image|p5.Element'
},
{
name: 'sx',
description:
"<p>X coordinate of the source's upper left corner</p>\n",
type: 'Integer'
},
{
name: 'sy',
description:
"<p>Y coordinate of the source's upper left corner</p>\n",
type: 'Integer'
},
{
name: 'sw',
description: '<p>source image width</p>\n',
type: 'Integer'
},
{
name: 'sh',
description: '<p>source image height</p>\n',
type: 'Integer'
},
{
name: 'dx',
description:
"<p>X coordinate of the destination's upper left corner</p>\n",
type: 'Integer'
},
{
name: 'dy',
description:
"<p>Y coordinate of the destination's upper left corner</p>\n",
type: 'Integer'
},
{
name: 'dw',
description: '<p>destination image width</p>\n',
type: 'Integer'
},
{
name: 'dh',
description: '<p>destination image height</p>\n',
type: 'Integer'
}
]
},
{
params: [
{
name: 'sx',
description: '',
type: 'Integer'
},
{
name: 'sy',
description: '',
type: 'Integer'
},
{
name: 'sw',
description: '',
type: 'Integer'
},
{
name: 'sh',
description: '',
type: 'Integer'
},
{
name: 'dx',
description: '',
type: 'Integer'
},
{
name: 'dy',
description: '',
type: 'Integer'
},
{
name: 'dw',
description: '',
type: 'Integer'
},
{
name: 'dh',
description: '',
type: 'Integer'
}
]
}
]
},
filter: {
name: 'filter',
params: [
{
name: 'filterType',
description:
'<p>either THRESHOLD, GRAY, OPAQUE, INVERT,\n POSTERIZE, BLUR, ERODE, DILATE or BLUR.\n See Filters.js for docs on\n each available filter</p>\n',
type: 'Constant'
},
{
name: 'filterParam',
description:
'<p>an optional parameter unique\n to each filter, see above</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5',
module: 'Image'
},
get: {
name: 'get',
class: 'p5',
module: 'Image',
overloads: [
{
params: [
{
name: 'x',
description: '<p>x-coordinate of the pixel</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>y-coordinate of the pixel</p>\n',
type: 'Number'
},
{
name: 'w',
description: '<p>width</p>\n',
type: 'Number'
},
{
name: 'h',
description: '<p>height</p>\n',
type: 'Number'
}
]
},
{
params: []
},
{
params: [
{
name: 'x',
description: '',
type: 'Number'
},
{
name: 'y',
description: '',
type: 'Number'
}
]
}
]
},
loadPixels: {
name: 'loadPixels',
class: 'p5',
module: 'Image'
},
set: {
name: 'set',
params: [
{
name: 'x',
description: '<p>x-coordinate of the pixel</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>y-coordinate of the pixel</p>\n',
type: 'Number'
},
{
name: 'c',
description:
'<p>insert a grayscale value | a pixel array |\n a <a href="#/p5.Color">p5.Color</a> object | a <a href="#/p5.Image">p5.Image</a> to copy</p>\n',
type: 'Number|Number[]|Object'
}
],
class: 'p5',
module: 'Image'
},
updatePixels: {
name: 'updatePixels',
params: [
{
name: 'x',
description:
'<p>x-coordinate of the upper-left corner of region\n to update</p>\n',
type: 'Number',
optional: true
},
{
name: 'y',
description:
'<p>y-coordinate of the upper-left corner of region\n to update</p>\n',
type: 'Number',
optional: true
},
{
name: 'w',
description: '<p>width of region to update</p>\n',
type: 'Number',
optional: true
},
{
name: 'h',
description: '<p>height of region to update</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5',
module: 'Image'
},
loadJSON: {
name: 'loadJSON',
class: 'p5',
module: 'IO',
overloads: [
{
params: [
{
name: 'path',
description: '<p>name of the file or url to load</p>\n',
type: 'String'
},
{
name: 'jsonpOptions',
description: '<p>options object for jsonp related settings</p>\n',
type: 'Object',
optional: true
},
{
name: 'datatype',
description: '<p>"json" or "jsonp"</p>\n',
type: 'String',
optional: true
},
{
name: 'callback',
description:
'<p>function to be executed after\n <a href="#/p5/loadJSON">loadJSON()</a> completes, data is passed\n in as first argument</p>\n',
type: 'Function',
optional: true
},
{
name: 'errorCallback',
description:
'<p>function to be executed if\n there is an error, response is passed\n in as first argument</p>\n',
type: 'Function',
optional: true
}
]
},
{
params: [
{
name: 'path',
description: '',
type: 'String'
},
{
name: 'datatype',
description: '',
type: 'String'
},
{
name: 'callback',
description: '',
type: 'Function',
optional: true
},
{
name: 'errorCallback',
description: '',
type: 'Function',
optional: true
}
]
},
{
params: [
{
name: 'path',
description: '',
type: 'String'
},
{
name: 'callback',
description: '',
type: 'Function'
},
{
name: 'errorCallback',
description: '',
type: 'Function',
optional: true
}
]
}
]
},
loadStrings: {
name: 'loadStrings',
params: [
{
name: 'filename',
description: '<p>name of the file or url to load</p>\n',
type: 'String'
},
{
name: 'callback',
description:
'<p>function to be executed after <a href="#/p5/loadStrings">loadStrings()</a>\n completes, Array is passed in as first\n argument</p>\n',
type: 'Function',
optional: true
},
{
name: 'errorCallback',
description:
'<p>function to be executed if\n there is an error, response is passed\n in as first argument</p>\n',
type: 'Function',
optional: true
}
],
class: 'p5',
module: 'IO'
},
loadTable: {
name: 'loadTable',
params: [
{
name: 'filename',
description: '<p>name of the file or URL to load</p>\n',
type: 'String'
},
{
name: 'extension',
description:
'<p>parse the table by comma-separated values "csv", semicolon-separated\n values "ssv", or tab-separated values "tsv"</p>\n',
type: 'String',
optional: true
},
{
name: 'header',
description: '<p>"header" to indicate table has header row</p>\n',
type: 'String',
optional: true
},
{
name: 'callback',
description:
'<p>function to be executed after\n <a href="#/p5/loadTable">loadTable()</a> completes. On success, the\n <a href="#/p5.Table">Table</a> object is passed in as the\n first argument.</p>\n',
type: 'Function',
optional: true
},
{
name: 'errorCallback',
description:
'<p>function to be executed if\n there is an error, response is passed\n in as first argument</p>\n',
type: 'Function',
optional: true
}
],
class: 'p5',
module: 'IO'
},
loadXML: {
name: 'loadXML',
params: [
{
name: 'filename',
description: '<p>name of the file or URL to load</p>\n',
type: 'String'
},
{
name: 'callback',
description:
'<p>function to be executed after <a href="#/p5/loadXML">loadXML()</a>\n completes, XML object is passed in as\n first argument</p>\n',
type: 'Function',
optional: true
},
{
name: 'errorCallback',
description:
'<p>function to be executed if\n there is an error, response is passed\n in as first argument</p>\n',
type: 'Function',
optional: true
}
],
class: 'p5',
module: 'IO'
},
loadBytes: {
name: 'loadBytes',
params: [
{
name: 'file',
description: '<p>name of the file or URL to load</p>\n',
type: 'String'
},
{
name: 'callback',
description:
'<p>function to be executed after <a href="#/p5/loadBytes">loadBytes()</a>\n completes</p>\n',
type: 'Function',
optional: true
},
{
name: 'errorCallback',
description:
'<p>function to be executed if there\n is an error</p>\n',
type: 'Function',
optional: true
}
],
class: 'p5',
module: 'IO'
},
httpGet: {
name: 'httpGet',
class: 'p5',
module: 'IO',
overloads: [
{
params: [
{
name: 'path',
description: '<p>name of the file or url to load</p>\n',
type: 'String'
},
{
name: 'datatype',
description:
'<p>"json", "jsonp", "binary", "arrayBuffer",\n "xml", or "text"</p>\n',
type: 'String',
optional: true
},
{
name: 'data',
description: '<p>param data passed sent with request</p>\n',
type: 'Object|Boolean',
optional: true
},
{
name: 'callback',
description:
'<p>function to be executed after\n <a href="#/p5/httpGet">httpGet()</a> completes, data is passed in\n as first argument</p>\n',
type: 'Function',
optional: true
},
{
name: 'errorCallback',
description:
'<p>function to be executed if\n there is an error, response is passed\n in as first argument</p>\n',
type: 'Function',
optional: true
}
]
},
{
params: [
{
name: 'path',
description: '',
type: 'String'
},
{
name: 'data',
description: '',
type: 'Object|Boolean'
},
{
name: 'callback',
description: '',
type: 'Function',
optional: true
},
{
name: 'errorCallback',
description: '',
type: 'Function',
optional: true
}
]
},
{
params: [
{
name: 'path',
description: '',
type: 'String'
},
{
name: 'callback',
description: '',
type: 'Function'
},
{
name: 'errorCallback',
description: '',
type: 'Function',
optional: true
}
]
}
]
},
httpPost: {
name: 'httpPost',
class: 'p5',
module: 'IO',
overloads: [
{
params: [
{
name: 'path',
description: '<p>name of the file or url to load</p>\n',
type: 'String'
},
{
name: 'datatype',
description:
'<p>"json", "jsonp", "xml", or "text".\n If omitted, <a href="#/p5/httpPost">httpPost()</a> will guess.</p>\n',
type: 'String',
optional: true
},
{
name: 'data',
description: '<p>param data passed sent with request</p>\n',
type: 'Object|Boolean',
optional: true
},
{
name: 'callback',
description:
'<p>function to be executed after\n <a href="#/p5/httpPost">httpPost()</a> completes, data is passed in\n as first argument</p>\n',
type: 'Function',
optional: true
},
{
name: 'errorCallback',
description:
'<p>function to be executed if\n there is an error, response is passed\n in as first argument</p>\n',
type: 'Function',
optional: true
}
]
},
{
params: [
{
name: 'path',
description: '',
type: 'String'
},
{
name: 'data',
description: '',
type: 'Object|Boolean'
},
{
name: 'callback',
description: '',
type: 'Function',
optional: true
},
{
name: 'errorCallback',
description: '',
type: 'Function',
optional: true
}
]
},
{
params: [
{
name: 'path',
description: '',
type: 'String'
},
{
name: 'callback',
description: '',
type: 'Function'
},
{
name: 'errorCallback',
description: '',
type: 'Function',
optional: true
}
]
}
]
},
httpDo: {
name: 'httpDo',
class: 'p5',
module: 'IO',
overloads: [
{
params: [
{
name: 'path',
description: '<p>name of the file or url to load</p>\n',
type: 'String'
},
{
name: 'method',
description:
'<p>either "GET", "POST", or "PUT",\n defaults to "GET"</p>\n',
type: 'String',
optional: true
},
{
name: 'datatype',
description: '<p>"json", "jsonp", "xml", or "text"</p>\n',
type: 'String',
optional: true
},
{
name: 'data',
description: '<p>param data passed sent with request</p>\n',
type: 'Object',
optional: true
},
{
name: 'callback',
description:
'<p>function to be executed after\n <a href="#/p5/httpGet">httpGet()</a> completes, data is passed in\n as first argument</p>\n',
type: 'Function',
optional: true
},
{
name: 'errorCallback',
description:
'<p>function to be executed if\n there is an error, response is passed\n in as first argument</p>\n',
type: 'Function',
optional: true
}
]
},
{
params: [
{
name: 'path',
description: '',
type: 'String'
},
{
name: 'options',
description:
'<p>Request object options as documented in the\n "fetch" API\n<a href="https://developer.mozilla.org/en/docs/Web/API/Fetch_API">reference</a></p>\n',
type: 'Object'
},
{
name: 'callback',
description: '',
type: 'Function',
optional: true
},
{
name: 'errorCallback',
description: '',
type: 'Function',
optional: true
}
]
}
]
},
createWriter: {
name: 'createWriter',
params: [
{
name: 'name',
description: '<p>name of the file to be created</p>\n',
type: 'String'
},
{
name: 'extension',
description: '',
type: 'String',
optional: true
}
],
class: 'p5',
module: 'IO'
},
save: {
name: 'save',
params: [
{
name: 'objectOrFilename',
description:
'<p>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).</p>\n',
type: 'Object|String',
optional: true
},
{
name: 'filename',
description:
'<p>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).</p>\n',
type: 'String',
optional: true
},
{
name: 'options',
description:
'<p>Additional options depend on\n filetype. For example, when saving JSON,\n <code>true</code> indicates that the\n output will be optimized for filesize,\n rather than readability.</p>\n',
type: 'Boolean|String',
optional: true
}
],
class: 'p5',
module: 'IO'
},
saveJSON: {
name: 'saveJSON',
params: [
{
name: 'json',
description: '',
type: 'Array|Object'
},
{
name: 'filename',
description: '',
type: 'String'
},
{
name: 'optimize',
description:
'<p>If true, removes line breaks\n and spaces from the output\n file to optimize filesize\n (but not readability).</p>\n',
type: 'Boolean',
optional: true
}
],
class: 'p5',
module: 'IO'
},
saveStrings: {
name: 'saveStrings',
params: [
{
name: 'list',
description: '<p>string array to be written</p>\n',
type: 'String[]'
},
{
name: 'filename',
description: '<p>filename for output</p>\n',
type: 'String'
},
{
name: 'extension',
description: "<p>the filename's extension</p>\n",
type: 'String',
optional: true
},
{
name: 'isCRLF',
description: '<p>if true, change line-break to CRLF</p>\n',
type: 'Boolean',
optional: true
}
],
class: 'p5',
module: 'IO'
},
saveTable: {
name: 'saveTable',
params: [
{
name: 'Table',
description:
'<p>the <a href="#/p5.Table">Table</a> object to save to a file</p>\n',
type: 'p5.Table'
},
{
name: 'filename',
description: '<p>the filename to which the Table should be saved</p>\n',
type: 'String'
},
{
name: 'options',
description: '<p>can be one of "tsv", "csv", or "html"</p>\n',
type: 'String',
optional: true
}
],
class: 'p5',
module: 'IO'
},
abs: {
name: 'abs',
params: [
{
name: 'n',
description: '<p>number to compute</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
ceil: {
name: 'ceil',
params: [
{
name: 'n',
description: '<p>number to round up</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
constrain: {
name: 'constrain',
params: [
{
name: 'n',
description: '<p>number to constrain</p>\n',
type: 'Number'
},
{
name: 'low',
description: '<p>minimum limit</p>\n',
type: 'Number'
},
{
name: 'high',
description: '<p>maximum limit</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
dist: {
name: 'dist',
class: 'p5',
module: 'Math',
overloads: [
{
params: [
{
name: 'x1',
description: '<p>x-coordinate of the first point</p>\n',
type: 'Number'
},
{
name: 'y1',
description: '<p>y-coordinate of the first point</p>\n',
type: 'Number'
},
{
name: 'x2',
description: '<p>x-coordinate of the second point</p>\n',
type: 'Number'
},
{
name: 'y2',
description: '<p>y-coordinate of the second point</p>\n',
type: 'Number'
}
]
},
{
params: [
{
name: 'x1',
description: '',
type: 'Number'
},
{
name: 'y1',
description: '',
type: 'Number'
},
{
name: 'z1',
description: '<p>z-coordinate of the first point</p>\n',
type: 'Number'
},
{
name: 'x2',
description: '',
type: 'Number'
},
{
name: 'y2',
description: '',
type: 'Number'
},
{
name: 'z2',
description: '<p>z-coordinate of the second point</p>\n',
type: 'Number'
}
]
}
]
},
exp: {
name: 'exp',
params: [
{
name: 'n',
description: '<p>exponent to raise</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
floor: {
name: 'floor',
params: [
{
name: 'n',
description: '<p>number to round down</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
lerp: {
name: 'lerp',
params: [
{
name: 'start',
description: '<p>first value</p>\n',
type: 'Number'
},
{
name: 'stop',
description: '<p>second value</p>\n',
type: 'Number'
},
{
name: 'amt',
description: '<p>number</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
log: {
name: 'log',
params: [
{
name: 'n',
description: '<p>number greater than 0</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
mag: {
name: 'mag',
params: [
{
name: 'a',
description: '<p>first value</p>\n',
type: 'Number'
},
{
name: 'b',
description: '<p>second value</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
map: {
name: 'map',
params: [
{
name: 'value',
description: '<p>the incoming value to be converted</p>\n',
type: 'Number'
},
{
name: 'start1',
description: "<p>lower bound of the value's current range</p>\n",
type: 'Number'
},
{
name: 'stop1',
description: "<p>upper bound of the value's current range</p>\n",
type: 'Number'
},
{
name: 'start2',
description: "<p>lower bound of the value's target range</p>\n",
type: 'Number'
},
{
name: 'stop2',
description: "<p>upper bound of the value's target range</p>\n",
type: 'Number'
},
{
name: 'withinBounds',
description: '<p>constrain the value to the newly mapped range</p>\n',
type: 'Boolean',
optional: true
}
],
class: 'p5',
module: 'Math'
},
max: {
name: 'max',
class: 'p5',
module: 'Math',
overloads: [
{
params: [
{
name: 'n0',
description: '<p>Number to compare</p>\n',
type: 'Number'
},
{
name: 'n1',
description: '<p>Number to compare</p>\n',
type: 'Number'
}
]
},
{
params: [
{
name: 'nums',
description: '<p>Numbers to compare</p>\n',
type: 'Number[]'
}
]
}
]
},
min: {
name: 'min',
class: 'p5',
module: 'Math',
overloads: [
{
params: [
{
name: 'n0',
description: '<p>Number to compare</p>\n',
type: 'Number'
},
{
name: 'n1',
description: '<p>Number to compare</p>\n',
type: 'Number'
}
]
},
{
params: [
{
name: 'nums',
description: '<p>Numbers to compare</p>\n',
type: 'Number[]'
}
]
}
]
},
norm: {
name: 'norm',
params: [
{
name: 'value',
description: '<p>incoming value to be normalized</p>\n',
type: 'Number'
},
{
name: 'start',
description: "<p>lower bound of the value's current range</p>\n",
type: 'Number'
},
{
name: 'stop',
description: "<p>upper bound of the value's current range</p>\n",
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
pow: {
name: 'pow',
params: [
{
name: 'n',
description: '<p>base of the exponential expression</p>\n',
type: 'Number'
},
{
name: 'e',
description: '<p>power by which to raise the base</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
round: {
name: 'round',
params: [
{
name: 'n',
description: '<p>number to round</p>\n',
type: 'Number'
},
{
name: 'decimals',
description:
'<p>number of decimal places to round to, default is 0</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5',
module: 'Math'
},
sq: {
name: 'sq',
params: [
{
name: 'n',
description: '<p>number to square</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
sqrt: {
name: 'sqrt',
params: [
{
name: 'n',
description: '<p>non-negative number to square root</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
fract: {
name: 'fract',
params: [
{
name: 'num',
description:
'<p>Number whose fractional part needs to be found out</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
createVector: {
name: 'createVector',
params: [
{
name: 'x',
description: '<p>x component of the vector</p>\n',
type: 'Number',
optional: true
},
{
name: 'y',
description: '<p>y component of the vector</p>\n',
type: 'Number',
optional: true
},
{
name: 'z',
description: '<p>z component of the vector</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5',
module: 'Math'
},
noise: {
name: 'noise',
params: [
{
name: 'x',
description: '<p>x-coordinate in noise space</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>y-coordinate in noise space</p>\n',
type: 'Number',
optional: true
},
{
name: 'z',
description: '<p>z-coordinate in noise space</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5',
module: 'Math'
},
noiseDetail: {
name: 'noiseDetail',
params: [
{
name: 'lod',
description: '<p>number of octaves to be used by the noise</p>\n',
type: 'Number'
},
{
name: 'falloff',
description: '<p>falloff factor for each octave</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
noiseSeed: {
name: 'noiseSeed',
params: [
{
name: 'seed',
description: '<p>the seed value</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
randomSeed: {
name: 'randomSeed',
params: [
{
name: 'seed',
description: '<p>the seed value</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
random: {
name: 'random',
class: 'p5',
module: 'Math',
overloads: [
{
params: [
{
name: 'min',
description: '<p>the lower bound (inclusive)</p>\n',
type: 'Number',
optional: true
},
{
name: 'max',
description: '<p>the upper bound (exclusive)</p>\n',
type: 'Number',
optional: true
}
]
},
{
params: [
{
name: 'choices',
description: '<p>the array to choose from</p>\n',
type: 'Array'
}
]
}
]
},
randomGaussian: {
name: 'randomGaussian',
params: [
{
name: 'mean',
description: '<p>the mean</p>\n',
type: 'Number',
optional: true
},
{
name: 'sd',
description: '<p>the standard deviation</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5',
module: 'Math'
},
acos: {
name: 'acos',
params: [
{
name: 'value',
description: '<p>the value whose arc cosine is to be returned</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
asin: {
name: 'asin',
params: [
{
name: 'value',
description: '<p>the value whose arc sine is to be returned</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
atan: {
name: 'atan',
params: [
{
name: 'value',
description: '<p>the value whose arc tangent is to be returned</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
atan2: {
name: 'atan2',
params: [
{
name: 'y',
description: '<p>y-coordinate of the point</p>\n',
type: 'Number'
},
{
name: 'x',
description: '<p>x-coordinate of the point</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
cos: {
name: 'cos',
params: [
{
name: 'angle',
description: '<p>the angle</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
sin: {
name: 'sin',
params: [
{
name: 'angle',
description: '<p>the angle</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
tan: {
name: 'tan',
params: [
{
name: 'angle',
description: '<p>the angle</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
degrees: {
name: 'degrees',
params: [
{
name: 'radians',
description: '<p>the radians value to convert to degrees</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
radians: {
name: 'radians',
params: [
{
name: 'degrees',
description: '<p>the degree value to convert to radians</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Math'
},
angleMode: {
name: 'angleMode',
params: [
{
name: 'mode',
description: '<p>either RADIANS or DEGREES</p>\n',
type: 'Constant'
}
],
class: 'p5',
module: 'Math'
},
textAlign: {
name: 'textAlign',
class: 'p5',
module: 'Typography',
overloads: [
{
params: [
{
name: 'horizAlign',
description:
'<p>horizontal alignment, either LEFT,\n CENTER, or RIGHT</p>\n',
type: 'Constant'
},
{
name: 'vertAlign',
description:
'<p>vertical alignment, either TOP,\n BOTTOM, CENTER, or BASELINE</p>\n',
type: 'Constant',
optional: true
}
],
chainable: 1
},
{
params: []
}
]
},
textLeading: {
name: 'textLeading',
class: 'p5',
module: 'Typography',
overloads: [
{
params: [
{
name: 'leading',
description:
'<p>the size in pixels for spacing between lines</p>\n',
type: 'Number'
}
],
chainable: 1
},
{
params: []
}
]
},
textSize: {
name: 'textSize',
class: 'p5',
module: 'Typography',
overloads: [
{
params: [
{
name: 'theSize',
description: '<p>the size of the letters in units of pixels</p>\n',
type: 'Number'
}
],
chainable: 1
},
{
params: []
}
]
},
textStyle: {
name: 'textStyle',
class: 'p5',
module: 'Typography',
overloads: [
{
params: [
{
name: 'theStyle',
description:
'<p>styling for text, either NORMAL,\n ITALIC, BOLD or BOLDITALIC</p>\n',
type: 'Constant'
}
],
chainable: 1
},
{
params: []
}
]
},
textWidth: {
name: 'textWidth',
params: [
{
name: 'theText',
description: '<p>the String of characters to measure</p>\n',
type: 'String'
}
],
class: 'p5',
module: 'Typography'
},
textAscent: {
name: 'textAscent',
class: 'p5',
module: 'Typography'
},
textDescent: {
name: 'textDescent',
class: 'p5',
module: 'Typography'
},
loadFont: {
name: 'loadFont',
params: [
{
name: 'path',
description: '<p>name of the file or url to load</p>\n',
type: 'String'
},
{
name: 'callback',
description:
'<p>function to be executed after\n <a href="#/p5/loadFont">loadFont()</a> completes</p>\n',
type: 'Function',
optional: true
},
{
name: 'onError',
description:
'<p>function to be executed if\n an error occurs</p>\n',
type: 'Function',
optional: true
}
],
class: 'p5',
module: 'Typography'
},
text: {
name: 'text',
params: [
{
name: 'str',
description:
'<p>the alphanumeric\n symbols to be displayed</p>\n',
type: 'String|Object|Array|Number|Boolean'
},
{
name: 'x',
description: '<p>x-coordinate of text</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>y-coordinate of text</p>\n',
type: 'Number'
},
{
name: 'x2',
description:
'<p>by default, the width of the text box,\n see <a href="#/p5/rectMode">rectMode()</a> for more info</p>\n',
type: 'Number',
optional: true
},
{
name: 'y2',
description:
'<p>by default, the height of the text box,\n see <a href="#/p5/rectMode">rectMode()</a> for more info</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5',
module: 'Typography'
},
textFont: {
name: 'textFont',
class: 'p5',
module: 'Typography',
overloads: [
{
params: []
},
{
params: [
{
name: 'font',
description:
'<p>a font loaded via <a href="#/p5/loadFont">loadFont()</a>,\nor a String representing a <a href="https://mzl.la/2dOw8WD">web safe font</a>\n(a font that is generally available across all systems)</p>\n',
type: 'Object|String'
},
{
name: 'size',
description: '<p>the font size to use</p>\n',
type: 'Number',
optional: true
}
],
chainable: 1
}
]
},
append: {
name: 'append',
params: [
{
name: 'array',
description: '<p>Array to append</p>\n',
type: 'Array'
},
{
name: 'value',
description: '<p>to be added to the Array</p>\n',
type: 'Any'
}
],
class: 'p5',
module: 'Data'
},
arrayCopy: {
name: 'arrayCopy',
class: 'p5',
module: 'Data',
overloads: [
{
params: [
{
name: 'src',
description: '<p>the source Array</p>\n',
type: 'Array'
},
{
name: 'srcPosition',
description: '<p>starting position in the source Array</p>\n',
type: 'Integer'
},
{
name: 'dst',
description: '<p>the destination Array</p>\n',
type: 'Array'
},
{
name: 'dstPosition',
description: '<p>starting position in the destination Array</p>\n',
type: 'Integer'
},
{
name: 'length',
description: '<p>number of Array elements to be copied</p>\n',
type: 'Integer'
}
]
},
{
params: [
{
name: 'src',
description: '',
type: 'Array'
},
{
name: 'dst',
description: '',
type: 'Array'
},
{
name: 'length',
description: '',
type: 'Integer',
optional: true
}
]
}
]
},
concat: {
name: 'concat',
params: [
{
name: 'a',
description: '<p>first Array to concatenate</p>\n',
type: 'Array'
},
{
name: 'b',
description: '<p>second Array to concatenate</p>\n',
type: 'Array'
}
],
class: 'p5',
module: 'Data'
},
reverse: {
name: 'reverse',
params: [
{
name: 'list',
description: '<p>Array to reverse</p>\n',
type: 'Array'
}
],
class: 'p5',
module: 'Data'
},
shorten: {
name: 'shorten',
params: [
{
name: 'list',
description: '<p>Array to shorten</p>\n',
type: 'Array'
}
],
class: 'p5',
module: 'Data'
},
shuffle: {
name: 'shuffle',
params: [
{
name: 'array',
description: '<p>Array to shuffle</p>\n',
type: 'Array'
},
{
name: 'bool',
description: '<p>modify passed array</p>\n',
type: 'Boolean',
optional: true
}
],
class: 'p5',
module: 'Data'
},
sort: {
name: 'sort',
params: [
{
name: 'list',
description: '<p>Array to sort</p>\n',
type: 'Array'
},
{
name: 'count',
description: '<p>number of elements to sort, starting from 0</p>\n',
type: 'Integer',
optional: true
}
],
class: 'p5',
module: 'Data'
},
splice: {
name: 'splice',
params: [
{
name: 'list',
description: '<p>Array to splice into</p>\n',
type: 'Array'
},
{
name: 'value',
description: '<p>value to be spliced in</p>\n',
type: 'Any'
},
{
name: 'position',
description: '<p>in the array from which to insert data</p>\n',
type: 'Integer'
}
],
class: 'p5',
module: 'Data'
},
subset: {
name: 'subset',
params: [
{
name: 'list',
description: '<p>Array to extract from</p>\n',
type: 'Array'
},
{
name: 'start',
description: '<p>position to begin</p>\n',
type: 'Integer'
},
{
name: 'count',
description: '<p>number of values to extract</p>\n',
type: 'Integer',
optional: true
}
],
class: 'p5',
module: 'Data'
},
float: {
name: 'float',
params: [
{
name: 'str',
description: '<p>float string to parse</p>\n',
type: 'String'
}
],
class: 'p5',
module: 'Data'
},
int: {
name: 'int',
class: 'p5',
module: 'Data',
overloads: [
{
params: [
{
name: 'n',
description: '<p>value to parse</p>\n',
type: 'String|Boolean|Number'
},
{
name: 'radix',
description: '<p>the radix to convert to (default: 10)</p>\n',
type: 'Integer',
optional: true
}
]
},
{
params: [
{
name: 'ns',
description: '<p>values to parse</p>\n',
type: 'Array'
}
]
}
]
},
str: {
name: 'str',
params: [
{
name: 'n',
description: '<p>value to parse</p>\n',
type: 'String|Boolean|Number|Array'
}
],
class: 'p5',
module: 'Data'
},
byte: {
name: 'byte',
class: 'p5',
module: 'Data',
overloads: [
{
params: [
{
name: 'n',
description: '<p>value to parse</p>\n',
type: 'String|Boolean|Number'
}
]
},
{
params: [
{
name: 'ns',
description: '<p>values to parse</p>\n',
type: 'Array'
}
]
}
]
},
char: {
name: 'char',
class: 'p5',
module: 'Data',
overloads: [
{
params: [
{
name: 'n',
description: '<p>value to parse</p>\n',
type: 'String|Number'
}
]
},
{
params: [
{
name: 'ns',
description: '<p>values to parse</p>\n',
type: 'Array'
}
]
}
]
},
unchar: {
name: 'unchar',
class: 'p5',
module: 'Data',
overloads: [
{
params: [
{
name: 'n',
description: '<p>value to parse</p>\n',
type: 'String'
}
]
},
{
params: [
{
name: 'ns',
description: '<p>values to parse</p>\n',
type: 'Array'
}
]
}
]
},
hex: {
name: 'hex',
class: 'p5',
module: 'Data',
overloads: [
{
params: [
{
name: 'n',
description: '<p>value to parse</p>\n',
type: 'Number'
},
{
name: 'digits',
description: '',
type: 'Number',
optional: true
}
]
},
{
params: [
{
name: 'ns',
description: '<p>array of values to parse</p>\n',
type: 'Number[]'
},
{
name: 'digits',
description: '',
type: 'Number',
optional: true
}
]
}
]
},
unhex: {
name: 'unhex',
class: 'p5',
module: 'Data',
overloads: [
{
params: [
{
name: 'n',
description: '<p>value to parse</p>\n',
type: 'String'
}
]
},
{
params: [
{
name: 'ns',
description: '<p>values to parse</p>\n',
type: 'Array'
}
]
}
]
},
join: {
name: 'join',
params: [
{
name: 'list',
description: '<p>array of Strings to be joined</p>\n',
type: 'Array'
},
{
name: 'separator',
description: '<p>String to be placed between each item</p>\n',
type: 'String'
}
],
class: 'p5',
module: 'Data'
},
match: {
name: 'match',
params: [
{
name: 'str',
description: '<p>the String to be searched</p>\n',
type: 'String'
},
{
name: 'regexp',
description: '<p>the regexp to be used for matching</p>\n',
type: 'String'
}
],
class: 'p5',
module: 'Data'
},
matchAll: {
name: 'matchAll',
params: [
{
name: 'str',
description: '<p>the String to be searched</p>\n',
type: 'String'
},
{
name: 'regexp',
description: '<p>the regexp to be used for matching</p>\n',
type: 'String'
}
],
class: 'p5',
module: 'Data'
},
nf: {
name: 'nf',
class: 'p5',
module: 'Data',
overloads: [
{
params: [
{
name: 'num',
description: '<p>the Number to format</p>\n',
type: 'Number|String'
},
{
name: 'left',
description:
'<p>number of digits to the left of the\n decimal point</p>\n',
type: 'Integer|String',
optional: true
},
{
name: 'right',
description:
'<p>number of digits to the right of the\n decimal point</p>\n',
type: 'Integer|String',
optional: true
}
]
},
{
params: [
{
name: 'nums',
description: '<p>the Numbers to format</p>\n',
type: 'Array'
},
{
name: 'left',
description: '',
type: 'Integer|String',
optional: true
},
{
name: 'right',
description: '',
type: 'Integer|String',
optional: true
}
]
}
]
},
nfc: {
name: 'nfc',
class: 'p5',
module: 'Data',
overloads: [
{
params: [
{
name: 'num',
description: '<p>the Number to format</p>\n',
type: 'Number|String'
},
{
name: 'right',
description:
'<p>number of digits to the right of the\n decimal point</p>\n',
type: 'Integer|String',
optional: true
}
]
},
{
params: [
{
name: 'nums',
description: '<p>the Numbers to format</p>\n',
type: 'Array'
},
{
name: 'right',
description: '',
type: 'Integer|String',
optional: true
}
]
}
]
},
nfp: {
name: 'nfp',
class: 'p5',
module: 'Data',
overloads: [
{
params: [
{
name: 'num',
description: '<p>the Number to format</p>\n',
type: 'Number'
},
{
name: 'left',
description:
'<p>number of digits to the left of the decimal\n point</p>\n',
type: 'Integer',
optional: true
},
{
name: 'right',
description:
'<p>number of digits to the right of the\n decimal point</p>\n',
type: 'Integer',
optional: true
}
]
},
{
params: [
{
name: 'nums',
description: '<p>the Numbers to format</p>\n',
type: 'Number[]'
},
{
name: 'left',
description: '',
type: 'Integer',
optional: true
},
{
name: 'right',
description: '',
type: 'Integer',
optional: true
}
]
}
]
},
nfs: {
name: 'nfs',
class: 'p5',
module: 'Data',
overloads: [
{
params: [
{
name: 'num',
description: '<p>the Number to format</p>\n',
type: 'Number'
},
{
name: 'left',
description:
'<p>number of digits to the left of the decimal\n point</p>\n',
type: 'Integer',
optional: true
},
{
name: 'right',
description:
'<p>number of digits to the right of the\n decimal point</p>\n',
type: 'Integer',
optional: true
}
]
},
{
params: [
{
name: 'nums',
description: '<p>the Numbers to format</p>\n',
type: 'Array'
},
{
name: 'left',
description: '',
type: 'Integer',
optional: true
},
{
name: 'right',
description: '',
type: 'Integer',
optional: true
}
]
}
]
},
split: {
name: 'split',
params: [
{
name: 'value',
description: '<p>the String to be split</p>\n',
type: 'String'
},
{
name: 'delim',
description: '<p>the String used to separate the data</p>\n',
type: 'String'
}
],
class: 'p5',
module: 'Data'
},
splitTokens: {
name: 'splitTokens',
params: [
{
name: 'value',
description: '<p>the String to be split</p>\n',
type: 'String'
},
{
name: 'delim',
description:
'<p>list of individual Strings that will be used as\n separators</p>\n',
type: 'String',
optional: true
}
],
class: 'p5',
module: 'Data'
},
trim: {
name: 'trim',
class: 'p5',
module: 'Data',
overloads: [
{
params: [
{
name: 'str',
description: '<p>a String to be trimmed</p>\n',
type: 'String'
}
]
},
{
params: [
{
name: 'strs',
description: '<p>an Array of Strings to be trimmed</p>\n',
type: 'Array'
}
]
}
]
},
day: {
name: 'day',
class: 'p5',
module: 'IO'
},
hour: {
name: 'hour',
class: 'p5',
module: 'IO'
},
minute: {
name: 'minute',
class: 'p5',
module: 'IO'
},
millis: {
name: 'millis',
class: 'p5',
module: 'IO'
},
month: {
name: 'month',
class: 'p5',
module: 'IO'
},
second: {
name: 'second',
class: 'p5',
module: 'IO'
},
year: {
name: 'year',
class: 'p5',
module: 'IO'
},
plane: {
name: 'plane',
params: [
{
name: 'width',
description: '<p>width of the plane</p>\n',
type: 'Number',
optional: true
},
{
name: 'height',
description: '<p>height of the plane</p>\n',
type: 'Number',
optional: true
},
{
name: 'detailX',
description:
'<p>Optional number of triangle\n subdivisions in x-dimension</p>\n',
type: 'Integer',
optional: true
},
{
name: 'detailY',
description:
'<p>Optional number of triangle\n subdivisions in y-dimension</p>\n',
type: 'Integer',
optional: true
}
],
class: 'p5',
module: 'Shape'
},
box: {
name: 'box',
params: [
{
name: 'width',
description: '<p>width of the box</p>\n',
type: 'Number',
optional: true
},
{
name: 'Height',
description: '<p>height of the box</p>\n',
type: 'Number',
optional: true
},
{
name: 'depth',
description: '<p>depth of the box</p>\n',
type: 'Number',
optional: true
},
{
name: 'detailX',
description:
'<p>Optional number of triangle\n subdivisions in x-dimension</p>\n',
type: 'Integer',
optional: true
},
{
name: 'detailY',
description:
'<p>Optional number of triangle\n subdivisions in y-dimension</p>\n',
type: 'Integer',
optional: true
}
],
class: 'p5',
module: 'Shape'
},
sphere: {
name: 'sphere',
params: [
{
name: 'radius',
description: '<p>radius of circle</p>\n',
type: 'Number',
optional: true
},
{
name: 'detailX',
description: '<p>optional number of subdivisions in x-dimension</p>\n',
type: 'Integer',
optional: true
},
{
name: 'detailY',
description: '<p>optional number of subdivisions in y-dimension</p>\n',
type: 'Integer',
optional: true
}
],
class: 'p5',
module: 'Shape'
},
cylinder: {
name: 'cylinder',
params: [
{
name: 'radius',
description: '<p>radius of the surface</p>\n',
type: 'Number',
optional: true
},
{
name: 'height',
description: '<p>height of the cylinder</p>\n',
type: 'Number',
optional: true
},
{
name: 'detailX',
description:
'<p>number of subdivisions in x-dimension;\n default is 24</p>\n',
type: 'Integer',
optional: true
},
{
name: 'detailY',
description:
'<p>number of subdivisions in y-dimension;\n default is 1</p>\n',
type: 'Integer',
optional: true
},
{
name: 'bottomCap',
description: '<p>whether to draw the bottom of the cylinder</p>\n',
type: 'Boolean',
optional: true
},
{
name: 'topCap',
description: '<p>whether to draw the top of the cylinder</p>\n',
type: 'Boolean',
optional: true
}
],
class: 'p5',
module: 'Shape'
},
cone: {
name: 'cone',
params: [
{
name: 'radius',
description: '<p>radius of the bottom surface</p>\n',
type: 'Number',
optional: true
},
{
name: 'height',
description: '<p>height of the cone</p>\n',
type: 'Number',
optional: true
},
{
name: 'detailX',
description:
'<p>number of segments,\n the more segments the smoother geometry\n default is 24</p>\n',
type: 'Integer',
optional: true
},
{
name: 'detailY',
description:
'<p>number of segments,\n the more segments the smoother geometry\n default is 1</p>\n',
type: 'Integer',
optional: true
},
{
name: 'cap',
description: '<p>whether to draw the base of the cone</p>\n',
type: 'Boolean',
optional: true
}
],
class: 'p5',
module: 'Shape'
},
ellipsoid: {
name: 'ellipsoid',
params: [
{
name: 'radiusx',
description: '<p>x-radius of ellipsoid</p>\n',
type: 'Number',
optional: true
},
{
name: 'radiusy',
description: '<p>y-radius of ellipsoid</p>\n',
type: 'Number',
optional: true
},
{
name: 'radiusz',
description: '<p>z-radius of ellipsoid</p>\n',
type: 'Number',
optional: true
},
{
name: 'detailX',
description:
'<p>number of segments,\n the more segments the smoother geometry\n default is 24. Avoid detail number above\n 150, it may crash the browser.</p>\n',
type: 'Integer',
optional: true
},
{
name: 'detailY',
description:
'<p>number of segments,\n the more segments the smoother geometry\n default is 16. Avoid detail number above\n 150, it may crash the browser.</p>\n',
type: 'Integer',
optional: true
}
],
class: 'p5',
module: 'Shape'
},
torus: {
name: 'torus',
params: [
{
name: 'radius',
description: '<p>radius of the whole ring</p>\n',
type: 'Number',
optional: true
},
{
name: 'tubeRadius',
description: '<p>radius of the tube</p>\n',
type: 'Number',
optional: true
},
{
name: 'detailX',
description:
'<p>number of segments in x-dimension,\n the more segments the smoother geometry\n default is 24</p>\n',
type: 'Integer',
optional: true
},
{
name: 'detailY',
description:
'<p>number of segments in y-dimension,\n the more segments the smoother geometry\n default is 16</p>\n',
type: 'Integer',
optional: true
}
],
class: 'p5',
module: 'Shape'
},
orbitControl: {
name: 'orbitControl',
params: [
{
name: 'sensitivityX',
description: '<p>sensitivity to mouse movement along X axis</p>\n',
type: 'Number',
optional: true
},
{
name: 'sensitivityY',
description: '<p>sensitivity to mouse movement along Y axis</p>\n',
type: 'Number',
optional: true
},
{
name: 'sensitivityZ',
description: '<p>sensitivity to scroll movement along Z axis</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5',
module: 'Lights, Camera'
},
debugMode: {
name: 'debugMode',
class: 'p5',
module: 'Lights, Camera',
overloads: [
{
params: []
},
{
params: [
{
name: 'mode',
description: '<p>either GRID or AXES</p>\n',
type: 'Constant'
}
]
},
{
params: [
{
name: 'mode',
description: '',
type: 'Constant'
},
{
name: 'gridSize',
description: '<p>size of one side of the grid</p>\n',
type: 'Number',
optional: true
},
{
name: 'gridDivisions',
description: '<p>number of divisions in the grid</p>\n',
type: 'Number',
optional: true
},
{
name: 'xOff',
description: '<p>X axis offset from origin (0,0,0)</p>\n',
type: 'Number',
optional: true
},
{
name: 'yOff',
description: '<p>Y axis offset from origin (0,0,0)</p>\n',
type: 'Number',
optional: true
},
{
name: 'zOff',
description: '<p>Z axis offset from origin (0,0,0)</p>\n',
type: 'Number',
optional: true
}
]
},
{
params: [
{
name: 'mode',
description: '',
type: 'Constant'
},
{
name: 'axesSize',
description: '<p>size of axes icon</p>\n',
type: 'Number',
optional: true
},
{
name: 'xOff',
description: '',
type: 'Number',
optional: true
},
{
name: 'yOff',
description: '',
type: 'Number',
optional: true
},
{
name: 'zOff',
description: '',
type: 'Number',
optional: true
}
]
},
{
params: [
{
name: 'gridSize',
description: '',
type: 'Number',
optional: true
},
{
name: 'gridDivisions',
description: '',
type: 'Number',
optional: true
},
{
name: 'gridXOff',
description: '',
type: 'Number',
optional: true
},
{
name: 'gridYOff',
description: '',
type: 'Number',
optional: true
},
{
name: 'gridZOff',
description: '',
type: 'Number',
optional: true
},
{
name: 'axesSize',
description: '',
type: 'Number',
optional: true
},
{
name: 'axesXOff',
description: '',
type: 'Number',
optional: true
},
{
name: 'axesYOff',
description: '',
type: 'Number',
optional: true
},
{
name: 'axesZOff',
description: '',
type: 'Number',
optional: true
}
]
}
]
},
noDebugMode: {
name: 'noDebugMode',
class: 'p5',
module: 'Lights, Camera'
},
ambientLight: {
name: 'ambientLight',
class: 'p5',
module: 'Lights, Camera',
overloads: [
{
params: [
{
name: 'v1',
description:
'<p>red or hue value relative to\n the current color range</p>\n',
type: 'Number'
},
{
name: 'v2',
description:
'<p>green or saturation value\n relative to the current color range</p>\n',
type: 'Number'
},
{
name: 'v3',
description:
'<p>blue or brightness value\n relative to the current color range</p>\n',
type: 'Number'
},
{
name: 'alpha',
description: '<p>the alpha value</p>\n',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'value',
description: '<p>a color string</p>\n',
type: 'String'
}
],
chainable: 1
},
{
params: [
{
name: 'gray',
description: '<p>a gray value</p>\n',
type: 'Number'
},
{
name: 'alpha',
description: '',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'values',
description:
'<p>an array containing the red,green,blue &\n and alpha components of the color</p>\n',
type: 'Number[]'
}
],
chainable: 1
},
{
params: [
{
name: 'color',
description: '<p>the ambient light color</p>\n',
type: 'p5.Color'
}
],
chainable: 1
}
]
},
specularColor: {
name: 'specularColor',
class: 'p5',
module: 'Lights, Camera',
overloads: [
{
params: [
{
name: 'v1',
description:
'<p>red or hue value relative to\n the current color range</p>\n',
type: 'Number'
},
{
name: 'v2',
description:
'<p>green or saturation value\n relative to the current color range</p>\n',
type: 'Number'
},
{
name: 'v3',
description:
'<p>blue or brightness value\n relative to the current color range</p>\n',
type: 'Number'
}
],
chainable: 1
},
{
params: [
{
name: 'value',
description: '<p>a color string</p>\n',
type: 'String'
}
],
chainable: 1
},
{
params: [
{
name: 'gray',
description: '<p>a gray value</p>\n',
type: 'Number'
}
],
chainable: 1
},
{
params: [
{
name: 'values',
description:
'<p>an array containing the red,green,blue &\n and alpha components of the color</p>\n',
type: 'Number[]'
}
],
chainable: 1
},
{
params: [
{
name: 'color',
description: '<p>the ambient light color</p>\n',
type: 'p5.Color'
}
],
chainable: 1
}
]
},
directionalLight: {
name: 'directionalLight',
class: 'p5',
module: 'Lights, Camera',
overloads: [
{
params: [
{
name: 'v1',
description:
'<p>red or hue value (depending on the current\ncolor mode),</p>\n',
type: 'Number'
},
{
name: 'v2',
description: '<p>green or saturation value</p>\n',
type: 'Number'
},
{
name: 'v3',
description: '<p>blue or brightness value</p>\n',
type: 'Number'
},
{
name: 'position',
description: '<p>the direction of the light</p>\n',
type: 'p5.Vector'
}
],
chainable: 1
},
{
params: [
{
name: 'color',
description:
'<p>color Array, CSS color string,\n or <a href="#/p5.Color">p5.Color</a> value</p>\n',
type: 'Number[]|String|p5.Color'
},
{
name: 'x',
description: '<p>x axis direction</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>y axis direction</p>\n',
type: 'Number'
},
{
name: 'z',
description: '<p>z axis direction</p>\n',
type: 'Number'
}
],
chainable: 1
},
{
params: [
{
name: 'color',
description: '',
type: 'Number[]|String|p5.Color'
},
{
name: 'position',
description: '',
type: 'p5.Vector'
}
],
chainable: 1
},
{
params: [
{
name: 'v1',
description: '',
type: 'Number'
},
{
name: 'v2',
description: '',
type: 'Number'
},
{
name: 'v3',
description: '',
type: 'Number'
},
{
name: 'x',
description: '',
type: 'Number'
},
{
name: 'y',
description: '',
type: 'Number'
},
{
name: 'z',
description: '',
type: 'Number'
}
],
chainable: 1
}
]
},
pointLight: {
name: 'pointLight',
class: 'p5',
module: 'Lights, Camera',
overloads: [
{
params: [
{
name: 'v1',
description:
'<p>red or hue value (depending on the current\ncolor mode),</p>\n',
type: 'Number'
},
{
name: 'v2',
description: '<p>green or saturation value</p>\n',
type: 'Number'
},
{
name: 'v3',
description: '<p>blue or brightness value</p>\n',
type: 'Number'
},
{
name: 'x',
description: '<p>x axis position</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>y axis position</p>\n',
type: 'Number'
},
{
name: 'z',
description: '<p>z axis position</p>\n',
type: 'Number'
}
],
chainable: 1
},
{
params: [
{
name: 'v1',
description: '',
type: 'Number'
},
{
name: 'v2',
description: '',
type: 'Number'
},
{
name: 'v3',
description: '',
type: 'Number'
},
{
name: 'position',
description: '<p>the position of the light</p>\n',
type: 'p5.Vector'
}
],
chainable: 1
},
{
params: [
{
name: 'color',
description:
'<p>color Array, CSS color string,\nor <a href="#/p5.Color">p5.Color</a> value</p>\n',
type: 'Number[]|String|p5.Color'
},
{
name: 'x',
description: '',
type: 'Number'
},
{
name: 'y',
description: '',
type: 'Number'
},
{
name: 'z',
description: '',
type: 'Number'
}
],
chainable: 1
},
{
params: [
{
name: 'color',
description: '',
type: 'Number[]|String|p5.Color'
},
{
name: 'position',
description: '',
type: 'p5.Vector'
}
],
chainable: 1
}
]
},
lights: {
name: 'lights',
class: 'p5',
module: 'Lights, Camera'
},
lightFalloff: {
name: 'lightFalloff',
params: [
{
name: 'constant',
description: '<p>constant value for determining falloff</p>\n',
type: 'Number'
},
{
name: 'linear',
description: '<p>linear value for determining falloff</p>\n',
type: 'Number'
},
{
name: 'quadratic',
description: '<p>quadratic value for determining falloff</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Lights, Camera'
},
spotLight: {
name: 'spotLight',
class: 'p5',
module: 'Lights, Camera',
overloads: [
{
params: [
{
name: 'v1',
description:
'<p>red or hue value (depending on the current\ncolor mode),</p>\n',
type: 'Number'
},
{
name: 'v2',
description: '<p>green or saturation value</p>\n',
type: 'Number'
},
{
name: 'v3',
description: '<p>blue or brightness value</p>\n',
type: 'Number'
},
{
name: 'x',
description: '<p>x axis position</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>y axis position</p>\n',
type: 'Number'
},
{
name: 'z',
description: '<p>z axis position</p>\n',
type: 'Number'
},
{
name: 'rx',
description: '<p>x axis direction of light</p>\n',
type: 'Number'
},
{
name: 'ry',
description: '<p>y axis direction of light</p>\n',
type: 'Number'
},
{
name: 'rz',
description: '<p>z axis direction of light</p>\n',
type: 'Number'
},
{
name: 'angle',
description:
'<p>optional parameter for angle. Defaults to PI/3</p>\n',
type: 'Number',
optional: true
},
{
name: 'conc',
description:
'<p>optional parameter for concentration. Defaults to 100</p>\n',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'color',
description:
'<p>color Array, CSS color string,\nor <a href="#/p5.Color">p5.Color</a> value</p>\n',
type: 'Number[]|String|p5.Color'
},
{
name: 'position',
description: '<p>the position of the light</p>\n',
type: 'p5.Vector'
},
{
name: 'direction',
description: '<p>the direction of the light</p>\n',
type: 'p5.Vector'
},
{
name: 'angle',
description: '',
type: 'Number',
optional: true
},
{
name: 'conc',
description: '',
type: 'Number',
optional: true
}
]
},
{
params: [
{
name: 'v1',
description: '',
type: 'Number'
},
{
name: 'v2',
description: '',
type: 'Number'
},
{
name: 'v3',
description: '',
type: 'Number'
},
{
name: 'position',
description: '',
type: 'p5.Vector'
},
{
name: 'direction',
description: '',
type: 'p5.Vector'
},
{
name: 'angle',
description: '',
type: 'Number',
optional: true
},
{
name: 'conc',
description: '',
type: 'Number',
optional: true
}
]
},
{
params: [
{
name: 'color',
description: '',
type: 'Number[]|String|p5.Color'
},
{
name: 'x',
description: '',
type: 'Number'
},
{
name: 'y',
description: '',
type: 'Number'
},
{
name: 'z',
description: '',
type: 'Number'
},
{
name: 'direction',
description: '',
type: 'p5.Vector'
},
{
name: 'angle',
description: '',
type: 'Number',
optional: true
},
{
name: 'conc',
description: '',
type: 'Number',
optional: true
}
]
},
{
params: [
{
name: 'color',
description: '',
type: 'Number[]|String|p5.Color'
},
{
name: 'position',
description: '',
type: 'p5.Vector'
},
{
name: 'rx',
description: '',
type: 'Number'
},
{
name: 'ry',
description: '',
type: 'Number'
},
{
name: 'rz',
description: '',
type: 'Number'
},
{
name: 'angle',
description: '',
type: 'Number',
optional: true
},
{
name: 'conc',
description: '',
type: 'Number',
optional: true
}
]
},
{
params: [
{
name: 'v1',
description: '',
type: 'Number'
},
{
name: 'v2',
description: '',
type: 'Number'
},
{
name: 'v3',
description: '',
type: 'Number'
},
{
name: 'x',
description: '',
type: 'Number'
},
{
name: 'y',
description: '',
type: 'Number'
},
{
name: 'z',
description: '',
type: 'Number'
},
{
name: 'direction',
description: '',
type: 'p5.Vector'
},
{
name: 'angle',
description: '',
type: 'Number',
optional: true
},
{
name: 'conc',
description: '',
type: 'Number',
optional: true
}
]
},
{
params: [
{
name: 'v1',
description: '',
type: 'Number'
},
{
name: 'v2',
description: '',
type: 'Number'
},
{
name: 'v3',
description: '',
type: 'Number'
},
{
name: 'position',
description: '',
type: 'p5.Vector'
},
{
name: 'rx',
description: '',
type: 'Number'
},
{
name: 'ry',
description: '',
type: 'Number'
},
{
name: 'rz',
description: '',
type: 'Number'
},
{
name: 'angle',
description: '',
type: 'Number',
optional: true
},
{
name: 'conc',
description: '',
type: 'Number',
optional: true
}
]
},
{
params: [
{
name: 'color',
description: '',
type: 'Number[]|String|p5.Color'
},
{
name: 'x',
description: '',
type: 'Number'
},
{
name: 'y',
description: '',
type: 'Number'
},
{
name: 'z',
description: '',
type: 'Number'
},
{
name: 'rx',
description: '',
type: 'Number'
},
{
name: 'ry',
description: '',
type: 'Number'
},
{
name: 'rz',
description: '',
type: 'Number'
},
{
name: 'angle',
description: '',
type: 'Number',
optional: true
},
{
name: 'conc',
description: '',
type: 'Number',
optional: true
}
]
}
]
},
noLights: {
name: 'noLights',
class: 'p5',
module: 'Lights, Camera'
},
loadModel: {
name: 'loadModel',
class: 'p5',
module: 'Shape',
overloads: [
{
params: [
{
name: 'path',
description: '<p>Path of the model to be loaded</p>\n',
type: 'String'
},
{
name: 'normalize',
description:
'<p>If true, scale the model to a\n standardized size when loading</p>\n',
type: 'Boolean'
},
{
name: 'successCallback',
description:
'<p>Function to be called\n once the model is loaded. Will be passed\n the 3D model object.</p>\n',
type: 'function(p5.Geometry)',
optional: true
},
{
name: 'failureCallback',
description:
'<p>called with event error if\n the model fails to load.</p>\n',
type: 'Function(Event)',
optional: true
},
{
name: 'fileType',
description:
'<p>The file extension of the model\n (<code>.stl</code>, <code>.obj</code>).</p>\n',
type: 'String',
optional: true
}
]
},
{
params: [
{
name: 'path',
description: '',
type: 'String'
},
{
name: 'successCallback',
description: '',
type: 'function(p5.Geometry)',
optional: true
},
{
name: 'failureCallback',
description: '',
type: 'Function(Event)',
optional: true
},
{
name: 'fileType',
description: '',
type: 'String',
optional: true
}
]
}
]
},
model: {
name: 'model',
params: [
{
name: 'model',
description: '<p>Loaded 3d model to be rendered</p>\n',
type: 'p5.Geometry'
}
],
class: 'p5',
module: 'Shape'
},
loadShader: {
name: 'loadShader',
params: [
{
name: 'vertFilename',
description:
'<p>path to file containing vertex shader\nsource code</p>\n',
type: 'String'
},
{
name: 'fragFilename',
description:
'<p>path to file containing fragment shader\nsource code</p>\n',
type: 'String'
},
{
name: 'callback',
description:
'<p>callback to be executed after loadShader\ncompletes. On success, the Shader object is passed as the first argument.</p>\n',
type: 'Function',
optional: true
},
{
name: 'errorCallback',
description:
'<p>callback to be executed when an error\noccurs inside loadShader. On error, the error is passed as the first\nargument.</p>\n',
type: 'Function',
optional: true
}
],
class: 'p5',
module: 'Lights, Camera'
},
createShader: {
name: 'createShader',
params: [
{
name: 'vertSrc',
description: '<p>source code for the vertex shader</p>\n',
type: 'String'
},
{
name: 'fragSrc',
description: '<p>source code for the fragment shader</p>\n',
type: 'String'
}
],
class: 'p5',
module: 'Lights, Camera'
},
shader: {
name: 'shader',
params: [
{
name: 's',
description:
'<p>the desired <a href="#/p5.Shader">p5.Shader</a> to use for rendering\nshapes.</p>\n',
type: 'p5.Shader',
optional: true
}
],
class: 'p5',
module: 'Lights, Camera'
},
resetShader: {
name: 'resetShader',
class: 'p5',
module: 'Lights, Camera'
},
normalMaterial: {
name: 'normalMaterial',
class: 'p5',
module: 'Lights, Camera'
},
texture: {
name: 'texture',
params: [
{
name: 'tex',
description:
'<p>2-dimensional graphics\n to render as texture</p>\n',
type: 'p5.Image|p5.MediaElement|p5.Graphics'
}
],
class: 'p5',
module: 'Lights, Camera'
},
textureMode: {
name: 'textureMode',
params: [
{
name: 'mode',
description: '<p>either IMAGE or NORMAL</p>\n',
type: 'Constant'
}
],
class: 'p5',
module: 'Lights, Camera'
},
textureWrap: {
name: 'textureWrap',
params: [
{
name: 'wrapX',
description: '<p>either CLAMP, REPEAT, or MIRROR</p>\n',
type: 'Constant'
},
{
name: 'wrapY',
description: '<p>either CLAMP, REPEAT, or MIRROR</p>\n',
type: 'Constant',
optional: true
}
],
class: 'p5',
module: 'Lights, Camera'
},
ambientMaterial: {
name: 'ambientMaterial',
class: 'p5',
module: 'Lights, Camera',
overloads: [
{
params: [
{
name: 'v1',
description:
'<p>gray value, red or hue value\n (depending on the current color mode),</p>\n',
type: 'Number'
},
{
name: 'v2',
description: '<p>green or saturation value</p>\n',
type: 'Number',
optional: true
},
{
name: 'v3',
description: '<p>blue or brightness value</p>\n',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'color',
description: '<p>color, color Array, or CSS color string</p>\n',
type: 'Number[]|String|p5.Color'
}
],
chainable: 1
}
]
},
emissiveMaterial: {
name: 'emissiveMaterial',
class: 'p5',
module: 'Lights, Camera',
overloads: [
{
params: [
{
name: 'v1',
description:
'<p>gray value, red or hue value\n (depending on the current color mode),</p>\n',
type: 'Number'
},
{
name: 'v2',
description: '<p>green or saturation value</p>\n',
type: 'Number',
optional: true
},
{
name: 'v3',
description: '<p>blue or brightness value</p>\n',
type: 'Number',
optional: true
},
{
name: 'a',
description: '<p>opacity</p>\n',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'color',
description: '<p>color, color Array, or CSS color string</p>\n',
type: 'Number[]|String|p5.Color'
}
],
chainable: 1
}
]
},
specularMaterial: {
name: 'specularMaterial',
class: 'p5',
module: 'Lights, Camera',
overloads: [
{
params: [
{
name: 'gray',
description:
'<p>number specifying value between white and black.</p>\n',
type: 'Number'
},
{
name: 'alpha',
description:
'<p>alpha value relative to current color range\n (default is 0-255)</p>\n',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'v1',
description:
'<p>red or hue value relative to\n the current color range</p>\n',
type: 'Number'
},
{
name: 'v2',
description:
'<p>green or saturation value\n relative to the current color range</p>\n',
type: 'Number'
},
{
name: 'v3',
description:
'<p>blue or brightness value\n relative to the current color range</p>\n',
type: 'Number'
},
{
name: 'alpha',
description: '',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'color',
description: '<p>color Array, or CSS color string</p>\n',
type: 'Number[]|String|p5.Color'
}
],
chainable: 1
}
]
},
shininess: {
name: 'shininess',
params: [
{
name: 'shine',
description:
'<p>Degree of Shininess.\n Defaults to 1.</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'Lights, Camera'
},
camera: {
name: 'camera',
params: [
{
name: 'x',
description: '<p>camera position value on x axis</p>\n',
type: 'Number',
optional: true
},
{
name: 'y',
description: '<p>camera position value on y axis</p>\n',
type: 'Number',
optional: true
},
{
name: 'z',
description: '<p>camera position value on z axis</p>\n',
type: 'Number',
optional: true
},
{
name: 'centerX',
description: '<p>x coordinate representing center of the sketch</p>\n',
type: 'Number',
optional: true
},
{
name: 'centerY',
description: '<p>y coordinate representing center of the sketch</p>\n',
type: 'Number',
optional: true
},
{
name: 'centerZ',
description: '<p>z coordinate representing center of the sketch</p>\n',
type: 'Number',
optional: true
},
{
name: 'upX',
description: "<p>x component of direction 'up' from camera</p>\n",
type: 'Number',
optional: true
},
{
name: 'upY',
description: "<p>y component of direction 'up' from camera</p>\n",
type: 'Number',
optional: true
},
{
name: 'upZ',
description: "<p>z component of direction 'up' from camera</p>\n",
type: 'Number',
optional: true
}
],
class: 'p5',
module: 'Lights, Camera'
},
perspective: {
name: 'perspective',
params: [
{
name: 'fovy',
description:
'<p>camera frustum vertical field of view,\n from bottom to top of view, in <a href="#/p5/angleMode">angleMode</a> units</p>\n',
type: 'Number',
optional: true
},
{
name: 'aspect',
description: '<p>camera frustum aspect ratio</p>\n',
type: 'Number',
optional: true
},
{
name: 'near',
description: '<p>frustum near plane length</p>\n',
type: 'Number',
optional: true
},
{
name: 'far',
description: '<p>frustum far plane length</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5',
module: 'Lights, Camera'
},
ortho: {
name: 'ortho',
params: [
{
name: 'left',
description: '<p>camera frustum left plane</p>\n',
type: 'Number',
optional: true
},
{
name: 'right',
description: '<p>camera frustum right plane</p>\n',
type: 'Number',
optional: true
},
{
name: 'bottom',
description: '<p>camera frustum bottom plane</p>\n',
type: 'Number',
optional: true
},
{
name: 'top',
description: '<p>camera frustum top plane</p>\n',
type: 'Number',
optional: true
},
{
name: 'near',
description: '<p>camera frustum near plane</p>\n',
type: 'Number',
optional: true
},
{
name: 'far',
description: '<p>camera frustum far plane</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5',
module: 'Lights, Camera'
},
frustum: {
name: 'frustum',
params: [
{
name: 'left',
description: '<p>camera frustum left plane</p>\n',
type: 'Number',
optional: true
},
{
name: 'right',
description: '<p>camera frustum right plane</p>\n',
type: 'Number',
optional: true
},
{
name: 'bottom',
description: '<p>camera frustum bottom plane</p>\n',
type: 'Number',
optional: true
},
{
name: 'top',
description: '<p>camera frustum top plane</p>\n',
type: 'Number',
optional: true
},
{
name: 'near',
description: '<p>camera frustum near plane</p>\n',
type: 'Number',
optional: true
},
{
name: 'far',
description: '<p>camera frustum far plane</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5',
module: 'Lights, Camera'
},
createCamera: {
name: 'createCamera',
class: 'p5',
module: 'Lights, Camera'
},
setCamera: {
name: 'setCamera',
params: [
{
name: 'cam',
description: '<p>p5.Camera object</p>\n',
type: 'p5.Camera'
}
],
class: 'p5',
module: 'Lights, Camera'
},
setAttributes: {
name: 'setAttributes',
class: 'p5',
module: 'Rendering',
overloads: [
{
params: [
{
name: 'key',
description: '<p>Name of attribute</p>\n',
type: 'String'
},
{
name: 'value',
description: '<p>New value of named attribute</p>\n',
type: 'Boolean'
}
]
},
{
params: [
{
name: 'obj',
description: '<p>object with key-value pairs</p>\n',
type: 'Object'
}
]
}
]
},
sampleRate: {
name: 'sampleRate',
class: 'p5',
module: 'p5.sound'
},
freqToMidi: {
name: 'freqToMidi',
params: [
{
name: 'frequency',
description:
'<p>A freqeuncy, for example, the "A"\n above Middle C is 440Hz</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'p5.sound'
},
midiToFreq: {
name: 'midiToFreq',
params: [
{
name: 'midiNote',
description: '<p>The number of a MIDI note</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'p5.sound'
},
soundFormats: {
name: 'soundFormats',
params: [
{
name: 'formats',
description: "<p>i.e. 'mp3', 'wav', 'ogg'</p>\n",
type: 'String',
optional: true,
multiple: true
}
],
class: 'p5',
module: 'p5.sound'
},
getAudioContext: {
name: 'getAudioContext',
class: 'p5',
module: 'p5.sound'
},
userStartAudio: {
params: [
{
name: 'element(s)',
description:
'<p>This argument can be an Element,\n Selector String, NodeList, p5.Element,\n jQuery Element, or an Array of any of those.</p>\n',
type: 'Element|Array',
optional: true
},
{
name: 'callback',
description:
'<p>Callback to invoke when the AudioContext\n has started</p>\n',
type: 'Function',
optional: true
}
],
name: 'userStartAudio',
class: 'p5',
module: 'p5.sound'
},
loadSound: {
name: 'loadSound',
params: [
{
name: 'path',
description:
"<p>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.</p>\n",
type: 'String|Array'
},
{
name: 'successCallback',
description: '<p>Name of a function to call once file loads</p>\n',
type: 'Function',
optional: true
},
{
name: 'errorCallback',
description:
'<p>Name of a function to call if there is\n an error loading the file.</p>\n',
type: 'Function',
optional: true
},
{
name: 'whileLoading',
description:
'<p>Name of a function to call while file is loading.\n This function will receive the percentage loaded\n so far, from 0.0 to 1.0.</p>\n',
type: 'Function',
optional: true
}
],
class: 'p5',
module: 'p5.sound'
},
createConvolver: {
name: 'createConvolver',
params: [
{
name: 'path',
description: '<p>path to a sound file</p>\n',
type: 'String'
},
{
name: 'callback',
description:
'<p>function to call if loading is successful.\n The object will be passed in as the argument\n to the callback function.</p>\n',
type: 'Function',
optional: true
},
{
name: 'errorCallback',
description:
'<p>function to call if loading is not successful.\n A custom error will be passed in as the argument\n to the callback function.</p>\n',
type: 'Function',
optional: true
}
],
class: 'p5',
module: 'p5.sound'
},
setBPM: {
name: 'setBPM',
params: [
{
name: 'BPM',
description: '<p>Beats Per Minute</p>\n',
type: 'Number'
},
{
name: 'rampTime',
description: '<p>Seconds from now</p>\n',
type: 'Number'
}
],
class: 'p5',
module: 'p5.sound'
},
saveSound: {
name: 'saveSound',
params: [
{
name: 'soundFile',
description: '<p>p5.SoundFile that you wish to save</p>\n',
type: 'p5.SoundFile'
},
{
name: 'fileName',
description: '<p>name of the resulting .wav file.</p>\n',
type: 'String'
}
],
class: 'p5',
module: 'p5.sound'
}
},
'p5.Color': {
toString: {
name: 'toString',
params: [
{
name: 'format',
description:
"<p>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.</p>\n",
type: 'String',
optional: true
}
],
class: 'p5.Color',
module: 'Color'
},
setRed: {
name: 'setRed',
params: [
{
name: 'red',
description: '<p>the new red value</p>\n',
type: 'Number'
}
],
class: 'p5.Color',
module: 'Color'
},
setGreen: {
name: 'setGreen',
params: [
{
name: 'green',
description: '<p>the new green value</p>\n',
type: 'Number'
}
],
class: 'p5.Color',
module: 'Color'
},
setBlue: {
name: 'setBlue',
params: [
{
name: 'blue',
description: '<p>the new blue value</p>\n',
type: 'Number'
}
],
class: 'p5.Color',
module: 'Color'
},
setAlpha: {
name: 'setAlpha',
params: [
{
name: 'alpha',
description: '<p>the new alpha value</p>\n',
type: 'Number'
}
],
class: 'p5.Color',
module: 'Color'
}
},
'p5.Element': {
elt: {
name: 'elt',
class: 'p5.Element',
module: 'DOM'
},
parent: {
name: 'parent',
class: 'p5.Element',
module: 'DOM',
overloads: [
{
params: [
{
name: 'parent',
description:
'<p>the ID, DOM node, or <a href="#/p5.Element">p5.Element</a>\n of desired parent element</p>\n',
type: 'String|p5.Element|Object'
}
],
chainable: 1
},
{
params: []
}
]
},
id: {
name: 'id',
class: 'p5.Element',
module: 'DOM',
overloads: [
{
params: [
{
name: 'id',
description: '<p>ID of the element</p>\n',
type: 'String'
}
],
chainable: 1
},
{
params: []
}
]
},
class: {
name: 'class',
class: 'p5.Element',
module: 'DOM',
overloads: [
{
params: [
{
name: 'class',
description: '<p>class to add</p>\n',
type: 'String'
}
],
chainable: 1
},
{
params: []
}
]
},
mousePressed: {
name: 'mousePressed',
params: [
{
name: 'fxn',
description:
'<p>function to be fired when mouse is\n pressed over the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n',
type: 'Function|Boolean'
}
],
class: 'p5.Element',
module: 'DOM'
},
doubleClicked: {
name: 'doubleClicked',
params: [
{
name: 'fxn',
description:
'<p>function to be fired when mouse is\n double clicked over the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n',
type: 'Function|Boolean'
}
],
class: 'p5.Element',
module: 'DOM'
},
mouseWheel: {
name: 'mouseWheel',
params: [
{
name: 'fxn',
description:
'<p>function to be fired when mouse is\n scrolled over the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n',
type: 'Function|Boolean'
}
],
class: 'p5.Element',
module: 'DOM'
},
mouseReleased: {
name: 'mouseReleased',
params: [
{
name: 'fxn',
description:
'<p>function to be fired when mouse is\n released over the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n',
type: 'Function|Boolean'
}
],
class: 'p5.Element',
module: 'DOM'
},
mouseClicked: {
name: 'mouseClicked',
params: [
{
name: 'fxn',
description:
'<p>function to be fired when mouse is\n clicked over the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n',
type: 'Function|Boolean'
}
],
class: 'p5.Element',
module: 'DOM'
},
mouseMoved: {
name: 'mouseMoved',
params: [
{
name: 'fxn',
description:
'<p>function to be fired when a mouse moves\n over the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n',
type: 'Function|Boolean'
}
],
class: 'p5.Element',
module: 'DOM'
},
mouseOver: {
name: 'mouseOver',
params: [
{
name: 'fxn',
description:
'<p>function to be fired when a mouse moves\n onto the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n',
type: 'Function|Boolean'
}
],
class: 'p5.Element',
module: 'DOM'
},
mouseOut: {
name: 'mouseOut',
params: [
{
name: 'fxn',
description:
'<p>function to be fired when a mouse\n moves off of an element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n',
type: 'Function|Boolean'
}
],
class: 'p5.Element',
module: 'DOM'
},
touchStarted: {
name: 'touchStarted',
params: [
{
name: 'fxn',
description:
'<p>function to be fired when a touch\n starts over the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n',
type: 'Function|Boolean'
}
],
class: 'p5.Element',
module: 'DOM'
},
touchMoved: {
name: 'touchMoved',
params: [
{
name: 'fxn',
description:
'<p>function to be fired when a touch moves over\n the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n',
type: 'Function|Boolean'
}
],
class: 'p5.Element',
module: 'DOM'
},
touchEnded: {
name: 'touchEnded',
params: [
{
name: 'fxn',
description:
'<p>function to be fired when a touch ends\n over the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n',
type: 'Function|Boolean'
}
],
class: 'p5.Element',
module: 'DOM'
},
dragOver: {
name: 'dragOver',
params: [
{
name: 'fxn',
description:
'<p>function to be fired when a file is\n dragged over the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n',
type: 'Function|Boolean'
}
],
class: 'p5.Element',
module: 'DOM'
},
dragLeave: {
name: 'dragLeave',
params: [
{
name: 'fxn',
description:
'<p>function to be fired when a file is\n dragged off the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n',
type: 'Function|Boolean'
}
],
class: 'p5.Element',
module: 'DOM'
},
addClass: {
name: 'addClass',
params: [
{
name: 'class',
description: '<p>name of class to add</p>\n',
type: 'String'
}
],
class: 'p5.Element',
module: 'DOM'
},
removeClass: {
name: 'removeClass',
params: [
{
name: 'class',
description: '<p>name of class to remove</p>\n',
type: 'String'
}
],
class: 'p5.Element',
module: 'DOM'
},
hasClass: {
name: 'hasClass',
params: [
{
name: 'c',
description: '<p>class name of class to check</p>\n',
type: 'String'
}
],
class: 'p5.Element',
module: 'DOM'
},
toggleClass: {
name: 'toggleClass',
params: [
{
name: 'c',
description: '<p>class name to toggle</p>\n',
type: 'String'
}
],
class: 'p5.Element',
module: 'DOM'
},
child: {
name: 'child',
class: 'p5.Element',
module: 'DOM',
overloads: [
{
params: []
},
{
params: [
{
name: 'child',
description:
'<p>the ID, DOM node, or <a href="#/p5.Element">p5.Element</a>\n to add to the current element</p>\n',
type: 'String|p5.Element',
optional: true
}
],
chainable: 1
}
]
},
center: {
name: 'center',
params: [
{
name: 'align',
description:
"<p>passing 'vertical', 'horizontal' aligns element accordingly</p>\n",
type: 'String',
optional: true
}
],
class: 'p5.Element',
module: 'DOM'
},
html: {
name: 'html',
class: 'p5.Element',
module: 'DOM',
overloads: [
{
params: []
},
{
params: [
{
name: 'html',
description: '<p>the HTML to be placed inside the element</p>\n',
type: 'String',
optional: true
},
{
name: 'append',
description: '<p>whether to append HTML to existing</p>\n',
type: 'Boolean',
optional: true
}
],
chainable: 1
}
]
},
position: {
name: 'position',
class: 'p5.Element',
module: 'DOM',
overloads: [
{
params: []
},
{
params: [
{
name: 'x',
description:
'<p>x-position relative to upper left of window (optional)</p>\n',
type: 'Number',
optional: true
},
{
name: 'y',
description:
'<p>y-position relative to upper left of window (optional)</p>\n',
type: 'Number',
optional: true
},
{
name: 'positionType',
description:
'<p>it can be static, fixed, relative, sticky, initial or inherit (optional)</p>\n',
type: 'String'
}
],
chainable: 1
}
]
},
style: {
name: 'style',
class: 'p5.Element',
module: 'DOM',
overloads: [
{
params: [
{
name: 'property',
description: '<p>property to be set</p>\n',
type: 'String'
}
]
},
{
params: [
{
name: 'property',
description: '',
type: 'String'
},
{
name: 'value',
description: '<p>value to assign to property</p>\n',
type: 'String|p5.Color'
}
],
chainable: 1
}
]
},
attribute: {
name: 'attribute',
class: 'p5.Element',
module: 'DOM',
overloads: [
{
params: []
},
{
params: [
{
name: 'attr',
description: '<p>attribute to set</p>\n',
type: 'String'
},
{
name: 'value',
description: '<p>value to assign to attribute</p>\n',
type: 'String'
}
],
chainable: 1
}
]
},
removeAttribute: {
name: 'removeAttribute',
params: [
{
name: 'attr',
description: '<p>attribute to remove</p>\n',
type: 'String'
}
],
class: 'p5.Element',
module: 'DOM'
},
value: {
name: 'value',
class: 'p5.Element',
module: 'DOM',
overloads: [
{
params: []
},
{
params: [
{
name: 'value',
description: '',
type: 'String|Number'
}
],
chainable: 1
}
]
},
show: {
name: 'show',
class: 'p5.Element',
module: 'DOM'
},
hide: {
name: 'hide',
class: 'p5.Element',
module: 'DOM'
},
size: {
name: 'size',
class: 'p5.Element',
module: 'DOM',
overloads: [
{
params: []
},
{
params: [
{
name: 'w',
description:
'<p>width of the element, either AUTO, or a number</p>\n',
type: 'Number|Constant'
},
{
name: 'h',
description:
'<p>height of the element, either AUTO, or a number</p>\n',
type: 'Number|Constant',
optional: true
}
],
chainable: 1
}
]
},
remove: {
name: 'remove',
class: 'p5.Element',
module: 'DOM'
},
drop: {
name: 'drop',
params: [
{
name: 'callback',
description:
'<p>callback to receive loaded file, called for each file dropped.</p>\n',
type: 'Function'
},
{
name: 'fxn',
description:
'<p>callback triggered once when files are dropped with the drop event.</p>\n',
type: 'Function',
optional: true
}
],
class: 'p5.Element',
module: 'DOM'
}
},
'p5.Graphics': {
reset: {
name: 'reset',
class: 'p5.Graphics',
module: 'Rendering'
},
remove: {
name: 'remove',
class: 'p5.Graphics',
module: 'Rendering'
}
},
JSON: {
stringify: {
name: 'stringify',
params: [
{
name: 'object',
description:
'<p>:Javascript object that you would like to convert to JSON</p>\n',
type: 'Object'
}
],
class: 'JSON',
module: 'Foundation'
}
},
console: {
log: {
name: 'log',
params: [
{
name: 'message',
description:
'<p>:Message that you would like to print to the console</p>\n',
type: 'String|Expression|Object'
}
],
class: 'console',
module: 'Foundation'
}
},
'p5.TypedDict': {
size: {
name: 'size',
class: 'p5.TypedDict',
module: 'Data'
},
hasKey: {
name: 'hasKey',
params: [
{
name: 'key',
description: '<p>that you want to look up</p>\n',
type: 'Number|String'
}
],
class: 'p5.TypedDict',
module: 'Data'
},
get: {
name: 'get',
params: [
{
name: 'the',
description: '<p>key you want to access</p>\n',
type: 'Number|String'
}
],
class: 'p5.TypedDict',
module: 'Data'
},
set: {
name: 'set',
params: [
{
name: 'key',
description: '',
type: 'Number|String'
},
{
name: 'value',
description: '',
type: 'Number|String'
}
],
class: 'p5.TypedDict',
module: 'Data'
},
create: {
name: 'create',
class: 'p5.TypedDict',
module: 'Data',
overloads: [
{
params: [
{
name: 'key',
description: '',
type: 'Number|String'
},
{
name: 'value',
description: '',
type: 'Number|String'
}
]
},
{
params: [
{
name: 'obj',
description: '<p>key/value pair</p>\n',
type: 'Object'
}
]
}
]
},
clear: {
name: 'clear',
class: 'p5.TypedDict',
module: 'Data'
},
remove: {
name: 'remove',
params: [
{
name: 'key',
description: '<p>for the pair to remove</p>\n',
type: 'Number|String'
}
],
class: 'p5.TypedDict',
module: 'Data'
},
print: {
name: 'print',
class: 'p5.TypedDict',
module: 'Data'
},
saveTable: {
name: 'saveTable',
class: 'p5.TypedDict',
module: 'Data'
},
saveJSON: {
name: 'saveJSON',
class: 'p5.TypedDict',
module: 'Data'
}
},
'p5.NumberDict': {
add: {
name: 'add',
params: [
{
name: 'Key',
description: '<p>for the value you wish to add to</p>\n',
type: 'Number'
},
{
name: 'Number',
description: '<p>to add to the value</p>\n',
type: 'Number'
}
],
class: 'p5.NumberDict',
module: 'Data'
},
sub: {
name: 'sub',
params: [
{
name: 'Key',
description: '<p>for the value you wish to subtract from</p>\n',
type: 'Number'
},
{
name: 'Number',
description: '<p>to subtract from the value</p>\n',
type: 'Number'
}
],
class: 'p5.NumberDict',
module: 'Data'
},
mult: {
name: 'mult',
params: [
{
name: 'Key',
description: '<p>for value you wish to multiply</p>\n',
type: 'Number'
},
{
name: 'Amount',
description: '<p>to multiply the value by</p>\n',
type: 'Number'
}
],
class: 'p5.NumberDict',
module: 'Data'
},
div: {
name: 'div',
params: [
{
name: 'Key',
description: '<p>for value you wish to divide</p>\n',
type: 'Number'
},
{
name: 'Amount',
description: '<p>to divide the value by</p>\n',
type: 'Number'
}
],
class: 'p5.NumberDict',
module: 'Data'
},
minValue: {
name: 'minValue',
class: 'p5.NumberDict',
module: 'Data'
},
maxValue: {
name: 'maxValue',
class: 'p5.NumberDict',
module: 'Data'
},
minKey: {
name: 'minKey',
class: 'p5.NumberDict',
module: 'Data'
},
maxKey: {
name: 'maxKey',
class: 'p5.NumberDict',
module: 'Data'
}
},
'p5.MediaElement': {
src: {
name: 'src',
class: 'p5.MediaElement',
module: 'DOM'
},
play: {
name: 'play',
class: 'p5.MediaElement',
module: 'DOM'
},
stop: {
name: 'stop',
class: 'p5.MediaElement',
module: 'DOM'
},
pause: {
name: 'pause',
class: 'p5.MediaElement',
module: 'DOM'
},
loop: {
name: 'loop',
class: 'p5.MediaElement',
module: 'DOM'
},
noLoop: {
name: 'noLoop',
class: 'p5.MediaElement',
module: 'DOM'
},
autoplay: {
name: 'autoplay',
params: [
{
name: 'shouldAutoplay',
description: '<p>whether the element should autoplay</p>\n',
type: 'Boolean'
}
],
class: 'p5.MediaElement',
module: 'DOM'
},
volume: {
name: 'volume',
class: 'p5.MediaElement',
module: 'DOM',
overloads: [
{
params: []
},
{
params: [
{
name: 'val',
description: '<p>volume between 0.0 and 1.0</p>\n',
type: 'Number'
}
],
chainable: 1
}
]
},
speed: {
name: 'speed',
class: 'p5.MediaElement',
module: 'DOM',
overloads: [
{
params: []
},
{
params: [
{
name: 'speed',
description: '<p>speed multiplier for element playback</p>\n',
type: 'Number'
}
],
chainable: 1
}
]
},
time: {
name: 'time',
class: 'p5.MediaElement',
module: 'DOM',
overloads: [
{
params: []
},
{
params: [
{
name: 'time',
description: '<p>time to jump to (in seconds)</p>\n',
type: 'Number'
}
],
chainable: 1
}
]
},
duration: {
name: 'duration',
class: 'p5.MediaElement',
module: 'DOM'
},
onended: {
name: 'onended',
params: [
{
name: 'callback',
description:
'<p>function to call when the\n soundfile has ended. The\n media element will be passed\n in as the argument to the\n callback.</p>\n',
type: 'Function'
}
],
class: 'p5.MediaElement',
module: 'DOM'
},
connect: {
name: 'connect',
params: [
{
name: 'audioNode',
description:
'<p>AudioNode from the Web Audio API,\nor an object from the p5.sound library</p>\n',
type: 'AudioNode|Object'
}
],
class: 'p5.MediaElement',
module: 'DOM'
},
disconnect: {
name: 'disconnect',
class: 'p5.MediaElement',
module: 'DOM'
},
showControls: {
name: 'showControls',
class: 'p5.MediaElement',
module: 'DOM'
},
hideControls: {
name: 'hideControls',
class: 'p5.MediaElement',
module: 'DOM'
},
addCue: {
name: 'addCue',
params: [
{
name: 'time',
description:
"<p>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.</p>\n",
type: 'Number'
},
{
name: 'callback',
description:
'<p>Name of a function that will be\n called at the given time. The callback will\n receive time and (optionally) param as its\n two parameters.</p>\n',
type: 'Function'
},
{
name: 'value',
description:
'<p>An object to be passed as the\n second parameter to the\n callback function.</p>\n',
type: 'Object',
optional: true
}
],
class: 'p5.MediaElement',
module: 'DOM'
},
removeCue: {
name: 'removeCue',
params: [
{
name: 'id',
description: '<p>ID of the cue, as returned by addCue</p>\n',
type: 'Number'
}
],
class: 'p5.MediaElement',
module: 'DOM'
},
clearCues: {
name: 'clearCues',
params: [
{
name: 'id',
description: '<p>ID of the cue, as returned by addCue</p>\n',
type: 'Number'
}
],
class: 'p5.MediaElement',
module: 'DOM'
}
},
'p5.File': {
file: {
name: 'file',
class: 'p5.File',
module: 'DOM'
},
type: {
name: 'type',
class: 'p5.File',
module: 'DOM'
},
subtype: {
name: 'subtype',
class: 'p5.File',
module: 'DOM'
},
name: {
name: 'name',
class: 'p5.File',
module: 'DOM'
},
size: {
name: 'size',
class: 'p5.File',
module: 'DOM'
},
data: {
name: 'data',
class: 'p5.File',
module: 'DOM'
}
},
'p5.Image': {
width: {
name: 'width',
class: 'p5.Image',
module: 'Image'
},
height: {
name: 'height',
class: 'p5.Image',
module: 'Image'
},
pixels: {
name: 'pixels',
class: 'p5.Image',
module: 'Image'
},
loadPixels: {
name: 'loadPixels',
class: 'p5.Image',
module: 'Image'
},
updatePixels: {
name: 'updatePixels',
class: 'p5.Image',
module: 'Image',
overloads: [
{
params: [
{
name: 'x',
description:
'<p>x-offset of the target update area for the\n underlying canvas</p>\n',
type: 'Integer'
},
{
name: 'y',
description:
'<p>y-offset of the target update area for the\n underlying canvas</p>\n',
type: 'Integer'
},
{
name: 'w',
description:
'<p>height of the target update area for the\n underlying canvas</p>\n',
type: 'Integer'
},
{
name: 'h',
description:
'<p>height of the target update area for the\n underlying canvas</p>\n',
type: 'Integer'
}
]
},
{
params: []
}
]
},
get: {
name: 'get',
class: 'p5.Image',
module: 'Image',
overloads: [
{
params: [
{
name: 'x',
description: '<p>x-coordinate of the pixel</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>y-coordinate of the pixel</p>\n',
type: 'Number'
},
{
name: 'w',
description: '<p>width</p>\n',
type: 'Number'
},
{
name: 'h',
description: '<p>height</p>\n',
type: 'Number'
}
]
},
{
params: []
},
{
params: [
{
name: 'x',
description: '',
type: 'Number'
},
{
name: 'y',
description: '',
type: 'Number'
}
]
}
]
},
set: {
name: 'set',
params: [
{
name: 'x',
description: '<p>x-coordinate of the pixel</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>y-coordinate of the pixel</p>\n',
type: 'Number'
},
{
name: 'a',
description:
'<p>grayscale value | pixel array |\n a <a href="#/p5.Color">p5.Color</a> | image to copy</p>\n',
type: 'Number|Number[]|Object'
}
],
class: 'p5.Image',
module: 'Image'
},
resize: {
name: 'resize',
params: [
{
name: 'width',
description: '<p>the resized image width</p>\n',
type: 'Number'
},
{
name: 'height',
description: '<p>the resized image height</p>\n',
type: 'Number'
}
],
class: 'p5.Image',
module: 'Image'
},
copy: {
name: 'copy',
class: 'p5.Image',
module: 'Image',
overloads: [
{
params: [
{
name: 'srcImage',
description: '<p>source image</p>\n',
type: 'p5.Image|p5.Element'
},
{
name: 'sx',
description:
"<p>X coordinate of the source's upper left corner</p>\n",
type: 'Integer'
},
{
name: 'sy',
description:
"<p>Y coordinate of the source's upper left corner</p>\n",
type: 'Integer'
},
{
name: 'sw',
description: '<p>source image width</p>\n',
type: 'Integer'
},
{
name: 'sh',
description: '<p>source image height</p>\n',
type: 'Integer'
},
{
name: 'dx',
description:
"<p>X coordinate of the destination's upper left corner</p>\n",
type: 'Integer'
},
{
name: 'dy',
description:
"<p>Y coordinate of the destination's upper left corner</p>\n",
type: 'Integer'
},
{
name: 'dw',
description: '<p>destination image width</p>\n',
type: 'Integer'
},
{
name: 'dh',
description: '<p>destination image height</p>\n',
type: 'Integer'
}
]
},
{
params: [
{
name: 'sx',
description: '',
type: 'Integer'
},
{
name: 'sy',
description: '',
type: 'Integer'
},
{
name: 'sw',
description: '',
type: 'Integer'
},
{
name: 'sh',
description: '',
type: 'Integer'
},
{
name: 'dx',
description: '',
type: 'Integer'
},
{
name: 'dy',
description: '',
type: 'Integer'
},
{
name: 'dw',
description: '',
type: 'Integer'
},
{
name: 'dh',
description: '',
type: 'Integer'
}
]
}
]
},
mask: {
name: 'mask',
params: [
{
name: 'srcImage',
description: '<p>source image</p>\n',
type: 'p5.Image'
}
],
class: 'p5.Image',
module: 'Image'
},
filter: {
name: 'filter',
params: [
{
name: 'filterType',
description:
'<p>either THRESHOLD, GRAY, OPAQUE, INVERT,\n POSTERIZE, ERODE, DILATE or BLUR.\n See Filters.js for docs on\n each available filter</p>\n',
type: 'Constant'
},
{
name: 'filterParam',
description:
'<p>an optional parameter unique\n to each filter, see above</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Image',
module: 'Image'
},
blend: {
name: 'blend',
class: 'p5.Image',
module: 'Image',
overloads: [
{
params: [
{
name: 'srcImage',
description: '<p>source image</p>\n',
type: 'p5.Image'
},
{
name: 'sx',
description:
"<p>X coordinate of the source's upper left corner</p>\n",
type: 'Integer'
},
{
name: 'sy',
description:
"<p>Y coordinate of the source's upper left corner</p>\n",
type: 'Integer'
},
{
name: 'sw',
description: '<p>source image width</p>\n',
type: 'Integer'
},
{
name: 'sh',
description: '<p>source image height</p>\n',
type: 'Integer'
},
{
name: 'dx',
description:
"<p>X coordinate of the destination's upper left corner</p>\n",
type: 'Integer'
},
{
name: 'dy',
description:
"<p>Y coordinate of the destination's upper left corner</p>\n",
type: 'Integer'
},
{
name: 'dw',
description: '<p>destination image width</p>\n',
type: 'Integer'
},
{
name: 'dh',
description: '<p>destination image height</p>\n',
type: 'Integer'
},
{
name: 'blendMode',
description:
'<p>the blend mode. either\n BLEND, DARKEST, LIGHTEST, DIFFERENCE,\n MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.</p>\n<p>Available blend modes are: normal | multiply | screen | overlay |\n darken | lighten | color-dodge | color-burn | hard-light |\n soft-light | difference | exclusion | hue | saturation |\n color | luminosity</p>\n<p><a href="http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/">http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/</a></p>\n',
type: 'Constant'
}
]
},
{
params: [
{
name: 'sx',
description: '',
type: 'Integer'
},
{
name: 'sy',
description: '',
type: 'Integer'
},
{
name: 'sw',
description: '',
type: 'Integer'
},
{
name: 'sh',
description: '',
type: 'Integer'
},
{
name: 'dx',
description: '',
type: 'Integer'
},
{
name: 'dy',
description: '',
type: 'Integer'
},
{
name: 'dw',
description: '',
type: 'Integer'
},
{
name: 'dh',
description: '',
type: 'Integer'
},
{
name: 'blendMode',
description: '',
type: 'Constant'
}
]
}
]
},
save: {
name: 'save',
params: [
{
name: 'filename',
description: '<p>give your file a name</p>\n',
type: 'String'
},
{
name: 'extension',
description: "<p>'png' or 'jpg'</p>\n",
type: 'String'
}
],
class: 'p5.Image',
module: 'Image'
},
reset: {
name: 'reset',
class: 'p5.Image',
module: 'Image'
},
getCurrentFrame: {
name: 'getCurrentFrame',
class: 'p5.Image',
module: 'Image'
},
setFrame: {
name: 'setFrame',
params: [
{
name: 'index',
description:
'<p>the index for the frame that should be displayed</p>\n',
type: 'Number'
}
],
class: 'p5.Image',
module: 'Image'
},
numFrames: {
name: 'numFrames',
class: 'p5.Image',
module: 'Image'
},
play: {
name: 'play',
class: 'p5.Image',
module: 'Image'
},
pause: {
name: 'pause',
class: 'p5.Image',
module: 'Image'
},
delay: {
name: 'delay',
params: [
{
name: 'd',
description:
'<p>the amount in milliseconds to delay between switching frames</p>\n',
type: 'Number'
},
{
name: 'index',
description:
'<p>the index of the frame that should have the new delay value {optional}</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Image',
module: 'Image'
}
},
'p5.PrintWriter': {
write: {
name: 'write',
params: [
{
name: 'data',
description: '<p>all data to be written by the PrintWriter</p>\n',
type: 'Array'
}
],
class: 'p5.PrintWriter',
module: 'IO'
},
print: {
name: 'print',
params: [
{
name: 'data',
description: '<p>all data to be printed by the PrintWriter</p>\n',
type: 'Array'
}
],
class: 'p5.PrintWriter',
module: 'IO'
},
clear: {
name: 'clear',
class: 'p5.PrintWriter',
module: 'IO'
},
close: {
name: 'close',
class: 'p5.PrintWriter',
module: 'IO'
}
},
'p5.Table': {
columns: {
name: 'columns',
class: 'p5.Table',
module: 'IO'
},
rows: {
name: 'rows',
class: 'p5.Table',
module: 'IO'
},
addRow: {
name: 'addRow',
params: [
{
name: 'row',
description: '<p>row to be added to the table</p>\n',
type: 'p5.TableRow',
optional: true
}
],
class: 'p5.Table',
module: 'IO'
},
removeRow: {
name: 'removeRow',
params: [
{
name: 'id',
description: '<p>ID number of the row to remove</p>\n',
type: 'Integer'
}
],
class: 'p5.Table',
module: 'IO'
},
getRow: {
name: 'getRow',
params: [
{
name: 'rowID',
description: '<p>ID number of the row to get</p>\n',
type: 'Integer'
}
],
class: 'p5.Table',
module: 'IO'
},
getRows: {
name: 'getRows',
class: 'p5.Table',
module: 'IO'
},
findRow: {
name: 'findRow',
params: [
{
name: 'value',
description: '<p>The value to match</p>\n',
type: 'String'
},
{
name: 'column',
description:
'<p>ID number or title of the\n column to search</p>\n',
type: 'Integer|String'
}
],
class: 'p5.Table',
module: 'IO'
},
findRows: {
name: 'findRows',
params: [
{
name: 'value',
description: '<p>The value to match</p>\n',
type: 'String'
},
{
name: 'column',
description:
'<p>ID number or title of the\n column to search</p>\n',
type: 'Integer|String'
}
],
class: 'p5.Table',
module: 'IO'
},
matchRow: {
name: 'matchRow',
params: [
{
name: 'regexp',
description: '<p>The regular expression to match</p>\n',
type: 'String|RegExp'
},
{
name: 'column',
description:
'<p>The column ID (number) or\n title (string)</p>\n',
type: 'String|Integer'
}
],
class: 'p5.Table',
module: 'IO'
},
matchRows: {
name: 'matchRows',
params: [
{
name: 'regexp',
description: '<p>The regular expression to match</p>\n',
type: 'String'
},
{
name: 'column',
description:
'<p>The column ID (number) or\n title (string)</p>\n',
type: 'String|Integer',
optional: true
}
],
class: 'p5.Table',
module: 'IO'
},
getColumn: {
name: 'getColumn',
params: [
{
name: 'column',
description: '<p>String or Number of the column to return</p>\n',
type: 'String|Number'
}
],
class: 'p5.Table',
module: 'IO'
},
clearRows: {
name: 'clearRows',
class: 'p5.Table',
module: 'IO'
},
addColumn: {
name: 'addColumn',
params: [
{
name: 'title',
description: '<p>title of the given column</p>\n',
type: 'String',
optional: true
}
],
class: 'p5.Table',
module: 'IO'
},
getColumnCount: {
name: 'getColumnCount',
class: 'p5.Table',
module: 'IO'
},
getRowCount: {
name: 'getRowCount',
class: 'p5.Table',
module: 'IO'
},
removeTokens: {
name: 'removeTokens',
params: [
{
name: 'chars',
description: '<p>String listing characters to be removed</p>\n',
type: 'String'
},
{
name: 'column',
description:
'<p>Column ID (number)\n or name (string)</p>\n',
type: 'String|Integer',
optional: true
}
],
class: 'p5.Table',
module: 'IO'
},
trim: {
name: 'trim',
params: [
{
name: 'column',
description:
'<p>Column ID (number)\n or name (string)</p>\n',
type: 'String|Integer',
optional: true
}
],
class: 'p5.Table',
module: 'IO'
},
removeColumn: {
name: 'removeColumn',
params: [
{
name: 'column',
description: '<p>columnName (string) or ID (number)</p>\n',
type: 'String|Integer'
}
],
class: 'p5.Table',
module: 'IO'
},
set: {
name: 'set',
params: [
{
name: 'row',
description: '<p>row ID</p>\n',
type: 'Integer'
},
{
name: 'column',
description:
'<p>column ID (Number)\n or title (String)</p>\n',
type: 'String|Integer'
},
{
name: 'value',
description: '<p>value to assign</p>\n',
type: 'String|Number'
}
],
class: 'p5.Table',
module: 'IO'
},
setNum: {
name: 'setNum',
params: [
{
name: 'row',
description: '<p>row ID</p>\n',
type: 'Integer'
},
{
name: 'column',
description:
'<p>column ID (Number)\n or title (String)</p>\n',
type: 'String|Integer'
},
{
name: 'value',
description: '<p>value to assign</p>\n',
type: 'Number'
}
],
class: 'p5.Table',
module: 'IO'
},
setString: {
name: 'setString',
params: [
{
name: 'row',
description: '<p>row ID</p>\n',
type: 'Integer'
},
{
name: 'column',
description:
'<p>column ID (Number)\n or title (String)</p>\n',
type: 'String|Integer'
},
{
name: 'value',
description: '<p>value to assign</p>\n',
type: 'String'
}
],
class: 'p5.Table',
module: 'IO'
},
get: {
name: 'get',
params: [
{
name: 'row',
description: '<p>row ID</p>\n',
type: 'Integer'
},
{
name: 'column',
description:
'<p>columnName (string) or\n ID (number)</p>\n',
type: 'String|Integer'
}
],
class: 'p5.Table',
module: 'IO'
},
getNum: {
name: 'getNum',
params: [
{
name: 'row',
description: '<p>row ID</p>\n',
type: 'Integer'
},
{
name: 'column',
description:
'<p>columnName (string) or\n ID (number)</p>\n',
type: 'String|Integer'
}
],
class: 'p5.Table',
module: 'IO'
},
getString: {
name: 'getString',
params: [
{
name: 'row',
description: '<p>row ID</p>\n',
type: 'Integer'
},
{
name: 'column',
description:
'<p>columnName (string) or\n ID (number)</p>\n',
type: 'String|Integer'
}
],
class: 'p5.Table',
module: 'IO'
},
getObject: {
name: 'getObject',
params: [
{
name: 'headerColumn',
description:
'<p>Name of the column which should be used to\n title each row object (optional)</p>\n',
type: 'String',
optional: true
}
],
class: 'p5.Table',
module: 'IO'
},
getArray: {
name: 'getArray',
class: 'p5.Table',
module: 'IO'
}
},
'p5.TableRow': {
set: {
name: 'set',
params: [
{
name: 'column',
description:
'<p>Column ID (Number)\n or Title (String)</p>\n',
type: 'String|Integer'
},
{
name: 'value',
description: '<p>The value to be stored</p>\n',
type: 'String|Number'
}
],
class: 'p5.TableRow',
module: 'IO'
},
setNum: {
name: 'setNum',
params: [
{
name: 'column',
description:
'<p>Column ID (Number)\n or Title (String)</p>\n',
type: 'String|Integer'
},
{
name: 'value',
description:
'<p>The value to be stored\n as a Float</p>\n',
type: 'Number|String'
}
],
class: 'p5.TableRow',
module: 'IO'
},
setString: {
name: 'setString',
params: [
{
name: 'column',
description:
'<p>Column ID (Number)\n or Title (String)</p>\n',
type: 'String|Integer'
},
{
name: 'value',
description:
'<p>The value to be stored\n as a String</p>\n',
type: 'String|Number|Boolean|Object'
}
],
class: 'p5.TableRow',
module: 'IO'
},
get: {
name: 'get',
params: [
{
name: 'column',
description:
'<p>columnName (string) or\n ID (number)</p>\n',
type: 'String|Integer'
}
],
class: 'p5.TableRow',
module: 'IO'
},
getNum: {
name: 'getNum',
params: [
{
name: 'column',
description:
'<p>columnName (string) or\n ID (number)</p>\n',
type: 'String|Integer'
}
],
class: 'p5.TableRow',
module: 'IO'
},
getString: {
name: 'getString',
params: [
{
name: 'column',
description:
'<p>columnName (string) or\n ID (number)</p>\n',
type: 'String|Integer'
}
],
class: 'p5.TableRow',
module: 'IO'
}
},
'p5.XML': {
getParent: {
name: 'getParent',
class: 'p5.XML',
module: 'IO'
},
getName: {
name: 'getName',
class: 'p5.XML',
module: 'IO'
},
setName: {
name: 'setName',
params: [
{
name: 'the',
description: '<p>new name of the node</p>\n',
type: 'String'
}
],
class: 'p5.XML',
module: 'IO'
},
hasChildren: {
name: 'hasChildren',
class: 'p5.XML',
module: 'IO'
},
listChildren: {
name: 'listChildren',
class: 'p5.XML',
module: 'IO'
},
getChildren: {
name: 'getChildren',
params: [
{
name: 'name',
description: '<p>element name</p>\n',
type: 'String',
optional: true
}
],
class: 'p5.XML',
module: 'IO'
},
getChild: {
name: 'getChild',
params: [
{
name: 'name',
description: '<p>element name or index</p>\n',
type: 'String|Integer'
}
],
class: 'p5.XML',
module: 'IO'
},
addChild: {
name: 'addChild',
params: [
{
name: 'node',
description:
'<p>a <a href="#/p5.XML">p5.XML</a> Object which will be the child to be added</p>\n',
type: 'p5.XML'
}
],
class: 'p5.XML',
module: 'IO'
},
removeChild: {
name: 'removeChild',
params: [
{
name: 'name',
description: '<p>element name or index</p>\n',
type: 'String|Integer'
}
],
class: 'p5.XML',
module: 'IO'
},
getAttributeCount: {
name: 'getAttributeCount',
class: 'p5.XML',
module: 'IO'
},
listAttributes: {
name: 'listAttributes',
class: 'p5.XML',
module: 'IO'
},
hasAttribute: {
name: 'hasAttribute',
params: [
{
name: 'the',
description: '<p>attribute to be checked</p>\n',
type: 'String'
}
],
class: 'p5.XML',
module: 'IO'
},
getNum: {
name: 'getNum',
params: [
{
name: 'name',
description: '<p>the non-null full name of the attribute</p>\n',
type: 'String'
},
{
name: 'defaultValue',
description: '<p>the default value of the attribute</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.XML',
module: 'IO'
},
getString: {
name: 'getString',
params: [
{
name: 'name',
description: '<p>the non-null full name of the attribute</p>\n',
type: 'String'
},
{
name: 'defaultValue',
description: '<p>the default value of the attribute</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.XML',
module: 'IO'
},
setAttribute: {
name: 'setAttribute',
params: [
{
name: 'name',
description: '<p>the full name of the attribute</p>\n',
type: 'String'
},
{
name: 'value',
description: '<p>the value of the attribute</p>\n',
type: 'Number|String|Boolean'
}
],
class: 'p5.XML',
module: 'IO'
},
getContent: {
name: 'getContent',
params: [
{
name: 'defaultValue',
description: '<p>value returned if no content is found</p>\n',
type: 'String',
optional: true
}
],
class: 'p5.XML',
module: 'IO'
},
setContent: {
name: 'setContent',
params: [
{
name: 'text',
description: '<p>the new content</p>\n',
type: 'String'
}
],
class: 'p5.XML',
module: 'IO'
},
serialize: {
name: 'serialize',
class: 'p5.XML',
module: 'IO'
}
},
'p5.Vector': {
x: {
name: 'x',
class: 'p5.Vector',
module: 'Math'
},
y: {
name: 'y',
class: 'p5.Vector',
module: 'Math'
},
z: {
name: 'z',
class: 'p5.Vector',
module: 'Math'
},
toString: {
name: 'toString',
class: 'p5.Vector',
module: 'Math'
},
set: {
name: 'set',
class: 'p5.Vector',
module: 'Math',
overloads: [
{
params: [
{
name: 'x',
description: '<p>the x component of the vector</p>\n',
type: 'Number',
optional: true
},
{
name: 'y',
description: '<p>the y component of the vector</p>\n',
type: 'Number',
optional: true
},
{
name: 'z',
description: '<p>the z component of the vector</p>\n',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'value',
description: '<p>the vector to set</p>\n',
type: 'p5.Vector|Number[]'
}
],
chainable: 1
}
]
},
copy: {
name: 'copy',
class: 'p5.Vector',
module: 'Math'
},
add: {
name: 'add',
class: 'p5.Vector',
module: 'Math',
overloads: [
{
params: [
{
name: 'x',
description: '<p>the x component of the vector to be added</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>the y component of the vector to be added</p>\n',
type: 'Number',
optional: true
},
{
name: 'z',
description: '<p>the z component of the vector to be added</p>\n',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'value',
description: '<p>the vector to add</p>\n',
type: 'p5.Vector|Number[]'
}
],
chainable: 1
},
{
params: [
{
name: 'v1',
description:
'<p>a <a href="#/p5.Vector">p5.Vector</a> to add</p>\n',
type: 'p5.Vector'
},
{
name: 'v2',
description:
'<p>a <a href="#/p5.Vector">p5.Vector</a> to add</p>\n',
type: 'p5.Vector'
},
{
name: 'target',
description: '<p>the vector to receive the result (Optional)</p>\n',
type: 'p5.Vector',
optional: true
}
],
static: 1
}
]
},
rem: {
name: 'rem',
class: 'p5.Vector',
module: 'Math',
overloads: [
{
params: [
{
name: 'x',
description: '<p>the x component of divisor vector</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>the y component of divisor vector</p>\n',
type: 'Number'
},
{
name: 'z',
description: '<p>the z component of divisor vector</p>\n',
type: 'Number'
}
],
chainable: 1
},
{
params: [
{
name: 'value',
description: '<p>divisor vector</p>\n',
type: 'p5.Vector | Number[]'
}
],
chainable: 1
},
{
params: [
{
name: 'v1',
description:
'<p>dividend <a href="#/p5.Vector">p5.Vector</a></p>\n',
type: 'p5.Vector'
},
{
name: 'v2',
description: '<p>divisor <a href="#/p5.Vector">p5.Vector</a></p>\n',
type: 'p5.Vector'
}
],
static: 1
},
{
params: [
{
name: 'v1',
description: '',
type: 'p5.Vector'
},
{
name: 'v2',
description: '',
type: 'p5.Vector'
}
],
static: 1
}
]
},
sub: {
name: 'sub',
class: 'p5.Vector',
module: 'Math',
overloads: [
{
params: [
{
name: 'x',
description: '<p>the x component of the vector to subtract</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>the y component of the vector to subtract</p>\n',
type: 'Number',
optional: true
},
{
name: 'z',
description: '<p>the z component of the vector to subtract</p>\n',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'value',
description: '<p>the vector to subtract</p>\n',
type: 'p5.Vector|Number[]'
}
],
chainable: 1
},
{
params: [
{
name: 'v1',
description:
'<p>a <a href="#/p5.Vector">p5.Vector</a> to subtract from</p>\n',
type: 'p5.Vector'
},
{
name: 'v2',
description:
'<p>a <a href="#/p5.Vector">p5.Vector</a> to subtract</p>\n',
type: 'p5.Vector'
},
{
name: 'target',
description: '<p>the vector to receive the result (Optional)</p>\n',
type: 'p5.Vector',
optional: true
}
],
static: 1
}
]
},
mult: {
name: 'mult',
class: 'p5.Vector',
module: 'Math',
overloads: [
{
params: [
{
name: 'n',
description: '<p>The number to multiply with the vector</p>\n',
type: 'Number'
}
],
chainable: 1
},
{
params: [
{
name: 'x',
description:
'<p>The number to multiply with the x component of the vector</p>\n',
type: 'Number'
},
{
name: 'y',
description:
'<p>The number to multiply with the y component of the vector</p>\n',
type: 'Number'
},
{
name: 'z',
description:
'<p>The number to multiply with the z component of the vector</p>\n',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'arr',
description:
'<p>The array to multiply with the components of the vector</p>\n',
type: 'Number[]'
}
],
chainable: 1
},
{
params: [
{
name: 'v',
description:
'<p>The vector to multiply with the components of the original vector</p>\n',
type: 'p5.Vector'
}
],
chainable: 1
},
{
params: [
{
name: 'x',
description: '',
type: 'Number'
},
{
name: 'y',
description: '',
type: 'Number'
},
{
name: 'z',
description: '',
type: 'Number',
optional: true
}
],
static: 1
},
{
params: [
{
name: 'v',
description: '',
type: 'p5.Vector'
},
{
name: 'n',
description: '',
type: 'Number'
},
{
name: 'target',
description: '<p>the vector to receive the result (Optional)</p>\n',
type: 'p5.Vector',
optional: true
}
],
static: 1
},
{
params: [
{
name: 'v0',
description: '',
type: 'p5.Vector'
},
{
name: 'v1',
description: '',
type: 'p5.Vector'
},
{
name: 'target',
description: '',
type: 'p5.Vector',
optional: true
}
],
static: 1
},
{
params: [
{
name: 'v0',
description: '',
type: 'p5.Vector'
},
{
name: 'arr',
description: '',
type: 'Number[]'
},
{
name: 'target',
description: '',
type: 'p5.Vector',
optional: true
}
],
static: 1
}
]
},
div: {
name: 'div',
class: 'p5.Vector',
module: 'Math',
overloads: [
{
params: [
{
name: 'n',
description: '<p>The number to divide the vector by</p>\n',
type: 'Number'
}
],
chainable: 1
},
{
params: [
{
name: 'x',
description:
'<p>The number to divide with the x component of the vector</p>\n',
type: 'Number'
},
{
name: 'y',
description:
'<p>The number to divide with the y component of the vector</p>\n',
type: 'Number'
},
{
name: 'z',
description:
'<p>The number to divide with the z component of the vector</p>\n',
type: 'Number',
optional: true
}
],
chainable: 1
},
{
params: [
{
name: 'arr',
description:
'<p>The array to divide the components of the vector by</p>\n',
type: 'Number[]'
}
],
chainable: 1
},
{
params: [
{
name: 'v',
description:
'<p>The vector to divide the components of the original vector by</p>\n',
type: 'p5.Vector'
}
],
chainable: 1
},
{
params: [
{
name: 'x',
description: '',
type: 'Number'
},
{
name: 'y',
description: '',
type: 'Number'
},
{
name: 'z',
description: '',
type: 'Number',
optional: true
}
],
static: 1
},
{
params: [
{
name: 'v',
description: '',
type: 'p5.Vector'
},
{
name: 'n',
description: '',
type: 'Number'
},
{
name: 'target',
description: '<p>the vector to receive the result (Optional)</p>\n',
type: 'p5.Vector',
optional: true
}
],
static: 1
},
{
params: [
{
name: 'v0',
description: '',
type: 'p5.Vector'
},
{
name: 'v1',
description: '',
type: 'p5.Vector'
},
{
name: 'target',
description: '',
type: 'p5.Vector',
optional: true
}
],
static: 1
},
{
params: [
{
name: 'v0',
description: '',
type: 'p5.Vector'
},
{
name: 'arr',
description: '',
type: 'Number[]'
},
{
name: 'target',
description: '',
type: 'p5.Vector',
optional: true
}
],
static: 1
}
]
},
mag: {
name: 'mag',
class: 'p5.Vector',
module: 'Math',
overloads: [
{
params: []
},
{
params: [
{
name: 'vecT',
description: '<p>the vector to return the magnitude of</p>\n',
type: 'p5.Vector'
}
],
static: 1
}
]
},
magSq: {
name: 'magSq',
class: 'p5.Vector',
module: 'Math'
},
dot: {
name: 'dot',
class: 'p5.Vector',
module: 'Math',
overloads: [
{
params: [
{
name: 'x',
description: '<p>x component of the vector</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>y component of the vector</p>\n',
type: 'Number',
optional: true
},
{
name: 'z',
description: '<p>z component of the vector</p>\n',
type: 'Number',
optional: true
}
]
},
{
params: [
{
name: 'value',
description:
'<p>value component of the vector or a <a href="#/p5.Vector">p5.Vector</a></p>\n',
type: 'p5.Vector'
}
]
},
{
params: [
{
name: 'v1',
description:
'<p>the first <a href="#/p5.Vector">p5.Vector</a></p>\n',
type: 'p5.Vector'
},
{
name: 'v2',
description:
'<p>the second <a href="#/p5.Vector">p5.Vector</a></p>\n',
type: 'p5.Vector'
}
],
static: 1
}
]
},
cross: {
name: 'cross',
class: 'p5.Vector',
module: 'Math',
overloads: [
{
params: [
{
name: 'v',
description:
'<p><a href="#/p5.Vector">p5.Vector</a> to be crossed</p>\n',
type: 'p5.Vector'
}
]
},
{
params: [
{
name: 'v1',
description:
'<p>the first <a href="#/p5.Vector">p5.Vector</a></p>\n',
type: 'p5.Vector'
},
{
name: 'v2',
description:
'<p>the second <a href="#/p5.Vector">p5.Vector</a></p>\n',
type: 'p5.Vector'
}
],
static: 1
}
]
},
dist: {
name: 'dist',
class: 'p5.Vector',
module: 'Math',
overloads: [
{
params: [
{
name: 'v',
description:
'<p>the x, y, and z coordinates of a <a href="#/p5.Vector">p5.Vector</a></p>\n',
type: 'p5.Vector'
}
]
},
{
params: [
{
name: 'v1',
description:
'<p>the first <a href="#/p5.Vector">p5.Vector</a></p>\n',
type: 'p5.Vector'
},
{
name: 'v2',
description:
'<p>the second <a href="#/p5.Vector">p5.Vector</a></p>\n',
type: 'p5.Vector'
}
],
static: 1
}
]
},
normalize: {
name: 'normalize',
class: 'p5.Vector',
module: 'Math'
},
limit: {
name: 'limit',
params: [
{
name: 'max',
description: '<p>the maximum magnitude for the vector</p>\n',
type: 'Number'
}
],
class: 'p5.Vector',
module: 'Math'
},
setMag: {
name: 'setMag',
params: [
{
name: 'len',
description: '<p>the new length for this vector</p>\n',
type: 'Number'
}
],
class: 'p5.Vector',
module: 'Math'
},
heading: {
name: 'heading',
class: 'p5.Vector',
module: 'Math'
},
setHeading: {
name: 'setHeading',
params: [
{
name: 'angle',
description: '<p>the angle of rotation</p>\n',
type: 'Number'
}
],
class: 'p5.Vector',
module: 'Math'
},
rotate: {
name: 'rotate',
params: [
{
name: 'angle',
description: '<p>the angle of rotation</p>\n',
type: 'Number'
}
],
class: 'p5.Vector',
module: 'Math'
},
angleBetween: {
name: 'angleBetween',
params: [
{
name: 'value',
description:
'<p>the x, y, and z components of a <a href="#/p5.Vector">p5.Vector</a></p>\n',
type: 'p5.Vector'
}
],
class: 'p5.Vector',
module: 'Math'
},
lerp: {
name: 'lerp',
class: 'p5.Vector',
module: 'Math',
overloads: [
{
params: [
{
name: 'x',
description: '<p>the x component</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>the y component</p>\n',
type: 'Number'
},
{
name: 'z',
description: '<p>the z component</p>\n',
type: 'Number'
},
{
name: 'amt',
description:
'<p>the amount of interpolation; some value between 0.0\n (old vector) and 1.0 (new vector). 0.9 is very near\n the new vector. 0.5 is halfway in between.</p>\n',
type: 'Number'
}
],
chainable: 1
},
{
params: [
{
name: 'v',
description:
'<p>the <a href="#/p5.Vector">p5.Vector</a> to lerp to</p>\n',
type: 'p5.Vector'
},
{
name: 'amt',
description: '',
type: 'Number'
}
],
chainable: 1
},
{
params: [
{
name: 'v1',
description: '',
type: 'p5.Vector'
},
{
name: 'v2',
description: '',
type: 'p5.Vector'
},
{
name: 'amt',
description: '',
type: 'Number'
},
{
name: 'target',
description: '<p>the vector to receive the result (Optional)</p>\n',
type: 'p5.Vector',
optional: true
}
],
static: 1
}
]
},
reflect: {
name: 'reflect',
params: [
{
name: 'surfaceNormal',
description:
'<p>the <a href="#/p5.Vector">p5.Vector</a> to reflect about, will be normalized by this method</p>\n',
type: 'p5.Vector'
}
],
class: 'p5.Vector',
module: 'Math'
},
array: {
name: 'array',
class: 'p5.Vector',
module: 'Math'
},
equals: {
name: 'equals',
class: 'p5.Vector',
module: 'Math',
overloads: [
{
params: [
{
name: 'x',
description: '<p>the x component of the vector</p>\n',
type: 'Number',
optional: true
},
{
name: 'y',
description: '<p>the y component of the vector</p>\n',
type: 'Number',
optional: true
},
{
name: 'z',
description: '<p>the z component of the vector</p>\n',
type: 'Number',
optional: true
}
]
},
{
params: [
{
name: 'value',
description: '<p>the vector to compare</p>\n',
type: 'p5.Vector|Array'
}
]
}
]
},
fromAngle: {
name: 'fromAngle',
params: [
{
name: 'angle',
description:
'<p>the desired angle, in radians (unaffected by <a href="#/p5/angleMode">angleMode</a>)</p>\n',
type: 'Number'
},
{
name: 'length',
description: '<p>the length of the new vector (defaults to 1)</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Vector',
module: 'Math'
},
fromAngles: {
name: 'fromAngles',
params: [
{
name: 'theta',
description: '<p>the polar angle, in radians (zero is up)</p>\n',
type: 'Number'
},
{
name: 'phi',
description:
'<p>the azimuthal angle, in radians\n (zero is out of the screen)</p>\n',
type: 'Number'
},
{
name: 'length',
description: '<p>the length of the new vector (defaults to 1)</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Vector',
module: 'Math'
},
random2D: {
name: 'random2D',
class: 'p5.Vector',
module: 'Math'
},
random3D: {
name: 'random3D',
class: 'p5.Vector',
module: 'Math'
}
},
'p5.Font': {
font: {
name: 'font',
class: 'p5.Font',
module: 'Typography'
},
textBounds: {
name: 'textBounds',
params: [
{
name: 'line',
description: '<p>a line of text</p>\n',
type: 'String'
},
{
name: 'x',
description: '<p>x-position</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>y-position</p>\n',
type: 'Number'
},
{
name: 'fontSize',
description: '<p>font size to use (optional) Default is 12.</p>\n',
type: 'Number',
optional: true
},
{
name: 'options',
description:
"<p>opentype options (optional)\n opentype fonts contains alignment and baseline options.\n Default is 'LEFT' and 'alphabetic'</p>\n",
type: 'Object',
optional: true
}
],
class: 'p5.Font',
module: 'Typography'
},
textToPoints: {
name: 'textToPoints',
params: [
{
name: 'txt',
description: '<p>a line of text</p>\n',
type: 'String'
},
{
name: 'x',
description: '<p>x-position</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>y-position</p>\n',
type: 'Number'
},
{
name: 'fontSize',
description: '<p>font size to use (optional)</p>\n',
type: 'Number'
},
{
name: 'options',
description:
'<p>an (optional) object that can contain:</p>\n<p><br>sampleFactor - the ratio of path-length to number of samples\n(default=.1); higher values yield more points and are therefore\nmore precise</p>\n<p><br>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</p>\n',
type: 'Object',
optional: true
}
],
class: 'p5.Font',
module: 'Typography'
}
},
'p5.Camera': {
perspective: {
name: 'perspective',
class: 'p5.Camera',
module: 'Lights, Camera'
},
ortho: {
name: 'ortho',
class: 'p5.Camera',
module: 'Lights, Camera'
},
frustum: {
name: 'frustum',
class: 'p5.Camera',
module: 'Lights, Camera'
},
pan: {
name: 'pan',
params: [
{
name: 'angle',
description:
'<p>amount to rotate camera in current\n<a href="#/p5/angleMode">angleMode</a> units.\nGreater than 0 values rotate counterclockwise (to the left).</p>\n',
type: 'Number'
}
],
class: 'p5.Camera',
module: 'Lights, Camera'
},
tilt: {
name: 'tilt',
params: [
{
name: 'angle',
description:
'<p>amount to rotate camera in current\n<a href="#/p5/angleMode">angleMode</a> units.\nGreater than 0 values rotate counterclockwise (to the left).</p>\n',
type: 'Number'
}
],
class: 'p5.Camera',
module: 'Lights, Camera'
},
lookAt: {
name: 'lookAt',
params: [
{
name: 'x',
description: '<p>x position of a point in world space</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>y position of a point in world space</p>\n',
type: 'Number'
},
{
name: 'z',
description: '<p>z position of a point in world space</p>\n',
type: 'Number'
}
],
class: 'p5.Camera',
module: 'Lights, Camera'
},
camera: {
name: 'camera',
class: 'p5.Camera',
module: 'Lights, Camera'
},
move: {
name: 'move',
params: [
{
name: 'x',
description: "<p>amount to move along camera's left-right axis</p>\n",
type: 'Number'
},
{
name: 'y',
description: "<p>amount to move along camera's up-down axis</p>\n",
type: 'Number'
},
{
name: 'z',
description:
"<p>amount to move along camera's forward-backward axis</p>\n",
type: 'Number'
}
],
class: 'p5.Camera',
module: 'Lights, Camera'
},
setPosition: {
name: 'setPosition',
params: [
{
name: 'x',
description: '<p>x position of a point in world space</p>\n',
type: 'Number'
},
{
name: 'y',
description: '<p>y position of a point in world space</p>\n',
type: 'Number'
},
{
name: 'z',
description: '<p>z position of a point in world space</p>\n',
type: 'Number'
}
],
class: 'p5.Camera',
module: 'Lights, Camera'
}
},
'p5.Geometry': {
computeFaces: {
name: 'computeFaces',
class: 'p5.Geometry',
module: 'Lights, Camera'
},
computeNormals: {
name: 'computeNormals',
class: 'p5.Geometry',
module: 'Lights, Camera'
},
averageNormals: {
name: 'averageNormals',
class: 'p5.Geometry',
module: 'Lights, Camera'
},
averagePoleNormals: {
name: 'averagePoleNormals',
class: 'p5.Geometry',
module: 'Lights, Camera'
},
normalize: {
name: 'normalize',
class: 'p5.Geometry',
module: 'Lights, Camera'
}
},
'p5.Shader': {
setUniform: {
name: 'setUniform',
params: [
{
name: 'uniformName',
description: '<p>the name of the uniform in the\nshader program</p>\n',
type: 'String'
},
{
name: 'data',
description:
'<p>the data to be associated\nwith that uniform; type varies (could be a single numerical value, array,\nmatrix, or texture / sampler reference)</p>\n',
type: 'Object|Number|Boolean|Number[]'
}
],
class: 'p5.Shader',
module: 'Lights, Camera'
}
},
'p5.sound': {
getMasterVolume: {
name: 'getMasterVolume',
class: 'p5.sound',
module: 'p5.sound'
},
masterVolume: {
name: 'masterVolume',
params: [
{
name: 'volume',
description:
'<p>Volume (amplitude) between 0.0\n and 1.0 or modulating signal/oscillator</p>\n',
type: 'Number|Object'
},
{
name: 'rampTime',
description: '<p>Fade for t seconds</p>\n',
type: 'Number',
optional: true
},
{
name: 'timeFromNow',
description:
'<p>Schedule this event to happen at\n t seconds in the future</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.sound',
module: 'p5.sound'
},
soundOut: {
name: 'soundOut',
class: 'p5.sound',
module: 'p5.sound'
}
},
'p5.Effect': {
amp: {
name: 'amp',
params: [
{
name: 'vol',
description: '<p>amplitude between 0 and 1.0</p>\n',
type: 'Number',
optional: true
},
{
name: 'rampTime',
description: '<p>create a fade that lasts until rampTime</p>\n',
type: 'Number',
optional: true
},
{
name: 'tFromNow',
description:
'<p>schedule this event to happen in tFromNow seconds</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Effect',
module: 'p5.sound'
},
chain: {
name: 'chain',
params: [
{
name: 'arguments',
description: '<p>Chain together multiple sound objects</p>\n',
type: 'Object',
optional: true
}
],
class: 'p5.Effect',
module: 'p5.sound'
},
drywet: {
name: 'drywet',
params: [
{
name: 'fade',
description: '<p>The desired drywet value (0 - 1.0)</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Effect',
module: 'p5.sound'
},
connect: {
name: 'connect',
params: [
{
name: 'unit',
description: '',
type: 'Object'
}
],
class: 'p5.Effect',
module: 'p5.sound'
},
disconnect: {
name: 'disconnect',
class: 'p5.Effect',
module: 'p5.sound'
}
},
'p5.Filter': {
biquadFilter: {
name: 'biquadFilter',
class: 'p5.Filter',
module: 'p5.sound'
},
process: {
name: 'process',
params: [
{
name: 'Signal',
description: '<p>An object that outputs audio</p>\n',
type: 'Object'
},
{
name: 'freq',
description: '<p>Frequency in Hz, from 10 to 22050</p>\n',
type: 'Number',
optional: true
},
{
name: 'res',
description:
'<p>Resonance/Width of the filter frequency\n from 0.001 to 1000</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Filter',
module: 'p5.sound'
},
set: {
name: 'set',
params: [
{
name: 'freq',
description: '<p>Frequency in Hz, from 10 to 22050</p>\n',
type: 'Number',
optional: true
},
{
name: 'res',
description: '<p>Resonance (Q) from 0.001 to 1000</p>\n',
type: 'Number',
optional: true
},
{
name: 'timeFromNow',
description:
'<p>schedule this event to happen\n seconds from now</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Filter',
module: 'p5.sound'
},
freq: {
name: 'freq',
params: [
{
name: 'freq',
description: '<p>Filter Frequency</p>\n',
type: 'Number'
},
{
name: 'timeFromNow',
description:
'<p>schedule this event to happen\n seconds from now</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Filter',
module: 'p5.sound'
},
res: {
name: 'res',
params: [
{
name: 'res',
description:
'<p>Resonance/Width of filter freq\n from 0.001 to 1000</p>\n',
type: 'Number'
},
{
name: 'timeFromNow',
description:
'<p>schedule this event to happen\n seconds from now</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Filter',
module: 'p5.sound'
},
gain: {
name: 'gain',
params: [
{
name: 'gain',
description: '',
type: 'Number'
}
],
class: 'p5.Filter',
module: 'p5.sound'
},
toggle: {
name: 'toggle',
class: 'p5.Filter',
module: 'p5.sound'
},
setType: {
name: 'setType',
params: [
{
name: 't',
description: '',
type: 'String'
}
],
class: 'p5.Filter',
module: 'p5.sound'
}
},
'p5.Oscillator': {
start: {
name: 'start',
params: [
{
name: 'time',
description: '<p>startTime in seconds from now.</p>\n',
type: 'Number',
optional: true
},
{
name: 'frequency',
description: '<p>frequency in Hz.</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Oscillator',
module: 'p5.sound'
},
stop: {
name: 'stop',
params: [
{
name: 'secondsFromNow',
description: '<p>Time, in seconds from now.</p>\n',
type: 'Number'
}
],
class: 'p5.Oscillator',
module: 'p5.sound'
},
amp: {
name: 'amp',
params: [
{
name: 'vol',
description:
'<p>between 0 and 1.0\n or a modulating signal/oscillator</p>\n',
type: 'Number|Object'
},
{
name: 'rampTime',
description: '<p>create a fade that lasts rampTime</p>\n',
type: 'Number',
optional: true
},
{
name: 'timeFromNow',
description:
'<p>schedule this event to happen\n seconds from now</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Oscillator',
module: 'p5.sound'
},
freq: {
name: 'freq',
params: [
{
name: 'Frequency',
description:
'<p>Frequency in Hz\n or modulating signal/oscillator</p>\n',
type: 'Number|Object'
},
{
name: 'rampTime',
description: '<p>Ramp time (in seconds)</p>\n',
type: 'Number',
optional: true
},
{
name: 'timeFromNow',
description:
'<p>Schedule this event to happen\n at x seconds from now</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Oscillator',
module: 'p5.sound'
},
setType: {
name: 'setType',
params: [
{
name: 'type',
description: "<p>'sine', 'triangle', 'sawtooth' or 'square'.</p>\n",
type: 'String'
}
],
class: 'p5.Oscillator',
module: 'p5.sound'
},
connect: {
name: 'connect',
params: [
{
name: 'unit',
description: '<p>A p5.sound or Web Audio object</p>\n',
type: 'Object'
}
],
class: 'p5.Oscillator',
module: 'p5.sound'
},
disconnect: {
name: 'disconnect',
class: 'p5.Oscillator',
module: 'p5.sound'
},
pan: {
name: 'pan',
params: [
{
name: 'panning',
description: '<p>Number between -1 and 1</p>\n',
type: 'Number'
},
{
name: 'timeFromNow',
description:
'<p>schedule this event to happen\n seconds from now</p>\n',
type: 'Number'
}
],
class: 'p5.Oscillator',
module: 'p5.sound'
},
phase: {
name: 'phase',
params: [
{
name: 'phase',
description: '<p>float between 0.0 and 1.0</p>\n',
type: 'Number'
}
],
class: 'p5.Oscillator',
module: 'p5.sound'
},
add: {
name: 'add',
params: [
{
name: 'number',
description: '<p>Constant number to add</p>\n',
type: 'Number'
}
],
class: 'p5.Oscillator',
module: 'p5.sound'
},
mult: {
name: 'mult',
params: [
{
name: 'number',
description: '<p>Constant number to multiply</p>\n',
type: 'Number'
}
],
class: 'p5.Oscillator',
module: 'p5.sound'
},
scale: {
name: 'scale',
params: [
{
name: 'inMin',
description: '<p>input range minumum</p>\n',
type: 'Number'
},
{
name: 'inMax',
description: '<p>input range maximum</p>\n',
type: 'Number'
},
{
name: 'outMin',
description: '<p>input range minumum</p>\n',
type: 'Number'
},
{
name: 'outMax',
description: '<p>input range maximum</p>\n',
type: 'Number'
}
],
class: 'p5.Oscillator',
module: 'p5.sound'
}
},
'p5.MonoSynth': {
play: {
name: 'play',
params: [
{
name: 'note',
description:
'<p>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 <a href = "https://github.com/Tonejs/Tone.js/wiki/Instruments">\n Tone</a>. Defaults to 440 hz.</p>\n',
type: 'String | Number'
},
{
name: 'velocity',
description:
'<p>velocity of the note to play (ranging from 0 to 1)</p>\n',
type: 'Number',
optional: true
},
{
name: 'secondsFromNow',
description: '<p>time from now (in seconds) at which to play</p>\n',
type: 'Number',
optional: true
},
{
name: 'sustainTime',
description:
'<p>time to sustain before releasing the envelope. Defaults to 0.15 seconds.</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.MonoSynth',
module: 'p5.sound'
},
triggerAttack: {
params: [
{
name: 'note',
description:
'<p>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 <a href = "https://github.com/Tonejs/Tone.js/wiki/Instruments">\n Tone</a>. Defaults to 440 hz</p>\n',
type: 'String | Number'
},
{
name: 'velocity',
description:
'<p>velocity of the note to play (ranging from 0 to 1)</p>\n',
type: 'Number',
optional: true
},
{
name: 'secondsFromNow',
description: '<p>time from now (in seconds) at which to play</p>\n',
type: 'Number',
optional: true
}
],
name: 'triggerAttack',
class: 'p5.MonoSynth',
module: 'p5.sound'
},
triggerRelease: {
params: [
{
name: 'secondsFromNow',
description: '<p>time to trigger the release</p>\n',
type: 'Number'
}
],
name: 'triggerRelease',
class: 'p5.MonoSynth',
module: 'p5.sound'
},
setADSR: {
name: 'setADSR',
params: [
{
name: 'attackTime',
description:
'<p>Time (in seconds before envelope\n reaches Attack Level</p>\n',
type: 'Number'
},
{
name: 'decayTime',
description:
'<p>Time (in seconds) before envelope\n reaches Decay/Sustain Level</p>\n',
type: 'Number',
optional: true
},
{
name: 'susRatio',
description:
'<p>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 <code>setRange</code>),\n then decayLevel would increase proportionally, to become 0.5.</p>\n',
type: 'Number',
optional: true
},
{
name: 'releaseTime',
description: '<p>Time in seconds from now (defaults to 0)</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.MonoSynth',
module: 'p5.sound'
},
attack: {
name: 'attack',
class: 'p5.MonoSynth',
module: 'p5.sound'
},
decay: {
name: 'decay',
class: 'p5.MonoSynth',
module: 'p5.sound'
},
sustain: {
name: 'sustain',
class: 'p5.MonoSynth',
module: 'p5.sound'
},
release: {
name: 'release',
class: 'p5.MonoSynth',
module: 'p5.sound'
},
amp: {
name: 'amp',
params: [
{
name: 'vol',
description: '<p>desired volume</p>\n',
type: 'Number'
},
{
name: 'rampTime',
description: '<p>Time to reach new volume</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.MonoSynth',
module: 'p5.sound'
},
connect: {
name: 'connect',
params: [
{
name: 'unit',
description: '<p>A p5.sound or Web Audio object</p>\n',
type: 'Object'
}
],
class: 'p5.MonoSynth',
module: 'p5.sound'
},
disconnect: {
name: 'disconnect',
class: 'p5.MonoSynth',
module: 'p5.sound'
},
dispose: {
name: 'dispose',
class: 'p5.MonoSynth',
module: 'p5.sound'
}
},
'p5.AudioVoice': {
connect: {
name: 'connect',
params: [
{
name: 'unit',
description: '',
type: 'Object'
}
],
class: 'p5.AudioVoice',
module: 'p5.sound'
},
disconnect: {
name: 'disconnect',
class: 'p5.AudioVoice',
module: 'p5.sound'
}
},
'p5.PolySynth': {
notes: {
name: 'notes',
class: 'p5.PolySynth',
module: 'p5.sound'
},
polyvalue: {
name: 'polyvalue',
class: 'p5.PolySynth',
module: 'p5.sound'
},
AudioVoice: {
name: 'AudioVoice',
class: 'p5.PolySynth',
module: 'p5.sound'
},
play: {
name: 'play',
params: [
{
name: 'note',
description:
'<p>midi note to play (ranging from 0 to 127 - 60 being a middle C)</p>\n',
type: 'Number',
optional: true
},
{
name: 'velocity',
description:
'<p>velocity of the note to play (ranging from 0 to 1)</p>\n',
type: 'Number',
optional: true
},
{
name: 'secondsFromNow',
description: '<p>time from now (in seconds) at which to play</p>\n',
type: 'Number',
optional: true
},
{
name: 'sustainTime',
description: '<p>time to sustain before releasing the envelope</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.PolySynth',
module: 'p5.sound'
},
noteADSR: {
name: 'noteADSR',
params: [
{
name: 'note',
description: '<p>Midi note on which ADSR should be set.</p>\n',
type: 'Number',
optional: true
},
{
name: 'attackTime',
description:
'<p>Time (in seconds before envelope\n reaches Attack Level</p>\n',
type: 'Number',
optional: true
},
{
name: 'decayTime',
description:
'<p>Time (in seconds) before envelope\n reaches Decay/Sustain Level</p>\n',
type: 'Number',
optional: true
},
{
name: 'susRatio',
description:
'<p>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 <code>setRange</code>),\n then decayLevel would increase proportionally, to become 0.5.</p>\n',
type: 'Number',
optional: true
},
{
name: 'releaseTime',
description: '<p>Time in seconds from now (defaults to 0)</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.PolySynth',
module: 'p5.sound'
},
setADSR: {
name: 'setADSR',
params: [
{
name: 'attackTime',
description:
'<p>Time (in seconds before envelope\n reaches Attack Level</p>\n',
type: 'Number',
optional: true
},
{
name: 'decayTime',
description:
'<p>Time (in seconds) before envelope\n reaches Decay/Sustain Level</p>\n',
type: 'Number',
optional: true
},
{
name: 'susRatio',
description:
'<p>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 <code>setRange</code>),\n then decayLevel would increase proportionally, to become 0.5.</p>\n',
type: 'Number',
optional: true
},
{
name: 'releaseTime',
description: '<p>Time in seconds from now (defaults to 0)</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.PolySynth',
module: 'p5.sound'
},
noteAttack: {
name: 'noteAttack',
params: [
{
name: 'note',
description: '<p>midi note on which attack should be triggered.</p>\n',
type: 'Number',
optional: true
},
{
name: 'velocity',
description:
'<p>velocity of the note to play (ranging from 0 to 1)/</p>\n',
type: 'Number',
optional: true
},
{
name: 'secondsFromNow',
description: '<p>time from now (in seconds)</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.PolySynth',
module: 'p5.sound'
},
noteRelease: {
name: 'noteRelease',
params: [
{
name: 'note',
description:
'<p>midi note on which attack should be triggered.\n If no value is provided, all notes will be released.</p>\n',
type: 'Number',
optional: true
},
{
name: 'secondsFromNow',
description: '<p>time to trigger the release</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.PolySynth',
module: 'p5.sound'
},
connect: {
name: 'connect',
params: [
{
name: 'unit',
description: '<p>A p5.sound or Web Audio object</p>\n',
type: 'Object'
}
],
class: 'p5.PolySynth',
module: 'p5.sound'
},
disconnect: {
name: 'disconnect',
class: 'p5.PolySynth',
module: 'p5.sound'
},
dispose: {
name: 'dispose',
class: 'p5.PolySynth',
module: 'p5.sound'
}
},
'p5.SoundFile': {
isLoaded: {
name: 'isLoaded',
class: 'p5.SoundFile',
module: 'p5.sound'
},
play: {
name: 'play',
params: [
{
name: 'startTime',
description:
'<p>(optional) schedule playback to start (in seconds from now).</p>\n',
type: 'Number',
optional: true
},
{
name: 'rate',
description: '<p>(optional) playback rate</p>\n',
type: 'Number',
optional: true
},
{
name: 'amp',
description:
'<p>(optional) amplitude (volume)\n of playback</p>\n',
type: 'Number',
optional: true
},
{
name: 'cueStart',
description: '<p>(optional) cue start time in seconds</p>\n',
type: 'Number',
optional: true
},
{
name: 'duration',
description: '<p>(optional) duration of playback in seconds</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.SoundFile',
module: 'p5.sound'
},
playMode: {
name: 'playMode',
params: [
{
name: 'str',
description: "<p>'restart' or 'sustain' or 'untilDone'</p>\n",
type: 'String'
}
],
class: 'p5.SoundFile',
module: 'p5.sound'
},
pause: {
name: 'pause',
params: [
{
name: 'startTime',
description:
'<p>(optional) schedule event to occur\n seconds from now</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.SoundFile',
module: 'p5.sound'
},
loop: {
name: 'loop',
params: [
{
name: 'startTime',
description:
'<p>(optional) schedule event to occur\n seconds from now</p>\n',
type: 'Number',
optional: true
},
{
name: 'rate',
description: '<p>(optional) playback rate</p>\n',
type: 'Number',
optional: true
},
{
name: 'amp',
description: '<p>(optional) playback volume</p>\n',
type: 'Number',
optional: true
},
{
name: 'cueLoopStart',
description: '<p>(optional) startTime in seconds</p>\n',
type: 'Number',
optional: true
},
{
name: 'duration',
description: '<p>(optional) loop duration in seconds</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.SoundFile',
module: 'p5.sound'
},
setLoop: {
name: 'setLoop',
params: [
{
name: 'Boolean',
description: '<p>set looping to true or false</p>\n',
type: 'Boolean'
}
],
class: 'p5.SoundFile',
module: 'p5.sound'
},
isLooping: {
name: 'isLooping',
class: 'p5.SoundFile',
module: 'p5.sound'
},
isPlaying: {
name: 'isPlaying',
class: 'p5.SoundFile',
module: 'p5.sound'
},
isPaused: {
name: 'isPaused',
class: 'p5.SoundFile',
module: 'p5.sound'
},
stop: {
name: 'stop',
params: [
{
name: 'startTime',
description:
'<p>(optional) schedule event to occur\n in seconds from now</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.SoundFile',
module: 'p5.sound'
},
setVolume: {
name: 'setVolume',
params: [
{
name: 'volume',
description:
'<p>Volume (amplitude) between 0.0\n and 1.0 or modulating signal/oscillator</p>\n',
type: 'Number|Object'
},
{
name: 'rampTime',
description: '<p>Fade for t seconds</p>\n',
type: 'Number',
optional: true
},
{
name: 'timeFromNow',
description:
'<p>Schedule this event to happen at\n t seconds in the future</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.SoundFile',
module: 'p5.sound'
},
pan: {
name: 'pan',
params: [
{
name: 'panValue',
description: '<p>Set the stereo panner</p>\n',
type: 'Number',
optional: true
},
{
name: 'timeFromNow',
description:
'<p>schedule this event to happen\n seconds from now</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.SoundFile',
module: 'p5.sound'
},
getPan: {
name: 'getPan',
class: 'p5.SoundFile',
module: 'p5.sound'
},
rate: {
name: 'rate',
params: [
{
name: 'playbackRate',
description:
'<p>Set the playback rate. 1.0 is normal,\n .5 is half-speed, 2.0 is twice as fast.\n Values less than zero play backwards.</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.SoundFile',
module: 'p5.sound'
},
duration: {
name: 'duration',
class: 'p5.SoundFile',
module: 'p5.sound'
},
currentTime: {
name: 'currentTime',
class: 'p5.SoundFile',
module: 'p5.sound'
},
jump: {
name: 'jump',
params: [
{
name: 'cueTime',
description: '<p>cueTime of the soundFile in seconds.</p>\n',
type: 'Number'
},
{
name: 'duration',
description: '<p>duration in seconds.</p>\n',
type: 'Number'
}
],
class: 'p5.SoundFile',
module: 'p5.sound'
},
channels: {
name: 'channels',
class: 'p5.SoundFile',
module: 'p5.sound'
},
sampleRate: {
name: 'sampleRate',
class: 'p5.SoundFile',
module: 'p5.sound'
},
frames: {
name: 'frames',
class: 'p5.SoundFile',
module: 'p5.sound'
},
getPeaks: {
name: 'getPeaks',
params: [
{
name: 'length',
description:
'<p>length is the size of the returned array.\n Larger length results in more precision.\n Defaults to 5*width of the browser window.</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.SoundFile',
module: 'p5.sound'
},
reverseBuffer: {
name: 'reverseBuffer',
class: 'p5.SoundFile',
module: 'p5.sound'
},
onended: {
name: 'onended',
params: [
{
name: 'callback',
description:
'<p>function to call when the\n soundfile has ended.</p>\n',
type: 'Function'
}
],
class: 'p5.SoundFile',
module: 'p5.sound'
},
connect: {
name: 'connect',
params: [
{
name: 'object',
description: '<p>Audio object that accepts an input</p>\n',
type: 'Object',
optional: true
}
],
class: 'p5.SoundFile',
module: 'p5.sound'
},
disconnect: {
name: 'disconnect',
class: 'p5.SoundFile',
module: 'p5.sound'
},
setPath: {
name: 'setPath',
params: [
{
name: 'path',
description: '<p>path to audio file</p>\n',
type: 'String'
},
{
name: 'callback',
description: '<p>Callback</p>\n',
type: 'Function'
}
],
class: 'p5.SoundFile',
module: 'p5.sound'
},
setBuffer: {
name: 'setBuffer',
params: [
{
name: 'buf',
description:
'<p>Array of Float32 Array(s). 2 Float32 Arrays\n will create a stereo source. 1 will create\n a mono source.</p>\n',
type: 'Array'
}
],
class: 'p5.SoundFile',
module: 'p5.sound'
},
processPeaks: {
name: 'processPeaks',
params: [
{
name: 'callback',
description: '<p>a function to call once this data is returned</p>\n',
type: 'Function'
},
{
name: 'initThreshold',
description: '<p>initial threshold defaults to 0.9</p>\n',
type: 'Number',
optional: true
},
{
name: 'minThreshold',
description: '<p>minimum threshold defaults to 0.22</p>\n',
type: 'Number',
optional: true
},
{
name: 'minPeaks',
description: '<p>minimum number of peaks defaults to 200</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.SoundFile',
module: 'p5.sound'
},
addCue: {
name: 'addCue',
params: [
{
name: 'time',
description:
"<p>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.</p>\n",
type: 'Number'
},
{
name: 'callback',
description:
'<p>Name of a function that will be\n called at the given time. The callback will\n receive time and (optionally) param as its\n two parameters.</p>\n',
type: 'Function'
},
{
name: 'value',
description:
'<p>An object to be passed as the\n second parameter to the\n callback function.</p>\n',
type: 'Object',
optional: true
}
],
class: 'p5.SoundFile',
module: 'p5.sound'
},
removeCue: {
name: 'removeCue',
params: [
{
name: 'id',
description: '<p>ID of the cue, as returned by addCue</p>\n',
type: 'Number'
}
],
class: 'p5.SoundFile',
module: 'p5.sound'
},
clearCues: {
name: 'clearCues',
class: 'p5.SoundFile',
module: 'p5.sound'
},
save: {
name: 'save',
params: [
{
name: 'fileName',
description: '<p>name of the resulting .wav file.</p>\n',
type: 'String',
optional: true
}
],
class: 'p5.SoundFile',
module: 'p5.sound'
},
getBlob: {
name: 'getBlob',
class: 'p5.SoundFile',
module: 'p5.sound'
}
},
'p5.Amplitude': {
setInput: {
name: 'setInput',
params: [
{
name: 'snd',
description:
'<p>set the sound source\n (optional, defaults to\n master output)</p>\n',
type: 'SoundObject|undefined',
optional: true
},
{
name: 'smoothing',
description:
'<p>a range between 0.0 and 1.0\n to smooth amplitude readings</p>\n',
type: 'Number|undefined',
optional: true
}
],
class: 'p5.Amplitude',
module: 'p5.sound'
},
getLevel: {
name: 'getLevel',
params: [
{
name: 'channel',
description:
'<p>Optionally return only channel 0 (left) or 1 (right)</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Amplitude',
module: 'p5.sound'
},
toggleNormalize: {
name: 'toggleNormalize',
params: [
{
name: 'boolean',
description: '<p>set normalize to true (1) or false (0)</p>\n',
type: 'Boolean',
optional: true
}
],
class: 'p5.Amplitude',
module: 'p5.sound'
},
smooth: {
name: 'smooth',
params: [
{
name: 'set',
description: '<p>smoothing from 0.0 <= 1</p>\n',
type: 'Number'
}
],
class: 'p5.Amplitude',
module: 'p5.sound'
}
},
'p5.FFT': {
setInput: {
name: 'setInput',
params: [
{
name: 'source',
description: '<p>p5.sound object (or web audio API source node)</p>\n',
type: 'Object',
optional: true
}
],
class: 'p5.FFT',
module: 'p5.sound'
},
waveform: {
name: 'waveform',
params: [
{
name: 'bins',
description:
'<p>Must be a power of two between\n 16 and 1024. Defaults to 1024.</p>\n',
type: 'Number',
optional: true
},
{
name: 'precision',
description:
'<p>If any value is provided, will return results\n in a Float32 Array which is more precise\n than a regular array.</p>\n',
type: 'String',
optional: true
}
],
class: 'p5.FFT',
module: 'p5.sound'
},
analyze: {
name: 'analyze',
params: [
{
name: 'bins',
description:
'<p>Must be a power of two between\n 16 and 1024. Defaults to 1024.</p>\n',
type: 'Number',
optional: true
},
{
name: 'scale',
description:
'<p>If "dB," returns decibel\n float measurements between\n -140 and 0 (max).\n Otherwise returns integers from 0-255.</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.FFT',
module: 'p5.sound'
},
getEnergy: {
name: 'getEnergy',
params: [
{
name: 'frequency1',
description:
'<p>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.</p>\n',
type: 'Number|String'
},
{
name: 'frequency2',
description:
'<p>If a second frequency is given,\n will return average amount of\n energy that exists between the\n two frequencies.</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.FFT',
module: 'p5.sound'
},
getCentroid: {
name: 'getCentroid',
class: 'p5.FFT',
module: 'p5.sound'
},
smooth: {
name: 'smooth',
params: [
{
name: 'smoothing',
description:
'<p>0.0 < smoothing < 1.0.\n Defaults to 0.8.</p>\n',
type: 'Number'
}
],
class: 'p5.FFT',
module: 'p5.sound'
},
linAverages: {
name: 'linAverages',
params: [
{
name: 'N',
description: '<p>Number of returned frequency groups</p>\n',
type: 'Number'
}
],
class: 'p5.FFT',
module: 'p5.sound'
},
logAverages: {
name: 'logAverages',
params: [
{
name: 'octaveBands',
description: '<p>Array of Octave Bands objects for grouping</p>\n',
type: 'Array'
}
],
class: 'p5.FFT',
module: 'p5.sound'
},
getOctaveBands: {
name: 'getOctaveBands',
params: [
{
name: 'N',
description:
'<p>Specifies the 1/N type of generated octave bands</p>\n',
type: 'Number'
},
{
name: 'fCtr0',
description: '<p>Minimum central frequency for the lowest band</p>\n',
type: 'Number'
}
],
class: 'p5.FFT',
module: 'p5.sound'
}
},
'p5.Signal': {
fade: {
name: 'fade',
params: [
{
name: 'value',
description: '<p>Value to set this signal</p>\n',
type: 'Number'
},
{
name: 'secondsFromNow',
description: '<p>Length of fade, in seconds from now</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Signal',
module: 'p5.sound'
},
setInput: {
name: 'setInput',
params: [
{
name: 'input',
description: '',
type: 'Object'
}
],
class: 'p5.Signal',
module: 'p5.sound'
},
add: {
name: 'add',
params: [
{
name: 'number',
description: '',
type: 'Number'
}
],
class: 'p5.Signal',
module: 'p5.sound'
},
mult: {
name: 'mult',
params: [
{
name: 'number',
description: '<p>to multiply</p>\n',
type: 'Number'
}
],
class: 'p5.Signal',
module: 'p5.sound'
},
scale: {
name: 'scale',
params: [
{
name: 'number',
description: '<p>to multiply</p>\n',
type: 'Number'
},
{
name: 'inMin',
description: '<p>input range minumum</p>\n',
type: 'Number'
},
{
name: 'inMax',
description: '<p>input range maximum</p>\n',
type: 'Number'
},
{
name: 'outMin',
description: '<p>input range minumum</p>\n',
type: 'Number'
},
{
name: 'outMax',
description: '<p>input range maximum</p>\n',
type: 'Number'
}
],
class: 'p5.Signal',
module: 'p5.sound'
}
},
'p5.Envelope': {
attackTime: {
name: 'attackTime',
class: 'p5.Envelope',
module: 'p5.sound'
},
attackLevel: {
name: 'attackLevel',
class: 'p5.Envelope',
module: 'p5.sound'
},
decayTime: {
name: 'decayTime',
class: 'p5.Envelope',
module: 'p5.sound'
},
decayLevel: {
name: 'decayLevel',
class: 'p5.Envelope',
module: 'p5.sound'
},
releaseTime: {
name: 'releaseTime',
class: 'p5.Envelope',
module: 'p5.sound'
},
releaseLevel: {
name: 'releaseLevel',
class: 'p5.Envelope',
module: 'p5.sound'
},
set: {
name: 'set',
params: [
{
name: 'attackTime',
description:
'<p>Time (in seconds) before level\n reaches attackLevel</p>\n',
type: 'Number'
},
{
name: 'attackLevel',
description:
'<p>Typically an amplitude between\n 0.0 and 1.0</p>\n',
type: 'Number'
},
{
name: 'decayTime',
description: '<p>Time</p>\n',
type: 'Number'
},
{
name: 'decayLevel',
description:
'<p>Amplitude (In a standard ADSR envelope,\n decayLevel = sustainLevel)</p>\n',
type: 'Number'
},
{
name: 'releaseTime',
description: '<p>Release Time (in seconds)</p>\n',
type: 'Number'
},
{
name: 'releaseLevel',
description: '<p>Amplitude</p>\n',
type: 'Number'
}
],
class: 'p5.Envelope',
module: 'p5.sound'
},
setADSR: {
name: 'setADSR',
params: [
{
name: 'attackTime',
description:
'<p>Time (in seconds before envelope\n reaches Attack Level</p>\n',
type: 'Number'
},
{
name: 'decayTime',
description:
'<p>Time (in seconds) before envelope\n reaches Decay/Sustain Level</p>\n',
type: 'Number',
optional: true
},
{
name: 'susRatio',
description:
'<p>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 <code>setRange</code>),\n then decayLevel would increase proportionally, to become 0.5.</p>\n',
type: 'Number',
optional: true
},
{
name: 'releaseTime',
description: '<p>Time in seconds from now (defaults to 0)</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Envelope',
module: 'p5.sound'
},
setRange: {
name: 'setRange',
params: [
{
name: 'aLevel',
description: '<p>attack level (defaults to 1)</p>\n',
type: 'Number'
},
{
name: 'rLevel',
description: '<p>release level (defaults to 0)</p>\n',
type: 'Number'
}
],
class: 'p5.Envelope',
module: 'p5.sound'
},
setInput: {
name: 'setInput',
params: [
{
name: 'inputs',
description:
'<p>A p5.sound object or\n Web Audio Param.</p>\n',
type: 'Object',
optional: true,
multiple: true
}
],
class: 'p5.Envelope',
module: 'p5.sound'
},
setExp: {
name: 'setExp',
params: [
{
name: 'isExp',
description: '<p>true is exponential, false is linear</p>\n',
type: 'Boolean'
}
],
class: 'p5.Envelope',
module: 'p5.sound'
},
play: {
name: 'play',
params: [
{
name: 'unit',
description:
'<p>A p5.sound object or\n Web Audio Param.</p>\n',
type: 'Object'
},
{
name: 'startTime',
description: '<p>time from now (in seconds) at which to play</p>\n',
type: 'Number',
optional: true
},
{
name: 'sustainTime',
description: '<p>time to sustain before releasing the envelope</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Envelope',
module: 'p5.sound'
},
triggerAttack: {
name: 'triggerAttack',
params: [
{
name: 'unit',
description: '<p>p5.sound Object or Web Audio Param</p>\n',
type: 'Object'
},
{
name: 'secondsFromNow',
description: '<p>time from now (in seconds)</p>\n',
type: 'Number'
}
],
class: 'p5.Envelope',
module: 'p5.sound'
},
triggerRelease: {
name: 'triggerRelease',
params: [
{
name: 'unit',
description: '<p>p5.sound Object or Web Audio Param</p>\n',
type: 'Object'
},
{
name: 'secondsFromNow',
description: '<p>time to trigger the release</p>\n',
type: 'Number'
}
],
class: 'p5.Envelope',
module: 'p5.sound'
},
ramp: {
name: 'ramp',
params: [
{
name: 'unit',
description: '<p>p5.sound Object or Web Audio Param</p>\n',
type: 'Object'
},
{
name: 'secondsFromNow',
description: '<p>When to trigger the ramp</p>\n',
type: 'Number'
},
{
name: 'v',
description: '<p>Target value</p>\n',
type: 'Number'
},
{
name: 'v2',
description: '<p>Second target value (optional)</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Envelope',
module: 'p5.sound'
},
add: {
name: 'add',
params: [
{
name: 'number',
description: '<p>Constant number to add</p>\n',
type: 'Number'
}
],
class: 'p5.Envelope',
module: 'p5.sound'
},
mult: {
name: 'mult',
params: [
{
name: 'number',
description: '<p>Constant number to multiply</p>\n',
type: 'Number'
}
],
class: 'p5.Envelope',
module: 'p5.sound'
},
scale: {
name: 'scale',
params: [
{
name: 'inMin',
description: '<p>input range minumum</p>\n',
type: 'Number'
},
{
name: 'inMax',
description: '<p>input range maximum</p>\n',
type: 'Number'
},
{
name: 'outMin',
description: '<p>input range minumum</p>\n',
type: 'Number'
},
{
name: 'outMax',
description: '<p>input range maximum</p>\n',
type: 'Number'
}
],
class: 'p5.Envelope',
module: 'p5.sound'
}
},
'p5.Pulse': {
width: {
name: 'width',
params: [
{
name: 'width',
description:
'<p>Width between the pulses (0 to 1.0,\n defaults to 0)</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Pulse',
module: 'p5.sound'
}
},
'p5.Noise': {
setType: {
name: 'setType',
params: [
{
name: 'type',
description: "<p>'white', 'pink' or 'brown'</p>\n",
type: 'String',
optional: true
}
],
class: 'p5.Noise',
module: 'p5.sound'
}
},
'p5.AudioIn': {
input: {
name: 'input',
class: 'p5.AudioIn',
module: 'p5.sound'
},
output: {
name: 'output',
class: 'p5.AudioIn',
module: 'p5.sound'
},
stream: {
name: 'stream',
class: 'p5.AudioIn',
module: 'p5.sound'
},
mediaStream: {
name: 'mediaStream',
class: 'p5.AudioIn',
module: 'p5.sound'
},
currentSource: {
name: 'currentSource',
class: 'p5.AudioIn',
module: 'p5.sound'
},
enabled: {
name: 'enabled',
class: 'p5.AudioIn',
module: 'p5.sound'
},
amplitude: {
name: 'amplitude',
class: 'p5.AudioIn',
module: 'p5.sound'
},
start: {
name: 'start',
params: [
{
name: 'successCallback',
description:
'<p>Name of a function to call on\n success.</p>\n',
type: 'Function',
optional: true
},
{
name: 'errorCallback',
description:
'<p>Name of a function to call if\n there was an error. For example,\n some browsers do not support\n getUserMedia.</p>\n',
type: 'Function',
optional: true
}
],
class: 'p5.AudioIn',
module: 'p5.sound'
},
stop: {
name: 'stop',
class: 'p5.AudioIn',
module: 'p5.sound'
},
connect: {
name: 'connect',
params: [
{
name: 'unit',
description:
'<p>An object that accepts audio input,\n such as an FFT</p>\n',
type: 'Object',
optional: true
}
],
class: 'p5.AudioIn',
module: 'p5.sound'
},
disconnect: {
name: 'disconnect',
class: 'p5.AudioIn',
module: 'p5.sound'
},
getLevel: {
name: 'getLevel',
params: [
{
name: 'smoothing',
description:
'<p>Smoothing is 0.0 by default.\n Smooths values based on previous values.</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.AudioIn',
module: 'p5.sound'
},
amp: {
name: 'amp',
params: [
{
name: 'vol',
description: '<p>between 0 and 1.0</p>\n',
type: 'Number'
},
{
name: 'time',
description: '<p>ramp time (optional)</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.AudioIn',
module: 'p5.sound'
},
getSources: {
name: 'getSources',
params: [
{
name: 'successCallback',
description:
'<p>This callback function handles the sources when they\n have been enumerated. The callback function\n receives the deviceList array as its only argument</p>\n',
type: 'Function',
optional: true
},
{
name: 'errorCallback',
description:
'<p>This optional callback receives the error\n message as its argument.</p>\n',
type: 'Function',
optional: true
}
],
class: 'p5.AudioIn',
module: 'p5.sound'
},
setSource: {
name: 'setSource',
params: [
{
name: 'num',
description: '<p>position of input source in the array</p>\n',
type: 'Number'
}
],
class: 'p5.AudioIn',
module: 'p5.sound'
}
},
'p5.EQ': {
bands: {
name: 'bands',
class: 'p5.EQ',
module: 'p5.sound'
},
process: {
name: 'process',
params: [
{
name: 'src',
description: '<p>Audio source</p>\n',
type: 'Object'
}
],
class: 'p5.EQ',
module: 'p5.sound'
}
},
'p5.Panner3D': {
panner: {
name: 'panner',
class: 'p5.Panner3D',
module: 'p5.sound'
},
process: {
name: 'process',
params: [
{
name: 'src',
description: '<p>Input source</p>\n',
type: 'Object'
}
],
class: 'p5.Panner3D',
module: 'p5.sound'
},
set: {
name: 'set',
params: [
{
name: 'xVal',
description: '',
type: 'Number'
},
{
name: 'yVal',
description: '',
type: 'Number'
},
{
name: 'zVal',
description: '',
type: 'Number'
},
{
name: 'time',
description: '',
type: 'Number'
}
],
class: 'p5.Panner3D',
module: 'p5.sound'
},
positionX: {
name: 'positionX',
class: 'p5.Panner3D',
module: 'p5.sound'
},
positionY: {
name: 'positionY',
class: 'p5.Panner3D',
module: 'p5.sound'
},
positionZ: {
name: 'positionZ',
class: 'p5.Panner3D',
module: 'p5.sound'
},
orient: {
name: 'orient',
params: [
{
name: 'xVal',
description: '',
type: 'Number'
},
{
name: 'yVal',
description: '',
type: 'Number'
},
{
name: 'zVal',
description: '',
type: 'Number'
},
{
name: 'time',
description: '',
type: 'Number'
}
],
class: 'p5.Panner3D',
module: 'p5.sound'
},
orientX: {
name: 'orientX',
class: 'p5.Panner3D',
module: 'p5.sound'
},
orientY: {
name: 'orientY',
class: 'p5.Panner3D',
module: 'p5.sound'
},
orientZ: {
name: 'orientZ',
class: 'p5.Panner3D',
module: 'p5.sound'
},
setFalloff: {
name: 'setFalloff',
params: [
{
name: 'maxDistance',
description: '',
type: 'Number',
optional: true
},
{
name: 'rolloffFactor',
description: '',
type: 'Number',
optional: true
}
],
class: 'p5.Panner3D',
module: 'p5.sound'
},
maxDist: {
name: 'maxDist',
params: [
{
name: 'maxDistance',
description: '',
type: 'Number'
}
],
class: 'p5.Panner3D',
module: 'p5.sound'
},
rollof: {
name: 'rollof',
params: [
{
name: 'rolloffFactor',
description: '',
type: 'Number'
}
],
class: 'p5.Panner3D',
module: 'p5.sound'
}
},
'p5.Delay': {
leftDelay: {
name: 'leftDelay',
class: 'p5.Delay',
module: 'p5.sound'
},
rightDelay: {
name: 'rightDelay',
class: 'p5.Delay',
module: 'p5.sound'
},
process: {
name: 'process',
params: [
{
name: 'Signal',
description: '<p>An object that outputs audio</p>\n',
type: 'Object'
},
{
name: 'delayTime',
description:
'<p>Time (in seconds) of the delay/echo.\n Some browsers limit delayTime to\n 1 second.</p>\n',
type: 'Number',
optional: true
},
{
name: 'feedback',
description:
'<p>sends the delay back through itself\n in a loop that decreases in volume\n each time.</p>\n',
type: 'Number',
optional: true
},
{
name: 'lowPass',
description:
'<p>Cutoff frequency. Only frequencies\n below the lowPass will be part of the\n delay.</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Delay',
module: 'p5.sound'
},
delayTime: {
name: 'delayTime',
params: [
{
name: 'delayTime',
description: '<p>Time (in seconds) of the delay</p>\n',
type: 'Number'
}
],
class: 'p5.Delay',
module: 'p5.sound'
},
feedback: {
name: 'feedback',
params: [
{
name: 'feedback',
description:
'<p>0.0 to 1.0, or an object such as an\n Oscillator that can be used to\n modulate this param</p>\n',
type: 'Number|Object'
}
],
class: 'p5.Delay',
module: 'p5.sound'
},
filter: {
name: 'filter',
params: [
{
name: 'cutoffFreq',
description:
'<p>A lowpass filter will cut off any\n frequencies higher than the filter frequency.</p>\n',
type: 'Number|Object'
},
{
name: 'res',
description:
'<p>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.</p>\n',
type: 'Number|Object'
}
],
class: 'p5.Delay',
module: 'p5.sound'
},
setType: {
name: 'setType',
params: [
{
name: 'type',
description: "<p>'pingPong' (1) or 'default' (0)</p>\n",
type: 'String|Number'
}
],
class: 'p5.Delay',
module: 'p5.sound'
},
amp: {
name: 'amp',
params: [
{
name: 'volume',
description: '<p>amplitude between 0 and 1.0</p>\n',
type: 'Number'
},
{
name: 'rampTime',
description: '<p>create a fade that lasts rampTime</p>\n',
type: 'Number',
optional: true
},
{
name: 'timeFromNow',
description:
'<p>schedule this event to happen\n seconds from now</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Delay',
module: 'p5.sound'
},
connect: {
name: 'connect',
params: [
{
name: 'unit',
description: '',
type: 'Object'
}
],
class: 'p5.Delay',
module: 'p5.sound'
},
disconnect: {
name: 'disconnect',
class: 'p5.Delay',
module: 'p5.sound'
}
},
'p5.Reverb': {
process: {
name: 'process',
params: [
{
name: 'src',
description:
'<p>p5.sound / Web Audio object with a sound\n output.</p>\n',
type: 'Object'
},
{
name: 'seconds',
description:
'<p>Duration of the reverb, in seconds.\n Min: 0, Max: 10. Defaults to 3.</p>\n',
type: 'Number',
optional: true
},
{
name: 'decayRate',
description:
'<p>Percentage of decay with each echo.\n Min: 0, Max: 100. Defaults to 2.</p>\n',
type: 'Number',
optional: true
},
{
name: 'reverse',
description: '<p>Play the reverb backwards or forwards.</p>\n',
type: 'Boolean',
optional: true
}
],
class: 'p5.Reverb',
module: 'p5.sound'
},
set: {
name: 'set',
params: [
{
name: 'seconds',
description:
'<p>Duration of the reverb, in seconds.\n Min: 0, Max: 10. Defaults to 3.</p>\n',
type: 'Number',
optional: true
},
{
name: 'decayRate',
description:
'<p>Percentage of decay with each echo.\n Min: 0, Max: 100. Defaults to 2.</p>\n',
type: 'Number',
optional: true
},
{
name: 'reverse',
description: '<p>Play the reverb backwards or forwards.</p>\n',
type: 'Boolean',
optional: true
}
],
class: 'p5.Reverb',
module: 'p5.sound'
},
amp: {
name: 'amp',
params: [
{
name: 'volume',
description: '<p>amplitude between 0 and 1.0</p>\n',
type: 'Number'
},
{
name: 'rampTime',
description: '<p>create a fade that lasts rampTime</p>\n',
type: 'Number',
optional: true
},
{
name: 'timeFromNow',
description:
'<p>schedule this event to happen\n seconds from now</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Reverb',
module: 'p5.sound'
},
connect: {
name: 'connect',
params: [
{
name: 'unit',
description: '',
type: 'Object'
}
],
class: 'p5.Reverb',
module: 'p5.sound'
},
disconnect: {
name: 'disconnect',
class: 'p5.Reverb',
module: 'p5.sound'
}
},
'p5.Convolver': {
convolverNode: {
name: 'convolverNode',
class: 'p5.Convolver',
module: 'p5.sound'
},
process: {
name: 'process',
params: [
{
name: 'src',
description:
'<p>p5.sound / Web Audio object with a sound\n output.</p>\n',
type: 'Object'
}
],
class: 'p5.Convolver',
module: 'p5.sound'
},
impulses: {
name: 'impulses',
class: 'p5.Convolver',
module: 'p5.sound'
},
addImpulse: {
name: 'addImpulse',
params: [
{
name: 'path',
description: '<p>path to a sound file</p>\n',
type: 'String'
},
{
name: 'callback',
description: '<p>function (optional)</p>\n',
type: 'Function'
},
{
name: 'errorCallback',
description: '<p>function (optional)</p>\n',
type: 'Function'
}
],
class: 'p5.Convolver',
module: 'p5.sound'
},
resetImpulse: {
name: 'resetImpulse',
params: [
{
name: 'path',
description: '<p>path to a sound file</p>\n',
type: 'String'
},
{
name: 'callback',
description: '<p>function (optional)</p>\n',
type: 'Function'
},
{
name: 'errorCallback',
description: '<p>function (optional)</p>\n',
type: 'Function'
}
],
class: 'p5.Convolver',
module: 'p5.sound'
},
toggleImpulse: {
name: 'toggleImpulse',
params: [
{
name: 'id',
description:
'<p>Identify the impulse by its original filename\n (String), or by its position in the\n <code>.impulses</code> Array (Number).</p>\n',
type: 'String|Number'
}
],
class: 'p5.Convolver',
module: 'p5.sound'
}
},
'p5.Phrase': {
sequence: {
name: 'sequence',
class: 'p5.Phrase',
module: 'p5.sound'
}
},
'p5.Part': {
setBPM: {
name: 'setBPM',
params: [
{
name: 'BPM',
description: '<p>Beats Per Minute</p>\n',
type: 'Number'
},
{
name: 'rampTime',
description: '<p>Seconds from now</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Part',
module: 'p5.sound'
},
getBPM: {
name: 'getBPM',
class: 'p5.Part',
module: 'p5.sound'
},
start: {
name: 'start',
params: [
{
name: 'time',
description: '<p>seconds from now</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Part',
module: 'p5.sound'
},
loop: {
name: 'loop',
params: [
{
name: 'time',
description: '<p>seconds from now</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Part',
module: 'p5.sound'
},
noLoop: {
name: 'noLoop',
class: 'p5.Part',
module: 'p5.sound'
},
stop: {
name: 'stop',
params: [
{
name: 'time',
description: '<p>seconds from now</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Part',
module: 'p5.sound'
},
pause: {
name: 'pause',
params: [
{
name: 'time',
description: '<p>seconds from now</p>\n',
type: 'Number'
}
],
class: 'p5.Part',
module: 'p5.sound'
},
addPhrase: {
name: 'addPhrase',
params: [
{
name: 'phrase',
description: '<p>reference to a p5.Phrase</p>\n',
type: 'p5.Phrase'
}
],
class: 'p5.Part',
module: 'p5.sound'
},
removePhrase: {
name: 'removePhrase',
params: [
{
name: 'phraseName',
description: '',
type: 'String'
}
],
class: 'p5.Part',
module: 'p5.sound'
},
getPhrase: {
name: 'getPhrase',
params: [
{
name: 'phraseName',
description: '',
type: 'String'
}
],
class: 'p5.Part',
module: 'p5.sound'
},
replaceSequence: {
name: 'replaceSequence',
params: [
{
name: 'phraseName',
description: '',
type: 'String'
},
{
name: 'sequence',
description:
'<p>Array of values to pass into the callback\n at each step of the phrase.</p>\n',
type: 'Array'
}
],
class: 'p5.Part',
module: 'p5.sound'
},
onStep: {
name: 'onStep',
params: [
{
name: 'callback',
description:
'<p>The name of the callback\n you want to fire\n on every beat/tatum.</p>\n',
type: 'Function'
}
],
class: 'p5.Part',
module: 'p5.sound'
}
},
'p5.Score': {
start: {
name: 'start',
class: 'p5.Score',
module: 'p5.sound'
},
stop: {
name: 'stop',
class: 'p5.Score',
module: 'p5.sound'
},
pause: {
name: 'pause',
class: 'p5.Score',
module: 'p5.sound'
},
loop: {
name: 'loop',
class: 'p5.Score',
module: 'p5.sound'
},
noLoop: {
name: 'noLoop',
class: 'p5.Score',
module: 'p5.sound'
},
setBPM: {
name: 'setBPM',
params: [
{
name: 'BPM',
description: '<p>Beats Per Minute</p>\n',
type: 'Number'
},
{
name: 'rampTime',
description: '<p>Seconds from now</p>\n',
type: 'Number'
}
],
class: 'p5.Score',
module: 'p5.sound'
}
},
'p5.SoundLoop': {
musicalTimeMode: {
name: 'musicalTimeMode',
class: 'p5.SoundLoop',
module: 'p5.sound'
},
maxIterations: {
name: 'maxIterations',
class: 'p5.SoundLoop',
module: 'p5.sound'
},
start: {
name: 'start',
params: [
{
name: 'timeFromNow',
description: '<p>schedule a starting time</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.SoundLoop',
module: 'p5.sound'
},
stop: {
name: 'stop',
params: [
{
name: 'timeFromNow',
description: '<p>schedule a stopping time</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.SoundLoop',
module: 'p5.sound'
},
pause: {
name: 'pause',
params: [
{
name: 'timeFromNow',
description: '<p>schedule a pausing time</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.SoundLoop',
module: 'p5.sound'
},
syncedStart: {
name: 'syncedStart',
params: [
{
name: 'otherLoop',
description: '<p>a p5.SoundLoop to sync with</p>\n',
type: 'Object'
},
{
name: 'timeFromNow',
description:
'<p>Start the loops in sync after timeFromNow seconds</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.SoundLoop',
module: 'p5.sound'
},
bpm: {
name: 'bpm',
class: 'p5.SoundLoop',
module: 'p5.sound'
},
timeSignature: {
name: 'timeSignature',
class: 'p5.SoundLoop',
module: 'p5.sound'
},
interval: {
name: 'interval',
class: 'p5.SoundLoop',
module: 'p5.sound'
},
iterations: {
name: 'iterations',
class: 'p5.SoundLoop',
module: 'p5.sound'
}
},
'p5.Compressor': {
compressor: {
name: 'compressor',
class: 'p5.Compressor',
module: 'p5.sound'
},
process: {
name: 'process',
params: [
{
name: 'src',
description: '<p>Sound source to be connected</p>\n',
type: 'Object'
},
{
name: 'attack',
description:
'<p>The amount of time (in seconds) to reduce the gain by 10dB,\n default = .003, range 0 - 1</p>\n',
type: 'Number',
optional: true
},
{
name: 'knee',
description:
'<p>A decibel value representing the range above the\n threshold where the curve smoothly transitions to the "ratio" portion.\n default = 30, range 0 - 40</p>\n',
type: 'Number',
optional: true
},
{
name: 'ratio',
description:
'<p>The amount of dB change in input for a 1 dB change in output\n default = 12, range 1 - 20</p>\n',
type: 'Number',
optional: true
},
{
name: 'threshold',
description:
'<p>The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0</p>\n',
type: 'Number',
optional: true
},
{
name: 'release',
description:
'<p>The amount of time (in seconds) to increase the gain by 10dB\n default = .25, range 0 - 1</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Compressor',
module: 'p5.sound'
},
set: {
name: 'set',
params: [
{
name: 'attack',
description:
'<p>The amount of time (in seconds) to reduce the gain by 10dB,\n default = .003, range 0 - 1</p>\n',
type: 'Number'
},
{
name: 'knee',
description:
'<p>A decibel value representing the range above the\n threshold where the curve smoothly transitions to the "ratio" portion.\n default = 30, range 0 - 40</p>\n',
type: 'Number'
},
{
name: 'ratio',
description:
'<p>The amount of dB change in input for a 1 dB change in output\n default = 12, range 1 - 20</p>\n',
type: 'Number'
},
{
name: 'threshold',
description:
'<p>The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0</p>\n',
type: 'Number'
},
{
name: 'release',
description:
'<p>The amount of time (in seconds) to increase the gain by 10dB\n default = .25, range 0 - 1</p>\n',
type: 'Number'
}
],
class: 'p5.Compressor',
module: 'p5.sound'
},
attack: {
name: 'attack',
params: [
{
name: 'attack',
description:
'<p>Attack is the amount of time (in seconds) to reduce the gain by 10dB,\n default = .003, range 0 - 1</p>\n',
type: 'Number',
optional: true
},
{
name: 'time',
description:
'<p>Assign time value to schedule the change in value</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Compressor',
module: 'p5.sound'
},
knee: {
name: 'knee',
params: [
{
name: 'knee',
description:
'<p>A decibel value representing the range above the\n threshold where the curve smoothly transitions to the "ratio" portion.\n default = 30, range 0 - 40</p>\n',
type: 'Number',
optional: true
},
{
name: 'time',
description:
'<p>Assign time value to schedule the change in value</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Compressor',
module: 'p5.sound'
},
ratio: {
name: 'ratio',
params: [
{
name: 'ratio',
description:
'<p>The amount of dB change in input for a 1 dB change in output\n default = 12, range 1 - 20</p>\n',
type: 'Number',
optional: true
},
{
name: 'time',
description:
'<p>Assign time value to schedule the change in value</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Compressor',
module: 'p5.sound'
},
threshold: {
name: 'threshold',
params: [
{
name: 'threshold',
description:
'<p>The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0</p>\n',
type: 'Number'
},
{
name: 'time',
description:
'<p>Assign time value to schedule the change in value</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Compressor',
module: 'p5.sound'
},
release: {
name: 'release',
params: [
{
name: 'release',
description:
'<p>The amount of time (in seconds) to increase the gain by 10dB\n default = .25, range 0 - 1</p>\n',
type: 'Number'
},
{
name: 'time',
description:
'<p>Assign time value to schedule the change in value</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Compressor',
module: 'p5.sound'
},
reduction: {
name: 'reduction',
class: 'p5.Compressor',
module: 'p5.sound'
}
},
'p5.SoundRecorder': {
setInput: {
name: 'setInput',
params: [
{
name: 'unit',
description:
'<p>p5.sound object or a web audio unit\n that outputs sound</p>\n',
type: 'Object',
optional: true
}
],
class: 'p5.SoundRecorder',
module: 'p5.sound'
},
record: {
name: 'record',
params: [
{
name: 'soundFile',
description: '<p>p5.SoundFile</p>\n',
type: 'p5.SoundFile'
},
{
name: 'duration',
description: '<p>Time (in seconds)</p>\n',
type: 'Number',
optional: true
},
{
name: 'callback',
description:
'<p>The name of a function that will be\n called once the recording completes</p>\n',
type: 'Function',
optional: true
}
],
class: 'p5.SoundRecorder',
module: 'p5.sound'
},
stop: {
name: 'stop',
class: 'p5.SoundRecorder',
module: 'p5.sound'
}
},
'p5.PeakDetect': {
isDetected: {
name: 'isDetected',
class: 'p5.PeakDetect',
module: 'p5.sound'
},
update: {
name: 'update',
params: [
{
name: 'fftObject',
description: '<p>A p5.FFT object</p>\n',
type: 'p5.FFT'
}
],
class: 'p5.PeakDetect',
module: 'p5.sound'
},
onPeak: {
name: 'onPeak',
params: [
{
name: 'callback',
description:
'<p>Name of a function that will\n be called when a peak is\n detected.</p>\n',
type: 'Function'
},
{
name: 'val',
description:
'<p>Optional value to pass\n into the function when\n a peak is detected.</p>\n',
type: 'Object',
optional: true
}
],
class: 'p5.PeakDetect',
module: 'p5.sound'
}
},
'p5.Gain': {
setInput: {
name: 'setInput',
params: [
{
name: 'src',
description:
'<p>p5.sound / Web Audio object with a sound\n output.</p>\n',
type: 'Object'
}
],
class: 'p5.Gain',
module: 'p5.sound'
},
connect: {
name: 'connect',
params: [
{
name: 'unit',
description: '',
type: 'Object'
}
],
class: 'p5.Gain',
module: 'p5.sound'
},
disconnect: {
name: 'disconnect',
class: 'p5.Gain',
module: 'p5.sound'
},
amp: {
name: 'amp',
params: [
{
name: 'volume',
description: '<p>amplitude between 0 and 1.0</p>\n',
type: 'Number'
},
{
name: 'rampTime',
description: '<p>create a fade that lasts rampTime</p>\n',
type: 'Number',
optional: true
},
{
name: 'timeFromNow',
description:
'<p>schedule this event to happen\n seconds from now</p>\n',
type: 'Number',
optional: true
}
],
class: 'p5.Gain',
module: 'p5.sound'
}
},
'p5.Distortion': {
WaveShaperNode: {
name: 'WaveShaperNode',
class: 'p5.Distortion',
module: 'p5.sound'
},
process: {
name: 'process',
params: [
{
name: 'amount',
description:
'<p>Unbounded distortion amount.\n Normal values range from 0-1.</p>\n',
type: 'Number',
optional: true,
optdefault: '0.25'
},
{
name: 'oversample',
description: "<p>'none', '2x', or '4x'.</p>\n",
type: 'String',
optional: true,
optdefault: "'none'"
}
],
class: 'p5.Distortion',
module: 'p5.sound'
},
set: {
name: 'set',
params: [
{
name: 'amount',
description:
'<p>Unbounded distortion amount.\n Normal values range from 0-1.</p>\n',
type: 'Number',
optional: true,
optdefault: '0.25'
},
{
name: 'oversample',
description: "<p>'none', '2x', or '4x'.</p>\n",
type: 'String',
optional: true,
optdefault: "'none'"
}
],
class: 'p5.Distortion',
module: 'p5.sound'
},
getAmount: {
name: 'getAmount',
class: 'p5.Distortion',
module: 'p5.sound'
},
getOversample: {
name: 'getOversample',
class: 'p5.Distortion',
module: 'p5.sound'
}
}
};
},
{}
],
2: [
function(_dereq_, module, exports) {
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
module.exports = _arrayWithHoles;
},
{}
],
3: [
function(_dereq_, module, exports) {
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
arr2[i] = arr[i];
}
return arr2;
}
}
module.exports = _arrayWithoutHoles;
},
{}
],
4: [
function(_dereq_, module, exports) {
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError(
"this hasn't been initialised - super() hasn't been called"
);
}
return self;
}
module.exports = _assertThisInitialized;
},
{}
],
5: [
function(_dereq_, module, exports) {
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError('Cannot call a class as a function');
}
}
module.exports = _classCallCheck;
},
{}
],
6: [
function(_dereq_, module, exports) {
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ('value' in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
module.exports = _createClass;
},
{}
],
7: [
function(_dereq_, module, exports) {
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
module.exports = _defineProperty;
},
{}
],
8: [
function(_dereq_, module, exports) {
function _getPrototypeOf(o) {
module.exports = _getPrototypeOf = Object.setPrototypeOf
? Object.getPrototypeOf
: function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
module.exports = _getPrototypeOf;
},
{}
],
9: [
function(_dereq_, module, exports) {
var setPrototypeOf = _dereq_('./setPrototypeOf');
function _inherits(subClass, superClass) {
if (typeof superClass !== 'function' && superClass !== null) {
throw new TypeError('Super expression must either be null or a function');
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) setPrototypeOf(subClass, superClass);
}
module.exports = _inherits;
},
{ './setPrototypeOf': 16 }
],
10: [
function(_dereq_, module, exports) {
function _iterableToArray(iter) {
if (
Symbol.iterator in Object(iter) ||
Object.prototype.toString.call(iter) === '[object Arguments]'
)
return Array.from(iter);
}
module.exports = _iterableToArray;
},
{}
],
11: [
function(_dereq_, module, exports) {
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (
var _i = arr[Symbol.iterator](), _s;
!(_n = (_s = _i.next()).done);
_n = true
) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i['return'] != null) _i['return']();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
module.exports = _iterableToArrayLimit;
},
{}
],
12: [
function(_dereq_, module, exports) {
function _nonIterableRest() {
throw new TypeError('Invalid attempt to destructure non-iterable instance');
}
module.exports = _nonIterableRest;
},
{}
],
13: [
function(_dereq_, module, exports) {
function _nonIterableSpread() {
throw new TypeError('Invalid attempt to spread non-iterable instance');
}
module.exports = _nonIterableSpread;
},
{}
],
14: [
function(_dereq_, module, exports) {
var defineProperty = _dereq_('./defineProperty');
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === 'function') {
ownKeys = ownKeys.concat(
Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
})
);
}
ownKeys.forEach(function(key) {
defineProperty(target, key, source[key]);
});
}
return target;
}
module.exports = _objectSpread;
},
{ './defineProperty': 7 }
],
15: [
function(_dereq_, module, exports) {
var _typeof = _dereq_('../helpers/typeof');
var assertThisInitialized = _dereq_('./assertThisInitialized');
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === 'object' || typeof call === 'function')) {
return call;
}
return assertThisInitialized(self);
}
module.exports = _possibleConstructorReturn;
},
{ '../helpers/typeof': 19, './assertThisInitialized': 4 }
],
16: [
function(_dereq_, module, exports) {
function _setPrototypeOf(o, p) {
module.exports = _setPrototypeOf =
Object.setPrototypeOf ||
function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
module.exports = _setPrototypeOf;
},
{}
],
17: [
function(_dereq_, module, exports) {
var arrayWithHoles = _dereq_('./arrayWithHoles');
var iterableToArrayLimit = _dereq_('./iterableToArrayLimit');
var nonIterableRest = _dereq_('./nonIterableRest');
function _slicedToArray(arr, i) {
return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest();
}
module.exports = _slicedToArray;
},
{ './arrayWithHoles': 2, './iterableToArrayLimit': 11, './nonIterableRest': 12 }
],
18: [
function(_dereq_, module, exports) {
var arrayWithoutHoles = _dereq_('./arrayWithoutHoles');
var iterableToArray = _dereq_('./iterableToArray');
var nonIterableSpread = _dereq_('./nonIterableSpread');
function _toConsumableArray(arr) {
return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread();
}
module.exports = _toConsumableArray;
},
{ './arrayWithoutHoles': 3, './iterableToArray': 10, './nonIterableSpread': 13 }
],
19: [
function(_dereq_, module, exports) {
function _typeof2(obj) {
if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {
_typeof2 = function _typeof2(obj) {
return typeof obj;
};
} else {
_typeof2 = function _typeof2(obj) {
return obj &&
typeof Symbol === 'function' &&
obj.constructor === Symbol &&
obj !== Symbol.prototype
? 'symbol'
: typeof obj;
};
}
return _typeof2(obj);
}
function _typeof(obj) {
if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') {
module.exports = _typeof = function _typeof(obj) {
return _typeof2(obj);
};
} else {
module.exports = _typeof = function _typeof(obj) {
return obj &&
typeof Symbol === 'function' &&
obj.constructor === Symbol &&
obj !== Symbol.prototype
? 'symbol'
: _typeof2(obj);
};
}
return _typeof(obj);
}
module.exports = _typeof;
},
{}
],
20: [
function(_dereq_, module, exports) {
'use strict';
exports.byteLength = byteLength;
exports.toByteArray = toByteArray;
exports.fromByteArray = fromByteArray;
var lookup = [];
var revLookup = [];
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i];
revLookup[code.charCodeAt(i)] = i;
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62;
revLookup['_'.charCodeAt(0)] = 63;
function getLens(b64) {
var len = b64.length;
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4');
}
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
var validLen = b64.indexOf('=');
if (validLen === -1) validLen = len;
var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4;
return [validLen, placeHoldersLen];
}
// base64 is 4/3 + up to two characters of the original data
function byteLength(b64) {
var lens = getLens(b64);
var validLen = lens[0];
var placeHoldersLen = lens[1];
return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
}
function _byteLength(b64, validLen, placeHoldersLen) {
return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
}
function toByteArray(b64) {
var tmp;
var lens = getLens(b64);
var validLen = lens[0];
var placeHoldersLen = lens[1];
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
var curByte = 0;
// if there are placeholders, only get up to the last complete 4 chars
var len = placeHoldersLen > 0 ? validLen - 4 : validLen;
var i;
for (i = 0; i < len; i += 4) {
tmp =
(revLookup[b64.charCodeAt(i)] << 18) |
(revLookup[b64.charCodeAt(i + 1)] << 12) |
(revLookup[b64.charCodeAt(i + 2)] << 6) |
revLookup[b64.charCodeAt(i + 3)];
arr[curByte++] = (tmp >> 16) & 0xff;
arr[curByte++] = (tmp >> 8) & 0xff;
arr[curByte++] = tmp & 0xff;
}
if (placeHoldersLen === 2) {
tmp =
(revLookup[b64.charCodeAt(i)] << 2) |
(revLookup[b64.charCodeAt(i + 1)] >> 4);
arr[curByte++] = tmp & 0xff;
}
if (placeHoldersLen === 1) {
tmp =
(revLookup[b64.charCodeAt(i)] << 10) |
(revLookup[b64.charCodeAt(i + 1)] << 4) |
(revLookup[b64.charCodeAt(i + 2)] >> 2);
arr[curByte++] = (tmp >> 8) & 0xff;
arr[curByte++] = tmp & 0xff;
}
return arr;
}
function tripletToBase64(num) {
return (
lookup[(num >> 18) & 0x3f] +
lookup[(num >> 12) & 0x3f] +
lookup[(num >> 6) & 0x3f] +
lookup[num & 0x3f]
);
}
function encodeChunk(uint8, start, end) {
var tmp;
var output = [];
for (var i = start; i < end; i += 3) {
tmp =
((uint8[i] << 16) & 0xff0000) +
((uint8[i + 1] << 8) & 0xff00) +
(uint8[i + 2] & 0xff);
output.push(tripletToBase64(tmp));
}
return output.join('');
}
function fromByteArray(uint8) {
var tmp;
var len = uint8.length;
var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
var parts = [];
var maxChunkLength = 16383; // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(
encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)
);
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1];
parts.push(lookup[tmp >> 2] + lookup[(tmp << 4) & 0x3f] + '==');
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1];
parts.push(
lookup[tmp >> 10] +
lookup[(tmp >> 4) & 0x3f] +
lookup[(tmp << 2) & 0x3f] +
'='
);
}
return parts.join('');
}
},
{}
],
21: [function(_dereq_, module, exports) {}, {}],
22: [
function(_dereq_, module, exports) {
(function(Buffer) {
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict';
var base64 = _dereq_('base64-js');
var ieee754 = _dereq_('ieee754');
var customInspectSymbol =
typeof Symbol === 'function' && typeof Symbol.for === 'function'
? Symbol.for('nodejs.util.inspect.custom')
: null;
exports.Buffer = Buffer;
exports.SlowBuffer = SlowBuffer;
exports.INSPECT_MAX_BYTES = 50;
var K_MAX_LENGTH = 0x7fffffff;
exports.kMaxLength = K_MAX_LENGTH;
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport();
if (
!Buffer.TYPED_ARRAY_SUPPORT &&
typeof console !== 'undefined' &&
typeof console.error === 'function'
) {
console.error(
'This browser lacks typed array (Uint8Array) support which is required by ' +
'`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
);
}
function typedArraySupport() {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1);
var proto = {
foo: function() {
return 42;
}
};
Object.setPrototypeOf(proto, Uint8Array.prototype);
Object.setPrototypeOf(arr, proto);
return arr.foo() === 42;
} catch (e) {
return false;
}
}
Object.defineProperty(Buffer.prototype, 'parent', {
enumerable: true,
get: function() {
if (!Buffer.isBuffer(this)) return undefined;
return this.buffer;
}
});
Object.defineProperty(Buffer.prototype, 'offset', {
enumerable: true,
get: function() {
if (!Buffer.isBuffer(this)) return undefined;
return this.byteOffset;
}
});
function createBuffer(length) {
if (length > K_MAX_LENGTH) {
throw new RangeError(
'The value "' + length + '" is invalid for option "size"'
);
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length);
Object.setPrototypeOf(buf, Buffer.prototype);
return buf;
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer(arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new TypeError(
'The "string" argument must be of type string. Received type number'
);
}
return allocUnsafe(arg);
}
return from(arg, encodingOrOffset, length);
}
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (
typeof Symbol !== 'undefined' &&
Symbol.species != null &&
Buffer[Symbol.species] === Buffer
) {
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true,
enumerable: false,
writable: false
});
}
Buffer.poolSize = 8192; // not used by this implementation
function from(value, encodingOrOffset, length) {
if (typeof value === 'string') {
return fromString(value, encodingOrOffset);
}
if (ArrayBuffer.isView(value)) {
return fromArrayLike(value);
}
if (value == null) {
throw new TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' +
typeof value
);
}
if (
isInstance(value, ArrayBuffer) ||
(value && isInstance(value.buffer, ArrayBuffer))
) {
return fromArrayBuffer(value, encodingOrOffset, length);
}
if (typeof value === 'number') {
throw new TypeError(
'The "value" argument must not be of type number. Received type number'
);
}
var valueOf = value.valueOf && value.valueOf();
if (valueOf != null && valueOf !== value) {
return Buffer.from(valueOf, encodingOrOffset, length);
}
var b = fromObject(value);
if (b) return b;
if (
typeof Symbol !== 'undefined' &&
Symbol.toPrimitive != null &&
typeof value[Symbol.toPrimitive] === 'function'
) {
return Buffer.from(
value[Symbol.toPrimitive]('string'),
encodingOrOffset,
length
);
}
throw new TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' +
typeof value
);
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function(value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length);
};
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype);
Object.setPrototypeOf(Buffer, Uint8Array);
function assertSize(size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be of type number');
} else if (size < 0) {
throw new RangeError(
'The value "' + size + '" is invalid for option "size"'
);
}
}
function alloc(size, fill, encoding) {
assertSize(size);
if (size <= 0) {
return createBuffer(size);
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(size).fill(fill, encoding)
: createBuffer(size).fill(fill);
}
return createBuffer(size);
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function(size, fill, encoding) {
return alloc(size, fill, encoding);
};
function allocUnsafe(size) {
assertSize(size);
return createBuffer(size < 0 ? 0 : checked(size) | 0);
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function(size) {
return allocUnsafe(size);
};
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function(size) {
return allocUnsafe(size);
};
function fromString(string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8';
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding);
}
var length = byteLength(string, encoding) | 0;
var buf = createBuffer(length);
var actual = buf.write(string, encoding);
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual);
}
return buf;
}
function fromArrayLike(array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0;
var buf = createBuffer(length);
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255;
}
return buf;
}
function fromArrayBuffer(array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('"offset" is outside of buffer bounds');
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('"length" is outside of buffer bounds');
}
var buf;
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array);
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset);
} else {
buf = new Uint8Array(array, byteOffset, length);
}
// Return an augmented `Uint8Array` instance
Object.setPrototypeOf(buf, Buffer.prototype);
return buf;
}
function fromObject(obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0;
var buf = createBuffer(len);
if (buf.length === 0) {
return buf;
}
obj.copy(buf, 0, 0, len);
return buf;
}
if (obj.length !== undefined) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0);
}
return fromArrayLike(obj);
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data);
}
}
function checked(length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError(
'Attempt to allocate Buffer larger than maximum ' +
'size: 0x' +
K_MAX_LENGTH.toString(16) +
' bytes'
);
}
return length | 0;
}
function SlowBuffer(length) {
if (+length != length) {
// eslint-disable-line eqeqeq
length = 0;
}
return Buffer.alloc(+length);
}
Buffer.isBuffer = function isBuffer(b) {
return b != null && b._isBuffer === true && b !== Buffer.prototype; // so Buffer.isBuffer(Buffer.prototype) will be false
};
Buffer.compare = function compare(a, b) {
if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength);
if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength);
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError(
'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
);
}
if (a === b) return 0;
var x = a.length;
var y = b.length;
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i];
y = b[i];
break;
}
}
if (x < y) return -1;
if (y < x) return 1;
return 0;
};
Buffer.isEncoding = function isEncoding(encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true;
default:
return false;
}
};
Buffer.concat = function concat(list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers');
}
if (list.length === 0) {
return Buffer.alloc(0);
}
var i;
if (length === undefined) {
length = 0;
for (i = 0; i < list.length; ++i) {
length += list[i].length;
}
}
var buffer = Buffer.allocUnsafe(length);
var pos = 0;
for (i = 0; i < list.length; ++i) {
var buf = list[i];
if (isInstance(buf, Uint8Array)) {
buf = Buffer.from(buf);
}
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers');
}
buf.copy(buffer, pos);
pos += buf.length;
}
return buffer;
};
function byteLength(string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length;
}
if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
return string.byteLength;
}
if (typeof string !== 'string') {
throw new TypeError(
'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
'Received type ' +
typeof string
);
}
var len = string.length;
var mustMatch = arguments.length > 2 && arguments[2] === true;
if (!mustMatch && len === 0) return 0;
// Use a for loop to avoid recursion
var loweredCase = false;
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len;
case 'utf8':
case 'utf-8':
return utf8ToBytes(string).length;
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2;
case 'hex':
return len >>> 1;
case 'base64':
return base64ToBytes(string).length;
default:
if (loweredCase) {
return mustMatch ? -1 : utf8ToBytes(string).length; // assume utf8
}
encoding = ('' + encoding).toLowerCase();
loweredCase = true;
}
}
}
Buffer.byteLength = byteLength;
function slowToString(encoding, start, end) {
var loweredCase = false;
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0;
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return '';
}
if (end === undefined || end > this.length) {
end = this.length;
}
if (end <= 0) {
return '';
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0;
start >>>= 0;
if (end <= start) {
return '';
}
if (!encoding) encoding = 'utf8';
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end);
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end);
case 'ascii':
return asciiSlice(this, start, end);
case 'latin1':
case 'binary':
return latin1Slice(this, start, end);
case 'base64':
return base64Slice(this, start, end);
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end);
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
encoding = (encoding + '').toLowerCase();
loweredCase = true;
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true;
function swap(b, n, m) {
var i = b[n];
b[n] = b[m];
b[m] = i;
}
Buffer.prototype.swap16 = function swap16() {
var len = this.length;
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits');
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1);
}
return this;
};
Buffer.prototype.swap32 = function swap32() {
var len = this.length;
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits');
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3);
swap(this, i + 1, i + 2);
}
return this;
};
Buffer.prototype.swap64 = function swap64() {
var len = this.length;
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits');
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7);
swap(this, i + 1, i + 6);
swap(this, i + 2, i + 5);
swap(this, i + 3, i + 4);
}
return this;
};
Buffer.prototype.toString = function toString() {
var length = this.length;
if (length === 0) return '';
if (arguments.length === 0) return utf8Slice(this, 0, length);
return slowToString.apply(this, arguments);
};
Buffer.prototype.toLocaleString = Buffer.prototype.toString;
Buffer.prototype.equals = function equals(b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer');
if (this === b) return true;
return Buffer.compare(this, b) === 0;
};
Buffer.prototype.inspect = function inspect() {
var str = '';
var max = exports.INSPECT_MAX_BYTES;
str = this.toString('hex', 0, max)
.replace(/(.{2})/g, '$1 ')
.trim();
if (this.length > max) str += ' ... ';
return '<Buffer ' + str + '>';
};
if (customInspectSymbol) {
Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect;
}
Buffer.prototype.compare = function compare(
target,
start,
end,
thisStart,
thisEnd
) {
if (isInstance(target, Uint8Array)) {
target = Buffer.from(target, target.offset, target.byteLength);
}
if (!Buffer.isBuffer(target)) {
throw new TypeError(
'The "target" argument must be one of type Buffer or Uint8Array. ' +
'Received type ' +
typeof target
);
}
if (start === undefined) {
start = 0;
}
if (end === undefined) {
end = target ? target.length : 0;
}
if (thisStart === undefined) {
thisStart = 0;
}
if (thisEnd === undefined) {
thisEnd = this.length;
}
if (
start < 0 ||
end > target.length ||
thisStart < 0 ||
thisEnd > this.length
) {
throw new RangeError('out of range index');
}
if (thisStart >= thisEnd && start >= end) {
return 0;
}
if (thisStart >= thisEnd) {
return -1;
}
if (start >= end) {
return 1;
}
start >>>= 0;
end >>>= 0;
thisStart >>>= 0;
thisEnd >>>= 0;
if (this === target) return 0;
var x = thisEnd - thisStart;
var y = end - start;
var len = Math.min(x, y);
var thisCopy = this.slice(thisStart, thisEnd);
var targetCopy = target.slice(start, end);
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i];
y = targetCopy[i];
break;
}
}
if (x < y) return -1;
if (y < x) return 1;
return 0;
};
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1;
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset;
byteOffset = 0;
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff;
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000;
}
byteOffset = +byteOffset; // Coerce to Number.
if (numberIsNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : buffer.length - 1;
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
if (byteOffset >= buffer.length) {
if (dir) return -1;
else byteOffset = buffer.length - 1;
} else if (byteOffset < 0) {
if (dir) byteOffset = 0;
else return -1;
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding);
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1;
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
} else if (typeof val === 'number') {
val = val & 0xff; // Search for a byte value [0-255]
if (typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
}
}
return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
}
throw new TypeError('val must be string, number or Buffer');
}
function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
var indexSize = 1;
var arrLength = arr.length;
var valLength = val.length;
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase();
if (
encoding === 'ucs2' ||
encoding === 'ucs-2' ||
encoding === 'utf16le' ||
encoding === 'utf-16le'
) {
if (arr.length < 2 || val.length < 2) {
return -1;
}
indexSize = 2;
arrLength /= 2;
valLength /= 2;
byteOffset /= 2;
}
}
function read(buf, i) {
if (indexSize === 1) {
return buf[i];
} else {
return buf.readUInt16BE(i * indexSize);
}
}
var i;
if (dir) {
var foundIndex = -1;
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i;
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
} else {
if (foundIndex !== -1) i -= i - foundIndex;
foundIndex = -1;
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
for (i = byteOffset; i >= 0; i--) {
var found = true;
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false;
break;
}
}
if (found) return i;
}
}
return -1;
}
Buffer.prototype.includes = function includes(val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1;
};
Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
};
Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
};
function hexWrite(buf, string, offset, length) {
offset = Number(offset) || 0;
var remaining = buf.length - offset;
if (!length) {
length = remaining;
} else {
length = Number(length);
if (length > remaining) {
length = remaining;
}
}
var strLen = string.length;
if (length > strLen / 2) {
length = strLen / 2;
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16);
if (numberIsNaN(parsed)) return i;
buf[offset + i] = parsed;
}
return i;
}
function utf8Write(buf, string, offset, length) {
return blitBuffer(
utf8ToBytes(string, buf.length - offset),
buf,
offset,
length
);
}
function asciiWrite(buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length);
}
function latin1Write(buf, string, offset, length) {
return asciiWrite(buf, string, offset, length);
}
function base64Write(buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length);
}
function ucs2Write(buf, string, offset, length) {
return blitBuffer(
utf16leToBytes(string, buf.length - offset),
buf,
offset,
length
);
}
Buffer.prototype.write = function write(string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8';
length = this.length;
offset = 0;
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset;
length = this.length;
offset = 0;
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0;
if (isFinite(length)) {
length = length >>> 0;
if (encoding === undefined) encoding = 'utf8';
} else {
encoding = length;
length = undefined;
}
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
);
}
var remaining = this.length - offset;
if (length === undefined || length > remaining) length = remaining;
if (
(string.length > 0 && (length < 0 || offset < 0)) ||
offset > this.length
) {
throw new RangeError('Attempt to write outside buffer bounds');
}
if (!encoding) encoding = 'utf8';
var loweredCase = false;
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length);
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length);
case 'ascii':
return asciiWrite(this, string, offset, length);
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length);
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length);
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length);
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
encoding = ('' + encoding).toLowerCase();
loweredCase = true;
}
}
};
Buffer.prototype.toJSON = function toJSON() {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
};
};
function base64Slice(buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf);
} else {
return base64.fromByteArray(buf.slice(start, end));
}
}
function utf8Slice(buf, start, end) {
end = Math.min(buf.length, end);
var res = [];
var i = start;
while (i < end) {
var firstByte = buf[i];
var codePoint = null;
var bytesPerSequence =
firstByte > 0xef ? 4 : firstByte > 0xdf ? 3 : firstByte > 0xbf ? 2 : 1;
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint;
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte;
}
break;
case 2:
secondByte = buf[i + 1];
if ((secondByte & 0xc0) === 0x80) {
tempCodePoint = ((firstByte & 0x1f) << 0x6) | (secondByte & 0x3f);
if (tempCodePoint > 0x7f) {
codePoint = tempCodePoint;
}
}
break;
case 3:
secondByte = buf[i + 1];
thirdByte = buf[i + 2];
if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80) {
tempCodePoint =
((firstByte & 0xf) << 0xc) |
((secondByte & 0x3f) << 0x6) |
(thirdByte & 0x3f);
if (
tempCodePoint > 0x7ff &&
(tempCodePoint < 0xd800 || tempCodePoint > 0xdfff)
) {
codePoint = tempCodePoint;
}
}
break;
case 4:
secondByte = buf[i + 1];
thirdByte = buf[i + 2];
fourthByte = buf[i + 3];
if (
(secondByte & 0xc0) === 0x80 &&
(thirdByte & 0xc0) === 0x80 &&
(fourthByte & 0xc0) === 0x80
) {
tempCodePoint =
((firstByte & 0xf) << 0x12) |
((secondByte & 0x3f) << 0xc) |
((thirdByte & 0x3f) << 0x6) |
(fourthByte & 0x3f);
if (tempCodePoint > 0xffff && tempCodePoint < 0x110000) {
codePoint = tempCodePoint;
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xfffd;
bytesPerSequence = 1;
} else if (codePoint > 0xffff) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000;
res.push(((codePoint >>> 10) & 0x3ff) | 0xd800);
codePoint = 0xdc00 | (codePoint & 0x3ff);
}
res.push(codePoint);
i += bytesPerSequence;
}
return decodeCodePointsArray(res);
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000;
function decodeCodePointsArray(codePoints) {
var len = codePoints.length;
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints); // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = '';
var i = 0;
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, (i += MAX_ARGUMENTS_LENGTH))
);
}
return res;
}
function asciiSlice(buf, start, end) {
var ret = '';
end = Math.min(buf.length, end);
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7f);
}
return ret;
}
function latin1Slice(buf, start, end) {
var ret = '';
end = Math.min(buf.length, end);
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i]);
}
return ret;
}
function hexSlice(buf, start, end) {
var len = buf.length;
if (!start || start < 0) start = 0;
if (!end || end < 0 || end > len) end = len;
var out = '';
for (var i = start; i < end; ++i) {
out += hexSliceLookupTable[buf[i]];
}
return out;
}
function utf16leSlice(buf, start, end) {
var bytes = buf.slice(start, end);
var res = '';
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
}
return res;
}
Buffer.prototype.slice = function slice(start, end) {
var len = this.length;
start = ~~start;
end = end === undefined ? len : ~~end;
if (start < 0) {
start += len;
if (start < 0) start = 0;
} else if (start > len) {
start = len;
}
if (end < 0) {
end += len;
if (end < 0) end = 0;
} else if (end > len) {
end = len;
}
if (end < start) end = start;
var newBuf = this.subarray(start, end);
// Return an augmented `Uint8Array` instance
Object.setPrototypeOf(newBuf, Buffer.prototype);
return newBuf;
};
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset(offset, ext, length) {
if (offset % 1 !== 0 || offset < 0)
throw new RangeError('offset is not uint');
if (offset + ext > length)
throw new RangeError('Trying to access beyond buffer length');
}
Buffer.prototype.readUIntLE = function readUIntLE(
offset,
byteLength,
noAssert
) {
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var val = this[offset];
var mul = 1;
var i = 0;
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul;
}
return val;
};
Buffer.prototype.readUIntBE = function readUIntBE(
offset,
byteLength,
noAssert
) {
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) {
checkOffset(offset, byteLength, this.length);
}
var val = this[offset + --byteLength];
var mul = 1;
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul;
}
return val;
};
Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 1, this.length);
return this[offset];
};
Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
return this[offset] | (this[offset + 1] << 8);
};
Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
return (this[offset] << 8) | this[offset + 1];
};
Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return (
(this[offset] | (this[offset + 1] << 8) | (this[offset + 2] << 16)) +
this[offset + 3] * 0x1000000
);
};
Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return (
this[offset] * 0x1000000 +
((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3])
);
};
Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) {
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var val = this[offset];
var mul = 1;
var i = 0;
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul;
}
mul *= 0x80;
if (val >= mul) val -= Math.pow(2, 8 * byteLength);
return val;
};
Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) {
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var i = byteLength;
var mul = 1;
var val = this[offset + --i];
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul;
}
mul *= 0x80;
if (val >= mul) val -= Math.pow(2, 8 * byteLength);
return val;
};
Buffer.prototype.readInt8 = function readInt8(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 1, this.length);
if (!(this[offset] & 0x80)) return this[offset];
return (0xff - this[offset] + 1) * -1;
};
Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
var val = this[offset] | (this[offset + 1] << 8);
return val & 0x8000 ? val | 0xffff0000 : val;
};
Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
var val = this[offset + 1] | (this[offset] << 8);
return val & 0x8000 ? val | 0xffff0000 : val;
};
Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return (
this[offset] |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
);
};
Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return (
(this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3]
);
};
Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return ieee754.read(this, offset, true, 23, 4);
};
Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return ieee754.read(this, offset, false, 23, 4);
};
Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 8, this.length);
return ieee754.read(this, offset, true, 52, 8);
};
Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 8, this.length);
return ieee754.read(this, offset, false, 52, 8);
};
function checkInt(buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf))
throw new TypeError('"buffer" argument must be a Buffer instance');
if (value > max || value < min)
throw new RangeError('"value" argument is out of bounds');
if (offset + ext > buf.length) throw new RangeError('Index out of range');
}
Buffer.prototype.writeUIntLE = function writeUIntLE(
value,
offset,
byteLength,
noAssert
) {
value = +value;
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1;
checkInt(this, value, offset, byteLength, maxBytes, 0);
}
var mul = 1;
var i = 0;
this[offset] = value & 0xff;
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xff;
}
return offset + byteLength;
};
Buffer.prototype.writeUIntBE = function writeUIntBE(
value,
offset,
byteLength,
noAssert
) {
value = +value;
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1;
checkInt(this, value, offset, byteLength, maxBytes, 0);
}
var i = byteLength - 1;
var mul = 1;
this[offset + i] = value & 0xff;
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xff;
}
return offset + byteLength;
};
Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
this[offset] = value & 0xff;
return offset + 1;
};
Buffer.prototype.writeUInt16LE = function writeUInt16LE(
value,
offset,
noAssert
) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
this[offset] = value & 0xff;
this[offset + 1] = value >>> 8;
return offset + 2;
};
Buffer.prototype.writeUInt16BE = function writeUInt16BE(
value,
offset,
noAssert
) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
this[offset] = value >>> 8;
this[offset + 1] = value & 0xff;
return offset + 2;
};
Buffer.prototype.writeUInt32LE = function writeUInt32LE(
value,
offset,
noAssert
) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
this[offset + 3] = value >>> 24;
this[offset + 2] = value >>> 16;
this[offset + 1] = value >>> 8;
this[offset] = value & 0xff;
return offset + 4;
};
Buffer.prototype.writeUInt32BE = function writeUInt32BE(
value,
offset,
noAssert
) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
this[offset] = value >>> 24;
this[offset + 1] = value >>> 16;
this[offset + 2] = value >>> 8;
this[offset + 3] = value & 0xff;
return offset + 4;
};
Buffer.prototype.writeIntLE = function writeIntLE(
value,
offset,
byteLength,
noAssert
) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1);
checkInt(this, value, offset, byteLength, limit - 1, -limit);
}
var i = 0;
var mul = 1;
var sub = 0;
this[offset] = value & 0xff;
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1;
}
this[offset + i] = (((value / mul) >> 0) - sub) & 0xff;
}
return offset + byteLength;
};
Buffer.prototype.writeIntBE = function writeIntBE(
value,
offset,
byteLength,
noAssert
) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1);
checkInt(this, value, offset, byteLength, limit - 1, -limit);
}
var i = byteLength - 1;
var mul = 1;
var sub = 0;
this[offset + i] = value & 0xff;
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1;
}
this[offset + i] = (((value / mul) >> 0) - sub) & 0xff;
}
return offset + byteLength;
};
Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
if (value < 0) value = 0xff + value + 1;
this[offset] = value & 0xff;
return offset + 1;
};
Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
this[offset] = value & 0xff;
this[offset + 1] = value >>> 8;
return offset + 2;
};
Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
this[offset] = value >>> 8;
this[offset + 1] = value & 0xff;
return offset + 2;
};
Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
this[offset] = value & 0xff;
this[offset + 1] = value >>> 8;
this[offset + 2] = value >>> 16;
this[offset + 3] = value >>> 24;
return offset + 4;
};
Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
if (value < 0) value = 0xffffffff + value + 1;
this[offset] = value >>> 24;
this[offset + 1] = value >>> 16;
this[offset + 2] = value >>> 8;
this[offset + 3] = value & 0xff;
return offset + 4;
};
function checkIEEE754(buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range');
if (offset < 0) throw new RangeError('Index out of range');
}
function writeFloat(buf, value, offset, littleEndian, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
checkIEEE754(
buf,
value,
offset,
4,
3.4028234663852886e38,
-3.4028234663852886e38
);
}
ieee754.write(buf, value, offset, littleEndian, 23, 4);
return offset + 4;
}
Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert);
};
Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert);
};
function writeDouble(buf, value, offset, littleEndian, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
checkIEEE754(
buf,
value,
offset,
8,
1.7976931348623157e308,
-1.7976931348623157e308
);
}
ieee754.write(buf, value, offset, littleEndian, 52, 8);
return offset + 8;
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE(
value,
offset,
noAssert
) {
return writeDouble(this, value, offset, true, noAssert);
};
Buffer.prototype.writeDoubleBE = function writeDoubleBE(
value,
offset,
noAssert
) {
return writeDouble(this, value, offset, false, noAssert);
};
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy(target, targetStart, start, end) {
if (!Buffer.isBuffer(target))
throw new TypeError('argument should be a Buffer');
if (!start) start = 0;
if (!end && end !== 0) end = this.length;
if (targetStart >= target.length) targetStart = target.length;
if (!targetStart) targetStart = 0;
if (end > 0 && end < start) end = start;
// Copy 0 bytes; we're done
if (end === start) return 0;
if (target.length === 0 || this.length === 0) return 0;
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds');
}
if (start < 0 || start >= this.length)
throw new RangeError('Index out of range');
if (end < 0) throw new RangeError('sourceEnd out of bounds');
// Are we oob?
if (end > this.length) end = this.length;
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start;
}
var len = end - start;
if (
this === target &&
typeof Uint8Array.prototype.copyWithin === 'function'
) {
// Use built-in when available, missing from IE11
this.copyWithin(targetStart, start, end);
} else if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (var i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start];
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, end),
targetStart
);
}
return len;
};
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill(val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start;
start = 0;
end = this.length;
} else if (typeof end === 'string') {
encoding = end;
end = this.length;
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string');
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding);
}
if (val.length === 1) {
var code = val.charCodeAt(0);
if ((encoding === 'utf8' && code < 128) || encoding === 'latin1') {
// Fast path: If `val` fits into a single byte, use that numeric value.
val = code;
}
}
} else if (typeof val === 'number') {
val = val & 255;
} else if (typeof val === 'boolean') {
val = Number(val);
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index');
}
if (end <= start) {
return this;
}
start = start >>> 0;
end = end === undefined ? this.length : end >>> 0;
if (!val) val = 0;
var i;
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val;
}
} else {
var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding);
var len = bytes.length;
if (len === 0) {
throw new TypeError(
'The value "' + val + '" is invalid for argument "value"'
);
}
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len];
}
}
return this;
};
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
function base64clean(str) {
// Node takes equal signs as end of the Base64 encoding
str = str.split('=')[0];
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().replace(INVALID_BASE64_RE, '');
// Node converts strings with length < 2 to ''
if (str.length < 2) return '';
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '=';
}
return str;
}
function utf8ToBytes(string, units) {
units = units || Infinity;
var codePoint;
var length = string.length;
var leadSurrogate = null;
var bytes = [];
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i);
// is surrogate component
if (codePoint > 0xd7ff && codePoint < 0xe000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xdbff) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd);
continue;
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd);
continue;
}
// valid lead
leadSurrogate = codePoint;
continue;
}
// 2 leads in a row
if (codePoint < 0xdc00) {
if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd);
leadSurrogate = codePoint;
continue;
}
// valid surrogate pair
codePoint =
(((leadSurrogate - 0xd800) << 10) | (codePoint - 0xdc00)) + 0x10000;
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd);
}
leadSurrogate = null;
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break;
bytes.push(codePoint);
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break;
bytes.push((codePoint >> 0x6) | 0xc0, (codePoint & 0x3f) | 0x80);
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break;
bytes.push(
(codePoint >> 0xc) | 0xe0,
((codePoint >> 0x6) & 0x3f) | 0x80,
(codePoint & 0x3f) | 0x80
);
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break;
bytes.push(
(codePoint >> 0x12) | 0xf0,
((codePoint >> 0xc) & 0x3f) | 0x80,
((codePoint >> 0x6) & 0x3f) | 0x80,
(codePoint & 0x3f) | 0x80
);
} else {
throw new Error('Invalid code point');
}
}
return bytes;
}
function asciiToBytes(str) {
var byteArray = [];
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xff);
}
return byteArray;
}
function utf16leToBytes(str, units) {
var c, hi, lo;
var byteArray = [];
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break;
c = str.charCodeAt(i);
hi = c >> 8;
lo = c % 256;
byteArray.push(lo);
byteArray.push(hi);
}
return byteArray;
}
function base64ToBytes(str) {
return base64.toByteArray(base64clean(str));
}
function blitBuffer(src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if (i + offset >= dst.length || i >= src.length) break;
dst[i + offset] = src[i];
}
return i;
}
// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
// the `instanceof` check but they should be treated as of that type.
// See: https://github.com/feross/buffer/issues/166
function isInstance(obj, type) {
return (
obj instanceof type ||
(obj != null &&
obj.constructor != null &&
obj.constructor.name != null &&
obj.constructor.name === type.name)
);
}
function numberIsNaN(obj) {
// For IE11 support
return obj !== obj; // eslint-disable-line no-self-compare
}
// Create lookup table for `toString('hex')`
// See: https://github.com/feross/buffer/issues/219
var hexSliceLookupTable = (function() {
var alphabet = '0123456789abcdef';
var table = new Array(256);
for (var i = 0; i < 16; ++i) {
var i16 = i * 16;
for (var j = 0; j < 16; ++j) {
table[i16 + j] = alphabet[i] + alphabet[j];
}
}
return table;
})();
}.call(this, _dereq_('buffer').Buffer));
},
{ 'base64-js': 20, buffer: 22, ieee754: 31 }
],
23: [
function(_dereq_, module, exports) {
// This file can be required in Browserify and Node.js for automatic polyfill
// To use it: require('es6-promise/auto');
'use strict';
module.exports = _dereq_('./').polyfill();
},
{ './': 24 }
],
24: [
function(_dereq_, module, exports) {
(function(process, global) {
/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
* @version v4.2.8+1e68dce6
*/
(function(global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
? (module.exports = factory())
: typeof define === 'function' && define.amd
? define(factory)
: (global.ES6Promise = factory());
})(this, function() {
'use strict';
function objectOrFunction(x) {
var type = typeof x;
return x !== null && (type === 'object' || type === 'function');
}
function isFunction(x) {
return typeof x === 'function';
}
var _isArray = void 0;
if (Array.isArray) {
_isArray = Array.isArray;
} else {
_isArray = function(x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
}
var isArray = _isArray;
var len = 0;
var vertxNext = void 0;
var customSchedulerFn = void 0;
var asap = function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
// If len is 2, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
if (customSchedulerFn) {
customSchedulerFn(flush);
} else {
scheduleFlush();
}
}
};
function setScheduler(scheduleFn) {
customSchedulerFn = scheduleFn;
}
function setAsap(asapFn) {
asap = asapFn;
}
var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver =
browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode =
typeof self === 'undefined' &&
typeof process !== 'undefined' &&
{}.toString.call(process) === '[object process]';
// test for web worker but not in IE10
var isWorker =
typeof Uint8ClampedArray !== 'undefined' &&
typeof importScripts !== 'undefined' &&
typeof MessageChannel !== 'undefined';
// node
function useNextTick() {
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// see https://github.com/cujojs/when/issues/410 for details
return function() {
return process.nextTick(flush);
};
}
// vertx
function useVertxTimer() {
if (typeof vertxNext !== 'undefined') {
return function() {
vertxNext(flush);
};
}
return useSetTimeout();
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function() {
node.data = iterations = ++iterations % 2;
};
}
// web worker
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return function() {
return channel.port2.postMessage(0);
};
}
function useSetTimeout() {
// Store setTimeout reference so es6-promise will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var globalSetTimeout = setTimeout;
return function() {
return globalSetTimeout(flush, 1);
};
}
var queue = new Array(1000);
function flush() {
for (var i = 0; i < len; i += 2) {
var callback = queue[i];
var arg = queue[i + 1];
callback(arg);
queue[i] = undefined;
queue[i + 1] = undefined;
}
len = 0;
}
function attemptVertx() {
try {
var vertx = Function('return this')().require('vertx');
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch (e) {
return useSetTimeout();
}
}
var scheduleFlush = void 0;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && typeof _dereq_ === 'function') {
scheduleFlush = attemptVertx();
} else {
scheduleFlush = useSetTimeout();
}
function then(onFulfillment, onRejection) {
var parent = this;
var child = new this.constructor(noop);
if (child[PROMISE_ID] === undefined) {
makePromise(child);
}
var _state = parent._state;
if (_state) {
var callback = arguments[_state - 1];
asap(function() {
return invokeCallback(_state, child, callback, parent._result);
});
} else {
subscribe(parent, child, onFulfillment, onRejection);
}
return child;
}
/**
`Promise.resolve` returns a promise that will become resolved with the
passed `value`. It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
resolve(1);
});
promise.then(function(value){
// value === 1
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.resolve(1);
promise.then(function(value){
// value === 1
});
```
@method resolve
@static
@param {Any} value value that the returned promise will be resolved with
Useful for tooling.
@return {Promise} a promise that will become fulfilled with the given
`value`
*/
function resolve$1(object) {
/*jshint validthis:true */
var Constructor = this;
if (
object &&
typeof object === 'object' &&
object.constructor === Constructor
) {
return object;
}
var promise = new Constructor(noop);
resolve(promise, object);
return promise;
}
var PROMISE_ID = Math.random()
.toString(36)
.substring(2);
function noop() {}
var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;
function selfFulfillment() {
return new TypeError('You cannot resolve a promise with itself');
}
function cannotReturnOwn() {
return new TypeError(
'A promises callback cannot return that same promise.'
);
}
function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
try {
then$$1.call(value, fulfillmentHandler, rejectionHandler);
} catch (e) {
return e;
}
}
function handleForeignThenable(promise, thenable, then$$1) {
asap(function(promise) {
var sealed = false;
var error = tryThen(
then$$1,
thenable,
function(value) {
if (sealed) {
return;
}
sealed = true;
if (thenable !== value) {
resolve(promise, value);
} else {
fulfill(promise, value);
}
},
function(reason) {
if (sealed) {
return;
}
sealed = true;
reject(promise, reason);
},
'Settle: ' + (promise._label || ' unknown promise')
);
if (!sealed && error) {
sealed = true;
reject(promise, error);
}
}, promise);
}
function handleOwnThenable(promise, thenable) {
if (thenable._state === FULFILLED) {
fulfill(promise, thenable._result);
} else if (thenable._state === REJECTED) {
reject(promise, thenable._result);
} else {
subscribe(
thenable,
undefined,
function(value) {
return resolve(promise, value);
},
function(reason) {
return reject(promise, reason);
}
);
}
}
function handleMaybeThenable(promise, maybeThenable, then$$1) {
if (
maybeThenable.constructor === promise.constructor &&
then$$1 === then &&
maybeThenable.constructor.resolve === resolve$1
) {
handleOwnThenable(promise, maybeThenable);
} else {
if (then$$1 === undefined) {
fulfill(promise, maybeThenable);
} else if (isFunction(then$$1)) {
handleForeignThenable(promise, maybeThenable, then$$1);
} else {
fulfill(promise, maybeThenable);
}
}
}
function resolve(promise, value) {
if (promise === value) {
reject(promise, selfFulfillment());
} else if (objectOrFunction(value)) {
var then$$1 = void 0;
try {
then$$1 = value.then;
} catch (error) {
reject(promise, error);
return;
}
handleMaybeThenable(promise, value, then$$1);
} else {
fulfill(promise, value);
}
}
function publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
publish(promise);
}
function fulfill(promise, value) {
if (promise._state !== PENDING) {
return;
}
promise._result = value;
promise._state = FULFILLED;
if (promise._subscribers.length !== 0) {
asap(publish, promise);
}
}
function reject(promise, reason) {
if (promise._state !== PENDING) {
return;
}
promise._state = REJECTED;
promise._result = reason;
asap(publishRejection, promise);
}
function subscribe(parent, child, onFulfillment, onRejection) {
var _subscribers = parent._subscribers;
var length = _subscribers.length;
parent._onerror = null;
_subscribers[length] = child;
_subscribers[length + FULFILLED] = onFulfillment;
_subscribers[length + REJECTED] = onRejection;
if (length === 0 && parent._state) {
asap(publish, parent);
}
}
function publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (subscribers.length === 0) {
return;
}
var child = void 0,
callback = void 0,
detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
value = void 0,
error = void 0,
succeeded = true;
if (hasCallback) {
try {
value = callback(detail);
} catch (e) {
succeeded = false;
error = e;
}
if (promise === value) {
reject(promise, cannotReturnOwn());
return;
}
} else {
value = detail;
}
if (promise._state !== PENDING) {
// noop
} else if (hasCallback && succeeded) {
resolve(promise, value);
} else if (succeeded === false) {
reject(promise, error);
} else if (settled === FULFILLED) {
fulfill(promise, value);
} else if (settled === REJECTED) {
reject(promise, value);
}
}
function initializePromise(promise, resolver) {
try {
resolver(
function resolvePromise(value) {
resolve(promise, value);
},
function rejectPromise(reason) {
reject(promise, reason);
}
);
} catch (e) {
reject(promise, e);
}
}
var id = 0;
function nextId() {
return id++;
}
function makePromise(promise) {
promise[PROMISE_ID] = id++;
promise._state = undefined;
promise._result = undefined;
promise._subscribers = [];
}
function validationError() {
return new Error('Array Methods must be provided an Array');
}
var Enumerator = (function() {
function Enumerator(Constructor, input) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(noop);
if (!this.promise[PROMISE_ID]) {
makePromise(this.promise);
}
if (isArray(input)) {
this.length = input.length;
this._remaining = input.length;
this._result = new Array(this.length);
if (this.length === 0) {
fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate(input);
if (this._remaining === 0) {
fulfill(this.promise, this._result);
}
}
} else {
reject(this.promise, validationError());
}
}
Enumerator.prototype._enumerate = function _enumerate(input) {
for (var i = 0; this._state === PENDING && i < input.length; i++) {
this._eachEntry(input[i], i);
}
};
Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {
var c = this._instanceConstructor;
var resolve$$1 = c.resolve;
if (resolve$$1 === resolve$1) {
var _then = void 0;
var error = void 0;
var didError = false;
try {
_then = entry.then;
} catch (e) {
didError = true;
error = e;
}
if (_then === then && entry._state !== PENDING) {
this._settledAt(entry._state, i, entry._result);
} else if (typeof _then !== 'function') {
this._remaining--;
this._result[i] = entry;
} else if (c === Promise$1) {
var promise = new c(noop);
if (didError) {
reject(promise, error);
} else {
handleMaybeThenable(promise, entry, _then);
}
this._willSettleAt(promise, i);
} else {
this._willSettleAt(
new c(function(resolve$$1) {
return resolve$$1(entry);
}),
i
);
}
} else {
this._willSettleAt(resolve$$1(entry), i);
}
};
Enumerator.prototype._settledAt = function _settledAt(state, i, value) {
var promise = this.promise;
if (promise._state === PENDING) {
this._remaining--;
if (state === REJECTED) {
reject(promise, value);
} else {
this._result[i] = value;
}
}
if (this._remaining === 0) {
fulfill(promise, this._result);
}
};
Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {
var enumerator = this;
subscribe(
promise,
undefined,
function(value) {
return enumerator._settledAt(FULFILLED, i, value);
},
function(reason) {
return enumerator._settledAt(REJECTED, i, reason);
}
);
};
return Enumerator;
})();
/**
`Promise.all` accepts an array of promises, and returns a new promise which
is fulfilled with an array of fulfillment values for the passed promises, or
rejected with the reason of the first passed promise to be rejected. It casts all
elements of the passed iterable to promises as it runs this algorithm.
Example:
```javascript
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
let promise1 = resolve(1);
let promise2 = reject(new Error("2"));
let promise3 = reject(new Error("3"));
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@static
@param {Array} entries array of promises
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
@static
*/
function all(entries) {
return new Enumerator(this, entries).promise;
}
/**
`Promise.race` returns a new promise which is settled in the same way as the
first passed promise to settle.
Example:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 2');
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// result === 'promise 2' because it was resolved before promise1
// was resolved.
});
```
`Promise.race` is deterministic in that only the state of the first
settled promise matters. For example, even if other promises given to the
`promises` array argument are resolved, but the first settled promise has
become rejected before the other promises became fulfilled, the returned
promise will become rejected:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error('promise 2'));
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// Code here never runs
}, function(reason){
// reason.message === 'promise 2' because promise 2 became rejected before
// promise 1 became fulfilled
});
```
An example real-world use case is implementing timeouts:
```javascript
Promise.race([ajax('foo.json'), timeout(5000)])
```
@method race
@static
@param {Array} promises array of promises to observe
Useful for tooling.
@return {Promise} a promise which settles in the same way as the first passed
promise to settle.
*/
function race(entries) {
/*jshint validthis:true */
var Constructor = this;
if (!isArray(entries)) {
return new Constructor(function(_, reject) {
return reject(new TypeError('You must pass an array to race.'));
});
} else {
return new Constructor(function(resolve, reject) {
var length = entries.length;
for (var i = 0; i < length; i++) {
Constructor.resolve(entries[i]).then(resolve, reject);
}
});
}
}
/**
`Promise.reject` returns a promise rejected with the passed `reason`.
It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@static
@param {Any} reason value that the returned promise will be rejected with.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
function reject$1(reason) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(noop);
reject(promise, reason);
return promise;
}
function needsResolver() {
throw new TypeError(
'You must pass a resolver function as the first argument to the promise constructor'
);
}
function needsNew() {
throw new TypeError(
"Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."
);
}
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise's eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
let promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@param {Function} resolver
Useful for tooling.
@constructor
*/
var Promise$1 = (function() {
function Promise(resolver) {
this[PROMISE_ID] = nextId();
this._result = this._state = undefined;
this._subscribers = [];
if (noop !== resolver) {
typeof resolver !== 'function' && needsResolver();
this instanceof Promise
? initializePromise(this, resolver)
: needsNew();
}
}
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we're unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
let result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
let author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfilled
@param {Function} onRejected
Useful for tooling.
@return {Promise}
*/
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn't find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
Useful for tooling.
@return {Promise}
*/
Promise.prototype.catch = function _catch(onRejection) {
return this.then(null, onRejection);
};
/**
`finally` will be invoked regardless of the promise's fate just as native
try/catch/finally behaves
Synchronous example:
```js
findAuthor() {
if (Math.random() > 0.5) {
throw new Error();
}
return new Author();
}
try {
return findAuthor(); // succeed or fail
} catch(error) {
return findOtherAuther();
} finally {
// always runs
// doesn't affect the return value
}
```
Asynchronous example:
```js
findAuthor().catch(function(reason){
return findOtherAuther();
}).finally(function(){
// author was either found, or not
});
```
@method finally
@param {Function} callback
@return {Promise}
*/
Promise.prototype.finally = function _finally(callback) {
var promise = this;
var constructor = promise.constructor;
if (isFunction(callback)) {
return promise.then(
function(value) {
return constructor.resolve(callback()).then(function() {
return value;
});
},
function(reason) {
return constructor.resolve(callback()).then(function() {
throw reason;
});
}
);
}
return promise.then(callback, callback);
};
return Promise;
})();
Promise$1.prototype.then = then;
Promise$1.all = all;
Promise$1.race = race;
Promise$1.resolve = resolve$1;
Promise$1.reject = reject$1;
Promise$1._setScheduler = setScheduler;
Promise$1._setAsap = setAsap;
Promise$1._asap = asap;
/*global self*/
function polyfill() {
var local = void 0;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
throw new Error(
'polyfill failed because global object is unavailable in this environment'
);
}
}
var P = local.Promise;
if (P) {
var promiseToString = null;
try {
promiseToString = Object.prototype.toString.call(P.resolve());
} catch (e) {
// silently ignored
}
if (promiseToString === '[object Promise]' && !P.cast) {
return;
}
}
local.Promise = Promise$1;
}
// Strange compat..
Promise$1.polyfill = polyfill;
Promise$1.Promise = Promise$1;
return Promise$1;
});
}.call(
this,
_dereq_('_process'),
typeof global !== 'undefined'
? global
: typeof self !== 'undefined'
? self
: typeof window !== 'undefined' ? window : {}
));
},
{ _process: 36 }
],
25: [
function(_dereq_, module, exports) {
(function(global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'module'], factory);
} else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
factory(exports, module);
} else {
var mod = {
exports: {}
};
factory(mod.exports, mod);
global.fetchJsonp = mod.exports;
}
})(this, function(exports, module) {
'use strict';
var defaultOptions = {
timeout: 5000,
jsonpCallback: 'callback',
jsonpCallbackFunction: null
};
function generateCallbackFunction() {
return 'jsonp_' + Date.now() + '_' + Math.ceil(Math.random() * 100000);
}
function clearFunction(functionName) {
// IE8 throws an exception when you try to delete a property on window
// http://stackoverflow.com/a/1824228/751089
try {
delete window[functionName];
} catch (e) {
window[functionName] = undefined;
}
}
function removeScript(scriptId) {
var script = document.getElementById(scriptId);
if (script) {
document.getElementsByTagName('head')[0].removeChild(script);
}
}
function fetchJsonp(_url) {
var options =
arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
// to avoid param reassign
var url = _url;
var timeout = options.timeout || defaultOptions.timeout;
var jsonpCallback = options.jsonpCallback || defaultOptions.jsonpCallback;
var timeoutId = undefined;
return new Promise(function(resolve, reject) {
var callbackFunction =
options.jsonpCallbackFunction || generateCallbackFunction();
var scriptId = jsonpCallback + '_' + callbackFunction;
window[callbackFunction] = function(response) {
resolve({
ok: true,
// keep consistent with fetch API
json: function json() {
return Promise.resolve(response);
}
});
if (timeoutId) clearTimeout(timeoutId);
removeScript(scriptId);
clearFunction(callbackFunction);
};
// Check if the user set their own params, and if not add a ? to start a list of params
url += url.indexOf('?') === -1 ? '?' : '&';
var jsonpScript = document.createElement('script');
jsonpScript.setAttribute(
'src',
'' + url + jsonpCallback + '=' + callbackFunction
);
if (options.charset) {
jsonpScript.setAttribute('charset', options.charset);
}
jsonpScript.id = scriptId;
document.getElementsByTagName('head')[0].appendChild(jsonpScript);
timeoutId = setTimeout(function() {
reject(new Error('JSONP request to ' + _url + ' timed out'));
clearFunction(callbackFunction);
removeScript(scriptId);
window[callbackFunction] = function() {
clearFunction(callbackFunction);
};
}, timeout);
// Caught if got 404/500
jsonpScript.onerror = function() {
reject(new Error('JSONP request to ' + _url + ' failed'));
clearFunction(callbackFunction);
removeScript(scriptId);
if (timeoutId) clearTimeout(timeoutId);
};
});
}
// export as global function
/*
let local;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
throw new Error('polyfill failed because global object is unavailable in this environment');
}
}
local.fetchJsonp = fetchJsonp;
*/
module.exports = fetchJsonp;
});
},
{}
],
26: [
function(_dereq_, module, exports) {
/* FileSaver.js
* A saveAs() FileSaver implementation.
* 1.3.2
* 2016-06-16 18:25:19
*
* By Eli Grey, http://eligrey.com
* License: MIT
* See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
*/
/*global self */
/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
var saveAs =
saveAs ||
(function(view) {
'use strict';
// IE <10 is explicitly unsupported
if (
typeof view === 'undefined' ||
(typeof navigator !== 'undefined' &&
/MSIE [1-9]\./.test(navigator.userAgent))
) {
return;
}
var doc = view.document,
// only get URL when necessary in case Blob.js hasn't overridden it yet
get_URL = function() {
return view.URL || view.webkitURL || view;
},
save_link = doc.createElementNS('http://www.w3.org/1999/xhtml', 'a'),
can_use_save_link = 'download' in save_link,
click = function(node) {
var event = new MouseEvent('click');
node.dispatchEvent(event);
},
is_safari = /constructor/i.test(view.HTMLElement) || view.safari,
is_chrome_ios = /CriOS\/[\d]+/.test(navigator.userAgent),
throw_outside = function(ex) {
(view.setImmediate || view.setTimeout)(function() {
throw ex;
}, 0);
},
force_saveable_type = 'application/octet-stream',
// the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to
arbitrary_revoke_timeout = 1000 * 40, // in ms
revoke = function(file) {
var revoker = function() {
if (typeof file === 'string') {
// file is an object URL
get_URL().revokeObjectURL(file);
} else {
// file is a File
file.remove();
}
};
setTimeout(revoker, arbitrary_revoke_timeout);
},
dispatch = function(filesaver, event_types, event) {
event_types = [].concat(event_types);
var i = event_types.length;
while (i--) {
var listener = filesaver['on' + event_types[i]];
if (typeof listener === 'function') {
try {
listener.call(filesaver, event || filesaver);
} catch (ex) {
throw_outside(ex);
}
}
}
},
auto_bom = function(blob) {
// prepend BOM for UTF-8 XML and text/* types (including HTML)
// note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
if (
/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(
blob.type
)
) {
return new Blob([String.fromCharCode(0xfeff), blob], {
type: blob.type
});
}
return blob;
},
FileSaver = function(blob, name, no_auto_bom) {
if (!no_auto_bom) {
blob = auto_bom(blob);
}
// First try a.download, then web filesystem, then object URLs
var filesaver = this,
type = blob.type,
force = type === force_saveable_type,
object_url,
dispatch_all = function() {
dispatch(filesaver, 'writestart progress write writeend'.split(' '));
},
// on any filesys errors revert to saving with object URLs
fs_error = function() {
if ((is_chrome_ios || (force && is_safari)) && view.FileReader) {
// Safari doesn't allow downloading of blob urls
var reader = new FileReader();
reader.onloadend = function() {
var url = is_chrome_ios
? reader.result
: reader.result.replace(
/^data:[^;]*;/,
'data:attachment/file;'
);
var popup = view.open(url, '_blank');
if (!popup) view.location.href = url;
url = undefined; // release reference before dispatching
filesaver.readyState = filesaver.DONE;
dispatch_all();
};
reader.readAsDataURL(blob);
filesaver.readyState = filesaver.INIT;
return;
}
// don't create more object URLs than needed
if (!object_url) {
object_url = get_URL().createObjectURL(blob);
}
if (force) {
view.location.href = object_url;
} else {
var opened = view.open(object_url, '_blank');
if (!opened) {
// Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.html
view.location.href = object_url;
}
}
filesaver.readyState = filesaver.DONE;
dispatch_all();
revoke(object_url);
};
filesaver.readyState = filesaver.INIT;
if (can_use_save_link) {
object_url = get_URL().createObjectURL(blob);
setTimeout(function() {
save_link.href = object_url;
save_link.download = name;
click(save_link);
dispatch_all();
revoke(object_url);
filesaver.readyState = filesaver.DONE;
});
return;
}
fs_error();
},
FS_proto = FileSaver.prototype,
saveAs = function(blob, name, no_auto_bom) {
return new FileSaver(blob, name || blob.name || 'download', no_auto_bom);
};
// IE 10+ (native saveAs)
if (typeof navigator !== 'undefined' && navigator.msSaveOrOpenBlob) {
return function(blob, name, no_auto_bom) {
name = name || blob.name || 'download';
if (!no_auto_bom) {
blob = auto_bom(blob);
}
return navigator.msSaveOrOpenBlob(blob, name);
};
}
FS_proto.abort = function() {};
FS_proto.readyState = FS_proto.INIT = 0;
FS_proto.WRITING = 1;
FS_proto.DONE = 2;
FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = null;
return saveAs;
})(
(typeof self !== 'undefined' && self) ||
(typeof window !== 'undefined' && window) ||
this.content
);
// `self` is undefined in Firefox for Android content script context
// while `this` is nsIContentFrameMessageManager
// with an attribute `content` that corresponds to the window
if (typeof module !== 'undefined' && module.exports) {
module.exports.saveAs = saveAs;
} else if (
typeof define !== 'undefined' &&
define !== null &&
define.amd !== null
) {
define('FileSaver.js', function() {
return saveAs;
});
}
},
{}
],
27: [
function(_dereq_, module, exports) {
'use strict';
function _interopDefault(ex) {
return ex && typeof ex === 'object' && 'default' in ex ? ex['default'] : ex;
}
var _classCallCheck = _interopDefault(
_dereq_('@babel/runtime/helpers/classCallCheck')
);
var _createClass = _interopDefault(_dereq_('@babel/runtime/helpers/createClass'));
var arr = [];
var each = arr.forEach;
var slice = arr.slice;
function defaults(obj) {
each.call(slice.call(arguments, 1), function(source) {
if (source) {
for (var prop in source) {
if (obj[prop] === undefined) obj[prop] = source[prop];
}
}
});
return obj;
}
var cookie = {
create: function create(name, value, minutes, domain) {
var expires;
if (minutes) {
var date = new Date();
date.setTime(date.getTime() + minutes * 60 * 1000);
expires = '; expires=' + date.toGMTString();
} else expires = '';
domain = domain ? 'domain=' + domain + ';' : '';
document.cookie = name + '=' + value + expires + ';' + domain + 'path=/';
},
read: function read(name) {
var nameEQ = name + '=';
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
},
remove: function remove(name) {
this.create(name, '', -1);
}
};
var cookie$1 = {
name: 'cookie',
lookup: function lookup(options) {
var found;
if (options.lookupCookie && typeof document !== 'undefined') {
var c = cookie.read(options.lookupCookie);
if (c) found = c;
}
return found;
},
cacheUserLanguage: function cacheUserLanguage(lng, options) {
if (options.lookupCookie && typeof document !== 'undefined') {
cookie.create(
options.lookupCookie,
lng,
options.cookieMinutes,
options.cookieDomain
);
}
}
};
var querystring = {
name: 'querystring',
lookup: function lookup(options) {
var found;
if (typeof window !== 'undefined') {
var query = window.location.search.substring(1);
var params = query.split('&');
for (var i = 0; i < params.length; i++) {
var pos = params[i].indexOf('=');
if (pos > 0) {
var key = params[i].substring(0, pos);
if (key === options.lookupQuerystring) {
found = params[i].substring(pos + 1);
}
}
}
}
return found;
}
};
var hasLocalStorageSupport;
try {
hasLocalStorageSupport = window !== 'undefined' && window.localStorage !== null;
var testKey = 'i18next.translate.boo';
window.localStorage.setItem(testKey, 'foo');
window.localStorage.removeItem(testKey);
} catch (e) {
hasLocalStorageSupport = false;
}
var localStorage = {
name: 'localStorage',
lookup: function lookup(options) {
var found;
if (options.lookupLocalStorage && hasLocalStorageSupport) {
var lng = window.localStorage.getItem(options.lookupLocalStorage);
if (lng) found = lng;
}
return found;
},
cacheUserLanguage: function cacheUserLanguage(lng, options) {
if (options.lookupLocalStorage && hasLocalStorageSupport) {
window.localStorage.setItem(options.lookupLocalStorage, lng);
}
}
};
var navigator$1 = {
name: 'navigator',
lookup: function lookup(options) {
var found = [];
if (typeof navigator !== 'undefined') {
if (navigator.languages) {
// chrome only; not an array, so can't use .push.apply instead of iterating
for (var i = 0; i < navigator.languages.length; i++) {
found.push(navigator.languages[i]);
}
}
if (navigator.userLanguage) {
found.push(navigator.userLanguage);
}
if (navigator.language) {
found.push(navigator.language);
}
}
return found.length > 0 ? found : undefined;
}
};
var htmlTag = {
name: 'htmlTag',
lookup: function lookup(options) {
var found;
var htmlTag =
options.htmlTag ||
(typeof document !== 'undefined' ? document.documentElement : null);
if (htmlTag && typeof htmlTag.getAttribute === 'function') {
found = htmlTag.getAttribute('lang');
}
return found;
}
};
var path = {
name: 'path',
lookup: function lookup(options) {
var found;
if (typeof window !== 'undefined') {
var language = window.location.pathname.match(/\/([a-zA-Z-]*)/g);
if (language instanceof Array) {
if (typeof options.lookupFromPathIndex === 'number') {
if (typeof language[options.lookupFromPathIndex] !== 'string') {
return undefined;
}
found = language[options.lookupFromPathIndex].replace('/', '');
} else {
found = language[0].replace('/', '');
}
}
}
return found;
}
};
var subdomain = {
name: 'subdomain',
lookup: function lookup(options) {
var found;
if (typeof window !== 'undefined') {
var language = window.location.href.match(
/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/gi
);
if (language instanceof Array) {
if (typeof options.lookupFromSubdomainIndex === 'number') {
found = language[options.lookupFromSubdomainIndex]
.replace('http://', '')
.replace('https://', '')
.replace('.', '');
} else {
found = language[0]
.replace('http://', '')
.replace('https://', '')
.replace('.', '');
}
}
}
return found;
}
};
function getDefaults() {
return {
order: ['querystring', 'cookie', 'localStorage', 'navigator', 'htmlTag'],
lookupQuerystring: 'lng',
lookupCookie: 'i18next',
lookupLocalStorage: 'i18nextLng',
// cache user language
caches: ['localStorage'],
excludeCacheFor: ['cimode'],
//cookieMinutes: 10,
//cookieDomain: 'myDomain'
checkWhitelist: true
};
}
var Browser =
/*#__PURE__*/
(function() {
function Browser(services) {
var options =
arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, Browser);
this.type = 'languageDetector';
this.detectors = {};
this.init(services, options);
}
_createClass(Browser, [
{
key: 'init',
value: function init(services) {
var options =
arguments.length > 1 && arguments[1] !== undefined
? arguments[1]
: {};
var i18nOptions =
arguments.length > 2 && arguments[2] !== undefined
? arguments[2]
: {};
this.services = services;
this.options = defaults(options, this.options || {}, getDefaults()); // backwards compatibility
if (this.options.lookupFromUrlIndex)
this.options.lookupFromPathIndex = this.options.lookupFromUrlIndex;
this.i18nOptions = i18nOptions;
this.addDetector(cookie$1);
this.addDetector(querystring);
this.addDetector(localStorage);
this.addDetector(navigator$1);
this.addDetector(htmlTag);
this.addDetector(path);
this.addDetector(subdomain);
}
},
{
key: 'addDetector',
value: function addDetector(detector) {
this.detectors[detector.name] = detector;
}
},
{
key: 'detect',
value: function detect(detectionOrder) {
var _this = this;
if (!detectionOrder) detectionOrder = this.options.order;
var detected = [];
detectionOrder.forEach(function(detectorName) {
if (_this.detectors[detectorName]) {
var lookup = _this.detectors[detectorName].lookup(_this.options);
if (lookup && typeof lookup === 'string') lookup = [lookup];
if (lookup) detected = detected.concat(lookup);
}
});
var found;
detected.forEach(function(lng) {
if (found) return;
var cleanedLng = _this.services.languageUtils.formatLanguageCode(lng);
if (
!_this.options.checkWhitelist ||
_this.services.languageUtils.isWhitelisted(cleanedLng)
)
found = cleanedLng;
});
if (!found) {
var fallbacks = this.i18nOptions.fallbackLng;
if (typeof fallbacks === 'string') fallbacks = [fallbacks];
if (!fallbacks) fallbacks = [];
if (Object.prototype.toString.apply(fallbacks) === '[object Array]') {
found = fallbacks[0];
} else {
found =
fallbacks[0] || (fallbacks['default'] && fallbacks['default'][0]);
}
}
return found;
}
},
{
key: 'cacheUserLanguage',
value: function cacheUserLanguage(lng, caches) {
var _this2 = this;
if (!caches) caches = this.options.caches;
if (!caches) return;
if (
this.options.excludeCacheFor &&
this.options.excludeCacheFor.indexOf(lng) > -1
)
return;
caches.forEach(function(cacheName) {
if (_this2.detectors[cacheName])
_this2.detectors[cacheName].cacheUserLanguage(lng, _this2.options);
});
}
}
]);
return Browser;
})();
Browser.type = 'languageDetector';
module.exports = Browser;
},
{
'@babel/runtime/helpers/classCallCheck': 28,
'@babel/runtime/helpers/createClass': 29
}
],
28: [
function(_dereq_, module, exports) {
arguments[4][5][0].apply(exports, arguments);
},
{ dup: 5 }
],
29: [
function(_dereq_, module, exports) {
arguments[4][6][0].apply(exports, arguments);
},
{ dup: 6 }
],
30: [
function(_dereq_, module, exports) {
'use strict';
function _interopDefault(ex) {
return ex && typeof ex === 'object' && 'default' in ex ? ex['default'] : ex;
}
var _typeof = _interopDefault(_dereq_('@babel/runtime/helpers/typeof'));
var _objectSpread = _interopDefault(
_dereq_('@babel/runtime/helpers/objectSpread')
);
var _classCallCheck = _interopDefault(
_dereq_('@babel/runtime/helpers/classCallCheck')
);
var _createClass = _interopDefault(_dereq_('@babel/runtime/helpers/createClass'));
var _possibleConstructorReturn = _interopDefault(
_dereq_('@babel/runtime/helpers/possibleConstructorReturn')
);
var _getPrototypeOf = _interopDefault(
_dereq_('@babel/runtime/helpers/getPrototypeOf')
);
var _assertThisInitialized = _interopDefault(
_dereq_('@babel/runtime/helpers/assertThisInitialized')
);
var _inherits = _interopDefault(_dereq_('@babel/runtime/helpers/inherits'));
var _toConsumableArray = _interopDefault(
_dereq_('@babel/runtime/helpers/toConsumableArray')
);
var _slicedToArray = _interopDefault(
_dereq_('@babel/runtime/helpers/slicedToArray')
);
var consoleLogger = {
type: 'logger',
log: function log(args) {
this.output('log', args);
},
warn: function warn(args) {
this.output('warn', args);
},
error: function error(args) {
this.output('error', args);
},
output: function output(type, args) {
var _console;
/* eslint no-console: 0 */
if (console && console[type])
(_console = console)[type].apply(_console, _toConsumableArray(args));
}
};
var Logger =
/*#__PURE__*/
(function() {
function Logger(concreteLogger) {
var options =
arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, Logger);
this.init(concreteLogger, options);
}
_createClass(Logger, [
{
key: 'init',
value: function init(concreteLogger) {
var options =
arguments.length > 1 && arguments[1] !== undefined
? arguments[1]
: {};
this.prefix = options.prefix || 'i18next:';
this.logger = concreteLogger || consoleLogger;
this.options = options;
this.debug = options.debug;
}
},
{
key: 'setDebug',
value: function setDebug(bool) {
this.debug = bool;
}
},
{
key: 'log',
value: function log() {
for (
var _len = arguments.length, args = new Array(_len), _key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
return this.forward(args, 'log', '', true);
}
},
{
key: 'warn',
value: function warn() {
for (
var _len2 = arguments.length, args = new Array(_len2), _key2 = 0;
_key2 < _len2;
_key2++
) {
args[_key2] = arguments[_key2];
}
return this.forward(args, 'warn', '', true);
}
},
{
key: 'error',
value: function error() {
for (
var _len3 = arguments.length, args = new Array(_len3), _key3 = 0;
_key3 < _len3;
_key3++
) {
args[_key3] = arguments[_key3];
}
return this.forward(args, 'error', '');
}
},
{
key: 'deprecate',
value: function deprecate() {
for (
var _len4 = arguments.length, args = new Array(_len4), _key4 = 0;
_key4 < _len4;
_key4++
) {
args[_key4] = arguments[_key4];
}
return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);
}
},
{
key: 'forward',
value: function forward(args, lvl, prefix, debugOnly) {
if (debugOnly && !this.debug) return null;
if (typeof args[0] === 'string')
args[0] = ''
.concat(prefix)
.concat(this.prefix, ' ')
.concat(args[0]);
return this.logger[lvl](args);
}
},
{
key: 'create',
value: function create(moduleName) {
return new Logger(
this.logger,
_objectSpread(
{},
{
prefix: ''.concat(this.prefix, ':').concat(moduleName, ':')
},
this.options
)
);
}
}
]);
return Logger;
})();
var baseLogger = new Logger();
var EventEmitter =
/*#__PURE__*/
(function() {
function EventEmitter() {
_classCallCheck(this, EventEmitter);
this.observers = {};
}
_createClass(EventEmitter, [
{
key: 'on',
value: function on(events, listener) {
var _this = this;
events.split(' ').forEach(function(event) {
_this.observers[event] = _this.observers[event] || [];
_this.observers[event].push(listener);
});
return this;
}
},
{
key: 'off',
value: function off(event, listener) {
if (!this.observers[event]) return;
if (!listener) {
delete this.observers[event];
return;
}
this.observers[event] = this.observers[event].filter(function(l) {
return l !== listener;
});
}
},
{
key: 'emit',
value: function emit(event) {
for (
var _len = arguments.length,
args = new Array(_len > 1 ? _len - 1 : 0),
_key = 1;
_key < _len;
_key++
) {
args[_key - 1] = arguments[_key];
}
if (this.observers[event]) {
var cloned = [].concat(this.observers[event]);
cloned.forEach(function(observer) {
observer.apply(void 0, args);
});
}
if (this.observers['*']) {
var _cloned = [].concat(this.observers['*']);
_cloned.forEach(function(observer) {
observer.apply(observer, [event].concat(args));
});
}
}
}
]);
return EventEmitter;
})();
// http://lea.verou.me/2016/12/resolve-promises-externally-with-this-one-weird-trick/
function defer() {
var res;
var rej;
var promise = new Promise(function(resolve, reject) {
res = resolve;
rej = reject;
});
promise.resolve = res;
promise.reject = rej;
return promise;
}
function makeString(object) {
if (object == null) return '';
/* eslint prefer-template: 0 */
return '' + object;
}
function copy(a, s, t) {
a.forEach(function(m) {
if (s[m]) t[m] = s[m];
});
}
function getLastOfPath(object, path, Empty) {
function cleanKey(key) {
return key && key.indexOf('###') > -1 ? key.replace(/###/g, '.') : key;
}
function canNotTraverseDeeper() {
return !object || typeof object === 'string';
}
var stack = typeof path !== 'string' ? [].concat(path) : path.split('.');
while (stack.length > 1) {
if (canNotTraverseDeeper()) return {};
var key = cleanKey(stack.shift());
if (!object[key] && Empty) object[key] = new Empty();
object = object[key];
}
if (canNotTraverseDeeper()) return {};
return {
obj: object,
k: cleanKey(stack.shift())
};
}
function setPath(object, path, newValue) {
var _getLastOfPath = getLastOfPath(object, path, Object),
obj = _getLastOfPath.obj,
k = _getLastOfPath.k;
obj[k] = newValue;
}
function pushPath(object, path, newValue, concat) {
var _getLastOfPath2 = getLastOfPath(object, path, Object),
obj = _getLastOfPath2.obj,
k = _getLastOfPath2.k;
obj[k] = obj[k] || [];
if (concat) obj[k] = obj[k].concat(newValue);
if (!concat) obj[k].push(newValue);
}
function getPath(object, path) {
var _getLastOfPath3 = getLastOfPath(object, path),
obj = _getLastOfPath3.obj,
k = _getLastOfPath3.k;
if (!obj) return undefined;
return obj[k];
}
function getPathWithDefaults(data, defaultData, key) {
var value = getPath(data, key);
if (value !== undefined) {
return value;
} // Fallback to default values
return getPath(defaultData, key);
}
function deepExtend(target, source, overwrite) {
/* eslint no-restricted-syntax: 0 */
for (var prop in source) {
if (prop in target) {
// If we reached a leaf string in target or source then replace with source or skip depending on the 'overwrite' switch
if (
typeof target[prop] === 'string' ||
target[prop] instanceof String ||
typeof source[prop] === 'string' ||
source[prop] instanceof String
) {
if (overwrite) target[prop] = source[prop];
} else {
deepExtend(target[prop], source[prop], overwrite);
}
} else {
target[prop] = source[prop];
}
}
return target;
}
function regexEscape(str) {
/* eslint no-useless-escape: 0 */
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}
/* eslint-disable */
var _entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/'
};
/* eslint-enable */
function escape(data) {
if (typeof data === 'string') {
return data.replace(/[&<>"'\/]/g, function(s) {
return _entityMap[s];
});
}
return data;
}
var ResourceStore =
/*#__PURE__*/
(function(_EventEmitter) {
_inherits(ResourceStore, _EventEmitter);
function ResourceStore(data) {
var _this;
var options =
arguments.length > 1 && arguments[1] !== undefined
? arguments[1]
: {
ns: ['translation'],
defaultNS: 'translation'
};
_classCallCheck(this, ResourceStore);
_this = _possibleConstructorReturn(
this,
_getPrototypeOf(ResourceStore).call(this)
);
EventEmitter.call(_assertThisInitialized(_this)); // <=IE10 fix (unable to call parent constructor)
_this.data = data || {};
_this.options = options;
if (_this.options.keySeparator === undefined) {
_this.options.keySeparator = '.';
}
return _this;
}
_createClass(ResourceStore, [
{
key: 'addNamespaces',
value: function addNamespaces(ns) {
if (this.options.ns.indexOf(ns) < 0) {
this.options.ns.push(ns);
}
}
},
{
key: 'removeNamespaces',
value: function removeNamespaces(ns) {
var index = this.options.ns.indexOf(ns);
if (index > -1) {
this.options.ns.splice(index, 1);
}
}
},
{
key: 'getResource',
value: function getResource(lng, ns, key) {
var options =
arguments.length > 3 && arguments[3] !== undefined
? arguments[3]
: {};
var keySeparator =
options.keySeparator !== undefined
? options.keySeparator
: this.options.keySeparator;
var path = [lng, ns];
if (key && typeof key !== 'string') path = path.concat(key);
if (key && typeof key === 'string')
path = path.concat(keySeparator ? key.split(keySeparator) : key);
if (lng.indexOf('.') > -1) {
path = lng.split('.');
}
return getPath(this.data, path);
}
},
{
key: 'addResource',
value: function addResource(lng, ns, key, value) {
var options =
arguments.length > 4 && arguments[4] !== undefined
? arguments[4]
: {
silent: false
};
var keySeparator = this.options.keySeparator;
if (keySeparator === undefined) keySeparator = '.';
var path = [lng, ns];
if (key)
path = path.concat(keySeparator ? key.split(keySeparator) : key);
if (lng.indexOf('.') > -1) {
path = lng.split('.');
value = ns;
ns = path[1];
}
this.addNamespaces(ns);
setPath(this.data, path, value);
if (!options.silent) this.emit('added', lng, ns, key, value);
}
},
{
key: 'addResources',
value: function addResources(lng, ns, resources) {
var options =
arguments.length > 3 && arguments[3] !== undefined
? arguments[3]
: {
silent: false
};
/* eslint no-restricted-syntax: 0 */
for (var m in resources) {
if (
typeof resources[m] === 'string' ||
Object.prototype.toString.apply(resources[m]) === '[object Array]'
)
this.addResource(lng, ns, m, resources[m], {
silent: true
});
}
if (!options.silent) this.emit('added', lng, ns, resources);
}
},
{
key: 'addResourceBundle',
value: function addResourceBundle(lng, ns, resources, deep, overwrite) {
var options =
arguments.length > 5 && arguments[5] !== undefined
? arguments[5]
: {
silent: false
};
var path = [lng, ns];
if (lng.indexOf('.') > -1) {
path = lng.split('.');
deep = resources;
resources = ns;
ns = path[1];
}
this.addNamespaces(ns);
var pack = getPath(this.data, path) || {};
if (deep) {
deepExtend(pack, resources, overwrite);
} else {
pack = _objectSpread({}, pack, resources);
}
setPath(this.data, path, pack);
if (!options.silent) this.emit('added', lng, ns, resources);
}
},
{
key: 'removeResourceBundle',
value: function removeResourceBundle(lng, ns) {
if (this.hasResourceBundle(lng, ns)) {
delete this.data[lng][ns];
}
this.removeNamespaces(ns);
this.emit('removed', lng, ns);
}
},
{
key: 'hasResourceBundle',
value: function hasResourceBundle(lng, ns) {
return this.getResource(lng, ns) !== undefined;
}
},
{
key: 'getResourceBundle',
value: function getResourceBundle(lng, ns) {
if (!ns) ns = this.options.defaultNS; // COMPATIBILITY: remove extend in v2.1.0
if (this.options.compatibilityAPI === 'v1')
return _objectSpread({}, {}, this.getResource(lng, ns));
return this.getResource(lng, ns);
}
},
{
key: 'getDataByLanguage',
value: function getDataByLanguage(lng) {
return this.data[lng];
}
},
{
key: 'toJSON',
value: function toJSON() {
return this.data;
}
}
]);
return ResourceStore;
})(EventEmitter);
var postProcessor = {
processors: {},
addPostProcessor: function addPostProcessor(module) {
this.processors[module.name] = module;
},
handle: function handle(processors, value, key, options, translator) {
var _this = this;
processors.forEach(function(processor) {
if (_this.processors[processor])
value = _this.processors[processor].process(
value,
key,
options,
translator
);
});
return value;
}
};
var checkedLoadedFor = {};
var Translator =
/*#__PURE__*/
(function(_EventEmitter) {
_inherits(Translator, _EventEmitter);
function Translator(services) {
var _this;
var options =
arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, Translator);
_this = _possibleConstructorReturn(
this,
_getPrototypeOf(Translator).call(this)
);
EventEmitter.call(_assertThisInitialized(_this)); // <=IE10 fix (unable to call parent constructor)
copy(
[
'resourceStore',
'languageUtils',
'pluralResolver',
'interpolator',
'backendConnector',
'i18nFormat',
'utils'
],
services,
_assertThisInitialized(_this)
);
_this.options = options;
if (_this.options.keySeparator === undefined) {
_this.options.keySeparator = '.';
}
_this.logger = baseLogger.create('translator');
return _this;
}
_createClass(Translator, [
{
key: 'changeLanguage',
value: function changeLanguage(lng) {
if (lng) this.language = lng;
}
},
{
key: 'exists',
value: function exists(key) {
var options =
arguments.length > 1 && arguments[1] !== undefined
? arguments[1]
: {
interpolation: {}
};
var resolved = this.resolve(key, options);
return resolved && resolved.res !== undefined;
}
},
{
key: 'extractFromKey',
value: function extractFromKey(key, options) {
var nsSeparator = options.nsSeparator || this.options.nsSeparator;
if (nsSeparator === undefined) nsSeparator = ':';
var keySeparator =
options.keySeparator !== undefined
? options.keySeparator
: this.options.keySeparator;
var namespaces = options.ns || this.options.defaultNS;
if (nsSeparator && key.indexOf(nsSeparator) > -1) {
var parts = key.split(nsSeparator);
if (
nsSeparator !== keySeparator ||
(nsSeparator === keySeparator &&
this.options.ns.indexOf(parts[0]) > -1)
)
namespaces = parts.shift();
key = parts.join(keySeparator);
}
if (typeof namespaces === 'string') namespaces = [namespaces];
return {
key: key,
namespaces: namespaces
};
}
},
{
key: 'translate',
value: function translate(keys, options) {
var _this2 = this;
if (
_typeof(options) !== 'object' &&
this.options.overloadTranslationOptionHandler
) {
/* eslint prefer-rest-params: 0 */
options = this.options.overloadTranslationOptionHandler(arguments);
}
if (!options) options = {}; // non valid keys handling
if (
keys === undefined ||
keys === null
/* || keys === ''*/
)
return '';
if (!Array.isArray(keys)) keys = [String(keys)]; // separators
var keySeparator =
options.keySeparator !== undefined
? options.keySeparator
: this.options.keySeparator; // get namespace(s)
var _this$extractFromKey = this.extractFromKey(
keys[keys.length - 1],
options
),
key = _this$extractFromKey.key,
namespaces = _this$extractFromKey.namespaces;
var namespace = namespaces[namespaces.length - 1]; // return key on CIMode
var lng = options.lng || this.language;
var appendNamespaceToCIMode =
options.appendNamespaceToCIMode ||
this.options.appendNamespaceToCIMode;
if (lng && lng.toLowerCase() === 'cimode') {
if (appendNamespaceToCIMode) {
var nsSeparator = options.nsSeparator || this.options.nsSeparator;
return namespace + nsSeparator + key;
}
return key;
} // resolve from store
var resolved = this.resolve(keys, options);
var res = resolved && resolved.res;
var resUsedKey = (resolved && resolved.usedKey) || key;
var resExactUsedKey = (resolved && resolved.exactUsedKey) || key;
var resType = Object.prototype.toString.apply(res);
var noObject = [
'[object Number]',
'[object Function]',
'[object RegExp]'
];
var joinArrays =
options.joinArrays !== undefined
? options.joinArrays
: this.options.joinArrays; // object
var handleAsObjectInI18nFormat =
!this.i18nFormat || this.i18nFormat.handleAsObject;
var handleAsObject =
typeof res !== 'string' &&
typeof res !== 'boolean' &&
typeof res !== 'number';
if (
handleAsObjectInI18nFormat &&
res &&
handleAsObject &&
noObject.indexOf(resType) < 0 &&
!(typeof joinArrays === 'string' && resType === '[object Array]')
) {
if (!options.returnObjects && !this.options.returnObjects) {
this.logger.warn(
'accessing an object - but returnObjects options is not enabled!'
);
return this.options.returnedObjectHandler
? this.options.returnedObjectHandler(resUsedKey, res, options)
: "key '"
.concat(key, ' (')
.concat(
this.language,
")' returned an object instead of string."
);
} // if we got a separator we loop over children - else we just return object as is
// as having it set to false means no hierarchy so no lookup for nested values
if (keySeparator) {
var resTypeIsArray = resType === '[object Array]';
var copy$$1 = resTypeIsArray ? [] : {}; // apply child translation on a copy
/* eslint no-restricted-syntax: 0 */
var newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
for (var m in res) {
if (Object.prototype.hasOwnProperty.call(res, m)) {
var deepKey = ''
.concat(newKeyToUse)
.concat(keySeparator)
.concat(m);
copy$$1[m] = this.translate(
deepKey,
_objectSpread({}, options, {
joinArrays: false,
ns: namespaces
})
);
if (copy$$1[m] === deepKey) copy$$1[m] = res[m]; // if nothing found use orginal value as fallback
}
}
res = copy$$1;
}
} else if (
handleAsObjectInI18nFormat &&
typeof joinArrays === 'string' &&
resType === '[object Array]'
) {
// array special treatment
res = res.join(joinArrays);
if (res) res = this.extendTranslation(res, keys, options);
} else {
// string, empty or null
var usedDefault = false;
var usedKey = false; // fallback value
if (!this.isValidLookup(res) && options.defaultValue !== undefined) {
usedDefault = true;
if (options.count !== undefined) {
var suffix = this.pluralResolver.getSuffix(lng, options.count);
res = options['defaultValue'.concat(suffix)];
}
if (!res) res = options.defaultValue;
}
if (!this.isValidLookup(res)) {
usedKey = true;
res = key;
} // save missing
var updateMissing =
options.defaultValue &&
options.defaultValue !== res &&
this.options.updateMissing;
if (usedKey || usedDefault || updateMissing) {
this.logger.log(
updateMissing ? 'updateKey' : 'missingKey',
lng,
namespace,
key,
updateMissing ? options.defaultValue : res
);
var lngs = [];
var fallbackLngs = this.languageUtils.getFallbackCodes(
this.options.fallbackLng,
options.lng || this.language
);
if (
this.options.saveMissingTo === 'fallback' &&
fallbackLngs &&
fallbackLngs[0]
) {
for (var i = 0; i < fallbackLngs.length; i++) {
lngs.push(fallbackLngs[i]);
}
} else if (this.options.saveMissingTo === 'all') {
lngs = this.languageUtils.toResolveHierarchy(
options.lng || this.language
);
} else {
lngs.push(options.lng || this.language);
}
var send = function send(l, k) {
if (_this2.options.missingKeyHandler) {
_this2.options.missingKeyHandler(
l,
namespace,
k,
updateMissing ? options.defaultValue : res,
updateMissing,
options
);
} else if (
_this2.backendConnector &&
_this2.backendConnector.saveMissing
) {
_this2.backendConnector.saveMissing(
l,
namespace,
k,
updateMissing ? options.defaultValue : res,
updateMissing,
options
);
}
_this2.emit('missingKey', l, namespace, k, res);
};
if (this.options.saveMissing) {
var needsPluralHandling =
options.count !== undefined &&
typeof options.count !== 'string';
if (this.options.saveMissingPlurals && needsPluralHandling) {
lngs.forEach(function(l) {
var plurals = _this2.pluralResolver.getPluralFormsOfKey(
l,
key
);
plurals.forEach(function(p) {
return send([l], p);
});
});
} else {
send(lngs, key);
}
}
} // extend
res = this.extendTranslation(res, keys, options, resolved); // append namespace if still key
if (
usedKey &&
res === key &&
this.options.appendNamespaceToMissingKey
)
res = ''.concat(namespace, ':').concat(key); // parseMissingKeyHandler
if (usedKey && this.options.parseMissingKeyHandler)
res = this.options.parseMissingKeyHandler(res);
} // return
return res;
}
},
{
key: 'extendTranslation',
value: function extendTranslation(res, key, options, resolved) {
var _this3 = this;
if (this.i18nFormat && this.i18nFormat.parse) {
res = this.i18nFormat.parse(
res,
options,
resolved.usedLng,
resolved.usedNS,
resolved.usedKey,
{
resolved: resolved
}
);
} else if (!options.skipInterpolation) {
// i18next.parsing
if (options.interpolation)
this.interpolator.init(
_objectSpread({}, options, {
interpolation: _objectSpread(
{},
this.options.interpolation,
options.interpolation
)
})
); // interpolate
var data =
options.replace && typeof options.replace !== 'string'
? options.replace
: options;
if (this.options.interpolation.defaultVariables)
data = _objectSpread(
{},
this.options.interpolation.defaultVariables,
data
);
res = this.interpolator.interpolate(
res,
data,
options.lng || this.language,
options
); // nesting
if (options.nest !== false)
res = this.interpolator.nest(
res,
function() {
return _this3.translate.apply(_this3, arguments);
},
options
);
if (options.interpolation) this.interpolator.reset();
} // post process
var postProcess = options.postProcess || this.options.postProcess;
var postProcessorNames =
typeof postProcess === 'string' ? [postProcess] : postProcess;
if (
res !== undefined &&
res !== null &&
postProcessorNames &&
postProcessorNames.length &&
options.applyPostProcessor !== false
) {
res = postProcessor.handle(
postProcessorNames,
res,
key,
this.options && this.options.postProcessPassResolved
? _objectSpread(
{
i18nResolved: resolved
},
options
)
: options,
this
);
}
return res;
}
},
{
key: 'resolve',
value: function resolve(keys) {
var _this4 = this;
var options =
arguments.length > 1 && arguments[1] !== undefined
? arguments[1]
: {};
var found;
var usedKey; // plain key
var exactUsedKey; // key with context / plural
var usedLng;
var usedNS;
if (typeof keys === 'string') keys = [keys]; // forEach possible key
keys.forEach(function(k) {
if (_this4.isValidLookup(found)) return;
var extracted = _this4.extractFromKey(k, options);
var key = extracted.key;
usedKey = key;
var namespaces = extracted.namespaces;
if (_this4.options.fallbackNS)
namespaces = namespaces.concat(_this4.options.fallbackNS);
var needsPluralHandling =
options.count !== undefined && typeof options.count !== 'string';
var needsContextHandling =
options.context !== undefined &&
typeof options.context === 'string' &&
options.context !== '';
var codes = options.lngs
? options.lngs
: _this4.languageUtils.toResolveHierarchy(
options.lng || _this4.language,
options.fallbackLng
);
namespaces.forEach(function(ns) {
if (_this4.isValidLookup(found)) return;
usedNS = ns;
if (
!checkedLoadedFor[''.concat(codes[0], '-').concat(ns)] &&
_this4.utils &&
_this4.utils.hasLoadedNamespace &&
!_this4.utils.hasLoadedNamespace(usedNS)
) {
checkedLoadedFor[''.concat(codes[0], '-').concat(ns)] = true;
_this4.logger.warn(
'key "'
.concat(usedKey, '" for namespace "')
.concat(usedNS, '" for languages "')
.concat(
codes.join(', '),
'" won\'t get resolved as namespace was not yet loaded'
),
'This means something IS WRONG in your application setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!'
);
}
codes.forEach(function(code) {
if (_this4.isValidLookup(found)) return;
usedLng = code;
var finalKey = key;
var finalKeys = [finalKey];
if (_this4.i18nFormat && _this4.i18nFormat.addLookupKeys) {
_this4.i18nFormat.addLookupKeys(
finalKeys,
key,
code,
ns,
options
);
} else {
var pluralSuffix;
if (needsPluralHandling)
pluralSuffix = _this4.pluralResolver.getSuffix(
code,
options.count
); // fallback for plural if context not found
if (needsPluralHandling && needsContextHandling)
finalKeys.push(finalKey + pluralSuffix); // get key for context if needed
if (needsContextHandling)
finalKeys.push(
(finalKey += ''
.concat(_this4.options.contextSeparator)
.concat(options.context))
); // get key for plural if needed
if (needsPluralHandling)
finalKeys.push((finalKey += pluralSuffix));
} // iterate over finalKeys starting with most specific pluralkey (-> contextkey only) -> singularkey only
var possibleKey;
/* eslint no-cond-assign: 0 */
while ((possibleKey = finalKeys.pop())) {
if (!_this4.isValidLookup(found)) {
exactUsedKey = possibleKey;
found = _this4.getResource(code, ns, possibleKey, options);
}
}
});
});
});
return {
res: found,
usedKey: usedKey,
exactUsedKey: exactUsedKey,
usedLng: usedLng,
usedNS: usedNS
};
}
},
{
key: 'isValidLookup',
value: function isValidLookup(res) {
return (
res !== undefined &&
!(!this.options.returnNull && res === null) &&
!(!this.options.returnEmptyString && res === '')
);
}
},
{
key: 'getResource',
value: function getResource(code, ns, key) {
var options =
arguments.length > 3 && arguments[3] !== undefined
? arguments[3]
: {};
if (this.i18nFormat && this.i18nFormat.getResource)
return this.i18nFormat.getResource(code, ns, key, options);
return this.resourceStore.getResource(code, ns, key, options);
}
}
]);
return Translator;
})(EventEmitter);
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
var LanguageUtil =
/*#__PURE__*/
(function() {
function LanguageUtil(options) {
_classCallCheck(this, LanguageUtil);
this.options = options;
this.whitelist = this.options.whitelist || false;
this.logger = baseLogger.create('languageUtils');
}
_createClass(LanguageUtil, [
{
key: 'getScriptPartFromCode',
value: function getScriptPartFromCode(code) {
if (!code || code.indexOf('-') < 0) return null;
var p = code.split('-');
if (p.length === 2) return null;
p.pop();
return this.formatLanguageCode(p.join('-'));
}
},
{
key: 'getLanguagePartFromCode',
value: function getLanguagePartFromCode(code) {
if (!code || code.indexOf('-') < 0) return code;
var p = code.split('-');
return this.formatLanguageCode(p[0]);
}
},
{
key: 'formatLanguageCode',
value: function formatLanguageCode(code) {
// http://www.iana.org/assignments/language-tags/language-tags.xhtml
if (typeof code === 'string' && code.indexOf('-') > -1) {
var specialCases = [
'hans',
'hant',
'latn',
'cyrl',
'cans',
'mong',
'arab'
];
var p = code.split('-');
if (this.options.lowerCaseLng) {
p = p.map(function(part) {
return part.toLowerCase();
});
} else if (p.length === 2) {
p[0] = p[0].toLowerCase();
p[1] = p[1].toUpperCase();
if (specialCases.indexOf(p[1].toLowerCase()) > -1)
p[1] = capitalize(p[1].toLowerCase());
} else if (p.length === 3) {
p[0] = p[0].toLowerCase(); // if lenght 2 guess it's a country
if (p[1].length === 2) p[1] = p[1].toUpperCase();
if (p[0] !== 'sgn' && p[2].length === 2) p[2] = p[2].toUpperCase();
if (specialCases.indexOf(p[1].toLowerCase()) > -1)
p[1] = capitalize(p[1].toLowerCase());
if (specialCases.indexOf(p[2].toLowerCase()) > -1)
p[2] = capitalize(p[2].toLowerCase());
}
return p.join('-');
}
return this.options.cleanCode || this.options.lowerCaseLng
? code.toLowerCase()
: code;
}
},
{
key: 'isWhitelisted',
value: function isWhitelisted(code) {
if (
this.options.load === 'languageOnly' ||
this.options.nonExplicitWhitelist
) {
code = this.getLanguagePartFromCode(code);
}
return (
!this.whitelist ||
!this.whitelist.length ||
this.whitelist.indexOf(code) > -1
);
}
},
{
key: 'getFallbackCodes',
value: function getFallbackCodes(fallbacks, code) {
if (!fallbacks) return [];
if (typeof fallbacks === 'string') fallbacks = [fallbacks];
if (Object.prototype.toString.apply(fallbacks) === '[object Array]')
return fallbacks;
if (!code) return fallbacks['default'] || []; // asume we have an object defining fallbacks
var found = fallbacks[code];
if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
if (!found) found = fallbacks[this.formatLanguageCode(code)];
if (!found) found = fallbacks['default'];
return found || [];
}
},
{
key: 'toResolveHierarchy',
value: function toResolveHierarchy(code, fallbackCode) {
var _this = this;
var fallbackCodes = this.getFallbackCodes(
fallbackCode || this.options.fallbackLng || [],
code
);
var codes = [];
var addCode = function addCode(c) {
if (!c) return;
if (_this.isWhitelisted(c)) {
codes.push(c);
} else {
_this.logger.warn(
'rejecting non-whitelisted language code: '.concat(c)
);
}
};
if (typeof code === 'string' && code.indexOf('-') > -1) {
if (this.options.load !== 'languageOnly')
addCode(this.formatLanguageCode(code));
if (
this.options.load !== 'languageOnly' &&
this.options.load !== 'currentOnly'
)
addCode(this.getScriptPartFromCode(code));
if (this.options.load !== 'currentOnly')
addCode(this.getLanguagePartFromCode(code));
} else if (typeof code === 'string') {
addCode(this.formatLanguageCode(code));
}
fallbackCodes.forEach(function(fc) {
if (codes.indexOf(fc) < 0) addCode(_this.formatLanguageCode(fc));
});
return codes;
}
}
]);
return LanguageUtil;
})();
/* eslint-disable */
var sets = [
{
lngs: [
'ach',
'ak',
'am',
'arn',
'br',
'fil',
'gun',
'ln',
'mfe',
'mg',
'mi',
'oc',
'pt',
'pt-BR',
'tg',
'ti',
'tr',
'uz',
'wa'
],
nr: [1, 2],
fc: 1
},
{
lngs: [
'af',
'an',
'ast',
'az',
'bg',
'bn',
'ca',
'da',
'de',
'dev',
'el',
'en',
'eo',
'es',
'et',
'eu',
'fi',
'fo',
'fur',
'fy',
'gl',
'gu',
'ha',
'hi',
'hu',
'hy',
'ia',
'it',
'kn',
'ku',
'lb',
'mai',
'ml',
'mn',
'mr',
'nah',
'nap',
'nb',
'ne',
'nl',
'nn',
'no',
'nso',
'pa',
'pap',
'pms',
'ps',
'pt-PT',
'rm',
'sco',
'se',
'si',
'so',
'son',
'sq',
'sv',
'sw',
'ta',
'te',
'tk',
'ur',
'yo'
],
nr: [1, 2],
fc: 2
},
{
lngs: [
'ay',
'bo',
'cgg',
'fa',
'id',
'ja',
'jbo',
'ka',
'kk',
'km',
'ko',
'ky',
'lo',
'ms',
'sah',
'su',
'th',
'tt',
'ug',
'vi',
'wo',
'zh'
],
nr: [1],
fc: 3
},
{
lngs: ['be', 'bs', 'cnr', 'dz', 'hr', 'ru', 'sr', 'uk'],
nr: [1, 2, 5],
fc: 4
},
{
lngs: ['ar'],
nr: [0, 1, 2, 3, 11, 100],
fc: 5
},
{
lngs: ['cs', 'sk'],
nr: [1, 2, 5],
fc: 6
},
{
lngs: ['csb', 'pl'],
nr: [1, 2, 5],
fc: 7
},
{
lngs: ['cy'],
nr: [1, 2, 3, 8],
fc: 8
},
{
lngs: ['fr'],
nr: [1, 2],
fc: 9
},
{
lngs: ['ga'],
nr: [1, 2, 3, 7, 11],
fc: 10
},
{
lngs: ['gd'],
nr: [1, 2, 3, 20],
fc: 11
},
{
lngs: ['is'],
nr: [1, 2],
fc: 12
},
{
lngs: ['jv'],
nr: [0, 1],
fc: 13
},
{
lngs: ['kw'],
nr: [1, 2, 3, 4],
fc: 14
},
{
lngs: ['lt'],
nr: [1, 2, 10],
fc: 15
},
{
lngs: ['lv'],
nr: [1, 2, 0],
fc: 16
},
{
lngs: ['mk'],
nr: [1, 2],
fc: 17
},
{
lngs: ['mnk'],
nr: [0, 1, 2],
fc: 18
},
{
lngs: ['mt'],
nr: [1, 2, 11, 20],
fc: 19
},
{
lngs: ['or'],
nr: [2, 1],
fc: 2
},
{
lngs: ['ro'],
nr: [1, 2, 20],
fc: 20
},
{
lngs: ['sl'],
nr: [5, 1, 2, 3],
fc: 21
},
{
lngs: ['he'],
nr: [1, 2, 20, 21],
fc: 22
}
];
var _rulesPluralsTypes = {
1: function _(n) {
return Number(n > 1);
},
2: function _(n) {
return Number(n != 1);
},
3: function _(n) {
return 0;
},
4: function _(n) {
return Number(
n % 10 == 1 && n % 100 != 11
? 0
: n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2
);
},
5: function _(n) {
return Number(
n === 0
? 0
: n == 1
? 1
: n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5
);
},
6: function _(n) {
return Number(n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2);
},
7: function _(n) {
return Number(
n == 1
? 0
: n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2
);
},
8: function _(n) {
return Number(n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3);
},
9: function _(n) {
return Number(n >= 2);
},
10: function _(n) {
return Number(n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4);
},
11: function _(n) {
return Number(
n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3
);
},
12: function _(n) {
return Number(n % 10 != 1 || n % 100 == 11);
},
13: function _(n) {
return Number(n !== 0);
},
14: function _(n) {
return Number(n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3);
},
15: function _(n) {
return Number(
n % 10 == 1 && n % 100 != 11
? 0
: n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2
);
},
16: function _(n) {
return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n !== 0 ? 1 : 2);
},
17: function _(n) {
return Number(n == 1 || n % 10 == 1 ? 0 : 1);
},
18: function _(n) {
return Number(n == 0 ? 0 : n == 1 ? 1 : 2);
},
19: function _(n) {
return Number(
n == 1
? 0
: n === 0 || (n % 100 > 1 && n % 100 < 11)
? 1
: n % 100 > 10 && n % 100 < 20 ? 2 : 3
);
},
20: function _(n) {
return Number(n == 1 ? 0 : n === 0 || (n % 100 > 0 && n % 100 < 20) ? 1 : 2);
},
21: function _(n) {
return Number(
n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0
);
},
22: function _(n) {
return Number(
n === 1 ? 0 : n === 2 ? 1 : (n < 0 || n > 10) && n % 10 == 0 ? 2 : 3
);
}
};
/* eslint-enable */
function createRules() {
var rules = {};
sets.forEach(function(set) {
set.lngs.forEach(function(l) {
rules[l] = {
numbers: set.nr,
plurals: _rulesPluralsTypes[set.fc]
};
});
});
return rules;
}
var PluralResolver =
/*#__PURE__*/
(function() {
function PluralResolver(languageUtils) {
var options =
arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, PluralResolver);
this.languageUtils = languageUtils;
this.options = options;
this.logger = baseLogger.create('pluralResolver');
this.rules = createRules();
}
_createClass(PluralResolver, [
{
key: 'addRule',
value: function addRule(lng, obj) {
this.rules[lng] = obj;
}
},
{
key: 'getRule',
value: function getRule(code) {
return (
this.rules[code] ||
this.rules[this.languageUtils.getLanguagePartFromCode(code)]
);
}
},
{
key: 'needsPlural',
value: function needsPlural(code) {
var rule = this.getRule(code);
return rule && rule.numbers.length > 1;
}
},
{
key: 'getPluralFormsOfKey',
value: function getPluralFormsOfKey(code, key) {
var _this = this;
var ret = [];
var rule = this.getRule(code);
if (!rule) return ret;
rule.numbers.forEach(function(n) {
var suffix = _this.getSuffix(code, n);
ret.push(''.concat(key).concat(suffix));
});
return ret;
}
},
{
key: 'getSuffix',
value: function getSuffix(code, count) {
var _this2 = this;
var rule = this.getRule(code);
if (rule) {
// if (rule.numbers.length === 1) return ''; // only singular
var idx = rule.noAbs
? rule.plurals(count)
: rule.plurals(Math.abs(count));
var suffix = rule.numbers[idx]; // special treatment for lngs only having singular and plural
if (
this.options.simplifyPluralSuffix &&
rule.numbers.length === 2 &&
rule.numbers[0] === 1
) {
if (suffix === 2) {
suffix = 'plural';
} else if (suffix === 1) {
suffix = '';
}
}
var returnSuffix = function returnSuffix() {
return _this2.options.prepend && suffix.toString()
? _this2.options.prepend + suffix.toString()
: suffix.toString();
}; // COMPATIBILITY JSON
// v1
if (this.options.compatibilityJSON === 'v1') {
if (suffix === 1) return '';
if (typeof suffix === 'number')
return '_plural_'.concat(suffix.toString());
return returnSuffix();
} else if (
/* v2 */
this.options.compatibilityJSON === 'v2'
) {
return returnSuffix();
} else if (
/* v3 - gettext index */
this.options.simplifyPluralSuffix &&
rule.numbers.length === 2 &&
rule.numbers[0] === 1
) {
return returnSuffix();
}
return this.options.prepend && idx.toString()
? this.options.prepend + idx.toString()
: idx.toString();
}
this.logger.warn('no plural rule found for: '.concat(code));
return '';
}
}
]);
return PluralResolver;
})();
var Interpolator =
/*#__PURE__*/
(function() {
function Interpolator() {
var options =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, Interpolator);
this.logger = baseLogger.create('interpolator');
this.options = options;
this.format =
(options.interpolation && options.interpolation.format) ||
function(value) {
return value;
};
this.init(options);
}
/* eslint no-param-reassign: 0 */
_createClass(Interpolator, [
{
key: 'init',
value: function init() {
var options =
arguments.length > 0 && arguments[0] !== undefined
? arguments[0]
: {};
if (!options.interpolation)
options.interpolation = {
escapeValue: true
};
var iOpts = options.interpolation;
this.escape = iOpts.escape !== undefined ? iOpts.escape : escape;
this.escapeValue =
iOpts.escapeValue !== undefined ? iOpts.escapeValue : true;
this.useRawValueToEscape =
iOpts.useRawValueToEscape !== undefined
? iOpts.useRawValueToEscape
: false;
this.prefix = iOpts.prefix
? regexEscape(iOpts.prefix)
: iOpts.prefixEscaped || '{{';
this.suffix = iOpts.suffix
? regexEscape(iOpts.suffix)
: iOpts.suffixEscaped || '}}';
this.formatSeparator = iOpts.formatSeparator
? iOpts.formatSeparator
: iOpts.formatSeparator || ',';
this.unescapePrefix = iOpts.unescapeSuffix
? ''
: iOpts.unescapePrefix || '-';
this.unescapeSuffix = this.unescapePrefix
? ''
: iOpts.unescapeSuffix || '';
this.nestingPrefix = iOpts.nestingPrefix
? regexEscape(iOpts.nestingPrefix)
: iOpts.nestingPrefixEscaped || regexEscape('$t(');
this.nestingSuffix = iOpts.nestingSuffix
? regexEscape(iOpts.nestingSuffix)
: iOpts.nestingSuffixEscaped || regexEscape(')');
this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1000; // the regexp
this.resetRegExp();
}
},
{
key: 'reset',
value: function reset() {
if (this.options) this.init(this.options);
}
},
{
key: 'resetRegExp',
value: function resetRegExp() {
// the regexp
var regexpStr = ''.concat(this.prefix, '(.+?)').concat(this.suffix);
this.regexp = new RegExp(regexpStr, 'g');
var regexpUnescapeStr = ''
.concat(this.prefix)
.concat(this.unescapePrefix, '(.+?)')
.concat(this.unescapeSuffix)
.concat(this.suffix);
this.regexpUnescape = new RegExp(regexpUnescapeStr, 'g');
var nestingRegexpStr = ''
.concat(this.nestingPrefix, '(.+?)')
.concat(this.nestingSuffix);
this.nestingRegexp = new RegExp(nestingRegexpStr, 'g');
}
},
{
key: 'interpolate',
value: function interpolate(str, data, lng, options) {
var _this = this;
var match;
var value;
var replaces;
var defaultData =
(this.options &&
this.options.interpolation &&
this.options.interpolation.defaultVariables) ||
{};
function regexSafe(val) {
return val.replace(/\$/g, '$$$$');
}
var handleFormat = function handleFormat(key) {
if (key.indexOf(_this.formatSeparator) < 0) {
return getPathWithDefaults(data, defaultData, key);
}
var p = key.split(_this.formatSeparator);
var k = p.shift().trim();
var f = p.join(_this.formatSeparator).trim();
return _this.format(
getPathWithDefaults(data, defaultData, k),
f,
lng
);
};
this.resetRegExp();
var missingInterpolationHandler =
(options && options.missingInterpolationHandler) ||
this.options.missingInterpolationHandler;
replaces = 0; // unescape if has unescapePrefix/Suffix
/* eslint no-cond-assign: 0 */
while ((match = this.regexpUnescape.exec(str))) {
value = handleFormat(match[1].trim());
if (value === undefined) {
if (typeof missingInterpolationHandler === 'function') {
var temp = missingInterpolationHandler(str, match, options);
value = typeof temp === 'string' ? temp : '';
} else {
this.logger.warn(
'missed to pass in variable '
.concat(match[1], ' for interpolating ')
.concat(str)
);
value = '';
}
} else if (typeof value !== 'string' && !this.useRawValueToEscape) {
value = makeString(value);
}
str = str.replace(match[0], regexSafe(value));
this.regexpUnescape.lastIndex = 0;
replaces++;
if (replaces >= this.maxReplaces) {
break;
}
}
replaces = 0; // regular escape on demand
while ((match = this.regexp.exec(str))) {
value = handleFormat(match[1].trim());
if (value === undefined) {
if (typeof missingInterpolationHandler === 'function') {
var _temp = missingInterpolationHandler(str, match, options);
value = typeof _temp === 'string' ? _temp : '';
} else {
this.logger.warn(
'missed to pass in variable '
.concat(match[1], ' for interpolating ')
.concat(str)
);
value = '';
}
} else if (typeof value !== 'string' && !this.useRawValueToEscape) {
value = makeString(value);
}
value = this.escapeValue
? regexSafe(this.escape(value))
: regexSafe(value);
str = str.replace(match[0], value);
this.regexp.lastIndex = 0;
replaces++;
if (replaces >= this.maxReplaces) {
break;
}
}
return str;
}
},
{
key: 'nest',
value: function nest(str, fc) {
var options =
arguments.length > 2 && arguments[2] !== undefined
? arguments[2]
: {};
var match;
var value;
var clonedOptions = _objectSpread({}, options);
clonedOptions.applyPostProcessor = false; // avoid post processing on nested lookup
delete clonedOptions.defaultValue; // assert we do not get a endless loop on interpolating defaultValue again and again
// if value is something like "myKey": "lorem $(anotherKey, { "count": {{aValueInOptions}} })"
function handleHasOptions(key, inheritedOptions) {
if (key.indexOf(',') < 0) return key;
var p = key.split(',');
key = p.shift();
var optionsString = p.join(',');
optionsString = this.interpolate(optionsString, clonedOptions);
optionsString = optionsString.replace(/'/g, '"');
try {
clonedOptions = JSON.parse(optionsString);
if (inheritedOptions)
clonedOptions = _objectSpread(
{},
inheritedOptions,
clonedOptions
);
} catch (e) {
this.logger.error(
'failed parsing options string in nesting for key '.concat(key),
e
);
} // assert we do not get a endless loop on interpolating defaultValue again and again
delete clonedOptions.defaultValue;
return key;
} // regular escape on demand
while ((match = this.nestingRegexp.exec(str))) {
value = fc(
handleHasOptions.call(this, match[1].trim(), clonedOptions),
clonedOptions
); // is only the nesting key (key1 = '$(key2)') return the value without stringify
if (value && match[0] === str && typeof value !== 'string')
return value; // no string to include or empty
if (typeof value !== 'string') value = makeString(value);
if (!value) {
this.logger.warn(
'missed to resolve '.concat(match[1], ' for nesting ').concat(str)
);
value = '';
} // Nested keys should not be escaped by default #854
// value = this.escapeValue ? regexSafe(utils.escape(value)) : regexSafe(value);
str = str.replace(match[0], value);
this.regexp.lastIndex = 0;
}
return str;
}
}
]);
return Interpolator;
})();
function remove(arr, what) {
var found = arr.indexOf(what);
while (found !== -1) {
arr.splice(found, 1);
found = arr.indexOf(what);
}
}
var Connector =
/*#__PURE__*/
(function(_EventEmitter) {
_inherits(Connector, _EventEmitter);
function Connector(backend, store, services) {
var _this;
var options =
arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
_classCallCheck(this, Connector);
_this = _possibleConstructorReturn(
this,
_getPrototypeOf(Connector).call(this)
);
EventEmitter.call(_assertThisInitialized(_this)); // <=IE10 fix (unable to call parent constructor)
_this.backend = backend;
_this.store = store;
_this.services = services;
_this.languageUtils = services.languageUtils;
_this.options = options;
_this.logger = baseLogger.create('backendConnector');
_this.state = {};
_this.queue = [];
if (_this.backend && _this.backend.init) {
_this.backend.init(services, options.backend, options);
}
return _this;
}
_createClass(Connector, [
{
key: 'queueLoad',
value: function queueLoad(languages, namespaces, options, callback) {
var _this2 = this;
// find what needs to be loaded
var toLoad = [];
var pending = [];
var toLoadLanguages = [];
var toLoadNamespaces = [];
languages.forEach(function(lng) {
var hasAllNamespaces = true;
namespaces.forEach(function(ns) {
var name = ''.concat(lng, '|').concat(ns);
if (!options.reload && _this2.store.hasResourceBundle(lng, ns)) {
_this2.state[name] = 2; // loaded
} else if (_this2.state[name] < 0);
else if (_this2.state[name] === 1) {
if (pending.indexOf(name) < 0) pending.push(name);
} else {
_this2.state[name] = 1; // pending
hasAllNamespaces = false;
if (pending.indexOf(name) < 0) pending.push(name);
if (toLoad.indexOf(name) < 0) toLoad.push(name);
if (toLoadNamespaces.indexOf(ns) < 0) toLoadNamespaces.push(ns);
}
});
if (!hasAllNamespaces) toLoadLanguages.push(lng);
});
if (toLoad.length || pending.length) {
this.queue.push({
pending: pending,
loaded: {},
errors: [],
callback: callback
});
}
return {
toLoad: toLoad,
pending: pending,
toLoadLanguages: toLoadLanguages,
toLoadNamespaces: toLoadNamespaces
};
}
},
{
key: 'loaded',
value: function loaded(name, err, data) {
var _name$split = name.split('|'),
_name$split2 = _slicedToArray(_name$split, 2),
lng = _name$split2[0],
ns = _name$split2[1];
if (err) this.emit('failedLoading', lng, ns, err);
if (data) {
this.store.addResourceBundle(lng, ns, data);
} // set loaded
this.state[name] = err ? -1 : 2; // consolidated loading done in this run - only emit once for a loaded namespace
var loaded = {}; // callback if ready
this.queue.forEach(function(q) {
pushPath(q.loaded, [lng], ns);
remove(q.pending, name);
if (err) q.errors.push(err);
if (q.pending.length === 0 && !q.done) {
// only do once per loaded -> this.emit('loaded', q.loaded);
Object.keys(q.loaded).forEach(function(l) {
if (!loaded[l]) loaded[l] = [];
if (q.loaded[l].length) {
q.loaded[l].forEach(function(ns) {
if (loaded[l].indexOf(ns) < 0) loaded[l].push(ns);
});
}
});
/* eslint no-param-reassign: 0 */
q.done = true;
if (q.errors.length) {
q.callback(q.errors);
} else {
q.callback();
}
}
}); // emit consolidated loaded event
this.emit('loaded', loaded); // remove done load requests
this.queue = this.queue.filter(function(q) {
return !q.done;
});
}
},
{
key: 'read',
value: function read(lng, ns, fcName) {
var _this3 = this;
var tried =
arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
var wait =
arguments.length > 4 && arguments[4] !== undefined
? arguments[4]
: 250;
var callback = arguments.length > 5 ? arguments[5] : undefined;
if (!lng.length) return callback(null, {}); // noting to load
return this.backend[fcName](lng, ns, function(err, data) {
if (
err &&
data &&
/* = retryFlag */
tried < 5
) {
setTimeout(function() {
_this3.read.call(
_this3,
lng,
ns,
fcName,
tried + 1,
wait * 2,
callback
);
}, wait);
return;
}
callback(err, data);
});
}
/* eslint consistent-return: 0 */
},
{
key: 'prepareLoading',
value: function prepareLoading(languages, namespaces) {
var _this4 = this;
var options =
arguments.length > 2 && arguments[2] !== undefined
? arguments[2]
: {};
var callback = arguments.length > 3 ? arguments[3] : undefined;
if (!this.backend) {
this.logger.warn(
'No backend was added via i18next.use. Will not load resources.'
);
return callback && callback();
}
if (typeof languages === 'string')
languages = this.languageUtils.toResolveHierarchy(languages);
if (typeof namespaces === 'string') namespaces = [namespaces];
var toLoad = this.queueLoad(languages, namespaces, options, callback);
if (!toLoad.toLoad.length) {
if (!toLoad.pending.length) callback(); // nothing to load and no pendings...callback now
return null; // pendings will trigger callback
}
toLoad.toLoad.forEach(function(name) {
_this4.loadOne(name);
});
}
},
{
key: 'load',
value: function load(languages, namespaces, callback) {
this.prepareLoading(languages, namespaces, {}, callback);
}
},
{
key: 'reload',
value: function reload(languages, namespaces, callback) {
this.prepareLoading(
languages,
namespaces,
{
reload: true
},
callback
);
}
},
{
key: 'loadOne',
value: function loadOne(name) {
var _this5 = this;
var prefix =
arguments.length > 1 && arguments[1] !== undefined
? arguments[1]
: '';
var _name$split3 = name.split('|'),
_name$split4 = _slicedToArray(_name$split3, 2),
lng = _name$split4[0],
ns = _name$split4[1];
this.read(lng, ns, 'read', null, null, function(err, data) {
if (err)
_this5.logger.warn(
''
.concat(prefix, 'loading namespace ')
.concat(ns, ' for language ')
.concat(lng, ' failed'),
err
);
if (!err && data)
_this5.logger.log(
''
.concat(prefix, 'loaded namespace ')
.concat(ns, ' for language ')
.concat(lng),
data
);
_this5.loaded(name, err, data);
});
}
},
{
key: 'saveMissing',
value: function saveMissing(
languages,
namespace,
key,
fallbackValue,
isUpdate
) {
var options =
arguments.length > 5 && arguments[5] !== undefined
? arguments[5]
: {};
if (
this.services.utils &&
this.services.utils.hasLoadedNamespace &&
!this.services.utils.hasLoadedNamespace(namespace)
) {
this.logger.warn(
'did not save key "'
.concat(key, '" for namespace "')
.concat(namespace, '" as the namespace was not yet loaded'),
'This means something IS WRONG in your application setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!'
);
return;
} // ignore non valid keys
if (key === undefined || key === null || key === '') return;
if (this.backend && this.backend.create) {
this.backend.create(
languages,
namespace,
key,
fallbackValue,
null,
/* unused callback */
_objectSpread({}, options, {
isUpdate: isUpdate
})
);
} // write to store to avoid resending
if (!languages || !languages[0]) return;
this.store.addResource(languages[0], namespace, key, fallbackValue);
}
}
]);
return Connector;
})(EventEmitter);
function get() {
return {
debug: false,
initImmediate: true,
ns: ['translation'],
defaultNS: ['translation'],
fallbackLng: ['dev'],
fallbackNS: false,
// string or array of namespaces
whitelist: false,
// array with whitelisted languages
nonExplicitWhitelist: false,
load: 'all',
// | currentOnly | languageOnly
preload: false,
// array with preload languages
simplifyPluralSuffix: true,
keySeparator: '.',
nsSeparator: ':',
pluralSeparator: '_',
contextSeparator: '_',
partialBundledLanguages: false,
// allow bundling certain languages that are not remotely fetched
saveMissing: false,
// enable to send missing values
updateMissing: false,
// enable to update default values if different from translated value (only useful on initial development, or when keeping code as source of truth)
saveMissingTo: 'fallback',
// 'current' || 'all'
saveMissingPlurals: true,
// will save all forms not only singular key
missingKeyHandler: false,
// function(lng, ns, key, fallbackValue) -> override if prefer on handling
missingInterpolationHandler: false,
// function(str, match)
postProcess: false,
// string or array of postProcessor names
postProcessPassResolved: false,
// pass resolved object into 'options.i18nResolved' for postprocessor
returnNull: true,
// allows null value as valid translation
returnEmptyString: true,
// allows empty string value as valid translation
returnObjects: false,
joinArrays: false,
// or string to join array
returnedObjectHandler: false,
// function(key, value, options) triggered if key returns object but returnObjects is set to false
parseMissingKeyHandler: false,
// function(key) parsed a key that was not found in t() before returning
appendNamespaceToMissingKey: false,
appendNamespaceToCIMode: false,
overloadTranslationOptionHandler: function handle(args) {
var ret = {};
if (_typeof(args[1]) === 'object') ret = args[1];
if (typeof args[1] === 'string') ret.defaultValue = args[1];
if (typeof args[2] === 'string') ret.tDescription = args[2];
if (_typeof(args[2]) === 'object' || _typeof(args[3]) === 'object') {
var options = args[3] || args[2];
Object.keys(options).forEach(function(key) {
ret[key] = options[key];
});
}
return ret;
},
interpolation: {
escapeValue: true,
format: function format(value, _format, lng) {
return value;
},
prefix: '{{',
suffix: '}}',
formatSeparator: ',',
// prefixEscaped: '{{',
// suffixEscaped: '}}',
// unescapeSuffix: '',
unescapePrefix: '-',
nestingPrefix: '$t(',
nestingSuffix: ')',
// nestingPrefixEscaped: '$t(',
// nestingSuffixEscaped: ')',
// defaultVariables: undefined // object that can have values to interpolate on - extends passed in interpolation data
maxReplaces: 1000 // max replaces to prevent endless loop
}
};
}
/* eslint no-param-reassign: 0 */
function transformOptions(options) {
// create namespace object if namespace is passed in as string
if (typeof options.ns === 'string') options.ns = [options.ns];
if (typeof options.fallbackLng === 'string')
options.fallbackLng = [options.fallbackLng];
if (typeof options.fallbackNS === 'string')
options.fallbackNS = [options.fallbackNS]; // extend whitelist with cimode
if (options.whitelist && options.whitelist.indexOf('cimode') < 0) {
options.whitelist = options.whitelist.concat(['cimode']);
}
return options;
}
function noop() {}
var I18n =
/*#__PURE__*/
(function(_EventEmitter) {
_inherits(I18n, _EventEmitter);
function I18n() {
var _this;
var options =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var callback = arguments.length > 1 ? arguments[1] : undefined;
_classCallCheck(this, I18n);
_this = _possibleConstructorReturn(this, _getPrototypeOf(I18n).call(this));
EventEmitter.call(_assertThisInitialized(_this)); // <=IE10 fix (unable to call parent constructor)
_this.options = transformOptions(options);
_this.services = {};
_this.logger = baseLogger;
_this.modules = {
external: []
};
if (callback && !_this.isInitialized && !options.isClone) {
// https://github.com/i18next/i18next/issues/879
if (!_this.options.initImmediate) {
_this.init(options, callback);
return _possibleConstructorReturn(_this, _assertThisInitialized(_this));
}
setTimeout(function() {
_this.init(options, callback);
}, 0);
}
return _this;
}
_createClass(I18n, [
{
key: 'init',
value: function init() {
var _this2 = this;
var options =
arguments.length > 0 && arguments[0] !== undefined
? arguments[0]
: {};
var callback = arguments.length > 1 ? arguments[1] : undefined;
if (typeof options === 'function') {
callback = options;
options = {};
}
this.options = _objectSpread(
{},
get(),
this.options,
transformOptions(options)
);
this.format = this.options.interpolation.format;
if (!callback) callback = noop;
function createClassOnDemand(ClassOrObject) {
if (!ClassOrObject) return null;
if (typeof ClassOrObject === 'function') return new ClassOrObject();
return ClassOrObject;
} // init services
if (!this.options.isClone) {
if (this.modules.logger) {
baseLogger.init(
createClassOnDemand(this.modules.logger),
this.options
);
} else {
baseLogger.init(null, this.options);
}
var lu = new LanguageUtil(this.options);
this.store = new ResourceStore(this.options.resources, this.options);
var s = this.services;
s.logger = baseLogger;
s.resourceStore = this.store;
s.languageUtils = lu;
s.pluralResolver = new PluralResolver(lu, {
prepend: this.options.pluralSeparator,
compatibilityJSON: this.options.compatibilityJSON,
simplifyPluralSuffix: this.options.simplifyPluralSuffix
});
s.interpolator = new Interpolator(this.options);
s.utils = {
hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
};
s.backendConnector = new Connector(
createClassOnDemand(this.modules.backend),
s.resourceStore,
s,
this.options
); // pipe events from backendConnector
s.backendConnector.on('*', function(event) {
for (
var _len = arguments.length,
args = new Array(_len > 1 ? _len - 1 : 0),
_key = 1;
_key < _len;
_key++
) {
args[_key - 1] = arguments[_key];
}
_this2.emit.apply(_this2, [event].concat(args));
});
if (this.modules.languageDetector) {
s.languageDetector = createClassOnDemand(
this.modules.languageDetector
);
s.languageDetector.init(s, this.options.detection, this.options);
}
if (this.modules.i18nFormat) {
s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
if (s.i18nFormat.init) s.i18nFormat.init(this);
}
this.translator = new Translator(this.services, this.options); // pipe events from translator
this.translator.on('*', function(event) {
for (
var _len2 = arguments.length,
args = new Array(_len2 > 1 ? _len2 - 1 : 0),
_key2 = 1;
_key2 < _len2;
_key2++
) {
args[_key2 - 1] = arguments[_key2];
}
_this2.emit.apply(_this2, [event].concat(args));
});
this.modules.external.forEach(function(m) {
if (m.init) m.init(_this2);
});
} // append api
var storeApi = [
'getResource',
'addResource',
'addResources',
'addResourceBundle',
'removeResourceBundle',
'hasResourceBundle',
'getResourceBundle',
'getDataByLanguage'
];
storeApi.forEach(function(fcName) {
_this2[fcName] = function() {
var _this2$store;
return (_this2$store = _this2.store)[fcName].apply(
_this2$store,
arguments
);
};
});
var deferred = defer();
var load = function load() {
_this2.changeLanguage(_this2.options.lng, function(err, t) {
_this2.isInitialized = true;
_this2.logger.log('initialized', _this2.options);
_this2.emit('initialized', _this2.options);
deferred.resolve(t); // not rejecting on err (as err is only a loading translation failed warning)
callback(err, t);
});
};
if (this.options.resources || !this.options.initImmediate) {
load();
} else {
setTimeout(load, 0);
}
return deferred;
}
/* eslint consistent-return: 0 */
},
{
key: 'loadResources',
value: function loadResources(language) {
var _this3 = this;
var callback =
arguments.length > 1 && arguments[1] !== undefined
? arguments[1]
: noop;
var usedCallback = callback;
var usedLng = typeof language === 'string' ? language : this.language;
if (typeof language === 'function') usedCallback = language;
if (!this.options.resources || this.options.partialBundledLanguages) {
if (usedLng && usedLng.toLowerCase() === 'cimode')
return usedCallback(); // avoid loading resources for cimode
var toLoad = [];
var append = function append(lng) {
if (!lng) return;
var lngs = _this3.services.languageUtils.toResolveHierarchy(lng);
lngs.forEach(function(l) {
if (toLoad.indexOf(l) < 0) toLoad.push(l);
});
};
if (!usedLng) {
// at least load fallbacks in this case
var fallbacks = this.services.languageUtils.getFallbackCodes(
this.options.fallbackLng
);
fallbacks.forEach(function(l) {
return append(l);
});
} else {
append(usedLng);
}
if (this.options.preload) {
this.options.preload.forEach(function(l) {
return append(l);
});
}
this.services.backendConnector.load(
toLoad,
this.options.ns,
usedCallback
);
} else {
usedCallback(null);
}
}
},
{
key: 'reloadResources',
value: function reloadResources(lngs, ns, callback) {
var deferred = defer();
if (!lngs) lngs = this.languages;
if (!ns) ns = this.options.ns;
if (!callback) callback = noop;
this.services.backendConnector.reload(lngs, ns, function(err) {
deferred.resolve(); // not rejecting on err (as err is only a loading translation failed warning)
callback(err);
});
return deferred;
}
},
{
key: 'use',
value: function use(module) {
if (module.type === 'backend') {
this.modules.backend = module;
}
if (
module.type === 'logger' ||
(module.log && module.warn && module.error)
) {
this.modules.logger = module;
}
if (module.type === 'languageDetector') {
this.modules.languageDetector = module;
}
if (module.type === 'i18nFormat') {
this.modules.i18nFormat = module;
}
if (module.type === 'postProcessor') {
postProcessor.addPostProcessor(module);
}
if (module.type === '3rdParty') {
this.modules.external.push(module);
}
return this;
}
},
{
key: 'changeLanguage',
value: function changeLanguage(lng, callback) {
var _this4 = this;
this.isLanguageChangingTo = lng;
var deferred = defer();
this.emit('languageChanging', lng);
var done = function done(err, l) {
if (l) {
_this4.language = l;
_this4.languages = _this4.services.languageUtils.toResolveHierarchy(
l
);
_this4.translator.changeLanguage(l);
_this4.isLanguageChangingTo = undefined;
_this4.emit('languageChanged', l);
_this4.logger.log('languageChanged', l);
} else {
_this4.isLanguageChangingTo = undefined;
}
deferred.resolve(function() {
return _this4.t.apply(_this4, arguments);
});
if (callback)
callback(err, function() {
return _this4.t.apply(_this4, arguments);
});
};
var setLng = function setLng(l) {
if (l) {
if (!_this4.language) {
_this4.language = l;
_this4.languages = _this4.services.languageUtils.toResolveHierarchy(
l
);
}
if (!_this4.translator.language)
_this4.translator.changeLanguage(l);
if (_this4.services.languageDetector)
_this4.services.languageDetector.cacheUserLanguage(l);
}
_this4.loadResources(l, function(err) {
done(err, l);
});
};
if (
!lng &&
this.services.languageDetector &&
!this.services.languageDetector.async
) {
setLng(this.services.languageDetector.detect());
} else if (
!lng &&
this.services.languageDetector &&
this.services.languageDetector.async
) {
this.services.languageDetector.detect(setLng);
} else {
setLng(lng);
}
return deferred;
}
},
{
key: 'getFixedT',
value: function getFixedT(lng, ns) {
var _this5 = this;
var fixedT = function fixedT(key, opts) {
var options;
if (_typeof(opts) !== 'object') {
for (
var _len3 = arguments.length,
rest = new Array(_len3 > 2 ? _len3 - 2 : 0),
_key3 = 2;
_key3 < _len3;
_key3++
) {
rest[_key3 - 2] = arguments[_key3];
}
options = _this5.options.overloadTranslationOptionHandler(
[key, opts].concat(rest)
);
} else {
options = _objectSpread({}, opts);
}
options.lng = options.lng || fixedT.lng;
options.lngs = options.lngs || fixedT.lngs;
options.ns = options.ns || fixedT.ns;
return _this5.t(key, options);
};
if (typeof lng === 'string') {
fixedT.lng = lng;
} else {
fixedT.lngs = lng;
}
fixedT.ns = ns;
return fixedT;
}
},
{
key: 't',
value: function t() {
var _this$translator;
return (
this.translator &&
(_this$translator = this.translator).translate.apply(
_this$translator,
arguments
)
);
}
},
{
key: 'exists',
value: function exists() {
var _this$translator2;
return (
this.translator &&
(_this$translator2 = this.translator).exists.apply(
_this$translator2,
arguments
)
);
}
},
{
key: 'setDefaultNamespace',
value: function setDefaultNamespace(ns) {
this.options.defaultNS = ns;
}
},
{
key: 'hasLoadedNamespace',
value: function hasLoadedNamespace(ns) {
var _this6 = this;
if (!this.isInitialized) {
this.logger.warn(
'hasLoadedNamespace: i18next was not initialized',
this.languages
);
return false;
}
if (!this.languages || !this.languages.length) {
this.logger.warn(
'hasLoadedNamespace: i18n.languages were undefined or empty',
this.languages
);
return false;
}
var lng = this.languages[0];
var fallbackLng = this.options ? this.options.fallbackLng : false;
var lastLng = this.languages[this.languages.length - 1]; // we're in cimode so this shall pass
if (lng.toLowerCase() === 'cimode') return true;
var loadNotPending = function loadNotPending(l, n) {
var loadState =
_this6.services.backendConnector.state[''.concat(l, '|').concat(n)];
return loadState === -1 || loadState === 2;
}; // loaded -> SUCCESS
if (this.hasResourceBundle(lng, ns)) return true; // were not loading at all -> SEMI SUCCESS
if (!this.services.backendConnector.backend) return true; // failed loading ns - but at least fallback is not pending -> SEMI SUCCESS
if (
loadNotPending(lng, ns) &&
(!fallbackLng || loadNotPending(lastLng, ns))
)
return true;
return false;
}
},
{
key: 'loadNamespaces',
value: function loadNamespaces(ns, callback) {
var _this7 = this;
var deferred = defer();
if (!this.options.ns) {
callback && callback();
return Promise.resolve();
}
if (typeof ns === 'string') ns = [ns];
ns.forEach(function(n) {
if (_this7.options.ns.indexOf(n) < 0) _this7.options.ns.push(n);
});
this.loadResources(function(err) {
deferred.resolve();
if (callback) callback(err);
});
return deferred;
}
},
{
key: 'loadLanguages',
value: function loadLanguages(lngs, callback) {
var deferred = defer();
if (typeof lngs === 'string') lngs = [lngs];
var preloaded = this.options.preload || [];
var newLngs = lngs.filter(function(lng) {
return preloaded.indexOf(lng) < 0;
}); // Exit early if all given languages are already preloaded
if (!newLngs.length) {
if (callback) callback();
return Promise.resolve();
}
this.options.preload = preloaded.concat(newLngs);
this.loadResources(function(err) {
deferred.resolve();
if (callback) callback(err);
});
return deferred;
}
},
{
key: 'dir',
value: function dir(lng) {
if (!lng)
lng =
this.languages && this.languages.length > 0
? this.languages[0]
: this.language;
if (!lng) return 'rtl';
var rtlLngs = [
'ar',
'shu',
'sqr',
'ssh',
'xaa',
'yhd',
'yud',
'aao',
'abh',
'abv',
'acm',
'acq',
'acw',
'acx',
'acy',
'adf',
'ads',
'aeb',
'aec',
'afb',
'ajp',
'apc',
'apd',
'arb',
'arq',
'ars',
'ary',
'arz',
'auz',
'avl',
'ayh',
'ayl',
'ayn',
'ayp',
'bbz',
'pga',
'he',
'iw',
'ps',
'pbt',
'pbu',
'pst',
'prp',
'prd',
'ur',
'ydd',
'yds',
'yih',
'ji',
'yi',
'hbo',
'men',
'xmn',
'fa',
'jpr',
'peo',
'pes',
'prs',
'dv',
'sam'
];
return rtlLngs.indexOf(
this.services.languageUtils.getLanguagePartFromCode(lng)
) >= 0
? 'rtl'
: 'ltr';
}
/* eslint class-methods-use-this: 0 */
},
{
key: 'createInstance',
value: function createInstance() {
var options =
arguments.length > 0 && arguments[0] !== undefined
? arguments[0]
: {};
var callback = arguments.length > 1 ? arguments[1] : undefined;
return new I18n(options, callback);
}
},
{
key: 'cloneInstance',
value: function cloneInstance() {
var _this8 = this;
var options =
arguments.length > 0 && arguments[0] !== undefined
? arguments[0]
: {};
var callback =
arguments.length > 1 && arguments[1] !== undefined
? arguments[1]
: noop;
var mergedOptions = _objectSpread({}, this.options, options, {
isClone: true
});
var clone = new I18n(mergedOptions);
var membersToCopy = ['store', 'services', 'language'];
membersToCopy.forEach(function(m) {
clone[m] = _this8[m];
});
clone.translator = new Translator(clone.services, clone.options);
clone.translator.on('*', function(event) {
for (
var _len4 = arguments.length,
args = new Array(_len4 > 1 ? _len4 - 1 : 0),
_key4 = 1;
_key4 < _len4;
_key4++
) {
args[_key4 - 1] = arguments[_key4];
}
clone.emit.apply(clone, [event].concat(args));
});
clone.init(mergedOptions, callback);
clone.translator.options = clone.options; // sync options
return clone;
}
}
]);
return I18n;
})(EventEmitter);
var i18next = new I18n();
module.exports = i18next;
},
{
'@babel/runtime/helpers/assertThisInitialized': 4,
'@babel/runtime/helpers/classCallCheck': 5,
'@babel/runtime/helpers/createClass': 6,
'@babel/runtime/helpers/getPrototypeOf': 8,
'@babel/runtime/helpers/inherits': 9,
'@babel/runtime/helpers/objectSpread': 14,
'@babel/runtime/helpers/possibleConstructorReturn': 15,
'@babel/runtime/helpers/slicedToArray': 17,
'@babel/runtime/helpers/toConsumableArray': 18,
'@babel/runtime/helpers/typeof': 19
}
],
31: [
function(_dereq_, module, exports) {
exports.read = function(buffer, offset, isLE, mLen, nBytes) {
var e, m;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var nBits = -7;
var i = isLE ? nBytes - 1 : 0;
var d = isLE ? -1 : 1;
var s = buffer[offset + i];
i += d;
e = s & ((1 << -nBits) - 1);
s >>= -nBits;
nBits += eLen;
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << -nBits) - 1);
e >>= -nBits;
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : (s ? -1 : 1) * Infinity;
} else {
m = m + Math.pow(2, mLen);
e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
};
exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
var i = isLE ? 0 : nBytes - 1;
var d = isLE ? 1 : -1;
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
value = Math.abs(value);
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0;
e = eMax;
} else {
e = Math.floor(Math.log(value) / Math.LN2);
if (value * (c = Math.pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value += rt / c;
} else {
value += rt * Math.pow(2, 1 - eBias);
}
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen);
e = e + eBias;
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m;
eLen += mLen;
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128;
};
},
{}
],
32: [
function(_dereq_, module, exports) {
/*
Copyright 2000, Silicon Graphics, Inc. All Rights Reserved.
Copyright 2015, Google Inc. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice including the dates of first publication and
either this permission notice or a reference to http://oss.sgi.com/projects/FreeB/
shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
SILICON GRAPHICS, INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Original Code. The Original Code is: OpenGL Sample Implementation,
Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
Copyright in any portions created by third parties is as indicated
elsewhere herein. All Rights Reserved.
*/
'use strict';
var n;
function t(a, b) {
return a.b === b.b && a.a === b.a;
}
function u(a, b) {
return a.b < b.b || (a.b === b.b && a.a <= b.a);
}
function v(a, b, c) {
var d = b.b - a.b,
e = c.b - b.b;
return 0 < d + e
? d < e
? b.a - a.a + d / (d + e) * (a.a - c.a)
: b.a - c.a + e / (d + e) * (c.a - a.a)
: 0;
}
function x(a, b, c) {
var d = b.b - a.b,
e = c.b - b.b;
return 0 < d + e ? (b.a - c.a) * d + (b.a - a.a) * e : 0;
}
function z(a, b) {
return a.a < b.a || (a.a === b.a && a.b <= b.b);
}
function aa(a, b, c) {
var d = b.a - a.a,
e = c.a - b.a;
return 0 < d + e
? d < e
? b.b - a.b + d / (d + e) * (a.b - c.b)
: b.b - c.b + e / (d + e) * (c.b - a.b)
: 0;
}
function ba(a, b, c) {
var d = b.a - a.a,
e = c.a - b.a;
return 0 < d + e ? (b.b - c.b) * d + (b.b - a.b) * e : 0;
}
function ca(a) {
return u(a.b.a, a.a);
}
function da(a) {
return u(a.a, a.b.a);
}
function A(a, b, c, d) {
a = 0 > a ? 0 : a;
c = 0 > c ? 0 : c;
return a <= c
? 0 === c ? (b + d) / 2 : b + a / (a + c) * (d - b)
: d + c / (a + c) * (b - d);
}
function ea(a) {
var b = B(a.b);
C(b, a.c);
C(b.b, a.c);
D(b, a.a);
return b;
}
function E(a, b) {
var c = !1,
d = !1;
a !== b &&
(b.a !== a.a && ((d = !0), F(b.a, a.a)),
b.d !== a.d && ((c = !0), G(b.d, a.d)),
H(b, a),
d || (C(b, a.a), (a.a.c = a)),
c || (D(b, a.d), (a.d.a = a)));
}
function I(a) {
var b = a.b,
c = !1;
a.d !== a.b.d && ((c = !0), G(a.d, a.b.d));
a.c === a
? F(a.a, null)
: ((a.b.d.a = J(a)), (a.a.c = a.c), H(a, J(a)), c || D(a, a.d));
b.c === b
? (F(b.a, null), G(b.d, null))
: ((a.d.a = J(b)), (b.a.c = b.c), H(b, J(b)));
fa(a);
}
function K(a) {
var b = B(a),
c = b.b;
H(b, a.e);
b.a = a.b.a;
C(c, b.a);
b.d = c.d = a.d;
b = b.b;
H(a.b, J(a.b));
H(a.b, b);
a.b.a = b.a;
b.b.a.c = b.b;
b.b.d = a.b.d;
b.f = a.f;
b.b.f = a.b.f;
return b;
}
function L(a, b) {
var c = !1,
d = B(a),
e = d.b;
b.d !== a.d && ((c = !0), G(b.d, a.d));
H(d, a.e);
H(e, b);
d.a = a.b.a;
e.a = b.a;
d.d = e.d = a.d;
a.d.a = e;
c || D(d, a.d);
return d;
}
function B(a) {
var b = new M(),
c = new M(),
d = a.b.h;
c.h = d;
d.b.h = b;
b.h = a;
a.b.h = c;
b.b = c;
b.c = b;
b.e = c;
c.b = b;
c.c = c;
return (c.e = b);
}
function H(a, b) {
var c = a.c,
d = b.c;
c.b.e = b;
d.b.e = a;
a.c = d;
b.c = c;
}
function C(a, b) {
var c = b.f,
d = new N(b, c);
c.e = d;
b.f = d;
c = d.c = a;
do (c.a = d), (c = c.c);
while (c !== a);
}
function D(a, b) {
var c = b.d,
d = new ga(b, c);
c.b = d;
b.d = d;
d.a = a;
d.c = b.c;
c = a;
do (c.d = d), (c = c.e);
while (c !== a);
}
function fa(a) {
var b = a.h;
a = a.b.h;
b.b.h = a;
a.b.h = b;
}
function F(a, b) {
var c = a.c,
d = c;
do (d.a = b), (d = d.c);
while (d !== c);
c = a.f;
d = a.e;
d.f = c;
c.e = d;
}
function G(a, b) {
var c = a.a,
d = c;
do (d.d = b), (d = d.e);
while (d !== c);
c = a.d;
d = a.b;
d.d = c;
c.b = d;
}
function ha(a) {
var b = 0;
Math.abs(a[1]) > Math.abs(a[0]) && (b = 1);
Math.abs(a[2]) > Math.abs(a[b]) && (b = 2);
return b;
}
var O = 4 * 1e150;
function P(a, b) {
a.f += b.f;
a.b.f += b.b.f;
}
function ia(a, b, c) {
a = a.a;
b = b.a;
c = c.a;
if (b.b.a === a)
return c.b.a === a
? u(b.a, c.a) ? 0 >= x(c.b.a, b.a, c.a) : 0 <= x(b.b.a, c.a, b.a)
: 0 >= x(c.b.a, a, c.a);
if (c.b.a === a) return 0 <= x(b.b.a, a, b.a);
b = v(b.b.a, a, b.a);
a = v(c.b.a, a, c.a);
return b >= a;
}
function Q(a) {
a.a.i = null;
var b = a.e;
b.a.c = b.c;
b.c.a = b.a;
a.e = null;
}
function ja(a, b) {
I(a.a);
a.c = !1;
a.a = b;
b.i = a;
}
function ka(a) {
var b = a.a.a;
do a = R(a);
while (a.a.a === b);
a.c && ((b = L(S(a).a.b, a.a.e)), ja(a, b), (a = R(a)));
return a;
}
function la(a, b, c) {
var d = new ma();
d.a = c;
d.e = na(a.f, b.e, d);
return (c.i = d);
}
function oa(a, b) {
switch (a.s) {
case 100130:
return 0 !== (b & 1);
case 100131:
return 0 !== b;
case 100132:
return 0 < b;
case 100133:
return 0 > b;
case 100134:
return 2 <= b || -2 >= b;
}
return !1;
}
function pa(a) {
var b = a.a,
c = b.d;
c.c = a.d;
c.a = b;
Q(a);
}
function T(a, b, c) {
a = b;
for (b = b.a; a !== c; ) {
a.c = !1;
var d = S(a),
e = d.a;
if (e.a !== b.a) {
if (!d.c) {
pa(a);
break;
}
e = L(b.c.b, e.b);
ja(d, e);
}
b.c !== e && (E(J(e), e), E(b, e));
pa(a);
b = d.a;
a = d;
}
return b;
}
function U(a, b, c, d, e, f) {
var g = !0;
do la(a, b, c.b), (c = c.c);
while (c !== d);
for (null === e && (e = S(b).a.b.c); ; ) {
d = S(b);
c = d.a.b;
if (c.a !== e.a) break;
c.c !== e && (E(J(c), c), E(J(e), c));
d.f = b.f - c.f;
d.d = oa(a, d.f);
b.b = !0;
!g && qa(a, b) && (P(c, e), Q(b), I(e));
g = !1;
b = d;
e = c;
}
b.b = !0;
f && ra(a, b);
}
function sa(a, b, c, d, e) {
var f = [b.g[0], b.g[1], b.g[2]];
b.d = null;
b.d = a.o ? a.o(f, c, d, a.c) || null : null;
null === b.d && (e ? a.n || (V(a, 100156), (a.n = !0)) : (b.d = c[0]));
}
function ta(a, b, c) {
var d = [null, null, null, null];
d[0] = b.a.d;
d[1] = c.a.d;
sa(a, b.a, d, [0.5, 0.5, 0, 0], !1);
E(b, c);
}
function ua(a, b, c, d, e) {
var f = Math.abs(b.b - a.b) + Math.abs(b.a - a.a),
g = Math.abs(c.b - a.b) + Math.abs(c.a - a.a),
h = e + 1;
d[e] = 0.5 * g / (f + g);
d[h] = 0.5 * f / (f + g);
a.g[0] += d[e] * b.g[0] + d[h] * c.g[0];
a.g[1] += d[e] * b.g[1] + d[h] * c.g[1];
a.g[2] += d[e] * b.g[2] + d[h] * c.g[2];
}
function qa(a, b) {
var c = S(b),
d = b.a,
e = c.a;
if (u(d.a, e.a)) {
if (0 < x(e.b.a, d.a, e.a)) return !1;
if (!t(d.a, e.a)) K(e.b), E(d, J(e)), (b.b = c.b = !0);
else if (d.a !== e.a) {
var c = a.e,
f = d.a.h;
if (0 <= f) {
var c = c.b,
g = c.d,
h = c.e,
k = c.c,
l = k[f];
g[l] = g[c.a];
k[g[l]] = l;
l <= --c.a &&
(1 >= l ? W(c, l) : u(h[g[l >> 1]], h[g[l]]) ? W(c, l) : va(c, l));
h[f] = null;
k[f] = c.b;
c.b = f;
} else
for (c.c[-(f + 1)] = null; 0 < c.a && null === c.c[c.d[c.a - 1]]; ) --c.a;
ta(a, J(e), d);
}
} else {
if (0 > x(d.b.a, e.a, d.a)) return !1;
R(b).b = b.b = !0;
K(d.b);
E(J(e), d);
}
return !0;
}
function wa(a, b) {
var c = S(b),
d = b.a,
e = c.a,
f = d.a,
g = e.a,
h = d.b.a,
k = e.b.a,
l = new N();
x(h, a.a, f);
x(k, a.a, g);
if (f === g || Math.min(f.a, h.a) > Math.max(g.a, k.a)) return !1;
if (u(f, g)) {
if (0 < x(k, f, g)) return !1;
} else if (0 > x(h, g, f)) return !1;
var r = h,
p = f,
q = k,
y = g,
m,
w;
u(r, p) || ((m = r), (r = p), (p = m));
u(q, y) || ((m = q), (q = y), (y = m));
u(r, q) || ((m = r), (r = q), (q = m), (m = p), (p = y), (y = m));
u(q, p)
? u(p, y)
? ((m = v(r, q, p)),
(w = v(q, p, y)),
0 > m + w && ((m = -m), (w = -w)),
(l.b = A(m, q.b, w, p.b)))
: ((m = x(r, q, p)),
(w = -x(r, y, p)),
0 > m + w && ((m = -m), (w = -w)),
(l.b = A(m, q.b, w, y.b)))
: (l.b = (q.b + p.b) / 2);
z(r, p) || ((m = r), (r = p), (p = m));
z(q, y) || ((m = q), (q = y), (y = m));
z(r, q) || ((m = r), (r = q), (q = m), (m = p), (p = y), (y = m));
z(q, p)
? z(p, y)
? ((m = aa(r, q, p)),
(w = aa(q, p, y)),
0 > m + w && ((m = -m), (w = -w)),
(l.a = A(m, q.a, w, p.a)))
: ((m = ba(r, q, p)),
(w = -ba(r, y, p)),
0 > m + w && ((m = -m), (w = -w)),
(l.a = A(m, q.a, w, y.a)))
: (l.a = (q.a + p.a) / 2);
u(l, a.a) && ((l.b = a.a.b), (l.a = a.a.a));
r = u(f, g) ? f : g;
u(r, l) && ((l.b = r.b), (l.a = r.a));
if (t(l, f) || t(l, g)) return qa(a, b), !1;
if ((!t(h, a.a) && 0 <= x(h, a.a, l)) || (!t(k, a.a) && 0 >= x(k, a.a, l))) {
if (k === a.a)
return (
K(d.b),
E(e.b, d),
(b = ka(b)),
(d = S(b).a),
T(a, S(b), c),
U(a, b, J(d), d, d, !0),
!0
);
if (h === a.a) {
K(e.b);
E(d.e, J(e));
f = c = b;
g = f.a.b.a;
do f = R(f);
while (f.a.b.a === g);
b = f;
f = S(b).a.b.c;
c.a = J(e);
e = T(a, c, null);
U(a, b, e.c, d.b.c, f, !0);
return !0;
}
0 <= x(h, a.a, l) &&
((R(b).b = b.b = !0), K(d.b), (d.a.b = a.a.b), (d.a.a = a.a.a));
0 >= x(k, a.a, l) &&
((b.b = c.b = !0), K(e.b), (e.a.b = a.a.b), (e.a.a = a.a.a));
return !1;
}
K(d.b);
K(e.b);
E(J(e), d);
d.a.b = l.b;
d.a.a = l.a;
d.a.h = xa(a.e, d.a);
d = d.a;
e = [0, 0, 0, 0];
l = [f.d, h.d, g.d, k.d];
d.g[0] = d.g[1] = d.g[2] = 0;
ua(d, f, h, e, 0);
ua(d, g, k, e, 2);
sa(a, d, l, e, !0);
R(b).b = b.b = c.b = !0;
return !1;
}
function ra(a, b) {
for (var c = S(b); ; ) {
for (; c.b; ) (b = c), (c = S(c));
if (!b.b && ((c = b), (b = R(b)), null === b || !b.b)) break;
b.b = !1;
var d = b.a,
e = c.a,
f;
if ((f = d.b.a !== e.b.a))
a: {
f = b;
var g = S(f),
h = f.a,
k = g.a,
l = void 0;
if (u(h.b.a, k.b.a)) {
if (0 > x(h.b.a, k.b.a, h.a)) {
f = !1;
break a;
}
R(f).b = f.b = !0;
l = K(h);
E(k.b, l);
l.d.c = f.d;
} else {
if (0 < x(k.b.a, h.b.a, k.a)) {
f = !1;
break a;
}
f.b = g.b = !0;
l = K(k);
E(h.e, k.b);
l.b.d.c = f.d;
}
f = !0;
}
f &&
(c.c
? (Q(c), I(e), (c = S(b)), (e = c.a))
: b.c && (Q(b), I(d), (b = R(c)), (d = b.a)));
if (d.a !== e.a)
if (d.b.a === e.b.a || b.c || c.c || (d.b.a !== a.a && e.b.a !== a.a))
qa(a, b);
else if (wa(a, b)) break;
d.a === e.a && d.b.a === e.b.a && (P(e, d), Q(b), I(d), (b = R(c)));
}
}
function ya(a, b) {
a.a = b;
for (var c = b.c; null === c.i; )
if (((c = c.c), c === b.c)) {
var c = a,
d = b,
e = new ma();
e.a = d.c.b;
var f = c.f,
g = f.a;
do g = g.a;
while (null !== g.b && !f.c(f.b, e, g.b));
var f = g.b,
h = S(f),
e = f.a,
g = h.a;
if (0 === x(e.b.a, d, e.a))
(e = f.a),
t(e.a, d) ||
t(e.b.a, d) ||
(K(e.b), f.c && (I(e.c), (f.c = !1)), E(d.c, e), ya(c, d));
else {
var k = u(g.b.a, e.b.a) ? f : h,
h = void 0;
f.d || k.c
? (k === f ? (h = L(d.c.b, e.e)) : (h = L(g.b.c.b, d.c).b),
k.c
? ja(k, h)
: ((e = c),
(f = la(c, f, h)),
(f.f = R(f).f + f.a.f),
(f.d = oa(e, f.f))),
ya(c, d))
: U(c, f, d.c, d.c, null, !0);
}
return;
}
c = ka(c.i);
e = S(c);
f = e.a;
e = T(a, e, null);
if (e.c === f) {
var f = e,
e = f.c,
g = S(c),
h = c.a,
k = g.a,
l = !1;
h.b.a !== k.b.a && wa(a, c);
t(h.a, a.a) &&
(E(J(e), h), (c = ka(c)), (e = S(c).a), T(a, S(c), g), (l = !0));
t(k.a, a.a) && (E(f, J(k)), (f = T(a, g, null)), (l = !0));
l
? U(a, c, f.c, e, e, !0)
: (u(k.a, h.a) ? (d = J(k)) : (d = h),
(d = L(f.c.b, d)),
U(a, c, d, d.c, d.c, !1),
(d.b.i.c = !0),
ra(a, c));
} else U(a, c, e.c, f, f, !0);
}
function za(a, b) {
var c = new ma(),
d = ea(a.b);
d.a.b = O;
d.a.a = b;
d.b.a.b = -O;
d.b.a.a = b;
a.a = d.b.a;
c.a = d;
c.f = 0;
c.d = !1;
c.c = !1;
c.h = !0;
c.b = !1;
d = a.f;
d = na(d, d.a, c);
c.e = d;
}
function Aa(a) {
this.a = new Ba();
this.b = a;
this.c = ia;
}
function na(a, b, c) {
do b = b.c;
while (null !== b.b && !a.c(a.b, b.b, c));
a = new Ba(c, b.a, b);
b.a.c = a;
return (b.a = a);
}
function Ba(a, b, c) {
this.b = a || null;
this.a = b || this;
this.c = c || this;
}
function X() {
this.d = Y;
this.p = this.b = this.q = null;
this.j = [0, 0, 0];
this.s = 100130;
this.n = !1;
this.o = this.a = this.e = this.f = null;
this.m = !1;
this.c = this.r = this.i = this.k = this.l = this.h = null;
}
var Y = 0;
n = X.prototype;
n.x = function() {
Z(this, Y);
};
n.B = function(a, b) {
switch (a) {
case 100142:
return;
case 100140:
switch (b) {
case 100130:
case 100131:
case 100132:
case 100133:
case 100134:
this.s = b;
return;
}
break;
case 100141:
this.m = !!b;
return;
default:
V(this, 100900);
return;
}
V(this, 100901);
};
n.y = function(a) {
switch (a) {
case 100142:
return 0;
case 100140:
return this.s;
case 100141:
return this.m;
default:
V(this, 100900);
}
return !1;
};
n.A = function(a, b, c) {
this.j[0] = a;
this.j[1] = b;
this.j[2] = c;
};
n.z = function(a, b) {
var c = b ? b : null;
switch (a) {
case 100100:
case 100106:
this.h = c;
break;
case 100104:
case 100110:
this.l = c;
break;
case 100101:
case 100107:
this.k = c;
break;
case 100102:
case 100108:
this.i = c;
break;
case 100103:
case 100109:
this.p = c;
break;
case 100105:
case 100111:
this.o = c;
break;
case 100112:
this.r = c;
break;
default:
V(this, 100900);
}
};
n.C = function(a, b) {
var c = !1,
d = [0, 0, 0];
Z(this, 2);
for (var e = 0; 3 > e; ++e) {
var f = a[e];
-1e150 > f && ((f = -1e150), (c = !0));
1e150 < f && ((f = 1e150), (c = !0));
d[e] = f;
}
c && V(this, 100155);
c = this.q;
null === c ? ((c = ea(this.b)), E(c, c.b)) : (K(c), (c = c.e));
c.a.d = b;
c.a.g[0] = d[0];
c.a.g[1] = d[1];
c.a.g[2] = d[2];
c.f = 1;
c.b.f = -1;
this.q = c;
};
n.u = function(a) {
Z(this, Y);
this.d = 1;
this.b = new Ca();
this.c = a;
};
n.t = function() {
Z(this, 1);
this.d = 2;
this.q = null;
};
n.v = function() {
Z(this, 2);
this.d = 1;
};
n.w = function() {
Z(this, 1);
this.d = Y;
var a = this.j[0],
b = this.j[1],
c = this.j[2],
d = !1,
e = [a, b, c];
if (0 === a && 0 === b && 0 === c) {
for (
var b = [-2 * 1e150, -2 * 1e150, -2 * 1e150],
f = [2 * 1e150, 2 * 1e150, 2 * 1e150],
c = [],
g = [],
d = this.b.c,
a = d.e;
a !== d;
a = a.e
)
for (var h = 0; 3 > h; ++h) {
var k = a.g[h];
k < f[h] && ((f[h] = k), (g[h] = a));
k > b[h] && ((b[h] = k), (c[h] = a));
}
a = 0;
b[1] - f[1] > b[0] - f[0] && (a = 1);
b[2] - f[2] > b[a] - f[a] && (a = 2);
if (f[a] >= b[a]) (e[0] = 0), (e[1] = 0), (e[2] = 1);
else {
b = 0;
f = g[a];
c = c[a];
g = [0, 0, 0];
f = [f.g[0] - c.g[0], f.g[1] - c.g[1], f.g[2] - c.g[2]];
h = [0, 0, 0];
for (a = d.e; a !== d; a = a.e)
(h[0] = a.g[0] - c.g[0]),
(h[1] = a.g[1] - c.g[1]),
(h[2] = a.g[2] - c.g[2]),
(g[0] = f[1] * h[2] - f[2] * h[1]),
(g[1] = f[2] * h[0] - f[0] * h[2]),
(g[2] = f[0] * h[1] - f[1] * h[0]),
(k = g[0] * g[0] + g[1] * g[1] + g[2] * g[2]),
k > b && ((b = k), (e[0] = g[0]), (e[1] = g[1]), (e[2] = g[2]));
0 >= b && ((e[0] = e[1] = e[2] = 0), (e[ha(f)] = 1));
}
d = !0;
}
g = ha(e);
a = this.b.c;
b = (g + 1) % 3;
c = (g + 2) % 3;
g = 0 < e[g] ? 1 : -1;
for (e = a.e; e !== a; e = e.e) (e.b = e.g[b]), (e.a = g * e.g[c]);
if (d) {
e = 0;
d = this.b.a;
for (a = d.b; a !== d; a = a.b)
if (((b = a.a), !(0 >= b.f))) {
do (e += (b.a.b - b.b.a.b) * (b.a.a + b.b.a.a)), (b = b.e);
while (b !== a.a);
}
if (0 > e) for (e = this.b.c, d = e.e; d !== e; d = d.e) d.a = -d.a;
}
this.n = !1;
e = this.b.b;
for (a = e.h; a !== e; a = d)
if (
((d = a.h),
(b = a.e),
t(a.a, a.b.a) && a.e.e !== a && (ta(this, b, a), I(a), (a = b), (b = a.e)),
b.e === a)
) {
if (b !== a) {
if (b === d || b === d.b) d = d.h;
I(b);
}
if (a === d || a === d.b) d = d.h;
I(a);
}
this.e = e = new Da();
d = this.b.c;
for (a = d.e; a !== d; a = a.e) a.h = xa(e, a);
Ea(e);
this.f = new Aa(this);
za(this, -O);
for (za(this, O); null !== (e = Fa(this.e)); ) {
for (;;) {
a: if (((a = this.e), 0 === a.a)) d = Ga(a.b);
else if (
((d = a.c[a.d[a.a - 1]]), 0 !== a.b.a && ((a = Ga(a.b)), u(a, d)))
) {
d = a;
break a;
}
if (null === d || !t(d, e)) break;
d = Fa(this.e);
ta(this, e.c, d.c);
}
ya(this, e);
}
this.a = this.f.a.a.b.a.a;
for (e = 0; null !== (d = this.f.a.a.b); ) d.h || ++e, Q(d);
this.f = null;
e = this.e;
e.b = null;
e.d = null;
this.e = e.c = null;
e = this.b;
for (a = e.a.b; a !== e.a; a = d)
(d = a.b), (a = a.a), a.e.e === a && (P(a.c, a), I(a));
if (!this.n) {
e = this.b;
if (this.m)
for (a = e.b.h; a !== e.b; a = d)
(d = a.h), a.b.d.c !== a.d.c ? (a.f = a.d.c ? 1 : -1) : I(a);
else
for (a = e.a.b; a !== e.a; a = d)
if (((d = a.b), a.c)) {
for (a = a.a; u(a.b.a, a.a); a = a.c.b);
for (; u(a.a, a.b.a); a = a.e);
b = a.c.b;
for (c = void 0; a.e !== b; )
if (u(a.b.a, b.a)) {
for (; b.e !== a && (ca(b.e) || 0 >= x(b.a, b.b.a, b.e.b.a)); )
(c = L(b.e, b)), (b = c.b);
b = b.c.b;
} else {
for (; b.e !== a && (da(a.c.b) || 0 <= x(a.b.a, a.a, a.c.b.a)); )
(c = L(a, a.c.b)), (a = c.b);
a = a.e;
}
for (; b.e.e !== a; ) (c = L(b.e, b)), (b = c.b);
}
if (this.h || this.i || this.k || this.l)
if (this.m)
for (e = this.b, d = e.a.b; d !== e.a; d = d.b) {
if (d.c) {
this.h && this.h(2, this.c);
a = d.a;
do this.k && this.k(a.a.d, this.c), (a = a.e);
while (a !== d.a);
this.i && this.i(this.c);
}
}
else {
e = this.b;
d = !!this.l;
a = !1;
b = -1;
for (c = e.a.d; c !== e.a; c = c.d)
if (c.c) {
a || (this.h && this.h(4, this.c), (a = !0));
g = c.a;
do
d &&
((f = g.b.d.c ? 0 : 1),
b !== f && ((b = f), this.l && this.l(!!b, this.c))),
this.k && this.k(g.a.d, this.c),
(g = g.e);
while (g !== c.a);
}
a && this.i && this.i(this.c);
}
if (this.r) {
e = this.b;
for (a = e.a.b; a !== e.a; a = d)
if (((d = a.b), !a.c)) {
b = a.a;
c = b.e;
g = void 0;
do
(g = c),
(c = g.e),
(g.d = null),
null === g.b.d &&
(g.c === g ? F(g.a, null) : ((g.a.c = g.c), H(g, J(g))),
(f = g.b),
f.c === f ? F(f.a, null) : ((f.a.c = f.c), H(f, J(f))),
fa(g));
while (g !== b);
b = a.d;
a = a.b;
a.d = b;
b.b = a;
}
this.r(this.b);
this.c = this.b = null;
return;
}
}
this.b = this.c = null;
};
function Z(a, b) {
if (a.d !== b)
for (; a.d !== b; )
if (a.d < b)
switch (a.d) {
case Y:
V(a, 100151);
a.u(null);
break;
case 1:
V(a, 100152), a.t();
}
else
switch (a.d) {
case 2:
V(a, 100154);
a.v();
break;
case 1:
V(a, 100153), a.w();
}
}
function V(a, b) {
a.p && a.p(b, a.c);
}
function ga(a, b) {
this.b = a || this;
this.d = b || this;
this.a = null;
this.c = !1;
}
function M() {
this.h = this;
this.i = this.d = this.a = this.e = this.c = this.b = null;
this.f = 0;
}
function J(a) {
return a.b.e;
}
function Ca() {
this.c = new N();
this.a = new ga();
this.b = new M();
this.d = new M();
this.b.b = this.d;
this.d.b = this.b;
}
function N(a, b) {
this.e = a || this;
this.f = b || this;
this.d = this.c = null;
this.g = [0, 0, 0];
this.h = this.a = this.b = 0;
}
function Da() {
this.c = [];
this.d = null;
this.a = 0;
this.e = !1;
this.b = new Ha();
}
function Ea(a) {
a.d = [];
for (var b = 0; b < a.a; b++) a.d[b] = b;
a.d.sort(
(function(a) {
return function(b, e) {
return u(a[b], a[e]) ? 1 : -1;
};
})(a.c)
);
a.e = !0;
Ia(a.b);
}
function xa(a, b) {
if (a.e) {
var c = a.b,
d = ++c.a;
2 * d > c.f && ((c.f *= 2), (c.c = Ja(c.c, c.f + 1)));
var e;
0 === c.b ? (e = d) : ((e = c.b), (c.b = c.c[c.b]));
c.e[e] = b;
c.c[e] = d;
c.d[d] = e;
c.h && va(c, d);
return e;
}
c = a.a++;
a.c[c] = b;
return -(c + 1);
}
function Fa(a) {
if (0 === a.a) return Ka(a.b);
var b = a.c[a.d[a.a - 1]];
if (0 !== a.b.a && u(Ga(a.b), b)) return Ka(a.b);
do --a.a;
while (0 < a.a && null === a.c[a.d[a.a - 1]]);
return b;
}
function Ha() {
this.d = Ja([0], 33);
this.e = [null, null];
this.c = [0, 0];
this.a = 0;
this.f = 32;
this.b = 0;
this.h = !1;
this.d[1] = 1;
}
function Ja(a, b) {
for (var c = Array(b), d = 0; d < a.length; d++) c[d] = a[d];
for (; d < b; d++) c[d] = 0;
return c;
}
function Ia(a) {
for (var b = a.a; 1 <= b; --b) W(a, b);
a.h = !0;
}
function Ga(a) {
return a.e[a.d[1]];
}
function Ka(a) {
var b = a.d,
c = a.e,
d = a.c,
e = b[1],
f = c[e];
0 < a.a &&
((b[1] = b[a.a]),
(d[b[1]] = 1),
(c[e] = null),
(d[e] = a.b),
(a.b = e),
0 < --a.a && W(a, 1));
return f;
}
function W(a, b) {
for (var c = a.d, d = a.e, e = a.c, f = b, g = c[f]; ; ) {
var h = f << 1;
h < a.a && u(d[c[h + 1]], d[c[h]]) && (h += 1);
var k = c[h];
if (h > a.a || u(d[g], d[k])) {
c[f] = g;
e[g] = f;
break;
}
c[f] = k;
e[k] = f;
f = h;
}
}
function va(a, b) {
for (var c = a.d, d = a.e, e = a.c, f = b, g = c[f]; ; ) {
var h = f >> 1,
k = c[h];
if (0 === h || u(d[k], d[g])) {
c[f] = g;
e[g] = f;
break;
}
c[f] = k;
e[k] = f;
f = h;
}
}
function ma() {
this.e = this.a = null;
this.f = 0;
this.c = this.b = this.h = this.d = !1;
}
function S(a) {
return a.e.c.b;
}
function R(a) {
return a.e.a.b;
}
this.libtess = {
GluTesselator: X,
windingRule: {
GLU_TESS_WINDING_ODD: 100130,
GLU_TESS_WINDING_NONZERO: 100131,
GLU_TESS_WINDING_POSITIVE: 100132,
GLU_TESS_WINDING_NEGATIVE: 100133,
GLU_TESS_WINDING_ABS_GEQ_TWO: 100134
},
primitiveType: {
GL_LINE_LOOP: 2,
GL_TRIANGLES: 4,
GL_TRIANGLE_STRIP: 5,
GL_TRIANGLE_FAN: 6
},
errorType: {
GLU_TESS_MISSING_BEGIN_POLYGON: 100151,
GLU_TESS_MISSING_END_POLYGON: 100153,
GLU_TESS_MISSING_BEGIN_CONTOUR: 100152,
GLU_TESS_MISSING_END_CONTOUR: 100154,
GLU_TESS_COORD_TOO_LARGE: 100155,
GLU_TESS_NEED_COMBINE_CALLBACK: 100156
},
gluEnum: {
GLU_TESS_MESH: 100112,
GLU_TESS_TOLERANCE: 100142,
GLU_TESS_WINDING_RULE: 100140,
GLU_TESS_BOUNDARY_ONLY: 100141,
GLU_INVALID_ENUM: 100900,
GLU_INVALID_VALUE: 100901,
GLU_TESS_BEGIN: 100100,
GLU_TESS_VERTEX: 100101,
GLU_TESS_END: 100102,
GLU_TESS_ERROR: 100103,
GLU_TESS_EDGE_FLAG: 100104,
GLU_TESS_COMBINE: 100105,
GLU_TESS_BEGIN_DATA: 100106,
GLU_TESS_VERTEX_DATA: 100107,
GLU_TESS_END_DATA: 100108,
GLU_TESS_ERROR_DATA: 100109,
GLU_TESS_EDGE_FLAG_DATA: 100110,
GLU_TESS_COMBINE_DATA: 100111
}
};
X.prototype.gluDeleteTess = X.prototype.x;
X.prototype.gluTessProperty = X.prototype.B;
X.prototype.gluGetTessProperty = X.prototype.y;
X.prototype.gluTessNormal = X.prototype.A;
X.prototype.gluTessCallback = X.prototype.z;
X.prototype.gluTessVertex = X.prototype.C;
X.prototype.gluTessBeginPolygon = X.prototype.u;
X.prototype.gluTessBeginContour = X.prototype.t;
X.prototype.gluTessEndContour = X.prototype.v;
X.prototype.gluTessEndPolygon = X.prototype.w;
if (typeof module !== 'undefined') {
module.exports = this.libtess;
}
},
{}
],
33: [
function(_dereq_, module, exports) {
// (c) Dean McNamee <dean@gmail.com>, 2013.
//
// https://github.com/deanm/omggif
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
// omggif is a JavaScript implementation of a GIF 89a encoder and decoder,
// including animation and compression. It does not rely on any specific
// underlying system, so should run in the browser, Node, or Plask.
'use strict';
function GifWriter(buf, width, height, gopts) {
var p = 0;
var gopts = gopts === undefined ? {} : gopts;
var loop_count = gopts.loop === undefined ? null : gopts.loop;
var global_palette = gopts.palette === undefined ? null : gopts.palette;
if (width <= 0 || height <= 0 || width > 65535 || height > 65535)
throw new Error('Width/Height invalid.');
function check_palette_and_num_colors(palette) {
var num_colors = palette.length;
if (num_colors < 2 || num_colors > 256 || num_colors & (num_colors - 1)) {
throw new Error(
'Invalid code/color length, must be power of 2 and 2 .. 256.'
);
}
return num_colors;
}
// - Header.
buf[p++] = 0x47;
buf[p++] = 0x49;
buf[p++] = 0x46; // GIF
buf[p++] = 0x38;
buf[p++] = 0x39;
buf[p++] = 0x61; // 89a
// Handling of Global Color Table (palette) and background index.
var gp_num_colors_pow2 = 0;
var background = 0;
if (global_palette !== null) {
var gp_num_colors = check_palette_and_num_colors(global_palette);
while ((gp_num_colors >>= 1)) ++gp_num_colors_pow2;
gp_num_colors = 1 << gp_num_colors_pow2;
--gp_num_colors_pow2;
if (gopts.background !== undefined) {
background = gopts.background;
if (background >= gp_num_colors)
throw new Error('Background index out of range.');
// The GIF spec states that a background index of 0 should be ignored, so
// this is probably a mistake and you really want to set it to another
// slot in the palette. But actually in the end most browsers, etc end
// up ignoring this almost completely (including for dispose background).
if (background === 0)
throw new Error('Background index explicitly passed as 0.');
}
}
// - Logical Screen Descriptor.
// NOTE(deanm): w/h apparently ignored by implementations, but set anyway.
buf[p++] = width & 0xff;
buf[p++] = (width >> 8) & 0xff;
buf[p++] = height & 0xff;
buf[p++] = (height >> 8) & 0xff;
// NOTE: Indicates 0-bpp original color resolution (unused?).
buf[p++] =
(global_palette !== null ? 0x80 : 0) | gp_num_colors_pow2; // Global Color Table Flag. // NOTE: No sort flag (unused?).
buf[p++] = background; // Background Color Index.
buf[p++] = 0; // Pixel aspect ratio (unused?).
// - Global Color Table
if (global_palette !== null) {
for (var i = 0, il = global_palette.length; i < il; ++i) {
var rgb = global_palette[i];
buf[p++] = (rgb >> 16) & 0xff;
buf[p++] = (rgb >> 8) & 0xff;
buf[p++] = rgb & 0xff;
}
}
if (loop_count !== null) {
// Netscape block for looping.
if (loop_count < 0 || loop_count > 65535)
throw new Error('Loop count invalid.');
// Extension code, label, and length.
buf[p++] = 0x21;
buf[p++] = 0xff;
buf[p++] = 0x0b;
// NETSCAPE2.0
buf[p++] = 0x4e;
buf[p++] = 0x45;
buf[p++] = 0x54;
buf[p++] = 0x53;
buf[p++] = 0x43;
buf[p++] = 0x41;
buf[p++] = 0x50;
buf[p++] = 0x45;
buf[p++] = 0x32;
buf[p++] = 0x2e;
buf[p++] = 0x30;
// Sub-block
buf[p++] = 0x03;
buf[p++] = 0x01;
buf[p++] = loop_count & 0xff;
buf[p++] = (loop_count >> 8) & 0xff;
buf[p++] = 0x00; // Terminator.
}
var ended = false;
this.addFrame = function(x, y, w, h, indexed_pixels, opts) {
if (ended === true) {
--p;
ended = false;
} // Un-end.
opts = opts === undefined ? {} : opts;
// TODO(deanm): Bounds check x, y. Do they need to be within the virtual
// canvas width/height, I imagine?
if (x < 0 || y < 0 || x > 65535 || y > 65535) throw new Error('x/y invalid.');
if (w <= 0 || h <= 0 || w > 65535 || h > 65535)
throw new Error('Width/Height invalid.');
if (indexed_pixels.length < w * h)
throw new Error('Not enough pixels for the frame size.');
var using_local_palette = true;
var palette = opts.palette;
if (palette === undefined || palette === null) {
using_local_palette = false;
palette = global_palette;
}
if (palette === undefined || palette === null)
throw new Error('Must supply either a local or global palette.');
var num_colors = check_palette_and_num_colors(palette);
// Compute the min_code_size (power of 2), destroying num_colors.
var min_code_size = 0;
while ((num_colors >>= 1)) ++min_code_size;
num_colors = 1 << min_code_size; // Now we can easily get it back.
var delay = opts.delay === undefined ? 0 : opts.delay;
// From the spec:
// 0 - No disposal specified. The decoder is
// not required to take any action.
// 1 - Do not dispose. The graphic is to be left
// in place.
// 2 - Restore to background color. The area used by the
// graphic must be restored to the background color.
// 3 - Restore to previous. The decoder is required to
// restore the area overwritten by the graphic with
// what was there prior to rendering the graphic.
// 4-7 - To be defined.
// NOTE(deanm): Dispose background doesn't really work, apparently most
// browsers ignore the background palette index and clear to transparency.
var disposal = opts.disposal === undefined ? 0 : opts.disposal;
if (disposal < 0 || disposal > 3)
// 4-7 is reserved.
throw new Error('Disposal out of range.');
var use_transparency = false;
var transparent_index = 0;
if (opts.transparent !== undefined && opts.transparent !== null) {
use_transparency = true;
transparent_index = opts.transparent;
if (transparent_index < 0 || transparent_index >= num_colors)
throw new Error('Transparent color index.');
}
if (disposal !== 0 || use_transparency || delay !== 0) {
// - Graphics Control Extension
buf[p++] = 0x21;
buf[p++] = 0xf9; // Extension / Label.
buf[p++] = 4; // Byte size.
buf[p++] = (disposal << 2) | (use_transparency === true ? 1 : 0);
buf[p++] = delay & 0xff;
buf[p++] = (delay >> 8) & 0xff;
buf[p++] = transparent_index; // Transparent color index.
buf[p++] = 0; // Block Terminator.
}
// - Image Descriptor
buf[p++] = 0x2c; // Image Seperator.
buf[p++] = x & 0xff;
buf[p++] = (x >> 8) & 0xff; // Left.
buf[p++] = y & 0xff;
buf[p++] = (y >> 8) & 0xff; // Top.
buf[p++] = w & 0xff;
buf[p++] = (w >> 8) & 0xff;
buf[p++] = h & 0xff;
buf[p++] = (h >> 8) & 0xff;
// NOTE: No sort flag (unused?).
// TODO(deanm): Support interlace.
buf[p++] = using_local_palette === true ? 0x80 | (min_code_size - 1) : 0;
// - Local Color Table
if (using_local_palette === true) {
for (var i = 0, il = palette.length; i < il; ++i) {
var rgb = palette[i];
buf[p++] = (rgb >> 16) & 0xff;
buf[p++] = (rgb >> 8) & 0xff;
buf[p++] = rgb & 0xff;
}
}
p = GifWriterOutputLZWCodeStream(
buf,
p,
min_code_size < 2 ? 2 : min_code_size,
indexed_pixels
);
return p;
};
this.end = function() {
if (ended === false) {
buf[p++] = 0x3b; // Trailer.
ended = true;
}
return p;
};
this.getOutputBuffer = function() {
return buf;
};
this.setOutputBuffer = function(v) {
buf = v;
};
this.getOutputBufferPosition = function() {
return p;
};
this.setOutputBufferPosition = function(v) {
p = v;
};
}
// Main compression routine, palette indexes -> LZW code stream.
// |index_stream| must have at least one entry.
function GifWriterOutputLZWCodeStream(buf, p, min_code_size, index_stream) {
buf[p++] = min_code_size;
var cur_subblock = p++; // Pointing at the length field.
var clear_code = 1 << min_code_size;
var code_mask = clear_code - 1;
var eoi_code = clear_code + 1;
var next_code = eoi_code + 1;
var cur_code_size = min_code_size + 1; // Number of bits per code.
var cur_shift = 0;
// We have at most 12-bit codes, so we should have to hold a max of 19
// bits here (and then we would write out).
var cur = 0;
function emit_bytes_to_buffer(bit_block_size) {
while (cur_shift >= bit_block_size) {
buf[p++] = cur & 0xff;
cur >>= 8;
cur_shift -= 8;
if (p === cur_subblock + 256) {
// Finished a subblock.
buf[cur_subblock] = 255;
cur_subblock = p++;
}
}
}
function emit_code(c) {
cur |= c << cur_shift;
cur_shift += cur_code_size;
emit_bytes_to_buffer(8);
}
// I am not an expert on the topic, and I don't want to write a thesis.
// However, it is good to outline here the basic algorithm and the few data
// structures and optimizations here that make this implementation fast.
// The basic idea behind LZW is to build a table of previously seen runs
// addressed by a short id (herein called output code). All data is
// referenced by a code, which represents one or more values from the
// original input stream. All input bytes can be referenced as the same
// value as an output code. So if you didn't want any compression, you
// could more or less just output the original bytes as codes (there are
// some details to this, but it is the idea). In order to achieve
// compression, values greater then the input range (codes can be up to
// 12-bit while input only 8-bit) represent a sequence of previously seen
// inputs. The decompressor is able to build the same mapping while
// decoding, so there is always a shared common knowledge between the
// encoding and decoder, which is also important for "timing" aspects like
// how to handle variable bit width code encoding.
//
// One obvious but very important consequence of the table system is there
// is always a unique id (at most 12-bits) to map the runs. 'A' might be
// 4, then 'AA' might be 10, 'AAA' 11, 'AAAA' 12, etc. This relationship
// can be used for an effecient lookup strategy for the code mapping. We
// need to know if a run has been seen before, and be able to map that run
// to the output code. Since we start with known unique ids (input bytes),
// and then from those build more unique ids (table entries), we can
// continue this chain (almost like a linked list) to always have small
// integer values that represent the current byte chains in the encoder.
// This means instead of tracking the input bytes (AAAABCD) to know our
// current state, we can track the table entry for AAAABC (it is guaranteed
// to exist by the nature of the algorithm) and the next character D.
// Therefor the tuple of (table_entry, byte) is guaranteed to also be
// unique. This allows us to create a simple lookup key for mapping input
// sequences to codes (table indices) without having to store or search
// any of the code sequences. So if 'AAAA' has a table entry of 12, the
// tuple of ('AAAA', K) for any input byte K will be unique, and can be our
// key. This leads to a integer value at most 20-bits, which can always
// fit in an SMI value and be used as a fast sparse array / object key.
// Output code for the current contents of the index buffer.
var ib_code = index_stream[0] & code_mask; // Load first input index.
var code_table = {}; // Key'd on our 20-bit "tuple".
emit_code(clear_code); // Spec says first code should be a clear code.
// First index already loaded, process the rest of the stream.
for (var i = 1, il = index_stream.length; i < il; ++i) {
var k = index_stream[i] & code_mask;
var cur_key = (ib_code << 8) | k; // (prev, k) unique tuple.
var cur_code = code_table[cur_key]; // buffer + k.
// Check if we have to create a new code table entry.
if (cur_code === undefined) {
// We don't have buffer + k.
// Emit index buffer (without k).
// This is an inline version of emit_code, because this is the core
// writing routine of the compressor (and V8 cannot inline emit_code
// because it is a closure here in a different context). Additionally
// we can call emit_byte_to_buffer less often, because we can have
// 30-bits (from our 31-bit signed SMI), and we know our codes will only
// be 12-bits, so can safely have 18-bits there without overflow.
// emit_code(ib_code);
cur |= ib_code << cur_shift;
cur_shift += cur_code_size;
while (cur_shift >= 8) {
buf[p++] = cur & 0xff;
cur >>= 8;
cur_shift -= 8;
if (p === cur_subblock + 256) {
// Finished a subblock.
buf[cur_subblock] = 255;
cur_subblock = p++;
}
}
if (next_code === 4096) {
// Table full, need a clear.
emit_code(clear_code);
next_code = eoi_code + 1;
cur_code_size = min_code_size + 1;
code_table = {};
} else {
// Table not full, insert a new entry.
// Increase our variable bit code sizes if necessary. This is a bit
// tricky as it is based on "timing" between the encoding and
// decoder. From the encoders perspective this should happen after
// we've already emitted the index buffer and are about to create the
// first table entry that would overflow our current code bit size.
if (next_code >= 1 << cur_code_size) ++cur_code_size;
code_table[cur_key] = next_code++; // Insert into code table.
}
ib_code = k; // Index buffer to single input k.
} else {
ib_code = cur_code; // Index buffer to sequence in code table.
}
}
emit_code(ib_code); // There will still be something in the index buffer.
emit_code(eoi_code); // End Of Information.
// Flush / finalize the sub-blocks stream to the buffer.
emit_bytes_to_buffer(1);
// Finish the sub-blocks, writing out any unfinished lengths and
// terminating with a sub-block of length 0. If we have already started
// but not yet used a sub-block it can just become the terminator.
if (cur_subblock + 1 === p) {
// Started but unused.
buf[cur_subblock] = 0;
} else {
// Started and used, write length and additional terminator block.
buf[cur_subblock] = p - cur_subblock - 1;
buf[p++] = 0;
}
return p;
}
function GifReader(buf) {
var p = 0;
// - Header (GIF87a or GIF89a).
if (
buf[p++] !== 0x47 ||
buf[p++] !== 0x49 ||
buf[p++] !== 0x46 ||
buf[p++] !== 0x38 ||
((buf[p++] + 1) & 0xfd) !== 0x38 ||
buf[p++] !== 0x61
) {
throw new Error('Invalid GIF 87a/89a header.');
}
// - Logical Screen Descriptor.
var width = buf[p++] | (buf[p++] << 8);
var height = buf[p++] | (buf[p++] << 8);
var pf0 = buf[p++]; // <Packed Fields>.
var global_palette_flag = pf0 >> 7;
var num_global_colors_pow2 = pf0 & 0x7;
var num_global_colors = 1 << (num_global_colors_pow2 + 1);
var background = buf[p++];
buf[p++]; // Pixel aspect ratio (unused?).
var global_palette_offset = null;
var global_palette_size = null;
if (global_palette_flag) {
global_palette_offset = p;
global_palette_size = num_global_colors;
p += num_global_colors * 3; // Seek past palette.
}
var no_eof = true;
var frames = [];
var delay = 0;
var transparent_index = null;
var disposal = 0; // 0 - No disposal specified.
var loop_count = null;
this.width = width;
this.height = height;
while (no_eof && p < buf.length) {
switch (buf[p++]) {
case 0x21: // Graphics Control Extension Block
switch (buf[p++]) {
case 0xff: // Application specific block
// Try if it's a Netscape block (with animation loop counter).
if (
buf[p] !== 0x0b || // 21 FF already read, check block size.
// NETSCAPE2.0
(buf[p + 1] == 0x4e &&
buf[p + 2] == 0x45 &&
buf[p + 3] == 0x54 &&
buf[p + 4] == 0x53 &&
buf[p + 5] == 0x43 &&
buf[p + 6] == 0x41 &&
buf[p + 7] == 0x50 &&
buf[p + 8] == 0x45 &&
buf[p + 9] == 0x32 &&
buf[p + 10] == 0x2e &&
buf[p + 11] == 0x30 &&
// Sub-block
buf[p + 12] == 0x03 &&
buf[p + 13] == 0x01 &&
buf[p + 16] == 0)
) {
p += 14;
loop_count = buf[p++] | (buf[p++] << 8);
p++; // Skip terminator.
} else {
// We don't know what it is, just try to get past it.
p += 12;
while (true) {
// Seek through subblocks.
var block_size = buf[p++];
// Bad block size (ex: undefined from an out of bounds read).
if (!(block_size >= 0)) throw Error('Invalid block size');
if (block_size === 0) break; // 0 size is terminator
p += block_size;
}
}
break;
case 0xf9: // Graphics Control Extension
if (buf[p++] !== 0x4 || buf[p + 4] !== 0)
throw new Error('Invalid graphics extension block.');
var pf1 = buf[p++];
delay = buf[p++] | (buf[p++] << 8);
transparent_index = buf[p++];
if ((pf1 & 1) === 0) transparent_index = null;
disposal = (pf1 >> 2) & 0x7;
p++; // Skip terminator.
break;
case 0xfe: // Comment Extension.
while (true) {
// Seek through subblocks.
var block_size = buf[p++];
// Bad block size (ex: undefined from an out of bounds read).
if (!(block_size >= 0)) throw Error('Invalid block size');
if (block_size === 0) break; // 0 size is terminator
// console.log(buf.slice(p, p+block_size).toString('ascii'));
p += block_size;
}
break;
default:
throw new Error(
'Unknown graphic control label: 0x' + buf[p - 1].toString(16)
);
}
break;
case 0x2c: // Image Descriptor.
var x = buf[p++] | (buf[p++] << 8);
var y = buf[p++] | (buf[p++] << 8);
var w = buf[p++] | (buf[p++] << 8);
var h = buf[p++] | (buf[p++] << 8);
var pf2 = buf[p++];
var local_palette_flag = pf2 >> 7;
var interlace_flag = (pf2 >> 6) & 1;
var num_local_colors_pow2 = pf2 & 0x7;
var num_local_colors = 1 << (num_local_colors_pow2 + 1);
var palette_offset = global_palette_offset;
var palette_size = global_palette_size;
var has_local_palette = false;
if (local_palette_flag) {
var has_local_palette = true;
palette_offset = p; // Override with local palette.
palette_size = num_local_colors;
p += num_local_colors * 3; // Seek past palette.
}
var data_offset = p;
p++; // codesize
while (true) {
var block_size = buf[p++];
// Bad block size (ex: undefined from an out of bounds read).
if (!(block_size >= 0)) throw Error('Invalid block size');
if (block_size === 0) break; // 0 size is terminator
p += block_size;
}
frames.push({
x: x,
y: y,
width: w,
height: h,
has_local_palette: has_local_palette,
palette_offset: palette_offset,
palette_size: palette_size,
data_offset: data_offset,
data_length: p - data_offset,
transparent_index: transparent_index,
interlaced: !!interlace_flag,
delay: delay,
disposal: disposal
});
break;
case 0x3b: // Trailer Marker (end of file).
no_eof = false;
break;
default:
throw new Error('Unknown gif block: 0x' + buf[p - 1].toString(16));
break;
}
}
this.numFrames = function() {
return frames.length;
};
this.loopCount = function() {
return loop_count;
};
this.frameInfo = function(frame_num) {
if (frame_num < 0 || frame_num >= frames.length)
throw new Error('Frame index out of range.');
return frames[frame_num];
};
this.decodeAndBlitFrameBGRA = function(frame_num, pixels) {
var frame = this.frameInfo(frame_num);
var num_pixels = frame.width * frame.height;
var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices.
GifReaderLZWOutputIndexStream(
buf,
frame.data_offset,
index_stream,
num_pixels
);
var palette_offset = frame.palette_offset;
// NOTE(deanm): It seems to be much faster to compare index to 256 than
// to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in
// the profile, not sure if it's related to using a Uint8Array.
var trans = frame.transparent_index;
if (trans === null) trans = 256;
// We are possibly just blitting to a portion of the entire frame.
// That is a subrect within the framerect, so the additional pixels
// must be skipped over after we finished a scanline.
var framewidth = frame.width;
var framestride = width - framewidth;
var xleft = framewidth; // Number of subrect pixels left in scanline.
// Output indicies of the top left and bottom right corners of the subrect.
var opbeg = (frame.y * width + frame.x) * 4;
var opend = ((frame.y + frame.height) * width + frame.x) * 4;
var op = opbeg;
var scanstride = framestride * 4;
// Use scanstride to skip past the rows when interlacing. This is skipping
// 7 rows for the first two passes, then 3 then 1.
if (frame.interlaced === true) {
scanstride += width * 4 * 7; // Pass 1.
}
var interlaceskip = 8; // Tracking the row interval in the current pass.
for (var i = 0, il = index_stream.length; i < il; ++i) {
var index = index_stream[i];
if (xleft === 0) {
// Beginning of new scan line
op += scanstride;
xleft = framewidth;
if (op >= opend) {
// Catch the wrap to switch passes when interlacing.
scanstride = framestride * 4 + width * 4 * (interlaceskip - 1);
// interlaceskip / 2 * 4 is interlaceskip << 1.
op = opbeg + (framewidth + framestride) * (interlaceskip << 1);
interlaceskip >>= 1;
}
}
if (index === trans) {
op += 4;
} else {
var r = buf[palette_offset + index * 3];
var g = buf[palette_offset + index * 3 + 1];
var b = buf[palette_offset + index * 3 + 2];
pixels[op++] = b;
pixels[op++] = g;
pixels[op++] = r;
pixels[op++] = 255;
}
--xleft;
}
};
// I will go to copy and paste hell one day...
this.decodeAndBlitFrameRGBA = function(frame_num, pixels) {
var frame = this.frameInfo(frame_num);
var num_pixels = frame.width * frame.height;
var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices.
GifReaderLZWOutputIndexStream(
buf,
frame.data_offset,
index_stream,
num_pixels
);
var palette_offset = frame.palette_offset;
// NOTE(deanm): It seems to be much faster to compare index to 256 than
// to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in
// the profile, not sure if it's related to using a Uint8Array.
var trans = frame.transparent_index;
if (trans === null) trans = 256;
// We are possibly just blitting to a portion of the entire frame.
// That is a subrect within the framerect, so the additional pixels
// must be skipped over after we finished a scanline.
var framewidth = frame.width;
var framestride = width - framewidth;
var xleft = framewidth; // Number of subrect pixels left in scanline.
// Output indicies of the top left and bottom right corners of the subrect.
var opbeg = (frame.y * width + frame.x) * 4;
var opend = ((frame.y + frame.height) * width + frame.x) * 4;
var op = opbeg;
var scanstride = framestride * 4;
// Use scanstride to skip past the rows when interlacing. This is skipping
// 7 rows for the first two passes, then 3 then 1.
if (frame.interlaced === true) {
scanstride += width * 4 * 7; // Pass 1.
}
var interlaceskip = 8; // Tracking the row interval in the current pass.
for (var i = 0, il = index_stream.length; i < il; ++i) {
var index = index_stream[i];
if (xleft === 0) {
// Beginning of new scan line
op += scanstride;
xleft = framewidth;
if (op >= opend) {
// Catch the wrap to switch passes when interlacing.
scanstride = framestride * 4 + width * 4 * (interlaceskip - 1);
// interlaceskip / 2 * 4 is interlaceskip << 1.
op = opbeg + (framewidth + framestride) * (interlaceskip << 1);
interlaceskip >>= 1;
}
}
if (index === trans) {
op += 4;
} else {
var r = buf[palette_offset + index * 3];
var g = buf[palette_offset + index * 3 + 1];
var b = buf[palette_offset + index * 3 + 2];
pixels[op++] = r;
pixels[op++] = g;
pixels[op++] = b;
pixels[op++] = 255;
}
--xleft;
}
};
}
function GifReaderLZWOutputIndexStream(code_stream, p, output, output_length) {
var min_code_size = code_stream[p++];
var clear_code = 1 << min_code_size;
var eoi_code = clear_code + 1;
var next_code = eoi_code + 1;
var cur_code_size = min_code_size + 1; // Number of bits per code.
// NOTE: This shares the same name as the encoder, but has a different
// meaning here. Here this masks each code coming from the code stream.
var code_mask = (1 << cur_code_size) - 1;
var cur_shift = 0;
var cur = 0;
var op = 0; // Output pointer.
var subblock_size = code_stream[p++];
// TODO(deanm): Would using a TypedArray be any faster? At least it would
// solve the fast mode / backing store uncertainty.
// var code_table = Array(4096);
var code_table = new Int32Array(4096); // Can be signed, we only use 20 bits.
var prev_code = null; // Track code-1.
while (true) {
// Read up to two bytes, making sure we always 12-bits for max sized code.
while (cur_shift < 16) {
if (subblock_size === 0) break; // No more data to be read.
cur |= code_stream[p++] << cur_shift;
cur_shift += 8;
if (subblock_size === 1) {
// Never let it get to 0 to hold logic above.
subblock_size = code_stream[p++]; // Next subblock.
} else {
--subblock_size;
}
}
// TODO(deanm): We should never really get here, we should have received
// and EOI.
if (cur_shift < cur_code_size) break;
var code = cur & code_mask;
cur >>= cur_code_size;
cur_shift -= cur_code_size;
// TODO(deanm): Maybe should check that the first code was a clear code,
// at least this is what you're supposed to do. But actually our encoder
// now doesn't emit a clear code first anyway.
if (code === clear_code) {
// We don't actually have to clear the table. This could be a good idea
// for greater error checking, but we don't really do any anyway. We
// will just track it with next_code and overwrite old entries.
next_code = eoi_code + 1;
cur_code_size = min_code_size + 1;
code_mask = (1 << cur_code_size) - 1;
// Don't update prev_code ?
prev_code = null;
continue;
} else if (code === eoi_code) {
break;
}
// We have a similar situation as the decoder, where we want to store
// variable length entries (code table entries), but we want to do in a
// faster manner than an array of arrays. The code below stores sort of a
// linked list within the code table, and then "chases" through it to
// construct the dictionary entries. When a new entry is created, just the
// last byte is stored, and the rest (prefix) of the entry is only
// referenced by its table entry. Then the code chases through the
// prefixes until it reaches a single byte code. We have to chase twice,
// first to compute the length, and then to actually copy the data to the
// output (backwards, since we know the length). The alternative would be
// storing something in an intermediate stack, but that doesn't make any
// more sense. I implemented an approach where it also stored the length
// in the code table, although it's a bit tricky because you run out of
// bits (12 + 12 + 8), but I didn't measure much improvements (the table
// entries are generally not the long). Even when I created benchmarks for
// very long table entries the complexity did not seem worth it.
// The code table stores the prefix entry in 12 bits and then the suffix
// byte in 8 bits, so each entry is 20 bits.
var chase_code = code < next_code ? code : prev_code;
// Chase what we will output, either {CODE} or {CODE-1}.
var chase_length = 0;
var chase = chase_code;
while (chase > clear_code) {
chase = code_table[chase] >> 8;
++chase_length;
}
var k = chase;
var op_end = op + chase_length + (chase_code !== code ? 1 : 0);
if (op_end > output_length) {
console.log('Warning, gif stream longer than expected.');
return;
}
// Already have the first byte from the chase, might as well write it fast.
output[op++] = k;
op += chase_length;
var b = op; // Track pointer, writing backwards.
if (chase_code !== code)
// The case of emitting {CODE-1} + k.
output[op++] = k;
chase = chase_code;
while (chase_length--) {
chase = code_table[chase];
output[--b] = chase & 0xff; // Write backwards.
chase >>= 8; // Pull down to the prefix code.
}
if (prev_code !== null && next_code < 4096) {
code_table[next_code++] = (prev_code << 8) | k;
// TODO(deanm): Figure out this clearing vs code growth logic better. I
// have an feeling that it should just happen somewhere else, for now it
// is awkward between when we grow past the max and then hit a clear code.
// For now just check if we hit the max 12-bits (then a clear code should
// follow, also of course encoded in 12-bits).
if (next_code >= code_mask + 1 && cur_code_size < 12) {
++cur_code_size;
code_mask = (code_mask << 1) | 1;
}
}
prev_code = code;
}
if (op !== output_length) {
console.log('Warning, gif stream shorter than expected.');
}
return output;
}
// CommonJS.
try {
exports.GifWriter = GifWriter;
exports.GifReader = GifReader;
} catch (e) {}
},
{}
],
34: [
function(_dereq_, module, exports) {
(function(Buffer) {
/**
* https://opentype.js.org v0.9.0 | (c) Frederik De Bleser and other contributors | MIT License | Uses tiny-inflate by Devon Govett and string.prototype.codepointat polyfill by Mathias Bynens
*/
(function(global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
? factory(exports)
: typeof define === 'function' && define.amd
? define(['exports'], factory)
: factory((global.opentype = {}));
})(this, function(exports) {
'use strict';
/*! https://mths.be/codepointat v0.2.0 by @mathias */
if (!String.prototype.codePointAt) {
(function() {
var defineProperty = (function() {
// IE 8 only supports `Object.defineProperty` on DOM elements
try {
var object = {};
var $defineProperty = Object.defineProperty;
var result =
$defineProperty(object, object, object) && $defineProperty;
} catch (error) {}
return result;
})();
var codePointAt = function(position) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var size = string.length;
// `ToInteger`
var index = position ? Number(position) : 0;
if (index != index) {
// better `isNaN`
index = 0;
}
// Account for out-of-bounds indices:
if (index < 0 || index >= size) {
return undefined;
}
// Get the first code unit
var first = string.charCodeAt(index);
var second;
if (
// check if it’s the start of a surrogate pair
first >= 0xd800 &&
first <= 0xdbff && // high surrogate
size > index + 1 // there is a next code unit
) {
second = string.charCodeAt(index + 1);
if (second >= 0xdc00 && second <= 0xdfff) {
// low surrogate
// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
return (first - 0xd800) * 0x400 + second - 0xdc00 + 0x10000;
}
}
return first;
};
if (defineProperty) {
defineProperty(String.prototype, 'codePointAt', {
value: codePointAt,
configurable: true,
writable: true
});
} else {
String.prototype.codePointAt = codePointAt;
}
})();
}
var TINF_OK = 0;
var TINF_DATA_ERROR = -3;
function Tree() {
this.table = new Uint16Array(16); /* table of code length counts */
this.trans = new Uint16Array(288); /* code -> symbol translation table */
}
function Data(source, dest) {
this.source = source;
this.sourceIndex = 0;
this.tag = 0;
this.bitcount = 0;
this.dest = dest;
this.destLen = 0;
this.ltree = new Tree(); /* dynamic length/symbol tree */
this.dtree = new Tree(); /* dynamic distance tree */
}
/* --------------------------------------------------- *
* -- uninitialized global data (static structures) -- *
* --------------------------------------------------- */
var sltree = new Tree();
var sdtree = new Tree();
/* extra bits and base tables for length codes */
var length_bits = new Uint8Array(30);
var length_base = new Uint16Array(30);
/* extra bits and base tables for distance codes */
var dist_bits = new Uint8Array(30);
var dist_base = new Uint16Array(30);
/* special ordering of code length codes */
var clcidx = new Uint8Array([
16,
17,
18,
0,
8,
7,
9,
6,
10,
5,
11,
4,
12,
3,
13,
2,
14,
1,
15
]);
/* used by tinf_decode_trees, avoids allocations every call */
var code_tree = new Tree();
var lengths = new Uint8Array(288 + 32);
/* ----------------------- *
* -- utility functions -- *
* ----------------------- */
/* build extra bits and base tables */
function tinf_build_bits_base(bits, base, delta, first) {
var i, sum;
/* build bits table */
for (i = 0; i < delta; ++i) {
bits[i] = 0;
}
for (i = 0; i < 30 - delta; ++i) {
bits[i + delta] = (i / delta) | 0;
}
/* build base table */
for (sum = first, i = 0; i < 30; ++i) {
base[i] = sum;
sum += 1 << bits[i];
}
}
/* build the fixed huffman trees */
function tinf_build_fixed_trees(lt, dt) {
var i;
/* build fixed length tree */
for (i = 0; i < 7; ++i) {
lt.table[i] = 0;
}
lt.table[7] = 24;
lt.table[8] = 152;
lt.table[9] = 112;
for (i = 0; i < 24; ++i) {
lt.trans[i] = 256 + i;
}
for (i = 0; i < 144; ++i) {
lt.trans[24 + i] = i;
}
for (i = 0; i < 8; ++i) {
lt.trans[24 + 144 + i] = 280 + i;
}
for (i = 0; i < 112; ++i) {
lt.trans[24 + 144 + 8 + i] = 144 + i;
}
/* build fixed distance tree */
for (i = 0; i < 5; ++i) {
dt.table[i] = 0;
}
dt.table[5] = 32;
for (i = 0; i < 32; ++i) {
dt.trans[i] = i;
}
}
/* given an array of code lengths, build a tree */
var offs = new Uint16Array(16);
function tinf_build_tree(t, lengths, off, num) {
var i, sum;
/* clear code length count table */
for (i = 0; i < 16; ++i) {
t.table[i] = 0;
}
/* scan symbol lengths, and sum code length counts */
for (i = 0; i < num; ++i) {
t.table[lengths[off + i]]++;
}
t.table[0] = 0;
/* compute offset table for distribution sort */
for (sum = 0, i = 0; i < 16; ++i) {
offs[i] = sum;
sum += t.table[i];
}
/* create code->symbol translation table (symbols sorted by code) */
for (i = 0; i < num; ++i) {
if (lengths[off + i]) {
t.trans[offs[lengths[off + i]]++] = i;
}
}
}
/* ---------------------- *
* -- decode functions -- *
* ---------------------- */
/* get one bit from source stream */
function tinf_getbit(d) {
/* check if tag is empty */
if (!d.bitcount--) {
/* load next tag */
d.tag = d.source[d.sourceIndex++];
d.bitcount = 7;
}
/* shift bit out of tag */
var bit = d.tag & 1;
d.tag >>>= 1;
return bit;
}
/* read a num bit value from a stream and add base */
function tinf_read_bits(d, num, base) {
if (!num) {
return base;
}
while (d.bitcount < 24) {
d.tag |= d.source[d.sourceIndex++] << d.bitcount;
d.bitcount += 8;
}
var val = d.tag & (0xffff >>> (16 - num));
d.tag >>>= num;
d.bitcount -= num;
return val + base;
}
/* given a data stream and a tree, decode a symbol */
function tinf_decode_symbol(d, t) {
while (d.bitcount < 24) {
d.tag |= d.source[d.sourceIndex++] << d.bitcount;
d.bitcount += 8;
}
var sum = 0,
cur = 0,
len = 0;
var tag = d.tag;
/* get more bits while code value is above sum */
do {
cur = 2 * cur + (tag & 1);
tag >>>= 1;
++len;
sum += t.table[len];
cur -= t.table[len];
} while (cur >= 0);
d.tag = tag;
d.bitcount -= len;
return t.trans[sum + cur];
}
/* given a data stream, decode dynamic trees from it */
function tinf_decode_trees(d, lt, dt) {
var hlit, hdist, hclen;
var i, num, length;
/* get 5 bits HLIT (257-286) */
hlit = tinf_read_bits(d, 5, 257);
/* get 5 bits HDIST (1-32) */
hdist = tinf_read_bits(d, 5, 1);
/* get 4 bits HCLEN (4-19) */
hclen = tinf_read_bits(d, 4, 4);
for (i = 0; i < 19; ++i) {
lengths[i] = 0;
}
/* read code lengths for code length alphabet */
for (i = 0; i < hclen; ++i) {
/* get 3 bits code length (0-7) */
var clen = tinf_read_bits(d, 3, 0);
lengths[clcidx[i]] = clen;
}
/* build code length tree */
tinf_build_tree(code_tree, lengths, 0, 19);
/* decode code lengths for the dynamic trees */
for (num = 0; num < hlit + hdist; ) {
var sym = tinf_decode_symbol(d, code_tree);
switch (sym) {
case 16:
/* copy previous code length 3-6 times (read 2 bits) */
var prev = lengths[num - 1];
for (length = tinf_read_bits(d, 2, 3); length; --length) {
lengths[num++] = prev;
}
break;
case 17:
/* repeat code length 0 for 3-10 times (read 3 bits) */
for (length = tinf_read_bits(d, 3, 3); length; --length) {
lengths[num++] = 0;
}
break;
case 18:
/* repeat code length 0 for 11-138 times (read 7 bits) */
for (length = tinf_read_bits(d, 7, 11); length; --length) {
lengths[num++] = 0;
}
break;
default:
/* values 0-15 represent the actual code lengths */
lengths[num++] = sym;
break;
}
}
/* build dynamic trees */
tinf_build_tree(lt, lengths, 0, hlit);
tinf_build_tree(dt, lengths, hlit, hdist);
}
/* ----------------------------- *
* -- block inflate functions -- *
* ----------------------------- */
/* given a stream and two trees, inflate a block of data */
function tinf_inflate_block_data(d, lt, dt) {
while (1) {
var sym = tinf_decode_symbol(d, lt);
/* check for end of block */
if (sym === 256) {
return TINF_OK;
}
if (sym < 256) {
d.dest[d.destLen++] = sym;
} else {
var length, dist, offs;
var i;
sym -= 257;
/* possibly get more bits from length code */
length = tinf_read_bits(d, length_bits[sym], length_base[sym]);
dist = tinf_decode_symbol(d, dt);
/* possibly get more bits from distance code */
offs = d.destLen - tinf_read_bits(d, dist_bits[dist], dist_base[dist]);
/* copy match */
for (i = offs; i < offs + length; ++i) {
d.dest[d.destLen++] = d.dest[i];
}
}
}
}
/* inflate an uncompressed block of data */
function tinf_inflate_uncompressed_block(d) {
var length, invlength;
var i;
/* unread from bitbuffer */
while (d.bitcount > 8) {
d.sourceIndex--;
d.bitcount -= 8;
}
/* get length */
length = d.source[d.sourceIndex + 1];
length = 256 * length + d.source[d.sourceIndex];
/* get one's complement of length */
invlength = d.source[d.sourceIndex + 3];
invlength = 256 * invlength + d.source[d.sourceIndex + 2];
/* check length */
if (length !== (~invlength & 0x0000ffff)) {
return TINF_DATA_ERROR;
}
d.sourceIndex += 4;
/* copy block */
for (i = length; i; --i) {
d.dest[d.destLen++] = d.source[d.sourceIndex++];
}
/* make sure we start next block on a byte boundary */
d.bitcount = 0;
return TINF_OK;
}
/* inflate stream from source to dest */
function tinf_uncompress(source, dest) {
var d = new Data(source, dest);
var bfinal, btype, res;
do {
/* read final block flag */
bfinal = tinf_getbit(d);
/* read block type (2 bits) */
btype = tinf_read_bits(d, 2, 0);
/* decompress block */
switch (btype) {
case 0:
/* decompress uncompressed block */
res = tinf_inflate_uncompressed_block(d);
break;
case 1:
/* decompress block with fixed huffman trees */
res = tinf_inflate_block_data(d, sltree, sdtree);
break;
case 2:
/* decompress block with dynamic huffman trees */
tinf_decode_trees(d, d.ltree, d.dtree);
res = tinf_inflate_block_data(d, d.ltree, d.dtree);
break;
default:
res = TINF_DATA_ERROR;
}
if (res !== TINF_OK) {
throw new Error('Data error');
}
} while (!bfinal);
if (d.destLen < d.dest.length) {
if (typeof d.dest.slice === 'function') {
return d.dest.slice(0, d.destLen);
} else {
return d.dest.subarray(0, d.destLen);
}
}
return d.dest;
}
/* -------------------- *
* -- initialization -- *
* -------------------- */
/* build fixed huffman trees */
tinf_build_fixed_trees(sltree, sdtree);
/* build extra bits and base tables */
tinf_build_bits_base(length_bits, length_base, 4, 3);
tinf_build_bits_base(dist_bits, dist_base, 2, 1);
/* fix a special case */
length_bits[28] = 0;
length_base[28] = 258;
var tinyInflate = tinf_uncompress;
// The Bounding Box object
function derive(v0, v1, v2, v3, t) {
return (
Math.pow(1 - t, 3) * v0 +
3 * Math.pow(1 - t, 2) * t * v1 +
3 * (1 - t) * Math.pow(t, 2) * v2 +
Math.pow(t, 3) * v3
);
}
/**
* A bounding box is an enclosing box that describes the smallest measure within which all the points lie.
* It is used to calculate the bounding box of a glyph or text path.
*
* On initialization, x1/y1/x2/y2 will be NaN. Check if the bounding box is empty using `isEmpty()`.
*
* @exports opentype.BoundingBox
* @class
* @constructor
*/
function BoundingBox() {
this.x1 = Number.NaN;
this.y1 = Number.NaN;
this.x2 = Number.NaN;
this.y2 = Number.NaN;
}
/**
* Returns true if the bounding box is empty, that is, no points have been added to the box yet.
*/
BoundingBox.prototype.isEmpty = function() {
return isNaN(this.x1) || isNaN(this.y1) || isNaN(this.x2) || isNaN(this.y2);
};
/**
* Add the point to the bounding box.
* The x1/y1/x2/y2 coordinates of the bounding box will now encompass the given point.
* @param {number} x - The X coordinate of the point.
* @param {number} y - The Y coordinate of the point.
*/
BoundingBox.prototype.addPoint = function(x, y) {
if (typeof x === 'number') {
if (isNaN(this.x1) || isNaN(this.x2)) {
this.x1 = x;
this.x2 = x;
}
if (x < this.x1) {
this.x1 = x;
}
if (x > this.x2) {
this.x2 = x;
}
}
if (typeof y === 'number') {
if (isNaN(this.y1) || isNaN(this.y2)) {
this.y1 = y;
this.y2 = y;
}
if (y < this.y1) {
this.y1 = y;
}
if (y > this.y2) {
this.y2 = y;
}
}
};
/**
* Add a X coordinate to the bounding box.
* This extends the bounding box to include the X coordinate.
* This function is used internally inside of addBezier.
* @param {number} x - The X coordinate of the point.
*/
BoundingBox.prototype.addX = function(x) {
this.addPoint(x, null);
};
/**
* Add a Y coordinate to the bounding box.
* This extends the bounding box to include the Y coordinate.
* This function is used internally inside of addBezier.
* @param {number} y - The Y coordinate of the point.
*/
BoundingBox.prototype.addY = function(y) {
this.addPoint(null, y);
};
/**
* Add a Bézier curve to the bounding box.
* This extends the bounding box to include the entire Bézier.
* @param {number} x0 - The starting X coordinate.
* @param {number} y0 - The starting Y coordinate.
* @param {number} x1 - The X coordinate of the first control point.
* @param {number} y1 - The Y coordinate of the first control point.
* @param {number} x2 - The X coordinate of the second control point.
* @param {number} y2 - The Y coordinate of the second control point.
* @param {number} x - The ending X coordinate.
* @param {number} y - The ending Y coordinate.
*/
BoundingBox.prototype.addBezier = function(x0, y0, x1, y1, x2, y2, x, y) {
var this$1 = this;
// This code is based on http://nishiohirokazu.blogspot.com/2009/06/how-to-calculate-bezier-curves-bounding.html
// and https://github.com/icons8/svg-path-bounding-box
var p0 = [x0, y0];
var p1 = [x1, y1];
var p2 = [x2, y2];
var p3 = [x, y];
this.addPoint(x0, y0);
this.addPoint(x, y);
for (var i = 0; i <= 1; i++) {
var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i];
var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i];
var c = 3 * p1[i] - 3 * p0[i];
if (a === 0) {
if (b === 0) {
continue;
}
var t = -c / b;
if (0 < t && t < 1) {
if (i === 0) {
this$1.addX(derive(p0[i], p1[i], p2[i], p3[i], t));
}
if (i === 1) {
this$1.addY(derive(p0[i], p1[i], p2[i], p3[i], t));
}
}
continue;
}
var b2ac = Math.pow(b, 2) - 4 * c * a;
if (b2ac < 0) {
continue;
}
var t1 = (-b + Math.sqrt(b2ac)) / (2 * a);
if (0 < t1 && t1 < 1) {
if (i === 0) {
this$1.addX(derive(p0[i], p1[i], p2[i], p3[i], t1));
}
if (i === 1) {
this$1.addY(derive(p0[i], p1[i], p2[i], p3[i], t1));
}
}
var t2 = (-b - Math.sqrt(b2ac)) / (2 * a);
if (0 < t2 && t2 < 1) {
if (i === 0) {
this$1.addX(derive(p0[i], p1[i], p2[i], p3[i], t2));
}
if (i === 1) {
this$1.addY(derive(p0[i], p1[i], p2[i], p3[i], t2));
}
}
}
};
/**
* Add a quadratic curve to the bounding box.
* This extends the bounding box to include the entire quadratic curve.
* @param {number} x0 - The starting X coordinate.
* @param {number} y0 - The starting Y coordinate.
* @param {number} x1 - The X coordinate of the control point.
* @param {number} y1 - The Y coordinate of the control point.
* @param {number} x - The ending X coordinate.
* @param {number} y - The ending Y coordinate.
*/
BoundingBox.prototype.addQuad = function(x0, y0, x1, y1, x, y) {
var cp1x = x0 + 2 / 3 * (x1 - x0);
var cp1y = y0 + 2 / 3 * (y1 - y0);
var cp2x = cp1x + 1 / 3 * (x - x0);
var cp2y = cp1y + 1 / 3 * (y - y0);
this.addBezier(x0, y0, cp1x, cp1y, cp2x, cp2y, x, y);
};
// Geometric objects
/**
* A bézier path containing a set of path commands similar to a SVG path.
* Paths can be drawn on a context using `draw`.
* @exports opentype.Path
* @class
* @constructor
*/
function Path() {
this.commands = [];
this.fill = 'black';
this.stroke = null;
this.strokeWidth = 1;
}
/**
* @param {number} x
* @param {number} y
*/
Path.prototype.moveTo = function(x, y) {
this.commands.push({
type: 'M',
x: x,
y: y
});
};
/**
* @param {number} x
* @param {number} y
*/
Path.prototype.lineTo = function(x, y) {
this.commands.push({
type: 'L',
x: x,
y: y
});
};
/**
* Draws cubic curve
* @function
* curveTo
* @memberof opentype.Path.prototype
* @param {number} x1 - x of control 1
* @param {number} y1 - y of control 1
* @param {number} x2 - x of control 2
* @param {number} y2 - y of control 2
* @param {number} x - x of path point
* @param {number} y - y of path point
*/
/**
* Draws cubic curve
* @function
* bezierCurveTo
* @memberof opentype.Path.prototype
* @param {number} x1 - x of control 1
* @param {number} y1 - y of control 1
* @param {number} x2 - x of control 2
* @param {number} y2 - y of control 2
* @param {number} x - x of path point
* @param {number} y - y of path point
* @see curveTo
*/
Path.prototype.curveTo = Path.prototype.bezierCurveTo = function(
x1,
y1,
x2,
y2,
x,
y
) {
this.commands.push({
type: 'C',
x1: x1,
y1: y1,
x2: x2,
y2: y2,
x: x,
y: y
});
};
/**
* Draws quadratic curve
* @function
* quadraticCurveTo
* @memberof opentype.Path.prototype
* @param {number} x1 - x of control
* @param {number} y1 - y of control
* @param {number} x - x of path point
* @param {number} y - y of path point
*/
/**
* Draws quadratic curve
* @function
* quadTo
* @memberof opentype.Path.prototype
* @param {number} x1 - x of control
* @param {number} y1 - y of control
* @param {number} x - x of path point
* @param {number} y - y of path point
*/
Path.prototype.quadTo = Path.prototype.quadraticCurveTo = function(
x1,
y1,
x,
y
) {
this.commands.push({
type: 'Q',
x1: x1,
y1: y1,
x: x,
y: y
});
};
/**
* Closes the path
* @function closePath
* @memberof opentype.Path.prototype
*/
/**
* Close the path
* @function close
* @memberof opentype.Path.prototype
*/
Path.prototype.close = Path.prototype.closePath = function() {
this.commands.push({
type: 'Z'
});
};
/**
* Add the given path or list of commands to the commands of this path.
* @param {Array} pathOrCommands - another opentype.Path, an opentype.BoundingBox, or an array of commands.
*/
Path.prototype.extend = function(pathOrCommands) {
if (pathOrCommands.commands) {
pathOrCommands = pathOrCommands.commands;
} else if (pathOrCommands instanceof BoundingBox) {
var box = pathOrCommands;
this.moveTo(box.x1, box.y1);
this.lineTo(box.x2, box.y1);
this.lineTo(box.x2, box.y2);
this.lineTo(box.x1, box.y2);
this.close();
return;
}
Array.prototype.push.apply(this.commands, pathOrCommands);
};
/**
* Calculate the bounding box of the path.
* @returns {opentype.BoundingBox}
*/
Path.prototype.getBoundingBox = function() {
var this$1 = this;
var box = new BoundingBox();
var startX = 0;
var startY = 0;
var prevX = 0;
var prevY = 0;
for (var i = 0; i < this.commands.length; i++) {
var cmd = this$1.commands[i];
switch (cmd.type) {
case 'M':
box.addPoint(cmd.x, cmd.y);
startX = prevX = cmd.x;
startY = prevY = cmd.y;
break;
case 'L':
box.addPoint(cmd.x, cmd.y);
prevX = cmd.x;
prevY = cmd.y;
break;
case 'Q':
box.addQuad(prevX, prevY, cmd.x1, cmd.y1, cmd.x, cmd.y);
prevX = cmd.x;
prevY = cmd.y;
break;
case 'C':
box.addBezier(
prevX,
prevY,
cmd.x1,
cmd.y1,
cmd.x2,
cmd.y2,
cmd.x,
cmd.y
);
prevX = cmd.x;
prevY = cmd.y;
break;
case 'Z':
prevX = startX;
prevY = startY;
break;
default:
throw new Error('Unexpected path command ' + cmd.type);
}
}
if (box.isEmpty()) {
box.addPoint(0, 0);
}
return box;
};
/**
* Draw the path to a 2D context.
* @param {CanvasRenderingContext2D} ctx - A 2D drawing context.
*/
Path.prototype.draw = function(ctx) {
var this$1 = this;
ctx.beginPath();
for (var i = 0; i < this.commands.length; i += 1) {
var cmd = this$1.commands[i];
if (cmd.type === 'M') {
ctx.moveTo(cmd.x, cmd.y);
} else if (cmd.type === 'L') {
ctx.lineTo(cmd.x, cmd.y);
} else if (cmd.type === 'C') {
ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
} else if (cmd.type === 'Q') {
ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y);
} else if (cmd.type === 'Z') {
ctx.closePath();
}
}
if (this.fill) {
ctx.fillStyle = this.fill;
ctx.fill();
}
if (this.stroke) {
ctx.strokeStyle = this.stroke;
ctx.lineWidth = this.strokeWidth;
ctx.stroke();
}
};
/**
* Convert the Path to a string of path data instructions
* See http://www.w3.org/TR/SVG/paths.html#PathData
* @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values
* @return {string}
*/
Path.prototype.toPathData = function(decimalPlaces) {
var this$1 = this;
decimalPlaces = decimalPlaces !== undefined ? decimalPlaces : 2;
function floatToString(v) {
if (Math.round(v) === v) {
return '' + Math.round(v);
} else {
return v.toFixed(decimalPlaces);
}
}
function packValues() {
var arguments$1 = arguments;
var s = '';
for (var i = 0; i < arguments.length; i += 1) {
var v = arguments$1[i];
if (v >= 0 && i > 0) {
s += ' ';
}
s += floatToString(v);
}
return s;
}
var d = '';
for (var i = 0; i < this.commands.length; i += 1) {
var cmd = this$1.commands[i];
if (cmd.type === 'M') {
d += 'M' + packValues(cmd.x, cmd.y);
} else if (cmd.type === 'L') {
d += 'L' + packValues(cmd.x, cmd.y);
} else if (cmd.type === 'C') {
d += 'C' + packValues(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
} else if (cmd.type === 'Q') {
d += 'Q' + packValues(cmd.x1, cmd.y1, cmd.x, cmd.y);
} else if (cmd.type === 'Z') {
d += 'Z';
}
}
return d;
};
/**
* Convert the path to an SVG <path> element, as a string.
* @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values
* @return {string}
*/
Path.prototype.toSVG = function(decimalPlaces) {
var svg = '<path d="';
svg += this.toPathData(decimalPlaces);
svg += '"';
if (this.fill && this.fill !== 'black') {
if (this.fill === null) {
svg += ' fill="none"';
} else {
svg += ' fill="' + this.fill + '"';
}
}
if (this.stroke) {
svg +=
' stroke="' + this.stroke + '" stroke-width="' + this.strokeWidth + '"';
}
svg += '/>';
return svg;
};
/**
* Convert the path to a DOM element.
* @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values
* @return {SVGPathElement}
*/
Path.prototype.toDOMElement = function(decimalPlaces) {
var temporaryPath = this.toPathData(decimalPlaces);
var newPath = document.createElementNS(
'http://www.w3.org/2000/svg',
'path'
);
newPath.setAttribute('d', temporaryPath);
return newPath;
};
// Run-time checking of preconditions.
function fail(message) {
throw new Error(message);
}
// Precondition function that checks if the given predicate is true.
// If not, it will throw an error.
function argument(predicate, message) {
if (!predicate) {
fail(message);
}
}
var check = { fail: fail, argument: argument, assert: argument };
// Data types used in the OpenType font file.
var LIMIT16 = 32768; // The limit at which a 16-bit number switches signs == 2^15
var LIMIT32 = 2147483648; // The limit at which a 32-bit number switches signs == 2 ^ 31
/**
* @exports opentype.decode
* @class
*/
var decode = {};
/**
* @exports opentype.encode
* @class
*/
var encode = {};
/**
* @exports opentype.sizeOf
* @class
*/
var sizeOf = {};
// Return a function that always returns the same value.
function constant(v) {
return function() {
return v;
};
}
// OpenType data types //////////////////////////////////////////////////////
/**
* Convert an 8-bit unsigned integer to a list of 1 byte.
* @param {number}
* @returns {Array}
*/
encode.BYTE = function(v) {
check.argument(
v >= 0 && v <= 255,
'Byte value should be between 0 and 255.'
);
return [v];
};
/**
* @constant
* @type {number}
*/
sizeOf.BYTE = constant(1);
/**
* Convert a 8-bit signed integer to a list of 1 byte.
* @param {string}
* @returns {Array}
*/
encode.CHAR = function(v) {
return [v.charCodeAt(0)];
};
/**
* @constant
* @type {number}
*/
sizeOf.CHAR = constant(1);
/**
* Convert an ASCII string to a list of bytes.
* @param {string}
* @returns {Array}
*/
encode.CHARARRAY = function(v) {
var b = [];
for (var i = 0; i < v.length; i += 1) {
b[i] = v.charCodeAt(i);
}
return b;
};
/**
* @param {Array}
* @returns {number}
*/
sizeOf.CHARARRAY = function(v) {
return v.length;
};
/**
* Convert a 16-bit unsigned integer to a list of 2 bytes.
* @param {number}
* @returns {Array}
*/
encode.USHORT = function(v) {
return [(v >> 8) & 0xff, v & 0xff];
};
/**
* @constant
* @type {number}
*/
sizeOf.USHORT = constant(2);
/**
* Convert a 16-bit signed integer to a list of 2 bytes.
* @param {number}
* @returns {Array}
*/
encode.SHORT = function(v) {
// Two's complement
if (v >= LIMIT16) {
v = -(2 * LIMIT16 - v);
}
return [(v >> 8) & 0xff, v & 0xff];
};
/**
* @constant
* @type {number}
*/
sizeOf.SHORT = constant(2);
/**
* Convert a 24-bit unsigned integer to a list of 3 bytes.
* @param {number}
* @returns {Array}
*/
encode.UINT24 = function(v) {
return [(v >> 16) & 0xff, (v >> 8) & 0xff, v & 0xff];
};
/**
* @constant
* @type {number}
*/
sizeOf.UINT24 = constant(3);
/**
* Convert a 32-bit unsigned integer to a list of 4 bytes.
* @param {number}
* @returns {Array}
*/
encode.ULONG = function(v) {
return [(v >> 24) & 0xff, (v >> 16) & 0xff, (v >> 8) & 0xff, v & 0xff];
};
/**
* @constant
* @type {number}
*/
sizeOf.ULONG = constant(4);
/**
* Convert a 32-bit unsigned integer to a list of 4 bytes.
* @param {number}
* @returns {Array}
*/
encode.LONG = function(v) {
// Two's complement
if (v >= LIMIT32) {
v = -(2 * LIMIT32 - v);
}
return [(v >> 24) & 0xff, (v >> 16) & 0xff, (v >> 8) & 0xff, v & 0xff];
};
/**
* @constant
* @type {number}
*/
sizeOf.LONG = constant(4);
encode.FIXED = encode.ULONG;
sizeOf.FIXED = sizeOf.ULONG;
encode.FWORD = encode.SHORT;
sizeOf.FWORD = sizeOf.SHORT;
encode.UFWORD = encode.USHORT;
sizeOf.UFWORD = sizeOf.USHORT;
/**
* Convert a 32-bit Apple Mac timestamp integer to a list of 8 bytes, 64-bit timestamp.
* @param {number}
* @returns {Array}
*/
encode.LONGDATETIME = function(v) {
return [
0,
0,
0,
0,
(v >> 24) & 0xff,
(v >> 16) & 0xff,
(v >> 8) & 0xff,
v & 0xff
];
};
/**
* @constant
* @type {number}
*/
sizeOf.LONGDATETIME = constant(8);
/**
* Convert a 4-char tag to a list of 4 bytes.
* @param {string}
* @returns {Array}
*/
encode.TAG = function(v) {
check.argument(v.length === 4, 'Tag should be exactly 4 ASCII characters.');
return [v.charCodeAt(0), v.charCodeAt(1), v.charCodeAt(2), v.charCodeAt(3)];
};
/**
* @constant
* @type {number}
*/
sizeOf.TAG = constant(4);
// CFF data types ///////////////////////////////////////////////////////////
encode.Card8 = encode.BYTE;
sizeOf.Card8 = sizeOf.BYTE;
encode.Card16 = encode.USHORT;
sizeOf.Card16 = sizeOf.USHORT;
encode.OffSize = encode.BYTE;
sizeOf.OffSize = sizeOf.BYTE;
encode.SID = encode.USHORT;
sizeOf.SID = sizeOf.USHORT;
// Convert a numeric operand or charstring number to a variable-size list of bytes.
/**
* Convert a numeric operand or charstring number to a variable-size list of bytes.
* @param {number}
* @returns {Array}
*/
encode.NUMBER = function(v) {
if (v >= -107 && v <= 107) {
return [v + 139];
} else if (v >= 108 && v <= 1131) {
v = v - 108;
return [(v >> 8) + 247, v & 0xff];
} else if (v >= -1131 && v <= -108) {
v = -v - 108;
return [(v >> 8) + 251, v & 0xff];
} else if (v >= -32768 && v <= 32767) {
return encode.NUMBER16(v);
} else {
return encode.NUMBER32(v);
}
};
/**
* @param {number}
* @returns {number}
*/
sizeOf.NUMBER = function(v) {
return encode.NUMBER(v).length;
};
/**
* Convert a signed number between -32768 and +32767 to a three-byte value.
* This ensures we always use three bytes, but is not the most compact format.
* @param {number}
* @returns {Array}
*/
encode.NUMBER16 = function(v) {
return [28, (v >> 8) & 0xff, v & 0xff];
};
/**
* @constant
* @type {number}
*/
sizeOf.NUMBER16 = constant(3);
/**
* Convert a signed number between -(2^31) and +(2^31-1) to a five-byte value.
* This is useful if you want to be sure you always use four bytes,
* at the expense of wasting a few bytes for smaller numbers.
* @param {number}
* @returns {Array}
*/
encode.NUMBER32 = function(v) {
return [29, (v >> 24) & 0xff, (v >> 16) & 0xff, (v >> 8) & 0xff, v & 0xff];
};
/**
* @constant
* @type {number}
*/
sizeOf.NUMBER32 = constant(5);
/**
* @param {number}
* @returns {Array}
*/
encode.REAL = function(v) {
var value = v.toString();
// Some numbers use an epsilon to encode the value. (e.g. JavaScript will store 0.0000001 as 1e-7)
// This code converts it back to a number without the epsilon.
var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value);
if (m) {
var epsilon = parseFloat('1e' + ((m[2] ? +m[2] : 0) + m[1].length));
value = (Math.round(v * epsilon) / epsilon).toString();
}
var nibbles = '';
for (var i = 0, ii = value.length; i < ii; i += 1) {
var c = value[i];
if (c === 'e') {
nibbles += value[++i] === '-' ? 'c' : 'b';
} else if (c === '.') {
nibbles += 'a';
} else if (c === '-') {
nibbles += 'e';
} else {
nibbles += c;
}
}
nibbles += nibbles.length & 1 ? 'f' : 'ff';
var out = [30];
for (var i$1 = 0, ii$1 = nibbles.length; i$1 < ii$1; i$1 += 2) {
out.push(parseInt(nibbles.substr(i$1, 2), 16));
}
return out;
};
/**
* @param {number}
* @returns {number}
*/
sizeOf.REAL = function(v) {
return encode.REAL(v).length;
};
encode.NAME = encode.CHARARRAY;
sizeOf.NAME = sizeOf.CHARARRAY;
encode.STRING = encode.CHARARRAY;
sizeOf.STRING = sizeOf.CHARARRAY;
/**
* @param {DataView} data
* @param {number} offset
* @param {number} numBytes
* @returns {string}
*/
decode.UTF8 = function(data, offset, numBytes) {
var codePoints = [];
var numChars = numBytes;
for (var j = 0; j < numChars; j++, offset += 1) {
codePoints[j] = data.getUint8(offset);
}
return String.fromCharCode.apply(null, codePoints);
};
/**
* @param {DataView} data
* @param {number} offset
* @param {number} numBytes
* @returns {string}
*/
decode.UTF16 = function(data, offset, numBytes) {
var codePoints = [];
var numChars = numBytes / 2;
for (var j = 0; j < numChars; j++, offset += 2) {
codePoints[j] = data.getUint16(offset);
}
return String.fromCharCode.apply(null, codePoints);
};
/**
* Convert a JavaScript string to UTF16-BE.
* @param {string}
* @returns {Array}
*/
encode.UTF16 = function(v) {
var b = [];
for (var i = 0; i < v.length; i += 1) {
var codepoint = v.charCodeAt(i);
b[b.length] = (codepoint >> 8) & 0xff;
b[b.length] = codepoint & 0xff;
}
return b;
};
/**
* @param {string}
* @returns {number}
*/
sizeOf.UTF16 = function(v) {
return v.length * 2;
};
// Data for converting old eight-bit Macintosh encodings to Unicode.
// This representation is optimized for decoding; encoding is slower
// and needs more memory. The assumption is that all opentype.js users
// want to open fonts, but saving a font will be comparatively rare
// so it can be more expensive. Keyed by IANA character set name.
//
// Python script for generating these strings:
//
// s = u''.join([chr(c).decode('mac_greek') for c in range(128, 256)])
// print(s.encode('utf-8'))
/**
* @private
*/
var eightBitMacEncodings = {
// Python: 'mac_croatian'
'x-mac-croatian':
'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø' +
'¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ',
// Python: 'mac_cyrillic'
'x-mac-cyrillic':
'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњ' +
'јЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю',
// http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/GAELIC.TXT
'x-mac-gaelic':
'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæø' +
'ṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ',
// Python: 'mac_greek'
'x-mac-greek':
'Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩ' +
'άΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ\u00AD',
// Python: 'mac_iceland'
'x-mac-icelandic':
'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' +
'¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ',
// http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/INUIT.TXT
'x-mac-inuit':
'ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗ' +
'ᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł',
// Python: 'mac_latin2'
'x-mac-ce':
'ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅ' +
'ņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ',
// Python: 'mac_roman'
macintosh:
'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' +
'¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ',
// Python: 'mac_romanian'
'x-mac-romanian':
'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș' +
'¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ',
// Python: 'mac_turkish'
'x-mac-turkish':
'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' +
'¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ'
};
/**
* Decodes an old-style Macintosh string. Returns either a Unicode JavaScript
* string, or 'undefined' if the encoding is unsupported. For example, we do
* not support Chinese, Japanese or Korean because these would need large
* mapping tables.
* @param {DataView} dataView
* @param {number} offset
* @param {number} dataLength
* @param {string} encoding
* @returns {string}
*/
decode.MACSTRING = function(dataView, offset, dataLength, encoding) {
var table = eightBitMacEncodings[encoding];
if (table === undefined) {
return undefined;
}
var result = '';
for (var i = 0; i < dataLength; i++) {
var c = dataView.getUint8(offset + i);
// In all eight-bit Mac encodings, the characters 0x00..0x7F are
// mapped to U+0000..U+007F; we only need to look up the others.
if (c <= 0x7f) {
result += String.fromCharCode(c);
} else {
result += table[c & 0x7f];
}
}
return result;
};
// Helper function for encode.MACSTRING. Returns a dictionary for mapping
// Unicode character codes to their 8-bit MacOS equivalent. This table
// is not exactly a super cheap data structure, but we do not care because
// encoding Macintosh strings is only rarely needed in typical applications.
var macEncodingTableCache = typeof WeakMap === 'function' && new WeakMap();
var macEncodingCacheKeys;
var getMacEncodingTable = function(encoding) {
// Since we use encoding as a cache key for WeakMap, it has to be
// a String object and not a literal. And at least on NodeJS 2.10.1,
// WeakMap requires that the same String instance is passed for cache hits.
if (!macEncodingCacheKeys) {
macEncodingCacheKeys = {};
for (var e in eightBitMacEncodings) {
/*jshint -W053 */ // Suppress "Do not use String as a constructor."
macEncodingCacheKeys[e] = new String(e);
}
}
var cacheKey = macEncodingCacheKeys[encoding];
if (cacheKey === undefined) {
return undefined;
}
// We can't do "if (cache.has(key)) {return cache.get(key)}" here:
// since garbage collection may run at any time, it could also kick in
// between the calls to cache.has() and cache.get(). In that case,
// we would return 'undefined' even though we do support the encoding.
if (macEncodingTableCache) {
var cachedTable = macEncodingTableCache.get(cacheKey);
if (cachedTable !== undefined) {
return cachedTable;
}
}
var decodingTable = eightBitMacEncodings[encoding];
if (decodingTable === undefined) {
return undefined;
}
var encodingTable = {};
for (var i = 0; i < decodingTable.length; i++) {
encodingTable[decodingTable.charCodeAt(i)] = i + 0x80;
}
if (macEncodingTableCache) {
macEncodingTableCache.set(cacheKey, encodingTable);
}
return encodingTable;
};
/**
* Encodes an old-style Macintosh string. Returns a byte array upon success.
* If the requested encoding is unsupported, or if the input string contains
* a character that cannot be expressed in the encoding, the function returns
* 'undefined'.
* @param {string} str
* @param {string} encoding
* @returns {Array}
*/
encode.MACSTRING = function(str, encoding) {
var table = getMacEncodingTable(encoding);
if (table === undefined) {
return undefined;
}
var result = [];
for (var i = 0; i < str.length; i++) {
var c = str.charCodeAt(i);
// In all eight-bit Mac encodings, the characters 0x00..0x7F are
// mapped to U+0000..U+007F; we only need to look up the others.
if (c >= 0x80) {
c = table[c];
if (c === undefined) {
// str contains a Unicode character that cannot be encoded
// in the requested encoding.
return undefined;
}
}
result[i] = c;
// result.push(c);
}
return result;
};
/**
* @param {string} str
* @param {string} encoding
* @returns {number}
*/
sizeOf.MACSTRING = function(str, encoding) {
var b = encode.MACSTRING(str, encoding);
if (b !== undefined) {
return b.length;
} else {
return 0;
}
};
// Helper for encode.VARDELTAS
function isByteEncodable(value) {
return value >= -128 && value <= 127;
}
// Helper for encode.VARDELTAS
function encodeVarDeltaRunAsZeroes(deltas, pos, result) {
var runLength = 0;
var numDeltas = deltas.length;
while (pos < numDeltas && runLength < 64 && deltas[pos] === 0) {
++pos;
++runLength;
}
result.push(0x80 | (runLength - 1));
return pos;
}
// Helper for encode.VARDELTAS
function encodeVarDeltaRunAsBytes(deltas, offset, result) {
var runLength = 0;
var numDeltas = deltas.length;
var pos = offset;
while (pos < numDeltas && runLength < 64) {
var value = deltas[pos];
if (!isByteEncodable(value)) {
break;
}
// Within a byte-encoded run of deltas, a single zero is best
// stored literally as 0x00 value. However, if we have two or
// more zeroes in a sequence, it is better to start a new run.
// Fore example, the sequence of deltas [15, 15, 0, 15, 15]
// becomes 6 bytes (04 0F 0F 00 0F 0F) when storing the zero
// within the current run, but 7 bytes (01 0F 0F 80 01 0F 0F)
// when starting a new run.
if (value === 0 && pos + 1 < numDeltas && deltas[pos + 1] === 0) {
break;
}
++pos;
++runLength;
}
result.push(runLength - 1);
for (var i = offset; i < pos; ++i) {
result.push((deltas[i] + 256) & 0xff);
}
return pos;
}
// Helper for encode.VARDELTAS
function encodeVarDeltaRunAsWords(deltas, offset, result) {
var runLength = 0;
var numDeltas = deltas.length;
var pos = offset;
while (pos < numDeltas && runLength < 64) {
var value = deltas[pos];
// Within a word-encoded run of deltas, it is easiest to start
// a new run (with a different encoding) whenever we encounter
// a zero value. For example, the sequence [0x6666, 0, 0x7777]
// needs 7 bytes when storing the zero inside the current run
// (42 66 66 00 00 77 77), and equally 7 bytes when starting a
// new run (40 66 66 80 40 77 77).
if (value === 0) {
break;
}
// Within a word-encoded run of deltas, a single value in the
// range (-128..127) should be encoded within the current run
// because it is more compact. For example, the sequence
// [0x6666, 2, 0x7777] becomes 7 bytes when storing the value
// literally (42 66 66 00 02 77 77), but 8 bytes when starting
// a new run (40 66 66 00 02 40 77 77).
if (
isByteEncodable(value) &&
pos + 1 < numDeltas &&
isByteEncodable(deltas[pos + 1])
) {
break;
}
++pos;
++runLength;
}
result.push(0x40 | (runLength - 1));
for (var i = offset; i < pos; ++i) {
var val = deltas[i];
result.push(((val + 0x10000) >> 8) & 0xff, (val + 0x100) & 0xff);
}
return pos;
}
/**
* Encode a list of variation adjustment deltas.
*
* Variation adjustment deltas are used in ‘gvar’ and ‘cvar’ tables.
* They indicate how points (in ‘gvar’) or values (in ‘cvar’) get adjusted
* when generating instances of variation fonts.
*
* @see https://www.microsoft.com/typography/otspec/gvar.htm
* @see https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6gvar.html
* @param {Array}
* @return {Array}
*/
encode.VARDELTAS = function(deltas) {
var pos = 0;
var result = [];
while (pos < deltas.length) {
var value = deltas[pos];
if (value === 0) {
pos = encodeVarDeltaRunAsZeroes(deltas, pos, result);
} else if (value >= -128 && value <= 127) {
pos = encodeVarDeltaRunAsBytes(deltas, pos, result);
} else {
pos = encodeVarDeltaRunAsWords(deltas, pos, result);
}
}
return result;
};
// Convert a list of values to a CFF INDEX structure.
// The values should be objects containing name / type / value.
/**
* @param {Array} l
* @returns {Array}
*/
encode.INDEX = function(l) {
//var offset, offsets, offsetEncoder, encodedOffsets, encodedOffset, data,
// i, v;
// Because we have to know which data type to use to encode the offsets,
// we have to go through the values twice: once to encode the data and
// calculate the offsets, then again to encode the offsets using the fitting data type.
var offset = 1; // First offset is always 1.
var offsets = [offset];
var data = [];
for (var i = 0; i < l.length; i += 1) {
var v = encode.OBJECT(l[i]);
Array.prototype.push.apply(data, v);
offset += v.length;
offsets.push(offset);
}
if (data.length === 0) {
return [0, 0];
}
var encodedOffsets = [];
var offSize = (1 + Math.floor(Math.log(offset) / Math.log(2)) / 8) | 0;
var offsetEncoder = [
undefined,
encode.BYTE,
encode.USHORT,
encode.UINT24,
encode.ULONG
][offSize];
for (var i$1 = 0; i$1 < offsets.length; i$1 += 1) {
var encodedOffset = offsetEncoder(offsets[i$1]);
Array.prototype.push.apply(encodedOffsets, encodedOffset);
}
return Array.prototype.concat(
encode.Card16(l.length),
encode.OffSize(offSize),
encodedOffsets,
data
);
};
/**
* @param {Array}
* @returns {number}
*/
sizeOf.INDEX = function(v) {
return encode.INDEX(v).length;
};
/**
* Convert an object to a CFF DICT structure.
* The keys should be numeric.
* The values should be objects containing name / type / value.
* @param {Object} m
* @returns {Array}
*/
encode.DICT = function(m) {
var d = [];
var keys = Object.keys(m);
var length = keys.length;
for (var i = 0; i < length; i += 1) {
// Object.keys() return string keys, but our keys are always numeric.
var k = parseInt(keys[i], 0);
var v = m[k];
// Value comes before the key.
d = d.concat(encode.OPERAND(v.value, v.type));
d = d.concat(encode.OPERATOR(k));
}
return d;
};
/**
* @param {Object}
* @returns {number}
*/
sizeOf.DICT = function(m) {
return encode.DICT(m).length;
};
/**
* @param {number}
* @returns {Array}
*/
encode.OPERATOR = function(v) {
if (v < 1200) {
return [v];
} else {
return [12, v - 1200];
}
};
/**
* @param {Array} v
* @param {string}
* @returns {Array}
*/
encode.OPERAND = function(v, type) {
var d = [];
if (Array.isArray(type)) {
for (var i = 0; i < type.length; i += 1) {
check.argument(
v.length === type.length,
'Not enough arguments given for type' + type
);
d = d.concat(encode.OPERAND(v[i], type[i]));
}
} else {
if (type === 'SID') {
d = d.concat(encode.NUMBER(v));
} else if (type === 'offset') {
// We make it easy for ourselves and always encode offsets as
// 4 bytes. This makes offset calculation for the top dict easier.
d = d.concat(encode.NUMBER32(v));
} else if (type === 'number') {
d = d.concat(encode.NUMBER(v));
} else if (type === 'real') {
d = d.concat(encode.REAL(v));
} else {
throw new Error('Unknown operand type ' + type);
// FIXME Add support for booleans
}
}
return d;
};
encode.OP = encode.BYTE;
sizeOf.OP = sizeOf.BYTE;
// memoize charstring encoding using WeakMap if available
var wmm = typeof WeakMap === 'function' && new WeakMap();
/**
* Convert a list of CharString operations to bytes.
* @param {Array}
* @returns {Array}
*/
encode.CHARSTRING = function(ops) {
// See encode.MACSTRING for why we don't do "if (wmm && wmm.has(ops))".
if (wmm) {
var cachedValue = wmm.get(ops);
if (cachedValue !== undefined) {
return cachedValue;
}
}
var d = [];
var length = ops.length;
for (var i = 0; i < length; i += 1) {
var op = ops[i];
d = d.concat(encode[op.type](op.value));
}
if (wmm) {
wmm.set(ops, d);
}
return d;
};
/**
* @param {Array}
* @returns {number}
*/
sizeOf.CHARSTRING = function(ops) {
return encode.CHARSTRING(ops).length;
};
// Utility functions ////////////////////////////////////////////////////////
/**
* Convert an object containing name / type / value to bytes.
* @param {Object}
* @returns {Array}
*/
encode.OBJECT = function(v) {
var encodingFunction = encode[v.type];
check.argument(
encodingFunction !== undefined,
'No encoding function for type ' + v.type
);
return encodingFunction(v.value);
};
/**
* @param {Object}
* @returns {number}
*/
sizeOf.OBJECT = function(v) {
var sizeOfFunction = sizeOf[v.type];
check.argument(
sizeOfFunction !== undefined,
'No sizeOf function for type ' + v.type
);
return sizeOfFunction(v.value);
};
/**
* Convert a table object to bytes.
* A table contains a list of fields containing the metadata (name, type and default value).
* The table itself has the field values set as attributes.
* @param {opentype.Table}
* @returns {Array}
*/
encode.TABLE = function(table) {
var d = [];
var length = table.fields.length;
var subtables = [];
var subtableOffsets = [];
for (var i = 0; i < length; i += 1) {
var field = table.fields[i];
var encodingFunction = encode[field.type];
check.argument(
encodingFunction !== undefined,
'No encoding function for field type ' +
field.type +
' (' +
field.name +
')'
);
var value = table[field.name];
if (value === undefined) {
value = field.value;
}
var bytes = encodingFunction(value);
if (field.type === 'TABLE') {
subtableOffsets.push(d.length);
d = d.concat([0, 0]);
subtables.push(bytes);
} else {
d = d.concat(bytes);
}
}
for (var i$1 = 0; i$1 < subtables.length; i$1 += 1) {
var o = subtableOffsets[i$1];
var offset = d.length;
check.argument(offset < 65536, 'Table ' + table.tableName + ' too big.');
d[o] = offset >> 8;
d[o + 1] = offset & 0xff;
d = d.concat(subtables[i$1]);
}
return d;
};
/**
* @param {opentype.Table}
* @returns {number}
*/
sizeOf.TABLE = function(table) {
var numBytes = 0;
var length = table.fields.length;
for (var i = 0; i < length; i += 1) {
var field = table.fields[i];
var sizeOfFunction = sizeOf[field.type];
check.argument(
sizeOfFunction !== undefined,
'No sizeOf function for field type ' +
field.type +
' (' +
field.name +
')'
);
var value = table[field.name];
if (value === undefined) {
value = field.value;
}
numBytes += sizeOfFunction(value);
// Subtables take 2 more bytes for offsets.
if (field.type === 'TABLE') {
numBytes += 2;
}
}
return numBytes;
};
encode.RECORD = encode.TABLE;
sizeOf.RECORD = sizeOf.TABLE;
// Merge in a list of bytes.
encode.LITERAL = function(v) {
return v;
};
sizeOf.LITERAL = function(v) {
return v.length;
};
// Table metadata
/**
* @exports opentype.Table
* @class
* @param {string} tableName
* @param {Array} fields
* @param {Object} options
* @constructor
*/
function Table(tableName, fields, options) {
var this$1 = this;
for (var i = 0; i < fields.length; i += 1) {
var field = fields[i];
this$1[field.name] = field.value;
}
this.tableName = tableName;
this.fields = fields;
if (options) {
var optionKeys = Object.keys(options);
for (var i$1 = 0; i$1 < optionKeys.length; i$1 += 1) {
var k = optionKeys[i$1];
var v = options[k];
if (this$1[k] !== undefined) {
this$1[k] = v;
}
}
}
}
/**
* Encodes the table and returns an array of bytes
* @return {Array}
*/
Table.prototype.encode = function() {
return encode.TABLE(this);
};
/**
* Get the size of the table.
* @return {number}
*/
Table.prototype.sizeOf = function() {
return sizeOf.TABLE(this);
};
/**
* @private
*/
function ushortList(itemName, list, count) {
if (count === undefined) {
count = list.length;
}
var fields = new Array(list.length + 1);
fields[0] = { name: itemName + 'Count', type: 'USHORT', value: count };
for (var i = 0; i < list.length; i++) {
fields[i + 1] = { name: itemName + i, type: 'USHORT', value: list[i] };
}
return fields;
}
/**
* @private
*/
function tableList(itemName, records, itemCallback) {
var count = records.length;
var fields = new Array(count + 1);
fields[0] = { name: itemName + 'Count', type: 'USHORT', value: count };
for (var i = 0; i < count; i++) {
fields[i + 1] = {
name: itemName + i,
type: 'TABLE',
value: itemCallback(records[i], i)
};
}
return fields;
}
/**
* @private
*/
function recordList(itemName, records, itemCallback) {
var count = records.length;
var fields = [];
fields[0] = { name: itemName + 'Count', type: 'USHORT', value: count };
for (var i = 0; i < count; i++) {
fields = fields.concat(itemCallback(records[i], i));
}
return fields;
}
// Common Layout Tables
/**
* @exports opentype.Coverage
* @class
* @param {opentype.Table}
* @constructor
* @extends opentype.Table
*/
function Coverage(coverageTable) {
if (coverageTable.format === 1) {
Table.call(
this,
'coverageTable',
[{ name: 'coverageFormat', type: 'USHORT', value: 1 }].concat(
ushortList('glyph', coverageTable.glyphs)
)
);
} else {
check.assert(false, "Can't create coverage table format 2 yet.");
}
}
Coverage.prototype = Object.create(Table.prototype);
Coverage.prototype.constructor = Coverage;
function ScriptList(scriptListTable) {
Table.call(
this,
'scriptListTable',
recordList('scriptRecord', scriptListTable, function(scriptRecord, i) {
var script = scriptRecord.script;
var defaultLangSys = script.defaultLangSys;
check.assert(
!!defaultLangSys,
'Unable to write GSUB: script ' +
scriptRecord.tag +
' has no default language system.'
);
return [
{ name: 'scriptTag' + i, type: 'TAG', value: scriptRecord.tag },
{
name: 'script' + i,
type: 'TABLE',
value: new Table(
'scriptTable',
[
{
name: 'defaultLangSys',
type: 'TABLE',
value: new Table(
'defaultLangSys',
[
{ name: 'lookupOrder', type: 'USHORT', value: 0 },
{
name: 'reqFeatureIndex',
type: 'USHORT',
value: defaultLangSys.reqFeatureIndex
}
].concat(
ushortList('featureIndex', defaultLangSys.featureIndexes)
)
)
}
].concat(
recordList('langSys', script.langSysRecords, function(
langSysRecord,
i
) {
var langSys = langSysRecord.langSys;
return [
{
name: 'langSysTag' + i,
type: 'TAG',
value: langSysRecord.tag
},
{
name: 'langSys' + i,
type: 'TABLE',
value: new Table(
'langSys',
[
{ name: 'lookupOrder', type: 'USHORT', value: 0 },
{
name: 'reqFeatureIndex',
type: 'USHORT',
value: langSys.reqFeatureIndex
}
].concat(
ushortList('featureIndex', langSys.featureIndexes)
)
)
}
];
})
)
)
}
];
})
);
}
ScriptList.prototype = Object.create(Table.prototype);
ScriptList.prototype.constructor = ScriptList;
/**
* @exports opentype.FeatureList
* @class
* @param {opentype.Table}
* @constructor
* @extends opentype.Table
*/
function FeatureList(featureListTable) {
Table.call(
this,
'featureListTable',
recordList('featureRecord', featureListTable, function(featureRecord, i) {
var feature = featureRecord.feature;
return [
{ name: 'featureTag' + i, type: 'TAG', value: featureRecord.tag },
{
name: 'feature' + i,
type: 'TABLE',
value: new Table(
'featureTable',
[
{
name: 'featureParams',
type: 'USHORT',
value: feature.featureParams
}
].concat(ushortList('lookupListIndex', feature.lookupListIndexes))
)
}
];
})
);
}
FeatureList.prototype = Object.create(Table.prototype);
FeatureList.prototype.constructor = FeatureList;
/**
* @exports opentype.LookupList
* @class
* @param {opentype.Table}
* @param {Object}
* @constructor
* @extends opentype.Table
*/
function LookupList(lookupListTable, subtableMakers) {
Table.call(
this,
'lookupListTable',
tableList('lookup', lookupListTable, function(lookupTable) {
var subtableCallback = subtableMakers[lookupTable.lookupType];
check.assert(
!!subtableCallback,
'Unable to write GSUB lookup type ' +
lookupTable.lookupType +
' tables.'
);
return new Table(
'lookupTable',
[
{
name: 'lookupType',
type: 'USHORT',
value: lookupTable.lookupType
},
{
name: 'lookupFlag',
type: 'USHORT',
value: lookupTable.lookupFlag
}
].concat(
tableList('subtable', lookupTable.subtables, subtableCallback)
)
);
})
);
}
LookupList.prototype = Object.create(Table.prototype);
LookupList.prototype.constructor = LookupList;
// Record = same as Table, but inlined (a Table has an offset and its data is further in the stream)
// Don't use offsets inside Records (probable bug), only in Tables.
var table = {
Table: Table,
Record: Table,
Coverage: Coverage,
ScriptList: ScriptList,
FeatureList: FeatureList,
LookupList: LookupList,
ushortList: ushortList,
tableList: tableList,
recordList: recordList
};
// Parsing utility functions
// Retrieve an unsigned byte from the DataView.
function getByte(dataView, offset) {
return dataView.getUint8(offset);
}
// Retrieve an unsigned 16-bit short from the DataView.
// The value is stored in big endian.
function getUShort(dataView, offset) {
return dataView.getUint16(offset, false);
}
// Retrieve a signed 16-bit short from the DataView.
// The value is stored in big endian.
function getShort(dataView, offset) {
return dataView.getInt16(offset, false);
}
// Retrieve an unsigned 32-bit long from the DataView.
// The value is stored in big endian.
function getULong(dataView, offset) {
return dataView.getUint32(offset, false);
}
// Retrieve a 32-bit signed fixed-point number (16.16) from the DataView.
// The value is stored in big endian.
function getFixed(dataView, offset) {
var decimal = dataView.getInt16(offset, false);
var fraction = dataView.getUint16(offset + 2, false);
return decimal + fraction / 65535;
}
// Retrieve a 4-character tag from the DataView.
// Tags are used to identify tables.
function getTag(dataView, offset) {
var tag = '';
for (var i = offset; i < offset + 4; i += 1) {
tag += String.fromCharCode(dataView.getInt8(i));
}
return tag;
}
// Retrieve an offset from the DataView.
// Offsets are 1 to 4 bytes in length, depending on the offSize argument.
function getOffset(dataView, offset, offSize) {
var v = 0;
for (var i = 0; i < offSize; i += 1) {
v <<= 8;
v += dataView.getUint8(offset + i);
}
return v;
}
// Retrieve a number of bytes from start offset to the end offset from the DataView.
function getBytes(dataView, startOffset, endOffset) {
var bytes = [];
for (var i = startOffset; i < endOffset; i += 1) {
bytes.push(dataView.getUint8(i));
}
return bytes;
}
// Convert the list of bytes to a string.
function bytesToString(bytes) {
var s = '';
for (var i = 0; i < bytes.length; i += 1) {
s += String.fromCharCode(bytes[i]);
}
return s;
}
var typeOffsets = {
byte: 1,
uShort: 2,
short: 2,
uLong: 4,
fixed: 4,
longDateTime: 8,
tag: 4
};
// A stateful parser that changes the offset whenever a value is retrieved.
// The data is a DataView.
function Parser(data, offset) {
this.data = data;
this.offset = offset;
this.relativeOffset = 0;
}
Parser.prototype.parseByte = function() {
var v = this.data.getUint8(this.offset + this.relativeOffset);
this.relativeOffset += 1;
return v;
};
Parser.prototype.parseChar = function() {
var v = this.data.getInt8(this.offset + this.relativeOffset);
this.relativeOffset += 1;
return v;
};
Parser.prototype.parseCard8 = Parser.prototype.parseByte;
Parser.prototype.parseUShort = function() {
var v = this.data.getUint16(this.offset + this.relativeOffset);
this.relativeOffset += 2;
return v;
};
Parser.prototype.parseCard16 = Parser.prototype.parseUShort;
Parser.prototype.parseSID = Parser.prototype.parseUShort;
Parser.prototype.parseOffset16 = Parser.prototype.parseUShort;
Parser.prototype.parseShort = function() {
var v = this.data.getInt16(this.offset + this.relativeOffset);
this.relativeOffset += 2;
return v;
};
Parser.prototype.parseF2Dot14 = function() {
var v = this.data.getInt16(this.offset + this.relativeOffset) / 16384;
this.relativeOffset += 2;
return v;
};
Parser.prototype.parseULong = function() {
var v = getULong(this.data, this.offset + this.relativeOffset);
this.relativeOffset += 4;
return v;
};
Parser.prototype.parseOffset32 = Parser.prototype.parseULong;
Parser.prototype.parseFixed = function() {
var v = getFixed(this.data, this.offset + this.relativeOffset);
this.relativeOffset += 4;
return v;
};
Parser.prototype.parseString = function(length) {
var dataView = this.data;
var offset = this.offset + this.relativeOffset;
var string = '';
this.relativeOffset += length;
for (var i = 0; i < length; i++) {
string += String.fromCharCode(dataView.getUint8(offset + i));
}
return string;
};
Parser.prototype.parseTag = function() {
return this.parseString(4);
};
// LONGDATETIME is a 64-bit integer.
// JavaScript and unix timestamps traditionally use 32 bits, so we
// only take the last 32 bits.
// + Since until 2038 those bits will be filled by zeros we can ignore them.
Parser.prototype.parseLongDateTime = function() {
var v = getULong(this.data, this.offset + this.relativeOffset + 4);
// Subtract seconds between 01/01/1904 and 01/01/1970
// to convert Apple Mac timestamp to Standard Unix timestamp
v -= 2082844800;
this.relativeOffset += 8;
return v;
};
Parser.prototype.parseVersion = function(minorBase) {
var major = getUShort(this.data, this.offset + this.relativeOffset);
// How to interpret the minor version is very vague in the spec. 0x5000 is 5, 0x1000 is 1
// Default returns the correct number if minor = 0xN000 where N is 0-9
// Set minorBase to 1 for tables that use minor = N where N is 0-9
var minor = getUShort(this.data, this.offset + this.relativeOffset + 2);
this.relativeOffset += 4;
if (minorBase === undefined) {
minorBase = 0x1000;
}
return major + minor / minorBase / 10;
};
Parser.prototype.skip = function(type, amount) {
if (amount === undefined) {
amount = 1;
}
this.relativeOffset += typeOffsets[type] * amount;
};
///// Parsing lists and records ///////////////////////////////
// Parse a list of 32 bit unsigned integers.
Parser.prototype.parseULongList = function(count) {
if (count === undefined) {
count = this.parseULong();
}
var offsets = new Array(count);
var dataView = this.data;
var offset = this.offset + this.relativeOffset;
for (var i = 0; i < count; i++) {
offsets[i] = dataView.getUint32(offset);
offset += 4;
}
this.relativeOffset += count * 4;
return offsets;
};
// Parse a list of 16 bit unsigned integers. The length of the list can be read on the stream
// or provided as an argument.
Parser.prototype.parseOffset16List = Parser.prototype.parseUShortList = function(
count
) {
if (count === undefined) {
count = this.parseUShort();
}
var offsets = new Array(count);
var dataView = this.data;
var offset = this.offset + this.relativeOffset;
for (var i = 0; i < count; i++) {
offsets[i] = dataView.getUint16(offset);
offset += 2;
}
this.relativeOffset += count * 2;
return offsets;
};
// Parses a list of 16 bit signed integers.
Parser.prototype.parseShortList = function(count) {
var list = new Array(count);
var dataView = this.data;
var offset = this.offset + this.relativeOffset;
for (var i = 0; i < count; i++) {
list[i] = dataView.getInt16(offset);
offset += 2;
}
this.relativeOffset += count * 2;
return list;
};
// Parses a list of bytes.
Parser.prototype.parseByteList = function(count) {
var list = new Array(count);
var dataView = this.data;
var offset = this.offset + this.relativeOffset;
for (var i = 0; i < count; i++) {
list[i] = dataView.getUint8(offset++);
}
this.relativeOffset += count;
return list;
};
/**
* Parse a list of items.
* Record count is optional, if omitted it is read from the stream.
* itemCallback is one of the Parser methods.
*/
Parser.prototype.parseList = function(count, itemCallback) {
var this$1 = this;
if (!itemCallback) {
itemCallback = count;
count = this.parseUShort();
}
var list = new Array(count);
for (var i = 0; i < count; i++) {
list[i] = itemCallback.call(this$1);
}
return list;
};
Parser.prototype.parseList32 = function(count, itemCallback) {
var this$1 = this;
if (!itemCallback) {
itemCallback = count;
count = this.parseULong();
}
var list = new Array(count);
for (var i = 0; i < count; i++) {
list[i] = itemCallback.call(this$1);
}
return list;
};
/**
* Parse a list of records.
* Record count is optional, if omitted it is read from the stream.
* Example of recordDescription: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort }
*/
Parser.prototype.parseRecordList = function(count, recordDescription) {
var this$1 = this;
// If the count argument is absent, read it in the stream.
if (!recordDescription) {
recordDescription = count;
count = this.parseUShort();
}
var records = new Array(count);
var fields = Object.keys(recordDescription);
for (var i = 0; i < count; i++) {
var rec = {};
for (var j = 0; j < fields.length; j++) {
var fieldName = fields[j];
var fieldType = recordDescription[fieldName];
rec[fieldName] = fieldType.call(this$1);
}
records[i] = rec;
}
return records;
};
Parser.prototype.parseRecordList32 = function(count, recordDescription) {
var this$1 = this;
// If the count argument is absent, read it in the stream.
if (!recordDescription) {
recordDescription = count;
count = this.parseULong();
}
var records = new Array(count);
var fields = Object.keys(recordDescription);
for (var i = 0; i < count; i++) {
var rec = {};
for (var j = 0; j < fields.length; j++) {
var fieldName = fields[j];
var fieldType = recordDescription[fieldName];
rec[fieldName] = fieldType.call(this$1);
}
records[i] = rec;
}
return records;
};
// Parse a data structure into an object
// Example of description: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort }
Parser.prototype.parseStruct = function(description) {
var this$1 = this;
if (typeof description === 'function') {
return description.call(this);
} else {
var fields = Object.keys(description);
var struct = {};
for (var j = 0; j < fields.length; j++) {
var fieldName = fields[j];
var fieldType = description[fieldName];
struct[fieldName] = fieldType.call(this$1);
}
return struct;
}
};
/**
* Parse a GPOS valueRecord
* https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#value-record
* valueFormat is optional, if omitted it is read from the stream.
*/
Parser.prototype.parseValueRecord = function(valueFormat) {
if (valueFormat === undefined) {
valueFormat = this.parseUShort();
}
if (valueFormat === 0) {
// valueFormat2 in kerning pairs is most often 0
// in this case return undefined instead of an empty object, to save space
return;
}
var valueRecord = {};
if (valueFormat & 0x0001) {
valueRecord.xPlacement = this.parseShort();
}
if (valueFormat & 0x0002) {
valueRecord.yPlacement = this.parseShort();
}
if (valueFormat & 0x0004) {
valueRecord.xAdvance = this.parseShort();
}
if (valueFormat & 0x0008) {
valueRecord.yAdvance = this.parseShort();
}
// Device table (non-variable font) / VariationIndex table (variable font) not supported
// https://docs.microsoft.com/fr-fr/typography/opentype/spec/chapter2#devVarIdxTbls
if (valueFormat & 0x0010) {
valueRecord.xPlaDevice = undefined;
this.parseShort();
}
if (valueFormat & 0x0020) {
valueRecord.yPlaDevice = undefined;
this.parseShort();
}
if (valueFormat & 0x0040) {
valueRecord.xAdvDevice = undefined;
this.parseShort();
}
if (valueFormat & 0x0080) {
valueRecord.yAdvDevice = undefined;
this.parseShort();
}
return valueRecord;
};
/**
* Parse a list of GPOS valueRecords
* https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#value-record
* valueFormat and valueCount are read from the stream.
*/
Parser.prototype.parseValueRecordList = function() {
var this$1 = this;
var valueFormat = this.parseUShort();
var valueCount = this.parseUShort();
var values = new Array(valueCount);
for (var i = 0; i < valueCount; i++) {
values[i] = this$1.parseValueRecord(valueFormat);
}
return values;
};
Parser.prototype.parsePointer = function(description) {
var structOffset = this.parseOffset16();
if (structOffset > 0) {
// NULL offset => return undefined
return new Parser(this.data, this.offset + structOffset).parseStruct(
description
);
}
return undefined;
};
Parser.prototype.parsePointer32 = function(description) {
var structOffset = this.parseOffset32();
if (structOffset > 0) {
// NULL offset => return undefined
return new Parser(this.data, this.offset + structOffset).parseStruct(
description
);
}
return undefined;
};
/**
* Parse a list of offsets to lists of 16-bit integers,
* or a list of offsets to lists of offsets to any kind of items.
* If itemCallback is not provided, a list of list of UShort is assumed.
* If provided, itemCallback is called on each item and must parse the item.
* See examples in tables/gsub.js
*/
Parser.prototype.parseListOfLists = function(itemCallback) {
var this$1 = this;
var offsets = this.parseOffset16List();
var count = offsets.length;
var relativeOffset = this.relativeOffset;
var list = new Array(count);
for (var i = 0; i < count; i++) {
var start = offsets[i];
if (start === 0) {
// NULL offset
// Add i as owned property to list. Convenient with assert.
list[i] = undefined;
continue;
}
this$1.relativeOffset = start;
if (itemCallback) {
var subOffsets = this$1.parseOffset16List();
var subList = new Array(subOffsets.length);
for (var j = 0; j < subOffsets.length; j++) {
this$1.relativeOffset = start + subOffsets[j];
subList[j] = itemCallback.call(this$1);
}
list[i] = subList;
} else {
list[i] = this$1.parseUShortList();
}
}
this.relativeOffset = relativeOffset;
return list;
};
///// Complex tables parsing //////////////////////////////////
// Parse a coverage table in a GSUB, GPOS or GDEF table.
// https://www.microsoft.com/typography/OTSPEC/chapter2.htm
// parser.offset must point to the start of the table containing the coverage.
Parser.prototype.parseCoverage = function() {
var this$1 = this;
var startOffset = this.offset + this.relativeOffset;
var format = this.parseUShort();
var count = this.parseUShort();
if (format === 1) {
return {
format: 1,
glyphs: this.parseUShortList(count)
};
} else if (format === 2) {
var ranges = new Array(count);
for (var i = 0; i < count; i++) {
ranges[i] = {
start: this$1.parseUShort(),
end: this$1.parseUShort(),
index: this$1.parseUShort()
};
}
return {
format: 2,
ranges: ranges
};
}
throw new Error(
'0x' + startOffset.toString(16) + ': Coverage format must be 1 or 2.'
);
};
// Parse a Class Definition Table in a GSUB, GPOS or GDEF table.
// https://www.microsoft.com/typography/OTSPEC/chapter2.htm
Parser.prototype.parseClassDef = function() {
var startOffset = this.offset + this.relativeOffset;
var format = this.parseUShort();
if (format === 1) {
return {
format: 1,
startGlyph: this.parseUShort(),
classes: this.parseUShortList()
};
} else if (format === 2) {
return {
format: 2,
ranges: this.parseRecordList({
start: Parser.uShort,
end: Parser.uShort,
classId: Parser.uShort
})
};
}
throw new Error(
'0x' + startOffset.toString(16) + ': ClassDef format must be 1 or 2.'
);
};
///// Static methods ///////////////////////////////////
// These convenience methods can be used as callbacks and should be called with "this" context set to a Parser instance.
Parser.list = function(count, itemCallback) {
return function() {
return this.parseList(count, itemCallback);
};
};
Parser.list32 = function(count, itemCallback) {
return function() {
return this.parseList32(count, itemCallback);
};
};
Parser.recordList = function(count, recordDescription) {
return function() {
return this.parseRecordList(count, recordDescription);
};
};
Parser.recordList32 = function(count, recordDescription) {
return function() {
return this.parseRecordList32(count, recordDescription);
};
};
Parser.pointer = function(description) {
return function() {
return this.parsePointer(description);
};
};
Parser.pointer32 = function(description) {
return function() {
return this.parsePointer32(description);
};
};
Parser.tag = Parser.prototype.parseTag;
Parser.byte = Parser.prototype.parseByte;
Parser.uShort = Parser.offset16 = Parser.prototype.parseUShort;
Parser.uShortList = Parser.prototype.parseUShortList;
Parser.uLong = Parser.offset32 = Parser.prototype.parseULong;
Parser.uLongList = Parser.prototype.parseULongList;
Parser.struct = Parser.prototype.parseStruct;
Parser.coverage = Parser.prototype.parseCoverage;
Parser.classDef = Parser.prototype.parseClassDef;
///// Script, Feature, Lookup lists ///////////////////////////////////////////////
// https://www.microsoft.com/typography/OTSPEC/chapter2.htm
var langSysTable = {
reserved: Parser.uShort,
reqFeatureIndex: Parser.uShort,
featureIndexes: Parser.uShortList
};
Parser.prototype.parseScriptList = function() {
return (
this.parsePointer(
Parser.recordList({
tag: Parser.tag,
script: Parser.pointer({
defaultLangSys: Parser.pointer(langSysTable),
langSysRecords: Parser.recordList({
tag: Parser.tag,
langSys: Parser.pointer(langSysTable)
})
})
})
) || []
);
};
Parser.prototype.parseFeatureList = function() {
return (
this.parsePointer(
Parser.recordList({
tag: Parser.tag,
feature: Parser.pointer({
featureParams: Parser.offset16,
lookupListIndexes: Parser.uShortList
})
})
) || []
);
};
Parser.prototype.parseLookupList = function(lookupTableParsers) {
return (
this.parsePointer(
Parser.list(
Parser.pointer(function() {
var lookupType = this.parseUShort();
check.argument(
1 <= lookupType && lookupType <= 9,
'GPOS/GSUB lookup type ' + lookupType + ' unknown.'
);
var lookupFlag = this.parseUShort();
var useMarkFilteringSet = lookupFlag & 0x10;
return {
lookupType: lookupType,
lookupFlag: lookupFlag,
subtables: this.parseList(
Parser.pointer(lookupTableParsers[lookupType])
),
markFilteringSet: useMarkFilteringSet
? this.parseUShort()
: undefined
};
})
)
) || []
);
};
Parser.prototype.parseFeatureVariationsList = function() {
return (
this.parsePointer32(function() {
var majorVersion = this.parseUShort();
var minorVersion = this.parseUShort();
check.argument(
majorVersion === 1 && minorVersion < 1,
'GPOS/GSUB feature variations table unknown.'
);
var featureVariations = this.parseRecordList32({
conditionSetOffset: Parser.offset32,
featureTableSubstitutionOffset: Parser.offset32
});
return featureVariations;
}) || []
);
};
var parse = {
getByte: getByte,
getCard8: getByte,
getUShort: getUShort,
getCard16: getUShort,
getShort: getShort,
getULong: getULong,
getFixed: getFixed,
getTag: getTag,
getOffset: getOffset,
getBytes: getBytes,
bytesToString: bytesToString,
Parser: Parser
};
// The `cmap` table stores the mappings from characters to glyphs.
function parseCmapTableFormat12(cmap, p) {
//Skip reserved.
p.parseUShort();
// Length in bytes of the sub-tables.
cmap.length = p.parseULong();
cmap.language = p.parseULong();
var groupCount;
cmap.groupCount = groupCount = p.parseULong();
cmap.glyphIndexMap = {};
for (var i = 0; i < groupCount; i += 1) {
var startCharCode = p.parseULong();
var endCharCode = p.parseULong();
var startGlyphId = p.parseULong();
for (var c = startCharCode; c <= endCharCode; c += 1) {
cmap.glyphIndexMap[c] = startGlyphId;
startGlyphId++;
}
}
}
function parseCmapTableFormat4(cmap, p, data, start, offset) {
// Length in bytes of the sub-tables.
cmap.length = p.parseUShort();
cmap.language = p.parseUShort();
// segCount is stored x 2.
var segCount;
cmap.segCount = segCount = p.parseUShort() >> 1;
// Skip searchRange, entrySelector, rangeShift.
p.skip('uShort', 3);
// The "unrolled" mapping from character codes to glyph indices.
cmap.glyphIndexMap = {};
var endCountParser = new parse.Parser(data, start + offset + 14);
var startCountParser = new parse.Parser(
data,
start + offset + 16 + segCount * 2
);
var idDeltaParser = new parse.Parser(
data,
start + offset + 16 + segCount * 4
);
var idRangeOffsetParser = new parse.Parser(
data,
start + offset + 16 + segCount * 6
);
var glyphIndexOffset = start + offset + 16 + segCount * 8;
for (var i = 0; i < segCount - 1; i += 1) {
var glyphIndex = void 0;
var endCount = endCountParser.parseUShort();
var startCount = startCountParser.parseUShort();
var idDelta = idDeltaParser.parseShort();
var idRangeOffset = idRangeOffsetParser.parseUShort();
for (var c = startCount; c <= endCount; c += 1) {
if (idRangeOffset !== 0) {
// The idRangeOffset is relative to the current position in the idRangeOffset array.
// Take the current offset in the idRangeOffset array.
glyphIndexOffset =
idRangeOffsetParser.offset + idRangeOffsetParser.relativeOffset - 2;
// Add the value of the idRangeOffset, which will move us into the glyphIndex array.
glyphIndexOffset += idRangeOffset;
// Then add the character index of the current segment, multiplied by 2 for USHORTs.
glyphIndexOffset += (c - startCount) * 2;
glyphIndex = parse.getUShort(data, glyphIndexOffset);
if (glyphIndex !== 0) {
glyphIndex = (glyphIndex + idDelta) & 0xffff;
}
} else {
glyphIndex = (c + idDelta) & 0xffff;
}
cmap.glyphIndexMap[c] = glyphIndex;
}
}
}
// Parse the `cmap` table. This table stores the mappings from characters to glyphs.
// There are many available formats, but we only support the Windows format 4 and 12.
// This function returns a `CmapEncoding` object or null if no supported format could be found.
function parseCmapTable(data, start) {
var cmap = {};
cmap.version = parse.getUShort(data, start);
check.argument(cmap.version === 0, 'cmap table version should be 0.');
// The cmap table can contain many sub-tables, each with their own format.
// We're only interested in a "platform 0" (Unicode format) and "platform 3" (Windows format) table.
cmap.numTables = parse.getUShort(data, start + 2);
var offset = -1;
for (var i = cmap.numTables - 1; i >= 0; i -= 1) {
var platformId = parse.getUShort(data, start + 4 + i * 8);
var encodingId = parse.getUShort(data, start + 4 + i * 8 + 2);
if (
(platformId === 3 &&
(encodingId === 0 || encodingId === 1 || encodingId === 10)) ||
(platformId === 0 &&
(encodingId === 0 ||
encodingId === 1 ||
encodingId === 2 ||
encodingId === 3 ||
encodingId === 4))
) {
offset = parse.getULong(data, start + 4 + i * 8 + 4);
break;
}
}
if (offset === -1) {
// There is no cmap table in the font that we support.
throw new Error('No valid cmap sub-tables found.');
}
var p = new parse.Parser(data, start + offset);
cmap.format = p.parseUShort();
if (cmap.format === 12) {
parseCmapTableFormat12(cmap, p);
} else if (cmap.format === 4) {
parseCmapTableFormat4(cmap, p, data, start, offset);
} else {
throw new Error(
'Only format 4 and 12 cmap tables are supported (found format ' +
cmap.format +
').'
);
}
return cmap;
}
function addSegment(t, code, glyphIndex) {
t.segments.push({
end: code,
start: code,
delta: -(code - glyphIndex),
offset: 0,
glyphIndex: glyphIndex
});
}
function addTerminatorSegment(t) {
t.segments.push({
end: 0xffff,
start: 0xffff,
delta: 1,
offset: 0
});
}
// Make cmap table, format 4 by default, 12 if needed only
function makeCmapTable(glyphs) {
// Plan 0 is the base Unicode Plan but emojis, for example are on another plan, and needs cmap 12 format (with 32bit)
var isPlan0Only = true;
var i;
// Check if we need to add cmap format 12 or if format 4 only is fine
for (i = glyphs.length - 1; i > 0; i -= 1) {
var g = glyphs.get(i);
if (g.unicode > 65535) {
console.log('Adding CMAP format 12 (needed!)');
isPlan0Only = false;
break;
}
}
var cmapTable = [
{ name: 'version', type: 'USHORT', value: 0 },
{ name: 'numTables', type: 'USHORT', value: isPlan0Only ? 1 : 2 },
// CMAP 4 header
{ name: 'platformID', type: 'USHORT', value: 3 },
{ name: 'encodingID', type: 'USHORT', value: 1 },
{ name: 'offset', type: 'ULONG', value: isPlan0Only ? 12 : 12 + 8 }
];
if (!isPlan0Only) {
cmapTable = cmapTable.concat([
// CMAP 12 header
{ name: 'cmap12PlatformID', type: 'USHORT', value: 3 }, // We encode only for PlatformID = 3 (Windows) because it is supported everywhere
{ name: 'cmap12EncodingID', type: 'USHORT', value: 10 },
{ name: 'cmap12Offset', type: 'ULONG', value: 0 }
]);
}
cmapTable = cmapTable.concat([
// CMAP 4 Subtable
{ name: 'format', type: 'USHORT', value: 4 },
{ name: 'cmap4Length', type: 'USHORT', value: 0 },
{ name: 'language', type: 'USHORT', value: 0 },
{ name: 'segCountX2', type: 'USHORT', value: 0 },
{ name: 'searchRange', type: 'USHORT', value: 0 },
{ name: 'entrySelector', type: 'USHORT', value: 0 },
{ name: 'rangeShift', type: 'USHORT', value: 0 }
]);
var t = new table.Table('cmap', cmapTable);
t.segments = [];
for (i = 0; i < glyphs.length; i += 1) {
var glyph = glyphs.get(i);
for (var j = 0; j < glyph.unicodes.length; j += 1) {
addSegment(t, glyph.unicodes[j], i);
}
t.segments = t.segments.sort(function(a, b) {
return a.start - b.start;
});
}
addTerminatorSegment(t);
var segCount = t.segments.length;
var segCountToRemove = 0;
// CMAP 4
// Set up parallel segment arrays.
var endCounts = [];
var startCounts = [];
var idDeltas = [];
var idRangeOffsets = [];
var glyphIds = [];
// CMAP 12
var cmap12Groups = [];
// Reminder this loop is not following the specification at 100%
// The specification -> find suites of characters and make a group
// Here we're doing one group for each letter
// Doing as the spec can save 8 times (or more) space
for (i = 0; i < segCount; i += 1) {
var segment = t.segments[i];
// CMAP 4
if (segment.end <= 65535 && segment.start <= 65535) {
endCounts = endCounts.concat({
name: 'end_' + i,
type: 'USHORT',
value: segment.end
});
startCounts = startCounts.concat({
name: 'start_' + i,
type: 'USHORT',
value: segment.start
});
idDeltas = idDeltas.concat({
name: 'idDelta_' + i,
type: 'SHORT',
value: segment.delta
});
idRangeOffsets = idRangeOffsets.concat({
name: 'idRangeOffset_' + i,
type: 'USHORT',
value: segment.offset
});
if (segment.glyphId !== undefined) {
glyphIds = glyphIds.concat({
name: 'glyph_' + i,
type: 'USHORT',
value: segment.glyphId
});
}
} else {
// Skip Unicode > 65535 (16bit unsigned max) for CMAP 4, will be added in CMAP 12
segCountToRemove += 1;
}
// CMAP 12
// Skip Terminator Segment
if (!isPlan0Only && segment.glyphIndex !== undefined) {
cmap12Groups = cmap12Groups.concat({
name: 'cmap12Start_' + i,
type: 'ULONG',
value: segment.start
});
cmap12Groups = cmap12Groups.concat({
name: 'cmap12End_' + i,
type: 'ULONG',
value: segment.end
});
cmap12Groups = cmap12Groups.concat({
name: 'cmap12Glyph_' + i,
type: 'ULONG',
value: segment.glyphIndex
});
}
}
// CMAP 4 Subtable
t.segCountX2 = (segCount - segCountToRemove) * 2;
t.searchRange =
Math.pow(
2,
Math.floor(Math.log(segCount - segCountToRemove) / Math.log(2))
) * 2;
t.entrySelector = Math.log(t.searchRange / 2) / Math.log(2);
t.rangeShift = t.segCountX2 - t.searchRange;
t.fields = t.fields.concat(endCounts);
t.fields.push({ name: 'reservedPad', type: 'USHORT', value: 0 });
t.fields = t.fields.concat(startCounts);
t.fields = t.fields.concat(idDeltas);
t.fields = t.fields.concat(idRangeOffsets);
t.fields = t.fields.concat(glyphIds);
t.cmap4Length =
14 + // Subtable header
endCounts.length * 2 +
2 + // reservedPad
startCounts.length * 2 +
idDeltas.length * 2 +
idRangeOffsets.length * 2 +
glyphIds.length * 2;
if (!isPlan0Only) {
// CMAP 12 Subtable
var cmap12Length =
16 + // Subtable header
cmap12Groups.length * 4;
t.cmap12Offset = 12 + 2 * 2 + 4 + t.cmap4Length;
t.fields = t.fields.concat([
{ name: 'cmap12Format', type: 'USHORT', value: 12 },
{ name: 'cmap12Reserved', type: 'USHORT', value: 0 },
{ name: 'cmap12Length', type: 'ULONG', value: cmap12Length },
{ name: 'cmap12Language', type: 'ULONG', value: 0 },
{ name: 'cmap12nGroups', type: 'ULONG', value: cmap12Groups.length / 3 }
]);
t.fields = t.fields.concat(cmap12Groups);
}
return t;
}
var cmap = { parse: parseCmapTable, make: makeCmapTable };
// Glyph encoding
var cffStandardStrings = [
'.notdef',
'space',
'exclam',
'quotedbl',
'numbersign',
'dollar',
'percent',
'ampersand',
'quoteright',
'parenleft',
'parenright',
'asterisk',
'plus',
'comma',
'hyphen',
'period',
'slash',
'zero',
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'colon',
'semicolon',
'less',
'equal',
'greater',
'question',
'at',
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
'K',
'L',
'M',
'N',
'O',
'P',
'Q',
'R',
'S',
'T',
'U',
'V',
'W',
'X',
'Y',
'Z',
'bracketleft',
'backslash',
'bracketright',
'asciicircum',
'underscore',
'quoteleft',
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v',
'w',
'x',
'y',
'z',
'braceleft',
'bar',
'braceright',
'asciitilde',
'exclamdown',
'cent',
'sterling',
'fraction',
'yen',
'florin',
'section',
'currency',
'quotesingle',
'quotedblleft',
'guillemotleft',
'guilsinglleft',
'guilsinglright',
'fi',
'fl',
'endash',
'dagger',
'daggerdbl',
'periodcentered',
'paragraph',
'bullet',
'quotesinglbase',
'quotedblbase',
'quotedblright',
'guillemotright',
'ellipsis',
'perthousand',
'questiondown',
'grave',
'acute',
'circumflex',
'tilde',
'macron',
'breve',
'dotaccent',
'dieresis',
'ring',
'cedilla',
'hungarumlaut',
'ogonek',
'caron',
'emdash',
'AE',
'ordfeminine',
'Lslash',
'Oslash',
'OE',
'ordmasculine',
'ae',
'dotlessi',
'lslash',
'oslash',
'oe',
'germandbls',
'onesuperior',
'logicalnot',
'mu',
'trademark',
'Eth',
'onehalf',
'plusminus',
'Thorn',
'onequarter',
'divide',
'brokenbar',
'degree',
'thorn',
'threequarters',
'twosuperior',
'registered',
'minus',
'eth',
'multiply',
'threesuperior',
'copyright',
'Aacute',
'Acircumflex',
'Adieresis',
'Agrave',
'Aring',
'Atilde',
'Ccedilla',
'Eacute',
'Ecircumflex',
'Edieresis',
'Egrave',
'Iacute',
'Icircumflex',
'Idieresis',
'Igrave',
'Ntilde',
'Oacute',
'Ocircumflex',
'Odieresis',
'Ograve',
'Otilde',
'Scaron',
'Uacute',
'Ucircumflex',
'Udieresis',
'Ugrave',
'Yacute',
'Ydieresis',
'Zcaron',
'aacute',
'acircumflex',
'adieresis',
'agrave',
'aring',
'atilde',
'ccedilla',
'eacute',
'ecircumflex',
'edieresis',
'egrave',
'iacute',
'icircumflex',
'idieresis',
'igrave',
'ntilde',
'oacute',
'ocircumflex',
'odieresis',
'ograve',
'otilde',
'scaron',
'uacute',
'ucircumflex',
'udieresis',
'ugrave',
'yacute',
'ydieresis',
'zcaron',
'exclamsmall',
'Hungarumlautsmall',
'dollaroldstyle',
'dollarsuperior',
'ampersandsmall',
'Acutesmall',
'parenleftsuperior',
'parenrightsuperior',
'266 ff',
'onedotenleader',
'zerooldstyle',
'oneoldstyle',
'twooldstyle',
'threeoldstyle',
'fouroldstyle',
'fiveoldstyle',
'sixoldstyle',
'sevenoldstyle',
'eightoldstyle',
'nineoldstyle',
'commasuperior',
'threequartersemdash',
'periodsuperior',
'questionsmall',
'asuperior',
'bsuperior',
'centsuperior',
'dsuperior',
'esuperior',
'isuperior',
'lsuperior',
'msuperior',
'nsuperior',
'osuperior',
'rsuperior',
'ssuperior',
'tsuperior',
'ff',
'ffi',
'ffl',
'parenleftinferior',
'parenrightinferior',
'Circumflexsmall',
'hyphensuperior',
'Gravesmall',
'Asmall',
'Bsmall',
'Csmall',
'Dsmall',
'Esmall',
'Fsmall',
'Gsmall',
'Hsmall',
'Ismall',
'Jsmall',
'Ksmall',
'Lsmall',
'Msmall',
'Nsmall',
'Osmall',
'Psmall',
'Qsmall',
'Rsmall',
'Ssmall',
'Tsmall',
'Usmall',
'Vsmall',
'Wsmall',
'Xsmall',
'Ysmall',
'Zsmall',
'colonmonetary',
'onefitted',
'rupiah',
'Tildesmall',
'exclamdownsmall',
'centoldstyle',
'Lslashsmall',
'Scaronsmall',
'Zcaronsmall',
'Dieresissmall',
'Brevesmall',
'Caronsmall',
'Dotaccentsmall',
'Macronsmall',
'figuredash',
'hypheninferior',
'Ogoneksmall',
'Ringsmall',
'Cedillasmall',
'questiondownsmall',
'oneeighth',
'threeeighths',
'fiveeighths',
'seveneighths',
'onethird',
'twothirds',
'zerosuperior',
'foursuperior',
'fivesuperior',
'sixsuperior',
'sevensuperior',
'eightsuperior',
'ninesuperior',
'zeroinferior',
'oneinferior',
'twoinferior',
'threeinferior',
'fourinferior',
'fiveinferior',
'sixinferior',
'seveninferior',
'eightinferior',
'nineinferior',
'centinferior',
'dollarinferior',
'periodinferior',
'commainferior',
'Agravesmall',
'Aacutesmall',
'Acircumflexsmall',
'Atildesmall',
'Adieresissmall',
'Aringsmall',
'AEsmall',
'Ccedillasmall',
'Egravesmall',
'Eacutesmall',
'Ecircumflexsmall',
'Edieresissmall',
'Igravesmall',
'Iacutesmall',
'Icircumflexsmall',
'Idieresissmall',
'Ethsmall',
'Ntildesmall',
'Ogravesmall',
'Oacutesmall',
'Ocircumflexsmall',
'Otildesmall',
'Odieresissmall',
'OEsmall',
'Oslashsmall',
'Ugravesmall',
'Uacutesmall',
'Ucircumflexsmall',
'Udieresissmall',
'Yacutesmall',
'Thornsmall',
'Ydieresissmall',
'001.000',
'001.001',
'001.002',
'001.003',
'Black',
'Bold',
'Book',
'Light',
'Medium',
'Regular',
'Roman',
'Semibold'
];
var cffStandardEncoding = [
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'space',
'exclam',
'quotedbl',
'numbersign',
'dollar',
'percent',
'ampersand',
'quoteright',
'parenleft',
'parenright',
'asterisk',
'plus',
'comma',
'hyphen',
'period',
'slash',
'zero',
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'colon',
'semicolon',
'less',
'equal',
'greater',
'question',
'at',
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
'K',
'L',
'M',
'N',
'O',
'P',
'Q',
'R',
'S',
'T',
'U',
'V',
'W',
'X',
'Y',
'Z',
'bracketleft',
'backslash',
'bracketright',
'asciicircum',
'underscore',
'quoteleft',
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v',
'w',
'x',
'y',
'z',
'braceleft',
'bar',
'braceright',
'asciitilde',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'exclamdown',
'cent',
'sterling',
'fraction',
'yen',
'florin',
'section',
'currency',
'quotesingle',
'quotedblleft',
'guillemotleft',
'guilsinglleft',
'guilsinglright',
'fi',
'fl',
'',
'endash',
'dagger',
'daggerdbl',
'periodcentered',
'',
'paragraph',
'bullet',
'quotesinglbase',
'quotedblbase',
'quotedblright',
'guillemotright',
'ellipsis',
'perthousand',
'',
'questiondown',
'',
'grave',
'acute',
'circumflex',
'tilde',
'macron',
'breve',
'dotaccent',
'dieresis',
'',
'ring',
'cedilla',
'',
'hungarumlaut',
'ogonek',
'caron',
'emdash',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'AE',
'',
'ordfeminine',
'',
'',
'',
'',
'Lslash',
'Oslash',
'OE',
'ordmasculine',
'',
'',
'',
'',
'',
'ae',
'',
'',
'',
'dotlessi',
'',
'',
'lslash',
'oslash',
'oe',
'germandbls'
];
var cffExpertEncoding = [
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'space',
'exclamsmall',
'Hungarumlautsmall',
'',
'dollaroldstyle',
'dollarsuperior',
'ampersandsmall',
'Acutesmall',
'parenleftsuperior',
'parenrightsuperior',
'twodotenleader',
'onedotenleader',
'comma',
'hyphen',
'period',
'fraction',
'zerooldstyle',
'oneoldstyle',
'twooldstyle',
'threeoldstyle',
'fouroldstyle',
'fiveoldstyle',
'sixoldstyle',
'sevenoldstyle',
'eightoldstyle',
'nineoldstyle',
'colon',
'semicolon',
'commasuperior',
'threequartersemdash',
'periodsuperior',
'questionsmall',
'',
'asuperior',
'bsuperior',
'centsuperior',
'dsuperior',
'esuperior',
'',
'',
'isuperior',
'',
'',
'lsuperior',
'msuperior',
'nsuperior',
'osuperior',
'',
'',
'rsuperior',
'ssuperior',
'tsuperior',
'',
'ff',
'fi',
'fl',
'ffi',
'ffl',
'parenleftinferior',
'',
'parenrightinferior',
'Circumflexsmall',
'hyphensuperior',
'Gravesmall',
'Asmall',
'Bsmall',
'Csmall',
'Dsmall',
'Esmall',
'Fsmall',
'Gsmall',
'Hsmall',
'Ismall',
'Jsmall',
'Ksmall',
'Lsmall',
'Msmall',
'Nsmall',
'Osmall',
'Psmall',
'Qsmall',
'Rsmall',
'Ssmall',
'Tsmall',
'Usmall',
'Vsmall',
'Wsmall',
'Xsmall',
'Ysmall',
'Zsmall',
'colonmonetary',
'onefitted',
'rupiah',
'Tildesmall',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'exclamdownsmall',
'centoldstyle',
'Lslashsmall',
'',
'',
'Scaronsmall',
'Zcaronsmall',
'Dieresissmall',
'Brevesmall',
'Caronsmall',
'',
'Dotaccentsmall',
'',
'',
'Macronsmall',
'',
'',
'figuredash',
'hypheninferior',
'',
'',
'Ogoneksmall',
'Ringsmall',
'Cedillasmall',
'',
'',
'',
'onequarter',
'onehalf',
'threequarters',
'questiondownsmall',
'oneeighth',
'threeeighths',
'fiveeighths',
'seveneighths',
'onethird',
'twothirds',
'',
'',
'zerosuperior',
'onesuperior',
'twosuperior',
'threesuperior',
'foursuperior',
'fivesuperior',
'sixsuperior',
'sevensuperior',
'eightsuperior',
'ninesuperior',
'zeroinferior',
'oneinferior',
'twoinferior',
'threeinferior',
'fourinferior',
'fiveinferior',
'sixinferior',
'seveninferior',
'eightinferior',
'nineinferior',
'centinferior',
'dollarinferior',
'periodinferior',
'commainferior',
'Agravesmall',
'Aacutesmall',
'Acircumflexsmall',
'Atildesmall',
'Adieresissmall',
'Aringsmall',
'AEsmall',
'Ccedillasmall',
'Egravesmall',
'Eacutesmall',
'Ecircumflexsmall',
'Edieresissmall',
'Igravesmall',
'Iacutesmall',
'Icircumflexsmall',
'Idieresissmall',
'Ethsmall',
'Ntildesmall',
'Ogravesmall',
'Oacutesmall',
'Ocircumflexsmall',
'Otildesmall',
'Odieresissmall',
'OEsmall',
'Oslashsmall',
'Ugravesmall',
'Uacutesmall',
'Ucircumflexsmall',
'Udieresissmall',
'Yacutesmall',
'Thornsmall',
'Ydieresissmall'
];
var standardNames = [
'.notdef',
'.null',
'nonmarkingreturn',
'space',
'exclam',
'quotedbl',
'numbersign',
'dollar',
'percent',
'ampersand',
'quotesingle',
'parenleft',
'parenright',
'asterisk',
'plus',
'comma',
'hyphen',
'period',
'slash',
'zero',
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'colon',
'semicolon',
'less',
'equal',
'greater',
'question',
'at',
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
'K',
'L',
'M',
'N',
'O',
'P',
'Q',
'R',
'S',
'T',
'U',
'V',
'W',
'X',
'Y',
'Z',
'bracketleft',
'backslash',
'bracketright',
'asciicircum',
'underscore',
'grave',
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v',
'w',
'x',
'y',
'z',
'braceleft',
'bar',
'braceright',
'asciitilde',
'Adieresis',
'Aring',
'Ccedilla',
'Eacute',
'Ntilde',
'Odieresis',
'Udieresis',
'aacute',
'agrave',
'acircumflex',
'adieresis',
'atilde',
'aring',
'ccedilla',
'eacute',
'egrave',
'ecircumflex',
'edieresis',
'iacute',
'igrave',
'icircumflex',
'idieresis',
'ntilde',
'oacute',
'ograve',
'ocircumflex',
'odieresis',
'otilde',
'uacute',
'ugrave',
'ucircumflex',
'udieresis',
'dagger',
'degree',
'cent',
'sterling',
'section',
'bullet',
'paragraph',
'germandbls',
'registered',
'copyright',
'trademark',
'acute',
'dieresis',
'notequal',
'AE',
'Oslash',
'infinity',
'plusminus',
'lessequal',
'greaterequal',
'yen',
'mu',
'partialdiff',
'summation',
'product',
'pi',
'integral',
'ordfeminine',
'ordmasculine',
'Omega',
'ae',
'oslash',
'questiondown',
'exclamdown',
'logicalnot',
'radical',
'florin',
'approxequal',
'Delta',
'guillemotleft',
'guillemotright',
'ellipsis',
'nonbreakingspace',
'Agrave',
'Atilde',
'Otilde',
'OE',
'oe',
'endash',
'emdash',
'quotedblleft',
'quotedblright',
'quoteleft',
'quoteright',
'divide',
'lozenge',
'ydieresis',
'Ydieresis',
'fraction',
'currency',
'guilsinglleft',
'guilsinglright',
'fi',
'fl',
'daggerdbl',
'periodcentered',
'quotesinglbase',
'quotedblbase',
'perthousand',
'Acircumflex',
'Ecircumflex',
'Aacute',
'Edieresis',
'Egrave',
'Iacute',
'Icircumflex',
'Idieresis',
'Igrave',
'Oacute',
'Ocircumflex',
'apple',
'Ograve',
'Uacute',
'Ucircumflex',
'Ugrave',
'dotlessi',
'circumflex',
'tilde',
'macron',
'breve',
'dotaccent',
'ring',
'cedilla',
'hungarumlaut',
'ogonek',
'caron',
'Lslash',
'lslash',
'Scaron',
'scaron',
'Zcaron',
'zcaron',
'brokenbar',
'Eth',
'eth',
'Yacute',
'yacute',
'Thorn',
'thorn',
'minus',
'multiply',
'onesuperior',
'twosuperior',
'threesuperior',
'onehalf',
'onequarter',
'threequarters',
'franc',
'Gbreve',
'gbreve',
'Idotaccent',
'Scedilla',
'scedilla',
'Cacute',
'cacute',
'Ccaron',
'ccaron',
'dcroat'
];
/**
* This is the encoding used for fonts created from scratch.
* It loops through all glyphs and finds the appropriate unicode value.
* Since it's linear time, other encodings will be faster.
* @exports opentype.DefaultEncoding
* @class
* @constructor
* @param {opentype.Font}
*/
function DefaultEncoding(font) {
this.font = font;
}
DefaultEncoding.prototype.charToGlyphIndex = function(c) {
var code = c.codePointAt(0);
var glyphs = this.font.glyphs;
if (glyphs) {
for (var i = 0; i < glyphs.length; i += 1) {
var glyph = glyphs.get(i);
for (var j = 0; j < glyph.unicodes.length; j += 1) {
if (glyph.unicodes[j] === code) {
return i;
}
}
}
}
return null;
};
/**
* @exports opentype.CmapEncoding
* @class
* @constructor
* @param {Object} cmap - a object with the cmap encoded data
*/
function CmapEncoding(cmap) {
this.cmap = cmap;
}
/**
* @param {string} c - the character
* @return {number} The glyph index.
*/
CmapEncoding.prototype.charToGlyphIndex = function(c) {
return this.cmap.glyphIndexMap[c.codePointAt(0)] || 0;
};
/**
* @exports opentype.CffEncoding
* @class
* @constructor
* @param {string} encoding - The encoding
* @param {Array} charset - The character set.
*/
function CffEncoding(encoding, charset) {
this.encoding = encoding;
this.charset = charset;
}
/**
* @param {string} s - The character
* @return {number} The index.
*/
CffEncoding.prototype.charToGlyphIndex = function(s) {
var code = s.codePointAt(0);
var charName = this.encoding[code];
return this.charset.indexOf(charName);
};
/**
* @exports opentype.GlyphNames
* @class
* @constructor
* @param {Object} post
*/
function GlyphNames(post) {
var this$1 = this;
switch (post.version) {
case 1:
this.names = standardNames.slice();
break;
case 2:
this.names = new Array(post.numberOfGlyphs);
for (var i = 0; i < post.numberOfGlyphs; i++) {
if (post.glyphNameIndex[i] < standardNames.length) {
this$1.names[i] = standardNames[post.glyphNameIndex[i]];
} else {
this$1.names[i] =
post.names[post.glyphNameIndex[i] - standardNames.length];
}
}
break;
case 2.5:
this.names = new Array(post.numberOfGlyphs);
for (var i$1 = 0; i$1 < post.numberOfGlyphs; i$1++) {
this$1.names[i$1] = standardNames[i$1 + post.glyphNameIndex[i$1]];
}
break;
case 3:
this.names = [];
break;
default:
this.names = [];
break;
}
}
/**
* Gets the index of a glyph by name.
* @param {string} name - The glyph name
* @return {number} The index
*/
GlyphNames.prototype.nameToGlyphIndex = function(name) {
return this.names.indexOf(name);
};
/**
* @param {number} gid
* @return {string}
*/
GlyphNames.prototype.glyphIndexToName = function(gid) {
return this.names[gid];
};
/**
* @alias opentype.addGlyphNames
* @param {opentype.Font}
*/
function addGlyphNames(font) {
var glyph;
var glyphIndexMap = font.tables.cmap.glyphIndexMap;
var charCodes = Object.keys(glyphIndexMap);
for (var i = 0; i < charCodes.length; i += 1) {
var c = charCodes[i];
var glyphIndex = glyphIndexMap[c];
glyph = font.glyphs.get(glyphIndex);
glyph.addUnicode(parseInt(c));
}
for (var i$1 = 0; i$1 < font.glyphs.length; i$1 += 1) {
glyph = font.glyphs.get(i$1);
if (font.cffEncoding) {
if (font.isCIDFont) {
glyph.name = 'gid' + i$1;
} else {
glyph.name = font.cffEncoding.charset[i$1];
}
} else if (font.glyphNames.names) {
glyph.name = font.glyphNames.glyphIndexToName(i$1);
}
}
}
// Drawing utility functions.
// Draw a line on the given context from point `x1,y1` to point `x2,y2`.
function line(ctx, x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
var draw = { line: line };
// The Glyph object
// import glyf from './tables/glyf' Can't be imported here, because it's a circular dependency
function getPathDefinition(glyph, path) {
var _path = path || new Path();
return {
configurable: true,
get: function() {
if (typeof _path === 'function') {
_path = _path();
}
return _path;
},
set: function(p) {
_path = p;
}
};
}
/**
* @typedef GlyphOptions
* @type Object
* @property {string} [name] - The glyph name
* @property {number} [unicode]
* @property {Array} [unicodes]
* @property {number} [xMin]
* @property {number} [yMin]
* @property {number} [xMax]
* @property {number} [yMax]
* @property {number} [advanceWidth]
*/
// A Glyph is an individual mark that often corresponds to a character.
// Some glyphs, such as ligatures, are a combination of many characters.
// Glyphs are the basic building blocks of a font.
//
// The `Glyph` class contains utility methods for drawing the path and its points.
/**
* @exports opentype.Glyph
* @class
* @param {GlyphOptions}
* @constructor
*/
function Glyph(options) {
// By putting all the code on a prototype function (which is only declared once)
// we reduce the memory requirements for larger fonts by some 2%
this.bindConstructorValues(options);
}
/**
* @param {GlyphOptions}
*/
Glyph.prototype.bindConstructorValues = function(options) {
this.index = options.index || 0;
// These three values cannot be deferred for memory optimization:
this.name = options.name || null;
this.unicode = options.unicode || undefined;
this.unicodes =
options.unicodes || options.unicode !== undefined
? [options.unicode]
: [];
// But by binding these values only when necessary, we reduce can
// the memory requirements by almost 3% for larger fonts.
if (options.xMin) {
this.xMin = options.xMin;
}
if (options.yMin) {
this.yMin = options.yMin;
}
if (options.xMax) {
this.xMax = options.xMax;
}
if (options.yMax) {
this.yMax = options.yMax;
}
if (options.advanceWidth) {
this.advanceWidth = options.advanceWidth;
}
// The path for a glyph is the most memory intensive, and is bound as a value
// with a getter/setter to ensure we actually do path parsing only once the
// path is actually needed by anything.
Object.defineProperty(this, 'path', getPathDefinition(this, options.path));
};
/**
* @param {number}
*/
Glyph.prototype.addUnicode = function(unicode) {
if (this.unicodes.length === 0) {
this.unicode = unicode;
}
this.unicodes.push(unicode);
};
/**
* Calculate the minimum bounding box for this glyph.
* @return {opentype.BoundingBox}
*/
Glyph.prototype.getBoundingBox = function() {
return this.path.getBoundingBox();
};
/**
* Convert the glyph to a Path we can draw on a drawing context.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
* @param {Object=} options - xScale, yScale to stretch the glyph.
* @param {opentype.Font} if hinting is to be used, the font
* @return {opentype.Path}
*/
Glyph.prototype.getPath = function(x, y, fontSize, options, font) {
x = x !== undefined ? x : 0;
y = y !== undefined ? y : 0;
fontSize = fontSize !== undefined ? fontSize : 72;
var commands;
var hPoints;
if (!options) {
options = {};
}
var xScale = options.xScale;
var yScale = options.yScale;
if (options.hinting && font && font.hinting) {
// in case of hinting, the hinting engine takes care
// of scaling the points (not the path) before hinting.
hPoints = this.path && font.hinting.exec(this, fontSize);
// in case the hinting engine failed hPoints is undefined
// and thus reverts to plain rending
}
if (hPoints) {
// Call font.hinting.getCommands instead of `glyf.getPath(hPoints).commands` to avoid a circular dependency
commands = font.hinting.getCommands(hPoints);
x = Math.round(x);
y = Math.round(y);
// TODO in case of hinting xyScaling is not yet supported
xScale = yScale = 1;
} else {
commands = this.path.commands;
var scale = 1 / this.path.unitsPerEm * fontSize;
if (xScale === undefined) {
xScale = scale;
}
if (yScale === undefined) {
yScale = scale;
}
}
var p = new Path();
for (var i = 0; i < commands.length; i += 1) {
var cmd = commands[i];
if (cmd.type === 'M') {
p.moveTo(x + cmd.x * xScale, y + -cmd.y * yScale);
} else if (cmd.type === 'L') {
p.lineTo(x + cmd.x * xScale, y + -cmd.y * yScale);
} else if (cmd.type === 'Q') {
p.quadraticCurveTo(
x + cmd.x1 * xScale,
y + -cmd.y1 * yScale,
x + cmd.x * xScale,
y + -cmd.y * yScale
);
} else if (cmd.type === 'C') {
p.curveTo(
x + cmd.x1 * xScale,
y + -cmd.y1 * yScale,
x + cmd.x2 * xScale,
y + -cmd.y2 * yScale,
x + cmd.x * xScale,
y + -cmd.y * yScale
);
} else if (cmd.type === 'Z') {
p.closePath();
}
}
return p;
};
/**
* Split the glyph into contours.
* This function is here for backwards compatibility, and to
* provide raw access to the TrueType glyph outlines.
* @return {Array}
*/
Glyph.prototype.getContours = function() {
var this$1 = this;
if (this.points === undefined) {
return [];
}
var contours = [];
var currentContour = [];
for (var i = 0; i < this.points.length; i += 1) {
var pt = this$1.points[i];
currentContour.push(pt);
if (pt.lastPointOfContour) {
contours.push(currentContour);
currentContour = [];
}
}
check.argument(
currentContour.length === 0,
'There are still points left in the current contour.'
);
return contours;
};
/**
* Calculate the xMin/yMin/xMax/yMax/lsb/rsb for a Glyph.
* @return {Object}
*/
Glyph.prototype.getMetrics = function() {
var commands = this.path.commands;
var xCoords = [];
var yCoords = [];
for (var i = 0; i < commands.length; i += 1) {
var cmd = commands[i];
if (cmd.type !== 'Z') {
xCoords.push(cmd.x);
yCoords.push(cmd.y);
}
if (cmd.type === 'Q' || cmd.type === 'C') {
xCoords.push(cmd.x1);
yCoords.push(cmd.y1);
}
if (cmd.type === 'C') {
xCoords.push(cmd.x2);
yCoords.push(cmd.y2);
}
}
var metrics = {
xMin: Math.min.apply(null, xCoords),
yMin: Math.min.apply(null, yCoords),
xMax: Math.max.apply(null, xCoords),
yMax: Math.max.apply(null, yCoords),
leftSideBearing: this.leftSideBearing
};
if (!isFinite(metrics.xMin)) {
metrics.xMin = 0;
}
if (!isFinite(metrics.xMax)) {
metrics.xMax = this.advanceWidth;
}
if (!isFinite(metrics.yMin)) {
metrics.yMin = 0;
}
if (!isFinite(metrics.yMax)) {
metrics.yMax = 0;
}
metrics.rightSideBearing =
this.advanceWidth -
metrics.leftSideBearing -
(metrics.xMax - metrics.xMin);
return metrics;
};
/**
* Draw the glyph on the given context.
* @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
* @param {Object=} options - xScale, yScale to stretch the glyph.
*/
Glyph.prototype.draw = function(ctx, x, y, fontSize, options) {
this.getPath(x, y, fontSize, options).draw(ctx);
};
/**
* Draw the points of the glyph.
* On-curve points will be drawn in blue, off-curve points will be drawn in red.
* @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
*/
Glyph.prototype.drawPoints = function(ctx, x, y, fontSize) {
function drawCircles(l, x, y, scale) {
var PI_SQ = Math.PI * 2;
ctx.beginPath();
for (var j = 0; j < l.length; j += 1) {
ctx.moveTo(x + l[j].x * scale, y + l[j].y * scale);
ctx.arc(x + l[j].x * scale, y + l[j].y * scale, 2, 0, PI_SQ, false);
}
ctx.closePath();
ctx.fill();
}
x = x !== undefined ? x : 0;
y = y !== undefined ? y : 0;
fontSize = fontSize !== undefined ? fontSize : 24;
var scale = 1 / this.path.unitsPerEm * fontSize;
var blueCircles = [];
var redCircles = [];
var path = this.path;
for (var i = 0; i < path.commands.length; i += 1) {
var cmd = path.commands[i];
if (cmd.x !== undefined) {
blueCircles.push({ x: cmd.x, y: -cmd.y });
}
if (cmd.x1 !== undefined) {
redCircles.push({ x: cmd.x1, y: -cmd.y1 });
}
if (cmd.x2 !== undefined) {
redCircles.push({ x: cmd.x2, y: -cmd.y2 });
}
}
ctx.fillStyle = 'blue';
drawCircles(blueCircles, x, y, scale);
ctx.fillStyle = 'red';
drawCircles(redCircles, x, y, scale);
};
/**
* Draw lines indicating important font measurements.
* Black lines indicate the origin of the coordinate system (point 0,0).
* Blue lines indicate the glyph bounding box.
* Green line indicates the advance width of the glyph.
* @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
*/
Glyph.prototype.drawMetrics = function(ctx, x, y, fontSize) {
var scale;
x = x !== undefined ? x : 0;
y = y !== undefined ? y : 0;
fontSize = fontSize !== undefined ? fontSize : 24;
scale = 1 / this.path.unitsPerEm * fontSize;
ctx.lineWidth = 1;
// Draw the origin
ctx.strokeStyle = 'black';
draw.line(ctx, x, -10000, x, 10000);
draw.line(ctx, -10000, y, 10000, y);
// This code is here due to memory optimization: by not using
// defaults in the constructor, we save a notable amount of memory.
var xMin = this.xMin || 0;
var yMin = this.yMin || 0;
var xMax = this.xMax || 0;
var yMax = this.yMax || 0;
var advanceWidth = this.advanceWidth || 0;
// Draw the glyph box
ctx.strokeStyle = 'blue';
draw.line(ctx, x + xMin * scale, -10000, x + xMin * scale, 10000);
draw.line(ctx, x + xMax * scale, -10000, x + xMax * scale, 10000);
draw.line(ctx, -10000, y + -yMin * scale, 10000, y + -yMin * scale);
draw.line(ctx, -10000, y + -yMax * scale, 10000, y + -yMax * scale);
// Draw the advance width
ctx.strokeStyle = 'green';
draw.line(
ctx,
x + advanceWidth * scale,
-10000,
x + advanceWidth * scale,
10000
);
};
// The GlyphSet object
// Define a property on the glyph that depends on the path being loaded.
function defineDependentProperty(glyph, externalName, internalName) {
Object.defineProperty(glyph, externalName, {
get: function() {
// Request the path property to make sure the path is loaded.
glyph.path; // jshint ignore:line
return glyph[internalName];
},
set: function(newValue) {
glyph[internalName] = newValue;
},
enumerable: true,
configurable: true
});
}
/**
* A GlyphSet represents all glyphs available in the font, but modelled using
* a deferred glyph loader, for retrieving glyphs only once they are absolutely
* necessary, to keep the memory footprint down.
* @exports opentype.GlyphSet
* @class
* @param {opentype.Font}
* @param {Array}
*/
function GlyphSet(font, glyphs) {
var this$1 = this;
this.font = font;
this.glyphs = {};
if (Array.isArray(glyphs)) {
for (var i = 0; i < glyphs.length; i++) {
this$1.glyphs[i] = glyphs[i];
}
}
this.length = (glyphs && glyphs.length) || 0;
}
/**
* @param {number} index
* @return {opentype.Glyph}
*/
GlyphSet.prototype.get = function(index) {
if (typeof this.glyphs[index] === 'function') {
this.glyphs[index] = this.glyphs[index]();
}
return this.glyphs[index];
};
/**
* @param {number} index
* @param {Object}
*/
GlyphSet.prototype.push = function(index, loader) {
this.glyphs[index] = loader;
this.length++;
};
/**
* @alias opentype.glyphLoader
* @param {opentype.Font} font
* @param {number} index
* @return {opentype.Glyph}
*/
function glyphLoader(font, index) {
return new Glyph({ index: index, font: font });
}
/**
* Generate a stub glyph that can be filled with all metadata *except*
* the "points" and "path" properties, which must be loaded only once
* the glyph's path is actually requested for text shaping.
* @alias opentype.ttfGlyphLoader
* @param {opentype.Font} font
* @param {number} index
* @param {Function} parseGlyph
* @param {Object} data
* @param {number} position
* @param {Function} buildPath
* @return {opentype.Glyph}
*/
function ttfGlyphLoader(font, index, parseGlyph, data, position, buildPath) {
return function() {
var glyph = new Glyph({ index: index, font: font });
glyph.path = function() {
parseGlyph(glyph, data, position);
var path = buildPath(font.glyphs, glyph);
path.unitsPerEm = font.unitsPerEm;
return path;
};
defineDependentProperty(glyph, 'xMin', '_xMin');
defineDependentProperty(glyph, 'xMax', '_xMax');
defineDependentProperty(glyph, 'yMin', '_yMin');
defineDependentProperty(glyph, 'yMax', '_yMax');
return glyph;
};
}
/**
* @alias opentype.cffGlyphLoader
* @param {opentype.Font} font
* @param {number} index
* @param {Function} parseCFFCharstring
* @param {string} charstring
* @return {opentype.Glyph}
*/
function cffGlyphLoader(font, index, parseCFFCharstring, charstring) {
return function() {
var glyph = new Glyph({ index: index, font: font });
glyph.path = function() {
var path = parseCFFCharstring(font, glyph, charstring);
path.unitsPerEm = font.unitsPerEm;
return path;
};
return glyph;
};
}
var glyphset = {
GlyphSet: GlyphSet,
glyphLoader: glyphLoader,
ttfGlyphLoader: ttfGlyphLoader,
cffGlyphLoader: cffGlyphLoader
};
// The `CFF` table contains the glyph outlines in PostScript format.
// Custom equals function that can also check lists.
function equals(a, b) {
if (a === b) {
return true;
} else if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) {
return false;
}
for (var i = 0; i < a.length; i += 1) {
if (!equals(a[i], b[i])) {
return false;
}
}
return true;
} else {
return false;
}
}
// Subroutines are encoded using the negative half of the number space.
// See type 2 chapter 4.7 "Subroutine operators".
function calcCFFSubroutineBias(subrs) {
var bias;
if (subrs.length < 1240) {
bias = 107;
} else if (subrs.length < 33900) {
bias = 1131;
} else {
bias = 32768;
}
return bias;
}
// Parse a `CFF` INDEX array.
// An index array consists of a list of offsets, then a list of objects at those offsets.
function parseCFFIndex(data, start, conversionFn) {
var offsets = [];
var objects = [];
var count = parse.getCard16(data, start);
var objectOffset;
var endOffset;
if (count !== 0) {
var offsetSize = parse.getByte(data, start + 2);
objectOffset = start + (count + 1) * offsetSize + 2;
var pos = start + 3;
for (var i = 0; i < count + 1; i += 1) {
offsets.push(parse.getOffset(data, pos, offsetSize));
pos += offsetSize;
}
// The total size of the index array is 4 header bytes + the value of the last offset.
endOffset = objectOffset + offsets[count];
} else {
endOffset = start + 2;
}
for (var i$1 = 0; i$1 < offsets.length - 1; i$1 += 1) {
var value = parse.getBytes(
data,
objectOffset + offsets[i$1],
objectOffset + offsets[i$1 + 1]
);
if (conversionFn) {
value = conversionFn(value);
}
objects.push(value);
}
return { objects: objects, startOffset: start, endOffset: endOffset };
}
// Parse a `CFF` DICT real value.
function parseFloatOperand(parser) {
var s = '';
var eof = 15;
var lookup = [
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'.',
'E',
'E-',
null,
'-'
];
while (true) {
var b = parser.parseByte();
var n1 = b >> 4;
var n2 = b & 15;
if (n1 === eof) {
break;
}
s += lookup[n1];
if (n2 === eof) {
break;
}
s += lookup[n2];
}
return parseFloat(s);
}
// Parse a `CFF` DICT operand.
function parseOperand(parser, b0) {
var b1;
var b2;
var b3;
var b4;
if (b0 === 28) {
b1 = parser.parseByte();
b2 = parser.parseByte();
return (b1 << 8) | b2;
}
if (b0 === 29) {
b1 = parser.parseByte();
b2 = parser.parseByte();
b3 = parser.parseByte();
b4 = parser.parseByte();
return (b1 << 24) | (b2 << 16) | (b3 << 8) | b4;
}
if (b0 === 30) {
return parseFloatOperand(parser);
}
if (b0 >= 32 && b0 <= 246) {
return b0 - 139;
}
if (b0 >= 247 && b0 <= 250) {
b1 = parser.parseByte();
return (b0 - 247) * 256 + b1 + 108;
}
if (b0 >= 251 && b0 <= 254) {
b1 = parser.parseByte();
return -(b0 - 251) * 256 - b1 - 108;
}
throw new Error('Invalid b0 ' + b0);
}
// Convert the entries returned by `parseDict` to a proper dictionary.
// If a value is a list of one, it is unpacked.
function entriesToObject(entries) {
var o = {};
for (var i = 0; i < entries.length; i += 1) {
var key = entries[i][0];
var values = entries[i][1];
var value = void 0;
if (values.length === 1) {
value = values[0];
} else {
value = values;
}
if (o.hasOwnProperty(key) && !isNaN(o[key])) {
throw new Error('Object ' + o + ' already has key ' + key);
}
o[key] = value;
}
return o;
}
// Parse a `CFF` DICT object.
// A dictionary contains key-value pairs in a compact tokenized format.
function parseCFFDict(data, start, size) {
start = start !== undefined ? start : 0;
var parser = new parse.Parser(data, start);
var entries = [];
var operands = [];
size = size !== undefined ? size : data.length;
while (parser.relativeOffset < size) {
var op = parser.parseByte();
// The first byte for each dict item distinguishes between operator (key) and operand (value).
// Values <= 21 are operators.
if (op <= 21) {
// Two-byte operators have an initial escape byte of 12.
if (op === 12) {
op = 1200 + parser.parseByte();
}
entries.push([op, operands]);
operands = [];
} else {
// Since the operands (values) come before the operators (keys), we store all operands in a list
// until we encounter an operator.
operands.push(parseOperand(parser, op));
}
}
return entriesToObject(entries);
}
// Given a String Index (SID), return the value of the string.
// Strings below index 392 are standard CFF strings and are not encoded in the font.
function getCFFString(strings, index) {
if (index <= 390) {
index = cffStandardStrings[index];
} else {
index = strings[index - 391];
}
return index;
}
// Interpret a dictionary and return a new dictionary with readable keys and values for missing entries.
// This function takes `meta` which is a list of objects containing `operand`, `name` and `default`.
function interpretDict(dict, meta, strings) {
var newDict = {};
var value;
// Because we also want to include missing values, we start out from the meta list
// and lookup values in the dict.
for (var i = 0; i < meta.length; i += 1) {
var m = meta[i];
if (Array.isArray(m.type)) {
var values = [];
values.length = m.type.length;
for (var j = 0; j < m.type.length; j++) {
value = dict[m.op] !== undefined ? dict[m.op][j] : undefined;
if (value === undefined) {
value =
m.value !== undefined && m.value[j] !== undefined
? m.value[j]
: null;
}
if (m.type[j] === 'SID') {
value = getCFFString(strings, value);
}
values[j] = value;
}
newDict[m.name] = values;
} else {
value = dict[m.op];
if (value === undefined) {
value = m.value !== undefined ? m.value : null;
}
if (m.type === 'SID') {
value = getCFFString(strings, value);
}
newDict[m.name] = value;
}
}
return newDict;
}
// Parse the CFF header.
function parseCFFHeader(data, start) {
var header = {};
header.formatMajor = parse.getCard8(data, start);
header.formatMinor = parse.getCard8(data, start + 1);
header.size = parse.getCard8(data, start + 2);
header.offsetSize = parse.getCard8(data, start + 3);
header.startOffset = start;
header.endOffset = start + 4;
return header;
}
var TOP_DICT_META = [
{ name: 'version', op: 0, type: 'SID' },
{ name: 'notice', op: 1, type: 'SID' },
{ name: 'copyright', op: 1200, type: 'SID' },
{ name: 'fullName', op: 2, type: 'SID' },
{ name: 'familyName', op: 3, type: 'SID' },
{ name: 'weight', op: 4, type: 'SID' },
{ name: 'isFixedPitch', op: 1201, type: 'number', value: 0 },
{ name: 'italicAngle', op: 1202, type: 'number', value: 0 },
{ name: 'underlinePosition', op: 1203, type: 'number', value: -100 },
{ name: 'underlineThickness', op: 1204, type: 'number', value: 50 },
{ name: 'paintType', op: 1205, type: 'number', value: 0 },
{ name: 'charstringType', op: 1206, type: 'number', value: 2 },
{
name: 'fontMatrix',
op: 1207,
type: ['real', 'real', 'real', 'real', 'real', 'real'],
value: [0.001, 0, 0, 0.001, 0, 0]
},
{ name: 'uniqueId', op: 13, type: 'number' },
{
name: 'fontBBox',
op: 5,
type: ['number', 'number', 'number', 'number'],
value: [0, 0, 0, 0]
},
{ name: 'strokeWidth', op: 1208, type: 'number', value: 0 },
{ name: 'xuid', op: 14, type: [], value: null },
{ name: 'charset', op: 15, type: 'offset', value: 0 },
{ name: 'encoding', op: 16, type: 'offset', value: 0 },
{ name: 'charStrings', op: 17, type: 'offset', value: 0 },
{ name: 'private', op: 18, type: ['number', 'offset'], value: [0, 0] },
{ name: 'ros', op: 1230, type: ['SID', 'SID', 'number'] },
{ name: 'cidFontVersion', op: 1231, type: 'number', value: 0 },
{ name: 'cidFontRevision', op: 1232, type: 'number', value: 0 },
{ name: 'cidFontType', op: 1233, type: 'number', value: 0 },
{ name: 'cidCount', op: 1234, type: 'number', value: 8720 },
{ name: 'uidBase', op: 1235, type: 'number' },
{ name: 'fdArray', op: 1236, type: 'offset' },
{ name: 'fdSelect', op: 1237, type: 'offset' },
{ name: 'fontName', op: 1238, type: 'SID' }
];
var PRIVATE_DICT_META = [
{ name: 'subrs', op: 19, type: 'offset', value: 0 },
{ name: 'defaultWidthX', op: 20, type: 'number', value: 0 },
{ name: 'nominalWidthX', op: 21, type: 'number', value: 0 }
];
// Parse the CFF top dictionary. A CFF table can contain multiple fonts, each with their own top dictionary.
// The top dictionary contains the essential metadata for the font, together with the private dictionary.
function parseCFFTopDict(data, strings) {
var dict = parseCFFDict(data, 0, data.byteLength);
return interpretDict(dict, TOP_DICT_META, strings);
}
// Parse the CFF private dictionary. We don't fully parse out all the values, only the ones we need.
function parseCFFPrivateDict(data, start, size, strings) {
var dict = parseCFFDict(data, start, size);
return interpretDict(dict, PRIVATE_DICT_META, strings);
}
// Returns a list of "Top DICT"s found using an INDEX list.
// Used to read both the usual high-level Top DICTs and also the FDArray
// discovered inside CID-keyed fonts. When a Top DICT has a reference to
// a Private DICT that is read and saved into the Top DICT.
//
// In addition to the expected/optional values as outlined in TOP_DICT_META
// the following values might be saved into the Top DICT.
//
// _subrs [] array of local CFF subroutines from Private DICT
// _subrsBias bias value computed from number of subroutines
// (see calcCFFSubroutineBias() and parseCFFCharstring())
// _defaultWidthX default widths for CFF characters
// _nominalWidthX bias added to width embedded within glyph description
//
// _privateDict saved copy of parsed Private DICT from Top DICT
function gatherCFFTopDicts(data, start, cffIndex, strings) {
var topDictArray = [];
for (var iTopDict = 0; iTopDict < cffIndex.length; iTopDict += 1) {
var topDictData = new DataView(new Uint8Array(cffIndex[iTopDict]).buffer);
var topDict = parseCFFTopDict(topDictData, strings);
topDict._subrs = [];
topDict._subrsBias = 0;
var privateSize = topDict.private[0];
var privateOffset = topDict.private[1];
if (privateSize !== 0 && privateOffset !== 0) {
var privateDict = parseCFFPrivateDict(
data,
privateOffset + start,
privateSize,
strings
);
topDict._defaultWidthX = privateDict.defaultWidthX;
topDict._nominalWidthX = privateDict.nominalWidthX;
if (privateDict.subrs !== 0) {
var subrOffset = privateOffset + privateDict.subrs;
var subrIndex = parseCFFIndex(data, subrOffset + start);
topDict._subrs = subrIndex.objects;
topDict._subrsBias = calcCFFSubroutineBias(topDict._subrs);
}
topDict._privateDict = privateDict;
}
topDictArray.push(topDict);
}
return topDictArray;
}
// Parse the CFF charset table, which contains internal names for all the glyphs.
// This function will return a list of glyph names.
// See Adobe TN #5176 chapter 13, "Charsets".
function parseCFFCharset(data, start, nGlyphs, strings) {
var sid;
var count;
var parser = new parse.Parser(data, start);
// The .notdef glyph is not included, so subtract 1.
nGlyphs -= 1;
var charset = ['.notdef'];
var format = parser.parseCard8();
if (format === 0) {
for (var i = 0; i < nGlyphs; i += 1) {
sid = parser.parseSID();
charset.push(getCFFString(strings, sid));
}
} else if (format === 1) {
while (charset.length <= nGlyphs) {
sid = parser.parseSID();
count = parser.parseCard8();
for (var i$1 = 0; i$1 <= count; i$1 += 1) {
charset.push(getCFFString(strings, sid));
sid += 1;
}
}
} else if (format === 2) {
while (charset.length <= nGlyphs) {
sid = parser.parseSID();
count = parser.parseCard16();
for (var i$2 = 0; i$2 <= count; i$2 += 1) {
charset.push(getCFFString(strings, sid));
sid += 1;
}
}
} else {
throw new Error('Unknown charset format ' + format);
}
return charset;
}
// Parse the CFF encoding data. Only one encoding can be specified per font.
// See Adobe TN #5176 chapter 12, "Encodings".
function parseCFFEncoding(data, start, charset) {
var code;
var enc = {};
var parser = new parse.Parser(data, start);
var format = parser.parseCard8();
if (format === 0) {
var nCodes = parser.parseCard8();
for (var i = 0; i < nCodes; i += 1) {
code = parser.parseCard8();
enc[code] = i;
}
} else if (format === 1) {
var nRanges = parser.parseCard8();
code = 1;
for (var i$1 = 0; i$1 < nRanges; i$1 += 1) {
var first = parser.parseCard8();
var nLeft = parser.parseCard8();
for (var j = first; j <= first + nLeft; j += 1) {
enc[j] = code;
code += 1;
}
}
} else {
throw new Error('Unknown encoding format ' + format);
}
return new CffEncoding(enc, charset);
}
// Take in charstring code and return a Glyph object.
// The encoding is described in the Type 2 Charstring Format
// https://www.microsoft.com/typography/OTSPEC/charstr2.htm
function parseCFFCharstring(font, glyph, code) {
var c1x;
var c1y;
var c2x;
var c2y;
var p = new Path();
var stack = [];
var nStems = 0;
var haveWidth = false;
var open = false;
var x = 0;
var y = 0;
var subrs;
var subrsBias;
var defaultWidthX;
var nominalWidthX;
if (font.isCIDFont) {
var fdIndex = font.tables.cff.topDict._fdSelect[glyph.index];
var fdDict = font.tables.cff.topDict._fdArray[fdIndex];
subrs = fdDict._subrs;
subrsBias = fdDict._subrsBias;
defaultWidthX = fdDict._defaultWidthX;
nominalWidthX = fdDict._nominalWidthX;
} else {
subrs = font.tables.cff.topDict._subrs;
subrsBias = font.tables.cff.topDict._subrsBias;
defaultWidthX = font.tables.cff.topDict._defaultWidthX;
nominalWidthX = font.tables.cff.topDict._nominalWidthX;
}
var width = defaultWidthX;
function newContour(x, y) {
if (open) {
p.closePath();
}
p.moveTo(x, y);
open = true;
}
function parseStems() {
var hasWidthArg;
// The number of stem operators on the stack is always even.
// If the value is uneven, that means a width is specified.
hasWidthArg = stack.length % 2 !== 0;
if (hasWidthArg && !haveWidth) {
width = stack.shift() + nominalWidthX;
}
nStems += stack.length >> 1;
stack.length = 0;
haveWidth = true;
}
function parse$$1(code) {
var b1;
var b2;
var b3;
var b4;
var codeIndex;
var subrCode;
var jpx;
var jpy;
var c3x;
var c3y;
var c4x;
var c4y;
var i = 0;
while (i < code.length) {
var v = code[i];
i += 1;
switch (v) {
case 1: // hstem
parseStems();
break;
case 3: // vstem
parseStems();
break;
case 4: // vmoveto
if (stack.length > 1 && !haveWidth) {
width = stack.shift() + nominalWidthX;
haveWidth = true;
}
y += stack.pop();
newContour(x, y);
break;
case 5: // rlineto
while (stack.length > 0) {
x += stack.shift();
y += stack.shift();
p.lineTo(x, y);
}
break;
case 6: // hlineto
while (stack.length > 0) {
x += stack.shift();
p.lineTo(x, y);
if (stack.length === 0) {
break;
}
y += stack.shift();
p.lineTo(x, y);
}
break;
case 7: // vlineto
while (stack.length > 0) {
y += stack.shift();
p.lineTo(x, y);
if (stack.length === 0) {
break;
}
x += stack.shift();
p.lineTo(x, y);
}
break;
case 8: // rrcurveto
while (stack.length > 0) {
c1x = x + stack.shift();
c1y = y + stack.shift();
c2x = c1x + stack.shift();
c2y = c1y + stack.shift();
x = c2x + stack.shift();
y = c2y + stack.shift();
p.curveTo(c1x, c1y, c2x, c2y, x, y);
}
break;
case 10: // callsubr
codeIndex = stack.pop() + subrsBias;
subrCode = subrs[codeIndex];
if (subrCode) {
parse$$1(subrCode);
}
break;
case 11: // return
return;
case 12: // flex operators
v = code[i];
i += 1;
switch (v) {
case 35: // flex
// |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 dx6 dy6 fd flex (12 35) |-
c1x = x + stack.shift(); // dx1
c1y = y + stack.shift(); // dy1
c2x = c1x + stack.shift(); // dx2
c2y = c1y + stack.shift(); // dy2
jpx = c2x + stack.shift(); // dx3
jpy = c2y + stack.shift(); // dy3
c3x = jpx + stack.shift(); // dx4
c3y = jpy + stack.shift(); // dy4
c4x = c3x + stack.shift(); // dx5
c4y = c3y + stack.shift(); // dy5
x = c4x + stack.shift(); // dx6
y = c4y + stack.shift(); // dy6
stack.shift(); // flex depth
p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy);
p.curveTo(c3x, c3y, c4x, c4y, x, y);
break;
case 34: // hflex
// |- dx1 dx2 dy2 dx3 dx4 dx5 dx6 hflex (12 34) |-
c1x = x + stack.shift(); // dx1
c1y = y; // dy1
c2x = c1x + stack.shift(); // dx2
c2y = c1y + stack.shift(); // dy2
jpx = c2x + stack.shift(); // dx3
jpy = c2y; // dy3
c3x = jpx + stack.shift(); // dx4
c3y = c2y; // dy4
c4x = c3x + stack.shift(); // dx5
c4y = y; // dy5
x = c4x + stack.shift(); // dx6
p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy);
p.curveTo(c3x, c3y, c4x, c4y, x, y);
break;
case 36: // hflex1
// |- dx1 dy1 dx2 dy2 dx3 dx4 dx5 dy5 dx6 hflex1 (12 36) |-
c1x = x + stack.shift(); // dx1
c1y = y + stack.shift(); // dy1
c2x = c1x + stack.shift(); // dx2
c2y = c1y + stack.shift(); // dy2
jpx = c2x + stack.shift(); // dx3
jpy = c2y; // dy3
c3x = jpx + stack.shift(); // dx4
c3y = c2y; // dy4
c4x = c3x + stack.shift(); // dx5
c4y = c3y + stack.shift(); // dy5
x = c4x + stack.shift(); // dx6
p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy);
p.curveTo(c3x, c3y, c4x, c4y, x, y);
break;
case 37: // flex1
// |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 d6 flex1 (12 37) |-
c1x = x + stack.shift(); // dx1
c1y = y + stack.shift(); // dy1
c2x = c1x + stack.shift(); // dx2
c2y = c1y + stack.shift(); // dy2
jpx = c2x + stack.shift(); // dx3
jpy = c2y + stack.shift(); // dy3
c3x = jpx + stack.shift(); // dx4
c3y = jpy + stack.shift(); // dy4
c4x = c3x + stack.shift(); // dx5
c4y = c3y + stack.shift(); // dy5
if (Math.abs(c4x - x) > Math.abs(c4y - y)) {
x = c4x + stack.shift();
} else {
y = c4y + stack.shift();
}
p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy);
p.curveTo(c3x, c3y, c4x, c4y, x, y);
break;
default:
console.log(
'Glyph ' + glyph.index + ': unknown operator ' + 1200 + v
);
stack.length = 0;
}
break;
case 14: // endchar
if (stack.length > 0 && !haveWidth) {
width = stack.shift() + nominalWidthX;
haveWidth = true;
}
if (open) {
p.closePath();
open = false;
}
break;
case 18: // hstemhm
parseStems();
break;
case 19: // hintmask
case 20: // cntrmask
parseStems();
i += (nStems + 7) >> 3;
break;
case 21: // rmoveto
if (stack.length > 2 && !haveWidth) {
width = stack.shift() + nominalWidthX;
haveWidth = true;
}
y += stack.pop();
x += stack.pop();
newContour(x, y);
break;
case 22: // hmoveto
if (stack.length > 1 && !haveWidth) {
width = stack.shift() + nominalWidthX;
haveWidth = true;
}
x += stack.pop();
newContour(x, y);
break;
case 23: // vstemhm
parseStems();
break;
case 24: // rcurveline
while (stack.length > 2) {
c1x = x + stack.shift();
c1y = y + stack.shift();
c2x = c1x + stack.shift();
c2y = c1y + stack.shift();
x = c2x + stack.shift();
y = c2y + stack.shift();
p.curveTo(c1x, c1y, c2x, c2y, x, y);
}
x += stack.shift();
y += stack.shift();
p.lineTo(x, y);
break;
case 25: // rlinecurve
while (stack.length > 6) {
x += stack.shift();
y += stack.shift();
p.lineTo(x, y);
}
c1x = x + stack.shift();
c1y = y + stack.shift();
c2x = c1x + stack.shift();
c2y = c1y + stack.shift();
x = c2x + stack.shift();
y = c2y + stack.shift();
p.curveTo(c1x, c1y, c2x, c2y, x, y);
break;
case 26: // vvcurveto
if (stack.length % 2) {
x += stack.shift();
}
while (stack.length > 0) {
c1x = x;
c1y = y + stack.shift();
c2x = c1x + stack.shift();
c2y = c1y + stack.shift();
x = c2x;
y = c2y + stack.shift();
p.curveTo(c1x, c1y, c2x, c2y, x, y);
}
break;
case 27: // hhcurveto
if (stack.length % 2) {
y += stack.shift();
}
while (stack.length > 0) {
c1x = x + stack.shift();
c1y = y;
c2x = c1x + stack.shift();
c2y = c1y + stack.shift();
x = c2x + stack.shift();
y = c2y;
p.curveTo(c1x, c1y, c2x, c2y, x, y);
}
break;
case 28: // shortint
b1 = code[i];
b2 = code[i + 1];
stack.push(((b1 << 24) | (b2 << 16)) >> 16);
i += 2;
break;
case 29: // callgsubr
codeIndex = stack.pop() + font.gsubrsBias;
subrCode = font.gsubrs[codeIndex];
if (subrCode) {
parse$$1(subrCode);
}
break;
case 30: // vhcurveto
while (stack.length > 0) {
c1x = x;
c1y = y + stack.shift();
c2x = c1x + stack.shift();
c2y = c1y + stack.shift();
x = c2x + stack.shift();
y = c2y + (stack.length === 1 ? stack.shift() : 0);
p.curveTo(c1x, c1y, c2x, c2y, x, y);
if (stack.length === 0) {
break;
}
c1x = x + stack.shift();
c1y = y;
c2x = c1x + stack.shift();
c2y = c1y + stack.shift();
y = c2y + stack.shift();
x = c2x + (stack.length === 1 ? stack.shift() : 0);
p.curveTo(c1x, c1y, c2x, c2y, x, y);
}
break;
case 31: // hvcurveto
while (stack.length > 0) {
c1x = x + stack.shift();
c1y = y;
c2x = c1x + stack.shift();
c2y = c1y + stack.shift();
y = c2y + stack.shift();
x = c2x + (stack.length === 1 ? stack.shift() : 0);
p.curveTo(c1x, c1y, c2x, c2y, x, y);
if (stack.length === 0) {
break;
}
c1x = x;
c1y = y + stack.shift();
c2x = c1x + stack.shift();
c2y = c1y + stack.shift();
x = c2x + stack.shift();
y = c2y + (stack.length === 1 ? stack.shift() : 0);
p.curveTo(c1x, c1y, c2x, c2y, x, y);
}
break;
default:
if (v < 32) {
console.log('Glyph ' + glyph.index + ': unknown operator ' + v);
} else if (v < 247) {
stack.push(v - 139);
} else if (v < 251) {
b1 = code[i];
i += 1;
stack.push((v - 247) * 256 + b1 + 108);
} else if (v < 255) {
b1 = code[i];
i += 1;
stack.push(-(v - 251) * 256 - b1 - 108);
} else {
b1 = code[i];
b2 = code[i + 1];
b3 = code[i + 2];
b4 = code[i + 3];
i += 4;
stack.push(((b1 << 24) | (b2 << 16) | (b3 << 8) | b4) / 65536);
}
}
}
}
parse$$1(code);
glyph.advanceWidth = width;
return p;
}
function parseCFFFDSelect(data, start, nGlyphs, fdArrayCount) {
var fdSelect = [];
var fdIndex;
var parser = new parse.Parser(data, start);
var format = parser.parseCard8();
if (format === 0) {
// Simple list of nGlyphs elements
for (var iGid = 0; iGid < nGlyphs; iGid++) {
fdIndex = parser.parseCard8();
if (fdIndex >= fdArrayCount) {
throw new Error(
'CFF table CID Font FDSelect has bad FD index value ' +
fdIndex +
' (FD count ' +
fdArrayCount +
')'
);
}
fdSelect.push(fdIndex);
}
} else if (format === 3) {
// Ranges
var nRanges = parser.parseCard16();
var first = parser.parseCard16();
if (first !== 0) {
throw new Error(
'CFF Table CID Font FDSelect format 3 range has bad initial GID ' +
first
);
}
var next;
for (var iRange = 0; iRange < nRanges; iRange++) {
fdIndex = parser.parseCard8();
next = parser.parseCard16();
if (fdIndex >= fdArrayCount) {
throw new Error(
'CFF table CID Font FDSelect has bad FD index value ' +
fdIndex +
' (FD count ' +
fdArrayCount +
')'
);
}
if (next > nGlyphs) {
throw new Error(
'CFF Table CID Font FDSelect format 3 range has bad GID ' + next
);
}
for (; first < next; first++) {
fdSelect.push(fdIndex);
}
first = next;
}
if (next !== nGlyphs) {
throw new Error(
'CFF Table CID Font FDSelect format 3 range has bad final GID ' + next
);
}
} else {
throw new Error(
'CFF Table CID Font FDSelect table has unsupported format ' + format
);
}
return fdSelect;
}
// Parse the `CFF` table, which contains the glyph outlines in PostScript format.
function parseCFFTable(data, start, font) {
font.tables.cff = {};
var header = parseCFFHeader(data, start);
var nameIndex = parseCFFIndex(data, header.endOffset, parse.bytesToString);
var topDictIndex = parseCFFIndex(data, nameIndex.endOffset);
var stringIndex = parseCFFIndex(
data,
topDictIndex.endOffset,
parse.bytesToString
);
var globalSubrIndex = parseCFFIndex(data, stringIndex.endOffset);
font.gsubrs = globalSubrIndex.objects;
font.gsubrsBias = calcCFFSubroutineBias(font.gsubrs);
var topDictArray = gatherCFFTopDicts(
data,
start,
topDictIndex.objects,
stringIndex.objects
);
if (topDictArray.length !== 1) {
throw new Error(
"CFF table has too many fonts in 'FontSet' - count of fonts NameIndex.length = " +
topDictArray.length
);
}
var topDict = topDictArray[0];
font.tables.cff.topDict = topDict;
if (topDict._privateDict) {
font.defaultWidthX = topDict._privateDict.defaultWidthX;
font.nominalWidthX = topDict._privateDict.nominalWidthX;
}
if (topDict.ros[0] !== undefined && topDict.ros[1] !== undefined) {
font.isCIDFont = true;
}
if (font.isCIDFont) {
var fdArrayOffset = topDict.fdArray;
var fdSelectOffset = topDict.fdSelect;
if (fdArrayOffset === 0 || fdSelectOffset === 0) {
throw new Error(
'Font is marked as a CID font, but FDArray and/or FDSelect information is missing'
);
}
fdArrayOffset += start;
var fdArrayIndex = parseCFFIndex(data, fdArrayOffset);
var fdArray = gatherCFFTopDicts(
data,
start,
fdArrayIndex.objects,
stringIndex.objects
);
topDict._fdArray = fdArray;
fdSelectOffset += start;
topDict._fdSelect = parseCFFFDSelect(
data,
fdSelectOffset,
font.numGlyphs,
fdArray.length
);
}
var privateDictOffset = start + topDict.private[1];
var privateDict = parseCFFPrivateDict(
data,
privateDictOffset,
topDict.private[0],
stringIndex.objects
);
font.defaultWidthX = privateDict.defaultWidthX;
font.nominalWidthX = privateDict.nominalWidthX;
if (privateDict.subrs !== 0) {
var subrOffset = privateDictOffset + privateDict.subrs;
var subrIndex = parseCFFIndex(data, subrOffset);
font.subrs = subrIndex.objects;
font.subrsBias = calcCFFSubroutineBias(font.subrs);
} else {
font.subrs = [];
font.subrsBias = 0;
}
// Offsets in the top dict are relative to the beginning of the CFF data, so add the CFF start offset.
var charStringsIndex = parseCFFIndex(data, start + topDict.charStrings);
font.nGlyphs = charStringsIndex.objects.length;
var charset = parseCFFCharset(
data,
start + topDict.charset,
font.nGlyphs,
stringIndex.objects
);
if (topDict.encoding === 0) {
// Standard encoding
font.cffEncoding = new CffEncoding(cffStandardEncoding, charset);
} else if (topDict.encoding === 1) {
// Expert encoding
font.cffEncoding = new CffEncoding(cffExpertEncoding, charset);
} else {
font.cffEncoding = parseCFFEncoding(
data,
start + topDict.encoding,
charset
);
}
// Prefer the CMAP encoding to the CFF encoding.
font.encoding = font.encoding || font.cffEncoding;
font.glyphs = new glyphset.GlyphSet(font);
for (var i = 0; i < font.nGlyphs; i += 1) {
var charString = charStringsIndex.objects[i];
font.glyphs.push(
i,
glyphset.cffGlyphLoader(font, i, parseCFFCharstring, charString)
);
}
}
// Convert a string to a String ID (SID).
// The list of strings is modified in place.
function encodeString(s, strings) {
var sid;
// Is the string in the CFF standard strings?
var i = cffStandardStrings.indexOf(s);
if (i >= 0) {
sid = i;
}
// Is the string already in the string index?
i = strings.indexOf(s);
if (i >= 0) {
sid = i + cffStandardStrings.length;
} else {
sid = cffStandardStrings.length + strings.length;
strings.push(s);
}
return sid;
}
function makeHeader() {
return new table.Record('Header', [
{ name: 'major', type: 'Card8', value: 1 },
{ name: 'minor', type: 'Card8', value: 0 },
{ name: 'hdrSize', type: 'Card8', value: 4 },
{ name: 'major', type: 'Card8', value: 1 }
]);
}
function makeNameIndex(fontNames) {
var t = new table.Record('Name INDEX', [
{ name: 'names', type: 'INDEX', value: [] }
]);
t.names = [];
for (var i = 0; i < fontNames.length; i += 1) {
t.names.push({ name: 'name_' + i, type: 'NAME', value: fontNames[i] });
}
return t;
}
// Given a dictionary's metadata, create a DICT structure.
function makeDict(meta, attrs, strings) {
var m = {};
for (var i = 0; i < meta.length; i += 1) {
var entry = meta[i];
var value = attrs[entry.name];
if (value !== undefined && !equals(value, entry.value)) {
if (entry.type === 'SID') {
value = encodeString(value, strings);
}
m[entry.op] = { name: entry.name, type: entry.type, value: value };
}
}
return m;
}
// The Top DICT houses the global font attributes.
function makeTopDict(attrs, strings) {
var t = new table.Record('Top DICT', [
{ name: 'dict', type: 'DICT', value: {} }
]);
t.dict = makeDict(TOP_DICT_META, attrs, strings);
return t;
}
function makeTopDictIndex(topDict) {
var t = new table.Record('Top DICT INDEX', [
{ name: 'topDicts', type: 'INDEX', value: [] }
]);
t.topDicts = [{ name: 'topDict_0', type: 'TABLE', value: topDict }];
return t;
}
function makeStringIndex(strings) {
var t = new table.Record('String INDEX', [
{ name: 'strings', type: 'INDEX', value: [] }
]);
t.strings = [];
for (var i = 0; i < strings.length; i += 1) {
t.strings.push({
name: 'string_' + i,
type: 'STRING',
value: strings[i]
});
}
return t;
}
function makeGlobalSubrIndex() {
// Currently we don't use subroutines.
return new table.Record('Global Subr INDEX', [
{ name: 'subrs', type: 'INDEX', value: [] }
]);
}
function makeCharsets(glyphNames, strings) {
var t = new table.Record('Charsets', [
{ name: 'format', type: 'Card8', value: 0 }
]);
for (var i = 0; i < glyphNames.length; i += 1) {
var glyphName = glyphNames[i];
var glyphSID = encodeString(glyphName, strings);
t.fields.push({ name: 'glyph_' + i, type: 'SID', value: glyphSID });
}
return t;
}
function glyphToOps(glyph) {
var ops = [];
var path = glyph.path;
ops.push({ name: 'width', type: 'NUMBER', value: glyph.advanceWidth });
var x = 0;
var y = 0;
for (var i = 0; i < path.commands.length; i += 1) {
var dx = void 0;
var dy = void 0;
var cmd = path.commands[i];
if (cmd.type === 'Q') {
// CFF only supports bézier curves, so convert the quad to a bézier.
var _13 = 1 / 3;
var _23 = 2 / 3;
// We're going to create a new command so we don't change the original path.
cmd = {
type: 'C',
x: cmd.x,
y: cmd.y,
x1: _13 * x + _23 * cmd.x1,
y1: _13 * y + _23 * cmd.y1,
x2: _13 * cmd.x + _23 * cmd.x1,
y2: _13 * cmd.y + _23 * cmd.y1
};
}
if (cmd.type === 'M') {
dx = Math.round(cmd.x - x);
dy = Math.round(cmd.y - y);
ops.push({ name: 'dx', type: 'NUMBER', value: dx });
ops.push({ name: 'dy', type: 'NUMBER', value: dy });
ops.push({ name: 'rmoveto', type: 'OP', value: 21 });
x = Math.round(cmd.x);
y = Math.round(cmd.y);
} else if (cmd.type === 'L') {
dx = Math.round(cmd.x - x);
dy = Math.round(cmd.y - y);
ops.push({ name: 'dx', type: 'NUMBER', value: dx });
ops.push({ name: 'dy', type: 'NUMBER', value: dy });
ops.push({ name: 'rlineto', type: 'OP', value: 5 });
x = Math.round(cmd.x);
y = Math.round(cmd.y);
} else if (cmd.type === 'C') {
var dx1 = Math.round(cmd.x1 - x);
var dy1 = Math.round(cmd.y1 - y);
var dx2 = Math.round(cmd.x2 - cmd.x1);
var dy2 = Math.round(cmd.y2 - cmd.y1);
dx = Math.round(cmd.x - cmd.x2);
dy = Math.round(cmd.y - cmd.y2);
ops.push({ name: 'dx1', type: 'NUMBER', value: dx1 });
ops.push({ name: 'dy1', type: 'NUMBER', value: dy1 });
ops.push({ name: 'dx2', type: 'NUMBER', value: dx2 });
ops.push({ name: 'dy2', type: 'NUMBER', value: dy2 });
ops.push({ name: 'dx', type: 'NUMBER', value: dx });
ops.push({ name: 'dy', type: 'NUMBER', value: dy });
ops.push({ name: 'rrcurveto', type: 'OP', value: 8 });
x = Math.round(cmd.x);
y = Math.round(cmd.y);
}
// Contours are closed automatically.
}
ops.push({ name: 'endchar', type: 'OP', value: 14 });
return ops;
}
function makeCharStringsIndex(glyphs) {
var t = new table.Record('CharStrings INDEX', [
{ name: 'charStrings', type: 'INDEX', value: [] }
]);
for (var i = 0; i < glyphs.length; i += 1) {
var glyph = glyphs.get(i);
var ops = glyphToOps(glyph);
t.charStrings.push({ name: glyph.name, type: 'CHARSTRING', value: ops });
}
return t;
}
function makePrivateDict(attrs, strings) {
var t = new table.Record('Private DICT', [
{ name: 'dict', type: 'DICT', value: {} }
]);
t.dict = makeDict(PRIVATE_DICT_META, attrs, strings);
return t;
}
function makeCFFTable(glyphs, options) {
var t = new table.Table('CFF ', [
{ name: 'header', type: 'RECORD' },
{ name: 'nameIndex', type: 'RECORD' },
{ name: 'topDictIndex', type: 'RECORD' },
{ name: 'stringIndex', type: 'RECORD' },
{ name: 'globalSubrIndex', type: 'RECORD' },
{ name: 'charsets', type: 'RECORD' },
{ name: 'charStringsIndex', type: 'RECORD' },
{ name: 'privateDict', type: 'RECORD' }
]);
var fontScale = 1 / options.unitsPerEm;
// We use non-zero values for the offsets so that the DICT encodes them.
// This is important because the size of the Top DICT plays a role in offset calculation,
// and the size shouldn't change after we've written correct offsets.
var attrs = {
version: options.version,
fullName: options.fullName,
familyName: options.familyName,
weight: options.weightName,
fontBBox: options.fontBBox || [0, 0, 0, 0],
fontMatrix: [fontScale, 0, 0, fontScale, 0, 0],
charset: 999,
encoding: 0,
charStrings: 999,
private: [0, 999]
};
var privateAttrs = {};
var glyphNames = [];
var glyph;
// Skip first glyph (.notdef)
for (var i = 1; i < glyphs.length; i += 1) {
glyph = glyphs.get(i);
glyphNames.push(glyph.name);
}
var strings = [];
t.header = makeHeader();
t.nameIndex = makeNameIndex([options.postScriptName]);
var topDict = makeTopDict(attrs, strings);
t.topDictIndex = makeTopDictIndex(topDict);
t.globalSubrIndex = makeGlobalSubrIndex();
t.charsets = makeCharsets(glyphNames, strings);
t.charStringsIndex = makeCharStringsIndex(glyphs);
t.privateDict = makePrivateDict(privateAttrs, strings);
// Needs to come at the end, to encode all custom strings used in the font.
t.stringIndex = makeStringIndex(strings);
var startOffset =
t.header.sizeOf() +
t.nameIndex.sizeOf() +
t.topDictIndex.sizeOf() +
t.stringIndex.sizeOf() +
t.globalSubrIndex.sizeOf();
attrs.charset = startOffset;
// We use the CFF standard encoding; proper encoding will be handled in cmap.
attrs.encoding = 0;
attrs.charStrings = attrs.charset + t.charsets.sizeOf();
attrs.private[1] = attrs.charStrings + t.charStringsIndex.sizeOf();
// Recreate the Top DICT INDEX with the correct offsets.
topDict = makeTopDict(attrs, strings);
t.topDictIndex = makeTopDictIndex(topDict);
return t;
}
var cff = { parse: parseCFFTable, make: makeCFFTable };
// The `head` table contains global information about the font.
// Parse the header `head` table
function parseHeadTable(data, start) {
var head = {};
var p = new parse.Parser(data, start);
head.version = p.parseVersion();
head.fontRevision = Math.round(p.parseFixed() * 1000) / 1000;
head.checkSumAdjustment = p.parseULong();
head.magicNumber = p.parseULong();
check.argument(
head.magicNumber === 0x5f0f3cf5,
'Font header has wrong magic number.'
);
head.flags = p.parseUShort();
head.unitsPerEm = p.parseUShort();
head.created = p.parseLongDateTime();
head.modified = p.parseLongDateTime();
head.xMin = p.parseShort();
head.yMin = p.parseShort();
head.xMax = p.parseShort();
head.yMax = p.parseShort();
head.macStyle = p.parseUShort();
head.lowestRecPPEM = p.parseUShort();
head.fontDirectionHint = p.parseShort();
head.indexToLocFormat = p.parseShort();
head.glyphDataFormat = p.parseShort();
return head;
}
function makeHeadTable(options) {
// Apple Mac timestamp epoch is 01/01/1904 not 01/01/1970
var timestamp = Math.round(new Date().getTime() / 1000) + 2082844800;
var createdTimestamp = timestamp;
if (options.createdTimestamp) {
createdTimestamp = options.createdTimestamp + 2082844800;
}
return new table.Table(
'head',
[
{ name: 'version', type: 'FIXED', value: 0x00010000 },
{ name: 'fontRevision', type: 'FIXED', value: 0x00010000 },
{ name: 'checkSumAdjustment', type: 'ULONG', value: 0 },
{ name: 'magicNumber', type: 'ULONG', value: 0x5f0f3cf5 },
{ name: 'flags', type: 'USHORT', value: 0 },
{ name: 'unitsPerEm', type: 'USHORT', value: 1000 },
{ name: 'created', type: 'LONGDATETIME', value: createdTimestamp },
{ name: 'modified', type: 'LONGDATETIME', value: timestamp },
{ name: 'xMin', type: 'SHORT', value: 0 },
{ name: 'yMin', type: 'SHORT', value: 0 },
{ name: 'xMax', type: 'SHORT', value: 0 },
{ name: 'yMax', type: 'SHORT', value: 0 },
{ name: 'macStyle', type: 'USHORT', value: 0 },
{ name: 'lowestRecPPEM', type: 'USHORT', value: 0 },
{ name: 'fontDirectionHint', type: 'SHORT', value: 2 },
{ name: 'indexToLocFormat', type: 'SHORT', value: 0 },
{ name: 'glyphDataFormat', type: 'SHORT', value: 0 }
],
options
);
}
var head = { parse: parseHeadTable, make: makeHeadTable };
// The `hhea` table contains information for horizontal layout.
// Parse the horizontal header `hhea` table
function parseHheaTable(data, start) {
var hhea = {};
var p = new parse.Parser(data, start);
hhea.version = p.parseVersion();
hhea.ascender = p.parseShort();
hhea.descender = p.parseShort();
hhea.lineGap = p.parseShort();
hhea.advanceWidthMax = p.parseUShort();
hhea.minLeftSideBearing = p.parseShort();
hhea.minRightSideBearing = p.parseShort();
hhea.xMaxExtent = p.parseShort();
hhea.caretSlopeRise = p.parseShort();
hhea.caretSlopeRun = p.parseShort();
hhea.caretOffset = p.parseShort();
p.relativeOffset += 8;
hhea.metricDataFormat = p.parseShort();
hhea.numberOfHMetrics = p.parseUShort();
return hhea;
}
function makeHheaTable(options) {
return new table.Table(
'hhea',
[
{ name: 'version', type: 'FIXED', value: 0x00010000 },
{ name: 'ascender', type: 'FWORD', value: 0 },
{ name: 'descender', type: 'FWORD', value: 0 },
{ name: 'lineGap', type: 'FWORD', value: 0 },
{ name: 'advanceWidthMax', type: 'UFWORD', value: 0 },
{ name: 'minLeftSideBearing', type: 'FWORD', value: 0 },
{ name: 'minRightSideBearing', type: 'FWORD', value: 0 },
{ name: 'xMaxExtent', type: 'FWORD', value: 0 },
{ name: 'caretSlopeRise', type: 'SHORT', value: 1 },
{ name: 'caretSlopeRun', type: 'SHORT', value: 0 },
{ name: 'caretOffset', type: 'SHORT', value: 0 },
{ name: 'reserved1', type: 'SHORT', value: 0 },
{ name: 'reserved2', type: 'SHORT', value: 0 },
{ name: 'reserved3', type: 'SHORT', value: 0 },
{ name: 'reserved4', type: 'SHORT', value: 0 },
{ name: 'metricDataFormat', type: 'SHORT', value: 0 },
{ name: 'numberOfHMetrics', type: 'USHORT', value: 0 }
],
options
);
}
var hhea = { parse: parseHheaTable, make: makeHheaTable };
// The `hmtx` table contains the horizontal metrics for all glyphs.
// Parse the `hmtx` table, which contains the horizontal metrics for all glyphs.
// This function augments the glyph array, adding the advanceWidth and leftSideBearing to each glyph.
function parseHmtxTable(data, start, numMetrics, numGlyphs, glyphs) {
var advanceWidth;
var leftSideBearing;
var p = new parse.Parser(data, start);
for (var i = 0; i < numGlyphs; i += 1) {
// If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs.
if (i < numMetrics) {
advanceWidth = p.parseUShort();
leftSideBearing = p.parseShort();
}
var glyph = glyphs.get(i);
glyph.advanceWidth = advanceWidth;
glyph.leftSideBearing = leftSideBearing;
}
}
function makeHmtxTable(glyphs) {
var t = new table.Table('hmtx', []);
for (var i = 0; i < glyphs.length; i += 1) {
var glyph = glyphs.get(i);
var advanceWidth = glyph.advanceWidth || 0;
var leftSideBearing = glyph.leftSideBearing || 0;
t.fields.push({
name: 'advanceWidth_' + i,
type: 'USHORT',
value: advanceWidth
});
t.fields.push({
name: 'leftSideBearing_' + i,
type: 'SHORT',
value: leftSideBearing
});
}
return t;
}
var hmtx = { parse: parseHmtxTable, make: makeHmtxTable };
// The `ltag` table stores IETF BCP-47 language tags. It allows supporting
function makeLtagTable(tags) {
var result = new table.Table('ltag', [
{ name: 'version', type: 'ULONG', value: 1 },
{ name: 'flags', type: 'ULONG', value: 0 },
{ name: 'numTags', type: 'ULONG', value: tags.length }
]);
var stringPool = '';
var stringPoolOffset = 12 + tags.length * 4;
for (var i = 0; i < tags.length; ++i) {
var pos = stringPool.indexOf(tags[i]);
if (pos < 0) {
pos = stringPool.length;
stringPool += tags[i];
}
result.fields.push({
name: 'offset ' + i,
type: 'USHORT',
value: stringPoolOffset + pos
});
result.fields.push({
name: 'length ' + i,
type: 'USHORT',
value: tags[i].length
});
}
result.fields.push({
name: 'stringPool',
type: 'CHARARRAY',
value: stringPool
});
return result;
}
function parseLtagTable(data, start) {
var p = new parse.Parser(data, start);
var tableVersion = p.parseULong();
check.argument(tableVersion === 1, 'Unsupported ltag table version.');
// The 'ltag' specification does not define any flags; skip the field.
p.skip('uLong', 1);
var numTags = p.parseULong();
var tags = [];
for (var i = 0; i < numTags; i++) {
var tag = '';
var offset = start + p.parseUShort();
var length = p.parseUShort();
for (var j = offset; j < offset + length; ++j) {
tag += String.fromCharCode(data.getInt8(j));
}
tags.push(tag);
}
return tags;
}
var ltag = { make: makeLtagTable, parse: parseLtagTable };
// The `maxp` table establishes the memory requirements for the font.
// Parse the maximum profile `maxp` table.
function parseMaxpTable(data, start) {
var maxp = {};
var p = new parse.Parser(data, start);
maxp.version = p.parseVersion();
maxp.numGlyphs = p.parseUShort();
if (maxp.version === 1.0) {
maxp.maxPoints = p.parseUShort();
maxp.maxContours = p.parseUShort();
maxp.maxCompositePoints = p.parseUShort();
maxp.maxCompositeContours = p.parseUShort();
maxp.maxZones = p.parseUShort();
maxp.maxTwilightPoints = p.parseUShort();
maxp.maxStorage = p.parseUShort();
maxp.maxFunctionDefs = p.parseUShort();
maxp.maxInstructionDefs = p.parseUShort();
maxp.maxStackElements = p.parseUShort();
maxp.maxSizeOfInstructions = p.parseUShort();
maxp.maxComponentElements = p.parseUShort();
maxp.maxComponentDepth = p.parseUShort();
}
return maxp;
}
function makeMaxpTable(numGlyphs) {
return new table.Table('maxp', [
{ name: 'version', type: 'FIXED', value: 0x00005000 },
{ name: 'numGlyphs', type: 'USHORT', value: numGlyphs }
]);
}
var maxp = { parse: parseMaxpTable, make: makeMaxpTable };
// The `name` naming table.
// NameIDs for the name table.
var nameTableNames = [
'copyright', // 0
'fontFamily', // 1
'fontSubfamily', // 2
'uniqueID', // 3
'fullName', // 4
'version', // 5
'postScriptName', // 6
'trademark', // 7
'manufacturer', // 8
'designer', // 9
'description', // 10
'manufacturerURL', // 11
'designerURL', // 12
'license', // 13
'licenseURL', // 14
'reserved', // 15
'preferredFamily', // 16
'preferredSubfamily', // 17
'compatibleFullName', // 18
'sampleText', // 19
'postScriptFindFontName', // 20
'wwsFamily', // 21
'wwsSubfamily' // 22
];
var macLanguages = {
0: 'en',
1: 'fr',
2: 'de',
3: 'it',
4: 'nl',
5: 'sv',
6: 'es',
7: 'da',
8: 'pt',
9: 'no',
10: 'he',
11: 'ja',
12: 'ar',
13: 'fi',
14: 'el',
15: 'is',
16: 'mt',
17: 'tr',
18: 'hr',
19: 'zh-Hant',
20: 'ur',
21: 'hi',
22: 'th',
23: 'ko',
24: 'lt',
25: 'pl',
26: 'hu',
27: 'es',
28: 'lv',
29: 'se',
30: 'fo',
31: 'fa',
32: 'ru',
33: 'zh',
34: 'nl-BE',
35: 'ga',
36: 'sq',
37: 'ro',
38: 'cz',
39: 'sk',
40: 'si',
41: 'yi',
42: 'sr',
43: 'mk',
44: 'bg',
45: 'uk',
46: 'be',
47: 'uz',
48: 'kk',
49: 'az-Cyrl',
50: 'az-Arab',
51: 'hy',
52: 'ka',
53: 'mo',
54: 'ky',
55: 'tg',
56: 'tk',
57: 'mn-CN',
58: 'mn',
59: 'ps',
60: 'ks',
61: 'ku',
62: 'sd',
63: 'bo',
64: 'ne',
65: 'sa',
66: 'mr',
67: 'bn',
68: 'as',
69: 'gu',
70: 'pa',
71: 'or',
72: 'ml',
73: 'kn',
74: 'ta',
75: 'te',
76: 'si',
77: 'my',
78: 'km',
79: 'lo',
80: 'vi',
81: 'id',
82: 'tl',
83: 'ms',
84: 'ms-Arab',
85: 'am',
86: 'ti',
87: 'om',
88: 'so',
89: 'sw',
90: 'rw',
91: 'rn',
92: 'ny',
93: 'mg',
94: 'eo',
128: 'cy',
129: 'eu',
130: 'ca',
131: 'la',
132: 'qu',
133: 'gn',
134: 'ay',
135: 'tt',
136: 'ug',
137: 'dz',
138: 'jv',
139: 'su',
140: 'gl',
141: 'af',
142: 'br',
143: 'iu',
144: 'gd',
145: 'gv',
146: 'ga',
147: 'to',
148: 'el-polyton',
149: 'kl',
150: 'az',
151: 'nn'
};
// MacOS language ID → MacOS script ID
//
// Note that the script ID is not sufficient to determine what encoding
// to use in TrueType files. For some languages, MacOS used a modification
// of a mainstream script. For example, an Icelandic name would be stored
// with smRoman in the TrueType naming table, but the actual encoding
// is a special Icelandic version of the normal Macintosh Roman encoding.
// As another example, Inuktitut uses an 8-bit encoding for Canadian Aboriginal
// Syllables but MacOS had run out of available script codes, so this was
// done as a (pretty radical) "modification" of Ethiopic.
//
// http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt
var macLanguageToScript = {
0: 0, // langEnglish → smRoman
1: 0, // langFrench → smRoman
2: 0, // langGerman → smRoman
3: 0, // langItalian → smRoman
4: 0, // langDutch → smRoman
5: 0, // langSwedish → smRoman
6: 0, // langSpanish → smRoman
7: 0, // langDanish → smRoman
8: 0, // langPortuguese → smRoman
9: 0, // langNorwegian → smRoman
10: 5, // langHebrew → smHebrew
11: 1, // langJapanese → smJapanese
12: 4, // langArabic → smArabic
13: 0, // langFinnish → smRoman
14: 6, // langGreek → smGreek
15: 0, // langIcelandic → smRoman (modified)
16: 0, // langMaltese → smRoman
17: 0, // langTurkish → smRoman (modified)
18: 0, // langCroatian → smRoman (modified)
19: 2, // langTradChinese → smTradChinese
20: 4, // langUrdu → smArabic
21: 9, // langHindi → smDevanagari
22: 21, // langThai → smThai
23: 3, // langKorean → smKorean
24: 29, // langLithuanian → smCentralEuroRoman
25: 29, // langPolish → smCentralEuroRoman
26: 29, // langHungarian → smCentralEuroRoman
27: 29, // langEstonian → smCentralEuroRoman
28: 29, // langLatvian → smCentralEuroRoman
29: 0, // langSami → smRoman
30: 0, // langFaroese → smRoman (modified)
31: 4, // langFarsi → smArabic (modified)
32: 7, // langRussian → smCyrillic
33: 25, // langSimpChinese → smSimpChinese
34: 0, // langFlemish → smRoman
35: 0, // langIrishGaelic → smRoman (modified)
36: 0, // langAlbanian → smRoman
37: 0, // langRomanian → smRoman (modified)
38: 29, // langCzech → smCentralEuroRoman
39: 29, // langSlovak → smCentralEuroRoman
40: 0, // langSlovenian → smRoman (modified)
41: 5, // langYiddish → smHebrew
42: 7, // langSerbian → smCyrillic
43: 7, // langMacedonian → smCyrillic
44: 7, // langBulgarian → smCyrillic
45: 7, // langUkrainian → smCyrillic (modified)
46: 7, // langByelorussian → smCyrillic
47: 7, // langUzbek → smCyrillic
48: 7, // langKazakh → smCyrillic
49: 7, // langAzerbaijani → smCyrillic
50: 4, // langAzerbaijanAr → smArabic
51: 24, // langArmenian → smArmenian
52: 23, // langGeorgian → smGeorgian
53: 7, // langMoldavian → smCyrillic
54: 7, // langKirghiz → smCyrillic
55: 7, // langTajiki → smCyrillic
56: 7, // langTurkmen → smCyrillic
57: 27, // langMongolian → smMongolian
58: 7, // langMongolianCyr → smCyrillic
59: 4, // langPashto → smArabic
60: 4, // langKurdish → smArabic
61: 4, // langKashmiri → smArabic
62: 4, // langSindhi → smArabic
63: 26, // langTibetan → smTibetan
64: 9, // langNepali → smDevanagari
65: 9, // langSanskrit → smDevanagari
66: 9, // langMarathi → smDevanagari
67: 13, // langBengali → smBengali
68: 13, // langAssamese → smBengali
69: 11, // langGujarati → smGujarati
70: 10, // langPunjabi → smGurmukhi
71: 12, // langOriya → smOriya
72: 17, // langMalayalam → smMalayalam
73: 16, // langKannada → smKannada
74: 14, // langTamil → smTamil
75: 15, // langTelugu → smTelugu
76: 18, // langSinhalese → smSinhalese
77: 19, // langBurmese → smBurmese
78: 20, // langKhmer → smKhmer
79: 22, // langLao → smLao
80: 30, // langVietnamese → smVietnamese
81: 0, // langIndonesian → smRoman
82: 0, // langTagalog → smRoman
83: 0, // langMalayRoman → smRoman
84: 4, // langMalayArabic → smArabic
85: 28, // langAmharic → smEthiopic
86: 28, // langTigrinya → smEthiopic
87: 28, // langOromo → smEthiopic
88: 0, // langSomali → smRoman
89: 0, // langSwahili → smRoman
90: 0, // langKinyarwanda → smRoman
91: 0, // langRundi → smRoman
92: 0, // langNyanja → smRoman
93: 0, // langMalagasy → smRoman
94: 0, // langEsperanto → smRoman
128: 0, // langWelsh → smRoman (modified)
129: 0, // langBasque → smRoman
130: 0, // langCatalan → smRoman
131: 0, // langLatin → smRoman
132: 0, // langQuechua → smRoman
133: 0, // langGuarani → smRoman
134: 0, // langAymara → smRoman
135: 7, // langTatar → smCyrillic
136: 4, // langUighur → smArabic
137: 26, // langDzongkha → smTibetan
138: 0, // langJavaneseRom → smRoman
139: 0, // langSundaneseRom → smRoman
140: 0, // langGalician → smRoman
141: 0, // langAfrikaans → smRoman
142: 0, // langBreton → smRoman (modified)
143: 28, // langInuktitut → smEthiopic (modified)
144: 0, // langScottishGaelic → smRoman (modified)
145: 0, // langManxGaelic → smRoman (modified)
146: 0, // langIrishGaelicScript → smRoman (modified)
147: 0, // langTongan → smRoman
148: 6, // langGreekAncient → smRoman
149: 0, // langGreenlandic → smRoman
150: 0, // langAzerbaijanRoman → smRoman
151: 0 // langNynorsk → smRoman
};
// While Microsoft indicates a region/country for all its language
// IDs, we omit the region code if it's equal to the "most likely
// region subtag" according to Unicode CLDR. For scripts, we omit
// the subtag if it is equal to the Suppress-Script entry in the
// IANA language subtag registry for IETF BCP 47.
//
// For example, Microsoft states that its language code 0x041A is
// Croatian in Croatia. We transform this to the BCP 47 language code 'hr'
// and not 'hr-HR' because Croatia is the default country for Croatian,
// according to Unicode CLDR. As another example, Microsoft states
// that 0x101A is Croatian (Latin) in Bosnia-Herzegovina. We transform
// this to 'hr-BA' and not 'hr-Latn-BA' because Latin is the default script
// for the Croatian language, according to IANA.
//
// http://www.unicode.org/cldr/charts/latest/supplemental/likely_subtags.html
// http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
var windowsLanguages = {
0x0436: 'af',
0x041c: 'sq',
0x0484: 'gsw',
0x045e: 'am',
0x1401: 'ar-DZ',
0x3c01: 'ar-BH',
0x0c01: 'ar',
0x0801: 'ar-IQ',
0x2c01: 'ar-JO',
0x3401: 'ar-KW',
0x3001: 'ar-LB',
0x1001: 'ar-LY',
0x1801: 'ary',
0x2001: 'ar-OM',
0x4001: 'ar-QA',
0x0401: 'ar-SA',
0x2801: 'ar-SY',
0x1c01: 'aeb',
0x3801: 'ar-AE',
0x2401: 'ar-YE',
0x042b: 'hy',
0x044d: 'as',
0x082c: 'az-Cyrl',
0x042c: 'az',
0x046d: 'ba',
0x042d: 'eu',
0x0423: 'be',
0x0845: 'bn',
0x0445: 'bn-IN',
0x201a: 'bs-Cyrl',
0x141a: 'bs',
0x047e: 'br',
0x0402: 'bg',
0x0403: 'ca',
0x0c04: 'zh-HK',
0x1404: 'zh-MO',
0x0804: 'zh',
0x1004: 'zh-SG',
0x0404: 'zh-TW',
0x0483: 'co',
0x041a: 'hr',
0x101a: 'hr-BA',
0x0405: 'cs',
0x0406: 'da',
0x048c: 'prs',
0x0465: 'dv',
0x0813: 'nl-BE',
0x0413: 'nl',
0x0c09: 'en-AU',
0x2809: 'en-BZ',
0x1009: 'en-CA',
0x2409: 'en-029',
0x4009: 'en-IN',
0x1809: 'en-IE',
0x2009: 'en-JM',
0x4409: 'en-MY',
0x1409: 'en-NZ',
0x3409: 'en-PH',
0x4809: 'en-SG',
0x1c09: 'en-ZA',
0x2c09: 'en-TT',
0x0809: 'en-GB',
0x0409: 'en',
0x3009: 'en-ZW',
0x0425: 'et',
0x0438: 'fo',
0x0464: 'fil',
0x040b: 'fi',
0x080c: 'fr-BE',
0x0c0c: 'fr-CA',
0x040c: 'fr',
0x140c: 'fr-LU',
0x180c: 'fr-MC',
0x100c: 'fr-CH',
0x0462: 'fy',
0x0456: 'gl',
0x0437: 'ka',
0x0c07: 'de-AT',
0x0407: 'de',
0x1407: 'de-LI',
0x1007: 'de-LU',
0x0807: 'de-CH',
0x0408: 'el',
0x046f: 'kl',
0x0447: 'gu',
0x0468: 'ha',
0x040d: 'he',
0x0439: 'hi',
0x040e: 'hu',
0x040f: 'is',
0x0470: 'ig',
0x0421: 'id',
0x045d: 'iu',
0x085d: 'iu-Latn',
0x083c: 'ga',
0x0434: 'xh',
0x0435: 'zu',
0x0410: 'it',
0x0810: 'it-CH',
0x0411: 'ja',
0x044b: 'kn',
0x043f: 'kk',
0x0453: 'km',
0x0486: 'quc',
0x0487: 'rw',
0x0441: 'sw',
0x0457: 'kok',
0x0412: 'ko',
0x0440: 'ky',
0x0454: 'lo',
0x0426: 'lv',
0x0427: 'lt',
0x082e: 'dsb',
0x046e: 'lb',
0x042f: 'mk',
0x083e: 'ms-BN',
0x043e: 'ms',
0x044c: 'ml',
0x043a: 'mt',
0x0481: 'mi',
0x047a: 'arn',
0x044e: 'mr',
0x047c: 'moh',
0x0450: 'mn',
0x0850: 'mn-CN',
0x0461: 'ne',
0x0414: 'nb',
0x0814: 'nn',
0x0482: 'oc',
0x0448: 'or',
0x0463: 'ps',
0x0415: 'pl',
0x0416: 'pt',
0x0816: 'pt-PT',
0x0446: 'pa',
0x046b: 'qu-BO',
0x086b: 'qu-EC',
0x0c6b: 'qu',
0x0418: 'ro',
0x0417: 'rm',
0x0419: 'ru',
0x243b: 'smn',
0x103b: 'smj-NO',
0x143b: 'smj',
0x0c3b: 'se-FI',
0x043b: 'se',
0x083b: 'se-SE',
0x203b: 'sms',
0x183b: 'sma-NO',
0x1c3b: 'sms',
0x044f: 'sa',
0x1c1a: 'sr-Cyrl-BA',
0x0c1a: 'sr',
0x181a: 'sr-Latn-BA',
0x081a: 'sr-Latn',
0x046c: 'nso',
0x0432: 'tn',
0x045b: 'si',
0x041b: 'sk',
0x0424: 'sl',
0x2c0a: 'es-AR',
0x400a: 'es-BO',
0x340a: 'es-CL',
0x240a: 'es-CO',
0x140a: 'es-CR',
0x1c0a: 'es-DO',
0x300a: 'es-EC',
0x440a: 'es-SV',
0x100a: 'es-GT',
0x480a: 'es-HN',
0x080a: 'es-MX',
0x4c0a: 'es-NI',
0x180a: 'es-PA',
0x3c0a: 'es-PY',
0x280a: 'es-PE',
0x500a: 'es-PR',
// Microsoft has defined two different language codes for
// “Spanish with modern sorting” and “Spanish with traditional
// sorting”. This makes sense for collation APIs, and it would be
// possible to express this in BCP 47 language tags via Unicode
// extensions (eg., es-u-co-trad is Spanish with traditional
// sorting). However, for storing names in fonts, the distinction
// does not make sense, so we give “es” in both cases.
0x0c0a: 'es',
0x040a: 'es',
0x540a: 'es-US',
0x380a: 'es-UY',
0x200a: 'es-VE',
0x081d: 'sv-FI',
0x041d: 'sv',
0x045a: 'syr',
0x0428: 'tg',
0x085f: 'tzm',
0x0449: 'ta',
0x0444: 'tt',
0x044a: 'te',
0x041e: 'th',
0x0451: 'bo',
0x041f: 'tr',
0x0442: 'tk',
0x0480: 'ug',
0x0422: 'uk',
0x042e: 'hsb',
0x0420: 'ur',
0x0843: 'uz-Cyrl',
0x0443: 'uz',
0x042a: 'vi',
0x0452: 'cy',
0x0488: 'wo',
0x0485: 'sah',
0x0478: 'ii',
0x046a: 'yo'
};
// Returns a IETF BCP 47 language code, for example 'zh-Hant'
// for 'Chinese in the traditional script'.
function getLanguageCode(platformID, languageID, ltag) {
switch (platformID) {
case 0: // Unicode
if (languageID === 0xffff) {
return 'und';
} else if (ltag) {
return ltag[languageID];
}
break;
case 1: // Macintosh
return macLanguages[languageID];
case 3: // Windows
return windowsLanguages[languageID];
}
return undefined;
}
var utf16 = 'utf-16';
// MacOS script ID → encoding. This table stores the default case,
// which can be overridden by macLanguageEncodings.
var macScriptEncodings = {
0: 'macintosh', // smRoman
1: 'x-mac-japanese', // smJapanese
2: 'x-mac-chinesetrad', // smTradChinese
3: 'x-mac-korean', // smKorean
6: 'x-mac-greek', // smGreek
7: 'x-mac-cyrillic', // smCyrillic
9: 'x-mac-devanagai', // smDevanagari
10: 'x-mac-gurmukhi', // smGurmukhi
11: 'x-mac-gujarati', // smGujarati
12: 'x-mac-oriya', // smOriya
13: 'x-mac-bengali', // smBengali
14: 'x-mac-tamil', // smTamil
15: 'x-mac-telugu', // smTelugu
16: 'x-mac-kannada', // smKannada
17: 'x-mac-malayalam', // smMalayalam
18: 'x-mac-sinhalese', // smSinhalese
19: 'x-mac-burmese', // smBurmese
20: 'x-mac-khmer', // smKhmer
21: 'x-mac-thai', // smThai
22: 'x-mac-lao', // smLao
23: 'x-mac-georgian', // smGeorgian
24: 'x-mac-armenian', // smArmenian
25: 'x-mac-chinesesimp', // smSimpChinese
26: 'x-mac-tibetan', // smTibetan
27: 'x-mac-mongolian', // smMongolian
28: 'x-mac-ethiopic', // smEthiopic
29: 'x-mac-ce', // smCentralEuroRoman
30: 'x-mac-vietnamese', // smVietnamese
31: 'x-mac-extarabic' // smExtArabic
};
// MacOS language ID → encoding. This table stores the exceptional
// cases, which override macScriptEncodings. For writing MacOS naming
// tables, we need to emit a MacOS script ID. Therefore, we cannot
// merge macScriptEncodings into macLanguageEncodings.
//
// http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt
var macLanguageEncodings = {
15: 'x-mac-icelandic', // langIcelandic
17: 'x-mac-turkish', // langTurkish
18: 'x-mac-croatian', // langCroatian
24: 'x-mac-ce', // langLithuanian
25: 'x-mac-ce', // langPolish
26: 'x-mac-ce', // langHungarian
27: 'x-mac-ce', // langEstonian
28: 'x-mac-ce', // langLatvian
30: 'x-mac-icelandic', // langFaroese
37: 'x-mac-romanian', // langRomanian
38: 'x-mac-ce', // langCzech
39: 'x-mac-ce', // langSlovak
40: 'x-mac-ce', // langSlovenian
143: 'x-mac-inuit', // langInuktitut
146: 'x-mac-gaelic' // langIrishGaelicScript
};
function getEncoding(platformID, encodingID, languageID) {
switch (platformID) {
case 0: // Unicode
return utf16;
case 1: // Apple Macintosh
return (
macLanguageEncodings[languageID] || macScriptEncodings[encodingID]
);
case 3: // Microsoft Windows
if (encodingID === 1 || encodingID === 10) {
return utf16;
}
break;
}
return undefined;
}
// Parse the naming `name` table.
// FIXME: Format 1 additional fields are not supported yet.
// ltag is the content of the `ltag' table, such as ['en', 'zh-Hans', 'de-CH-1904'].
function parseNameTable(data, start, ltag) {
var name = {};
var p = new parse.Parser(data, start);
var format = p.parseUShort();
var count = p.parseUShort();
var stringOffset = p.offset + p.parseUShort();
for (var i = 0; i < count; i++) {
var platformID = p.parseUShort();
var encodingID = p.parseUShort();
var languageID = p.parseUShort();
var nameID = p.parseUShort();
var property = nameTableNames[nameID] || nameID;
var byteLength = p.parseUShort();
var offset = p.parseUShort();
var language = getLanguageCode(platformID, languageID, ltag);
var encoding = getEncoding(platformID, encodingID, languageID);
if (encoding !== undefined && language !== undefined) {
var text = void 0;
if (encoding === utf16) {
text = decode.UTF16(data, stringOffset + offset, byteLength);
} else {
text = decode.MACSTRING(
data,
stringOffset + offset,
byteLength,
encoding
);
}
if (text) {
var translations = name[property];
if (translations === undefined) {
translations = name[property] = {};
}
translations[language] = text;
}
}
}
var langTagCount = 0;
if (format === 1) {
// FIXME: Also handle Microsoft's 'name' table 1.
langTagCount = p.parseUShort();
}
return name;
}
// {23: 'foo'} → {'foo': 23}
// ['bar', 'baz'] → {'bar': 0, 'baz': 1}
function reverseDict(dict) {
var result = {};
for (var key in dict) {
result[dict[key]] = parseInt(key);
}
return result;
}
function makeNameRecord(
platformID,
encodingID,
languageID,
nameID,
length,
offset
) {
return new table.Record('NameRecord', [
{ name: 'platformID', type: 'USHORT', value: platformID },
{ name: 'encodingID', type: 'USHORT', value: encodingID },
{ name: 'languageID', type: 'USHORT', value: languageID },
{ name: 'nameID', type: 'USHORT', value: nameID },
{ name: 'length', type: 'USHORT', value: length },
{ name: 'offset', type: 'USHORT', value: offset }
]);
}
// Finds the position of needle in haystack, or -1 if not there.
// Like String.indexOf(), but for arrays.
function findSubArray(needle, haystack) {
var needleLength = needle.length;
var limit = haystack.length - needleLength + 1;
loop: for (var pos = 0; pos < limit; pos++) {
for (; pos < limit; pos++) {
for (var k = 0; k < needleLength; k++) {
if (haystack[pos + k] !== needle[k]) {
continue loop;
}
}
return pos;
}
}
return -1;
}
function addStringToPool(s, pool) {
var offset = findSubArray(s, pool);
if (offset < 0) {
offset = pool.length;
var i = 0;
var len = s.length;
for (; i < len; ++i) {
pool.push(s[i]);
}
}
return offset;
}
function makeNameTable(names, ltag) {
var nameID;
var nameIDs = [];
var namesWithNumericKeys = {};
var nameTableIds = reverseDict(nameTableNames);
for (var key in names) {
var id = nameTableIds[key];
if (id === undefined) {
id = key;
}
nameID = parseInt(id);
if (isNaN(nameID)) {
throw new Error(
'Name table entry "' +
key +
'" does not exist, see nameTableNames for complete list.'
);
}
namesWithNumericKeys[nameID] = names[key];
nameIDs.push(nameID);
}
var macLanguageIds = reverseDict(macLanguages);
var windowsLanguageIds = reverseDict(windowsLanguages);
var nameRecords = [];
var stringPool = [];
for (var i = 0; i < nameIDs.length; i++) {
nameID = nameIDs[i];
var translations = namesWithNumericKeys[nameID];
for (var lang in translations) {
var text = translations[lang];
// For MacOS, we try to emit the name in the form that was introduced
// in the initial version of the TrueType spec (in the late 1980s).
// However, this can fail for various reasons: the requested BCP 47
// language code might not have an old-style Mac equivalent;
// we might not have a codec for the needed character encoding;
// or the name might contain characters that cannot be expressed
// in the old-style Macintosh encoding. In case of failure, we emit
// the name in a more modern fashion (Unicode encoding with BCP 47
// language tags) that is recognized by MacOS 10.5, released in 2009.
// If fonts were only read by operating systems, we could simply
// emit all names in the modern form; this would be much easier.
// However, there are many applications and libraries that read
// 'name' tables directly, and these will usually only recognize
// the ancient form (silently skipping the unrecognized names).
var macPlatform = 1; // Macintosh
var macLanguage = macLanguageIds[lang];
var macScript = macLanguageToScript[macLanguage];
var macEncoding = getEncoding(macPlatform, macScript, macLanguage);
var macName = encode.MACSTRING(text, macEncoding);
if (macName === undefined) {
macPlatform = 0; // Unicode
macLanguage = ltag.indexOf(lang);
if (macLanguage < 0) {
macLanguage = ltag.length;
ltag.push(lang);
}
macScript = 4; // Unicode 2.0 and later
macName = encode.UTF16(text);
}
var macNameOffset = addStringToPool(macName, stringPool);
nameRecords.push(
makeNameRecord(
macPlatform,
macScript,
macLanguage,
nameID,
macName.length,
macNameOffset
)
);
var winLanguage = windowsLanguageIds[lang];
if (winLanguage !== undefined) {
var winName = encode.UTF16(text);
var winNameOffset = addStringToPool(winName, stringPool);
nameRecords.push(
makeNameRecord(
3,
1,
winLanguage,
nameID,
winName.length,
winNameOffset
)
);
}
}
}
nameRecords.sort(function(a, b) {
return (
a.platformID - b.platformID ||
a.encodingID - b.encodingID ||
a.languageID - b.languageID ||
a.nameID - b.nameID
);
});
var t = new table.Table('name', [
{ name: 'format', type: 'USHORT', value: 0 },
{ name: 'count', type: 'USHORT', value: nameRecords.length },
{
name: 'stringOffset',
type: 'USHORT',
value: 6 + nameRecords.length * 12
}
]);
for (var r = 0; r < nameRecords.length; r++) {
t.fields.push({
name: 'record_' + r,
type: 'RECORD',
value: nameRecords[r]
});
}
t.fields.push({ name: 'strings', type: 'LITERAL', value: stringPool });
return t;
}
var _name = { parse: parseNameTable, make: makeNameTable };
// The `OS/2` table contains metrics required in OpenType fonts.
var unicodeRanges = [
{ begin: 0x0000, end: 0x007f }, // Basic Latin
{ begin: 0x0080, end: 0x00ff }, // Latin-1 Supplement
{ begin: 0x0100, end: 0x017f }, // Latin Extended-A
{ begin: 0x0180, end: 0x024f }, // Latin Extended-B
{ begin: 0x0250, end: 0x02af }, // IPA Extensions
{ begin: 0x02b0, end: 0x02ff }, // Spacing Modifier Letters
{ begin: 0x0300, end: 0x036f }, // Combining Diacritical Marks
{ begin: 0x0370, end: 0x03ff }, // Greek and Coptic
{ begin: 0x2c80, end: 0x2cff }, // Coptic
{ begin: 0x0400, end: 0x04ff }, // Cyrillic
{ begin: 0x0530, end: 0x058f }, // Armenian
{ begin: 0x0590, end: 0x05ff }, // Hebrew
{ begin: 0xa500, end: 0xa63f }, // Vai
{ begin: 0x0600, end: 0x06ff }, // Arabic
{ begin: 0x07c0, end: 0x07ff }, // NKo
{ begin: 0x0900, end: 0x097f }, // Devanagari
{ begin: 0x0980, end: 0x09ff }, // Bengali
{ begin: 0x0a00, end: 0x0a7f }, // Gurmukhi
{ begin: 0x0a80, end: 0x0aff }, // Gujarati
{ begin: 0x0b00, end: 0x0b7f }, // Oriya
{ begin: 0x0b80, end: 0x0bff }, // Tamil
{ begin: 0x0c00, end: 0x0c7f }, // Telugu
{ begin: 0x0c80, end: 0x0cff }, // Kannada
{ begin: 0x0d00, end: 0x0d7f }, // Malayalam
{ begin: 0x0e00, end: 0x0e7f }, // Thai
{ begin: 0x0e80, end: 0x0eff }, // Lao
{ begin: 0x10a0, end: 0x10ff }, // Georgian
{ begin: 0x1b00, end: 0x1b7f }, // Balinese
{ begin: 0x1100, end: 0x11ff }, // Hangul Jamo
{ begin: 0x1e00, end: 0x1eff }, // Latin Extended Additional
{ begin: 0x1f00, end: 0x1fff }, // Greek Extended
{ begin: 0x2000, end: 0x206f }, // General Punctuation
{ begin: 0x2070, end: 0x209f }, // Superscripts And Subscripts
{ begin: 0x20a0, end: 0x20cf }, // Currency Symbol
{ begin: 0x20d0, end: 0x20ff }, // Combining Diacritical Marks For Symbols
{ begin: 0x2100, end: 0x214f }, // Letterlike Symbols
{ begin: 0x2150, end: 0x218f }, // Number Forms
{ begin: 0x2190, end: 0x21ff }, // Arrows
{ begin: 0x2200, end: 0x22ff }, // Mathematical Operators
{ begin: 0x2300, end: 0x23ff }, // Miscellaneous Technical
{ begin: 0x2400, end: 0x243f }, // Control Pictures
{ begin: 0x2440, end: 0x245f }, // Optical Character Recognition
{ begin: 0x2460, end: 0x24ff }, // Enclosed Alphanumerics
{ begin: 0x2500, end: 0x257f }, // Box Drawing
{ begin: 0x2580, end: 0x259f }, // Block Elements
{ begin: 0x25a0, end: 0x25ff }, // Geometric Shapes
{ begin: 0x2600, end: 0x26ff }, // Miscellaneous Symbols
{ begin: 0x2700, end: 0x27bf }, // Dingbats
{ begin: 0x3000, end: 0x303f }, // CJK Symbols And Punctuation
{ begin: 0x3040, end: 0x309f }, // Hiragana
{ begin: 0x30a0, end: 0x30ff }, // Katakana
{ begin: 0x3100, end: 0x312f }, // Bopomofo
{ begin: 0x3130, end: 0x318f }, // Hangul Compatibility Jamo
{ begin: 0xa840, end: 0xa87f }, // Phags-pa
{ begin: 0x3200, end: 0x32ff }, // Enclosed CJK Letters And Months
{ begin: 0x3300, end: 0x33ff }, // CJK Compatibility
{ begin: 0xac00, end: 0xd7af }, // Hangul Syllables
{ begin: 0xd800, end: 0xdfff }, // Non-Plane 0 *
{ begin: 0x10900, end: 0x1091f }, // Phoenicia
{ begin: 0x4e00, end: 0x9fff }, // CJK Unified Ideographs
{ begin: 0xe000, end: 0xf8ff }, // Private Use Area (plane 0)
{ begin: 0x31c0, end: 0x31ef }, // CJK Strokes
{ begin: 0xfb00, end: 0xfb4f }, // Alphabetic Presentation Forms
{ begin: 0xfb50, end: 0xfdff }, // Arabic Presentation Forms-A
{ begin: 0xfe20, end: 0xfe2f }, // Combining Half Marks
{ begin: 0xfe10, end: 0xfe1f }, // Vertical Forms
{ begin: 0xfe50, end: 0xfe6f }, // Small Form Variants
{ begin: 0xfe70, end: 0xfeff }, // Arabic Presentation Forms-B
{ begin: 0xff00, end: 0xffef }, // Halfwidth And Fullwidth Forms
{ begin: 0xfff0, end: 0xffff }, // Specials
{ begin: 0x0f00, end: 0x0fff }, // Tibetan
{ begin: 0x0700, end: 0x074f }, // Syriac
{ begin: 0x0780, end: 0x07bf }, // Thaana
{ begin: 0x0d80, end: 0x0dff }, // Sinhala
{ begin: 0x1000, end: 0x109f }, // Myanmar
{ begin: 0x1200, end: 0x137f }, // Ethiopic
{ begin: 0x13a0, end: 0x13ff }, // Cherokee
{ begin: 0x1400, end: 0x167f }, // Unified Canadian Aboriginal Syllabics
{ begin: 0x1680, end: 0x169f }, // Ogham
{ begin: 0x16a0, end: 0x16ff }, // Runic
{ begin: 0x1780, end: 0x17ff }, // Khmer
{ begin: 0x1800, end: 0x18af }, // Mongolian
{ begin: 0x2800, end: 0x28ff }, // Braille Patterns
{ begin: 0xa000, end: 0xa48f }, // Yi Syllables
{ begin: 0x1700, end: 0x171f }, // Tagalog
{ begin: 0x10300, end: 0x1032f }, // Old Italic
{ begin: 0x10330, end: 0x1034f }, // Gothic
{ begin: 0x10400, end: 0x1044f }, // Deseret
{ begin: 0x1d000, end: 0x1d0ff }, // Byzantine Musical Symbols
{ begin: 0x1d400, end: 0x1d7ff }, // Mathematical Alphanumeric Symbols
{ begin: 0xff000, end: 0xffffd }, // Private Use (plane 15)
{ begin: 0xfe00, end: 0xfe0f }, // Variation Selectors
{ begin: 0xe0000, end: 0xe007f }, // Tags
{ begin: 0x1900, end: 0x194f }, // Limbu
{ begin: 0x1950, end: 0x197f }, // Tai Le
{ begin: 0x1980, end: 0x19df }, // New Tai Lue
{ begin: 0x1a00, end: 0x1a1f }, // Buginese
{ begin: 0x2c00, end: 0x2c5f }, // Glagolitic
{ begin: 0x2d30, end: 0x2d7f }, // Tifinagh
{ begin: 0x4dc0, end: 0x4dff }, // Yijing Hexagram Symbols
{ begin: 0xa800, end: 0xa82f }, // Syloti Nagri
{ begin: 0x10000, end: 0x1007f }, // Linear B Syllabary
{ begin: 0x10140, end: 0x1018f }, // Ancient Greek Numbers
{ begin: 0x10380, end: 0x1039f }, // Ugaritic
{ begin: 0x103a0, end: 0x103df }, // Old Persian
{ begin: 0x10450, end: 0x1047f }, // Shavian
{ begin: 0x10480, end: 0x104af }, // Osmanya
{ begin: 0x10800, end: 0x1083f }, // Cypriot Syllabary
{ begin: 0x10a00, end: 0x10a5f }, // Kharoshthi
{ begin: 0x1d300, end: 0x1d35f }, // Tai Xuan Jing Symbols
{ begin: 0x12000, end: 0x123ff }, // Cuneiform
{ begin: 0x1d360, end: 0x1d37f }, // Counting Rod Numerals
{ begin: 0x1b80, end: 0x1bbf }, // Sundanese
{ begin: 0x1c00, end: 0x1c4f }, // Lepcha
{ begin: 0x1c50, end: 0x1c7f }, // Ol Chiki
{ begin: 0xa880, end: 0xa8df }, // Saurashtra
{ begin: 0xa900, end: 0xa92f }, // Kayah Li
{ begin: 0xa930, end: 0xa95f }, // Rejang
{ begin: 0xaa00, end: 0xaa5f }, // Cham
{ begin: 0x10190, end: 0x101cf }, // Ancient Symbols
{ begin: 0x101d0, end: 0x101ff }, // Phaistos Disc
{ begin: 0x102a0, end: 0x102df }, // Carian
{ begin: 0x1f030, end: 0x1f09f } // Domino Tiles
];
function getUnicodeRange(unicode) {
for (var i = 0; i < unicodeRanges.length; i += 1) {
var range = unicodeRanges[i];
if (unicode >= range.begin && unicode < range.end) {
return i;
}
}
return -1;
}
// Parse the OS/2 and Windows metrics `OS/2` table
function parseOS2Table(data, start) {
var os2 = {};
var p = new parse.Parser(data, start);
os2.version = p.parseUShort();
os2.xAvgCharWidth = p.parseShort();
os2.usWeightClass = p.parseUShort();
os2.usWidthClass = p.parseUShort();
os2.fsType = p.parseUShort();
os2.ySubscriptXSize = p.parseShort();
os2.ySubscriptYSize = p.parseShort();
os2.ySubscriptXOffset = p.parseShort();
os2.ySubscriptYOffset = p.parseShort();
os2.ySuperscriptXSize = p.parseShort();
os2.ySuperscriptYSize = p.parseShort();
os2.ySuperscriptXOffset = p.parseShort();
os2.ySuperscriptYOffset = p.parseShort();
os2.yStrikeoutSize = p.parseShort();
os2.yStrikeoutPosition = p.parseShort();
os2.sFamilyClass = p.parseShort();
os2.panose = [];
for (var i = 0; i < 10; i++) {
os2.panose[i] = p.parseByte();
}
os2.ulUnicodeRange1 = p.parseULong();
os2.ulUnicodeRange2 = p.parseULong();
os2.ulUnicodeRange3 = p.parseULong();
os2.ulUnicodeRange4 = p.parseULong();
os2.achVendID = String.fromCharCode(
p.parseByte(),
p.parseByte(),
p.parseByte(),
p.parseByte()
);
os2.fsSelection = p.parseUShort();
os2.usFirstCharIndex = p.parseUShort();
os2.usLastCharIndex = p.parseUShort();
os2.sTypoAscender = p.parseShort();
os2.sTypoDescender = p.parseShort();
os2.sTypoLineGap = p.parseShort();
os2.usWinAscent = p.parseUShort();
os2.usWinDescent = p.parseUShort();
if (os2.version >= 1) {
os2.ulCodePageRange1 = p.parseULong();
os2.ulCodePageRange2 = p.parseULong();
}
if (os2.version >= 2) {
os2.sxHeight = p.parseShort();
os2.sCapHeight = p.parseShort();
os2.usDefaultChar = p.parseUShort();
os2.usBreakChar = p.parseUShort();
os2.usMaxContent = p.parseUShort();
}
return os2;
}
function makeOS2Table(options) {
return new table.Table(
'OS/2',
[
{ name: 'version', type: 'USHORT', value: 0x0003 },
{ name: 'xAvgCharWidth', type: 'SHORT', value: 0 },
{ name: 'usWeightClass', type: 'USHORT', value: 0 },
{ name: 'usWidthClass', type: 'USHORT', value: 0 },
{ name: 'fsType', type: 'USHORT', value: 0 },
{ name: 'ySubscriptXSize', type: 'SHORT', value: 650 },
{ name: 'ySubscriptYSize', type: 'SHORT', value: 699 },
{ name: 'ySubscriptXOffset', type: 'SHORT', value: 0 },
{ name: 'ySubscriptYOffset', type: 'SHORT', value: 140 },
{ name: 'ySuperscriptXSize', type: 'SHORT', value: 650 },
{ name: 'ySuperscriptYSize', type: 'SHORT', value: 699 },
{ name: 'ySuperscriptXOffset', type: 'SHORT', value: 0 },
{ name: 'ySuperscriptYOffset', type: 'SHORT', value: 479 },
{ name: 'yStrikeoutSize', type: 'SHORT', value: 49 },
{ name: 'yStrikeoutPosition', type: 'SHORT', value: 258 },
{ name: 'sFamilyClass', type: 'SHORT', value: 0 },
{ name: 'bFamilyType', type: 'BYTE', value: 0 },
{ name: 'bSerifStyle', type: 'BYTE', value: 0 },
{ name: 'bWeight', type: 'BYTE', value: 0 },
{ name: 'bProportion', type: 'BYTE', value: 0 },
{ name: 'bContrast', type: 'BYTE', value: 0 },
{ name: 'bStrokeVariation', type: 'BYTE', value: 0 },
{ name: 'bArmStyle', type: 'BYTE', value: 0 },
{ name: 'bLetterform', type: 'BYTE', value: 0 },
{ name: 'bMidline', type: 'BYTE', value: 0 },
{ name: 'bXHeight', type: 'BYTE', value: 0 },
{ name: 'ulUnicodeRange1', type: 'ULONG', value: 0 },
{ name: 'ulUnicodeRange2', type: 'ULONG', value: 0 },
{ name: 'ulUnicodeRange3', type: 'ULONG', value: 0 },
{ name: 'ulUnicodeRange4', type: 'ULONG', value: 0 },
{ name: 'achVendID', type: 'CHARARRAY', value: 'XXXX' },
{ name: 'fsSelection', type: 'USHORT', value: 0 },
{ name: 'usFirstCharIndex', type: 'USHORT', value: 0 },
{ name: 'usLastCharIndex', type: 'USHORT', value: 0 },
{ name: 'sTypoAscender', type: 'SHORT', value: 0 },
{ name: 'sTypoDescender', type: 'SHORT', value: 0 },
{ name: 'sTypoLineGap', type: 'SHORT', value: 0 },
{ name: 'usWinAscent', type: 'USHORT', value: 0 },
{ name: 'usWinDescent', type: 'USHORT', value: 0 },
{ name: 'ulCodePageRange1', type: 'ULONG', value: 0 },
{ name: 'ulCodePageRange2', type: 'ULONG', value: 0 },
{ name: 'sxHeight', type: 'SHORT', value: 0 },
{ name: 'sCapHeight', type: 'SHORT', value: 0 },
{ name: 'usDefaultChar', type: 'USHORT', value: 0 },
{ name: 'usBreakChar', type: 'USHORT', value: 0 },
{ name: 'usMaxContext', type: 'USHORT', value: 0 }
],
options
);
}
var os2 = {
parse: parseOS2Table,
make: makeOS2Table,
unicodeRanges: unicodeRanges,
getUnicodeRange: getUnicodeRange
};
// The `post` table stores additional PostScript information, such as glyph names.
// Parse the PostScript `post` table
function parsePostTable(data, start) {
var post = {};
var p = new parse.Parser(data, start);
post.version = p.parseVersion();
post.italicAngle = p.parseFixed();
post.underlinePosition = p.parseShort();
post.underlineThickness = p.parseShort();
post.isFixedPitch = p.parseULong();
post.minMemType42 = p.parseULong();
post.maxMemType42 = p.parseULong();
post.minMemType1 = p.parseULong();
post.maxMemType1 = p.parseULong();
switch (post.version) {
case 1:
post.names = standardNames.slice();
break;
case 2:
post.numberOfGlyphs = p.parseUShort();
post.glyphNameIndex = new Array(post.numberOfGlyphs);
for (var i = 0; i < post.numberOfGlyphs; i++) {
post.glyphNameIndex[i] = p.parseUShort();
}
post.names = [];
for (var i$1 = 0; i$1 < post.numberOfGlyphs; i$1++) {
if (post.glyphNameIndex[i$1] >= standardNames.length) {
var nameLength = p.parseChar();
post.names.push(p.parseString(nameLength));
}
}
break;
case 2.5:
post.numberOfGlyphs = p.parseUShort();
post.offset = new Array(post.numberOfGlyphs);
for (var i$2 = 0; i$2 < post.numberOfGlyphs; i$2++) {
post.offset[i$2] = p.parseChar();
}
break;
}
return post;
}
function makePostTable() {
return new table.Table('post', [
{ name: 'version', type: 'FIXED', value: 0x00030000 },
{ name: 'italicAngle', type: 'FIXED', value: 0 },
{ name: 'underlinePosition', type: 'FWORD', value: 0 },
{ name: 'underlineThickness', type: 'FWORD', value: 0 },
{ name: 'isFixedPitch', type: 'ULONG', value: 0 },
{ name: 'minMemType42', type: 'ULONG', value: 0 },
{ name: 'maxMemType42', type: 'ULONG', value: 0 },
{ name: 'minMemType1', type: 'ULONG', value: 0 },
{ name: 'maxMemType1', type: 'ULONG', value: 0 }
]);
}
var post = { parse: parsePostTable, make: makePostTable };
// The `GSUB` table contains ligatures, among other things.
var subtableParsers = new Array(9); // subtableParsers[0] is unused
// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#SS
subtableParsers[1] = function parseLookup1() {
var start = this.offset + this.relativeOffset;
var substFormat = this.parseUShort();
if (substFormat === 1) {
return {
substFormat: 1,
coverage: this.parsePointer(Parser.coverage),
deltaGlyphId: this.parseUShort()
};
} else if (substFormat === 2) {
return {
substFormat: 2,
coverage: this.parsePointer(Parser.coverage),
substitute: this.parseOffset16List()
};
}
check.assert(
false,
'0x' + start.toString(16) + ': lookup type 1 format must be 1 or 2.'
);
};
// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#MS
subtableParsers[2] = function parseLookup2() {
var substFormat = this.parseUShort();
check.argument(
substFormat === 1,
'GSUB Multiple Substitution Subtable identifier-format must be 1'
);
return {
substFormat: substFormat,
coverage: this.parsePointer(Parser.coverage),
sequences: this.parseListOfLists()
};
};
// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#AS
subtableParsers[3] = function parseLookup3() {
var substFormat = this.parseUShort();
check.argument(
substFormat === 1,
'GSUB Alternate Substitution Subtable identifier-format must be 1'
);
return {
substFormat: substFormat,
coverage: this.parsePointer(Parser.coverage),
alternateSets: this.parseListOfLists()
};
};
// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#LS
subtableParsers[4] = function parseLookup4() {
var substFormat = this.parseUShort();
check.argument(
substFormat === 1,
'GSUB ligature table identifier-format must be 1'
);
return {
substFormat: substFormat,
coverage: this.parsePointer(Parser.coverage),
ligatureSets: this.parseListOfLists(function() {
return {
ligGlyph: this.parseUShort(),
components: this.parseUShortList(this.parseUShort() - 1)
};
})
};
};
var lookupRecordDesc = {
sequenceIndex: Parser.uShort,
lookupListIndex: Parser.uShort
};
// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CSF
subtableParsers[5] = function parseLookup5() {
var start = this.offset + this.relativeOffset;
var substFormat = this.parseUShort();
if (substFormat === 1) {
return {
substFormat: substFormat,
coverage: this.parsePointer(Parser.coverage),
ruleSets: this.parseListOfLists(function() {
var glyphCount = this.parseUShort();
var substCount = this.parseUShort();
return {
input: this.parseUShortList(glyphCount - 1),
lookupRecords: this.parseRecordList(substCount, lookupRecordDesc)
};
})
};
} else if (substFormat === 2) {
return {
substFormat: substFormat,
coverage: this.parsePointer(Parser.coverage),
classDef: this.parsePointer(Parser.classDef),
classSets: this.parseListOfLists(function() {
var glyphCount = this.parseUShort();
var substCount = this.parseUShort();
return {
classes: this.parseUShortList(glyphCount - 1),
lookupRecords: this.parseRecordList(substCount, lookupRecordDesc)
};
})
};
} else if (substFormat === 3) {
var glyphCount = this.parseUShort();
var substCount = this.parseUShort();
return {
substFormat: substFormat,
coverages: this.parseList(glyphCount, Parser.pointer(Parser.coverage)),
lookupRecords: this.parseRecordList(substCount, lookupRecordDesc)
};
}
check.assert(
false,
'0x' + start.toString(16) + ': lookup type 5 format must be 1, 2 or 3.'
);
};
// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CC
subtableParsers[6] = function parseLookup6() {
var start = this.offset + this.relativeOffset;
var substFormat = this.parseUShort();
if (substFormat === 1) {
return {
substFormat: 1,
coverage: this.parsePointer(Parser.coverage),
chainRuleSets: this.parseListOfLists(function() {
return {
backtrack: this.parseUShortList(),
input: this.parseUShortList(this.parseShort() - 1),
lookahead: this.parseUShortList(),
lookupRecords: this.parseRecordList(lookupRecordDesc)
};
})
};
} else if (substFormat === 2) {
return {
substFormat: 2,
coverage: this.parsePointer(Parser.coverage),
backtrackClassDef: this.parsePointer(Parser.classDef),
inputClassDef: this.parsePointer(Parser.classDef),
lookaheadClassDef: this.parsePointer(Parser.classDef),
chainClassSet: this.parseListOfLists(function() {
return {
backtrack: this.parseUShortList(),
input: this.parseUShortList(this.parseShort() - 1),
lookahead: this.parseUShortList(),
lookupRecords: this.parseRecordList(lookupRecordDesc)
};
})
};
} else if (substFormat === 3) {
return {
substFormat: 3,
backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)),
inputCoverage: this.parseList(Parser.pointer(Parser.coverage)),
lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)),
lookupRecords: this.parseRecordList(lookupRecordDesc)
};
}
check.assert(
false,
'0x' + start.toString(16) + ': lookup type 6 format must be 1, 2 or 3.'
);
};
// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#ES
subtableParsers[7] = function parseLookup7() {
// Extension Substitution subtable
var substFormat = this.parseUShort();
check.argument(
substFormat === 1,
'GSUB Extension Substitution subtable identifier-format must be 1'
);
var extensionLookupType = this.parseUShort();
var extensionParser = new Parser(
this.data,
this.offset + this.parseULong()
);
return {
substFormat: 1,
lookupType: extensionLookupType,
extension: subtableParsers[extensionLookupType].call(extensionParser)
};
};
// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#RCCS
subtableParsers[8] = function parseLookup8() {
var substFormat = this.parseUShort();
check.argument(
substFormat === 1,
'GSUB Reverse Chaining Contextual Single Substitution Subtable identifier-format must be 1'
);
return {
substFormat: substFormat,
coverage: this.parsePointer(Parser.coverage),
backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)),
lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)),
substitutes: this.parseUShortList()
};
};
// https://www.microsoft.com/typography/OTSPEC/gsub.htm
function parseGsubTable(data, start) {
start = start || 0;
var p = new Parser(data, start);
var tableVersion = p.parseVersion(1);
check.argument(
tableVersion === 1 || tableVersion === 1.1,
'Unsupported GSUB table version.'
);
if (tableVersion === 1) {
return {
version: tableVersion,
scripts: p.parseScriptList(),
features: p.parseFeatureList(),
lookups: p.parseLookupList(subtableParsers)
};
} else {
return {
version: tableVersion,
scripts: p.parseScriptList(),
features: p.parseFeatureList(),
lookups: p.parseLookupList(subtableParsers),
variations: p.parseFeatureVariationsList()
};
}
}
// GSUB Writing //////////////////////////////////////////////
var subtableMakers = new Array(9);
subtableMakers[1] = function makeLookup1(subtable) {
if (subtable.substFormat === 1) {
return new table.Table('substitutionTable', [
{ name: 'substFormat', type: 'USHORT', value: 1 },
{
name: 'coverage',
type: 'TABLE',
value: new table.Coverage(subtable.coverage)
},
{ name: 'deltaGlyphID', type: 'USHORT', value: subtable.deltaGlyphId }
]);
} else {
return new table.Table(
'substitutionTable',
[
{ name: 'substFormat', type: 'USHORT', value: 2 },
{
name: 'coverage',
type: 'TABLE',
value: new table.Coverage(subtable.coverage)
}
].concat(table.ushortList('substitute', subtable.substitute))
);
}
check.fail('Lookup type 1 substFormat must be 1 or 2.');
};
subtableMakers[3] = function makeLookup3(subtable) {
check.assert(
subtable.substFormat === 1,
'Lookup type 3 substFormat must be 1.'
);
return new table.Table(
'substitutionTable',
[
{ name: 'substFormat', type: 'USHORT', value: 1 },
{
name: 'coverage',
type: 'TABLE',
value: new table.Coverage(subtable.coverage)
}
].concat(
table.tableList('altSet', subtable.alternateSets, function(
alternateSet
) {
return new table.Table(
'alternateSetTable',
table.ushortList('alternate', alternateSet)
);
})
)
);
};
subtableMakers[4] = function makeLookup4(subtable) {
check.assert(
subtable.substFormat === 1,
'Lookup type 4 substFormat must be 1.'
);
return new table.Table(
'substitutionTable',
[
{ name: 'substFormat', type: 'USHORT', value: 1 },
{
name: 'coverage',
type: 'TABLE',
value: new table.Coverage(subtable.coverage)
}
].concat(
table.tableList('ligSet', subtable.ligatureSets, function(ligatureSet) {
return new table.Table(
'ligatureSetTable',
table.tableList('ligature', ligatureSet, function(ligature) {
return new table.Table(
'ligatureTable',
[
{ name: 'ligGlyph', type: 'USHORT', value: ligature.ligGlyph }
].concat(
table.ushortList(
'component',
ligature.components,
ligature.components.length + 1
)
)
);
})
);
})
)
);
};
function makeGsubTable(gsub) {
return new table.Table('GSUB', [
{ name: 'version', type: 'ULONG', value: 0x10000 },
{
name: 'scripts',
type: 'TABLE',
value: new table.ScriptList(gsub.scripts)
},
{
name: 'features',
type: 'TABLE',
value: new table.FeatureList(gsub.features)
},
{
name: 'lookups',
type: 'TABLE',
value: new table.LookupList(gsub.lookups, subtableMakers)
}
]);
}
var gsub = { parse: parseGsubTable, make: makeGsubTable };
// The `GPOS` table contains kerning pairs, among other things.
// Parse the metadata `meta` table.
// https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6meta.html
function parseMetaTable(data, start) {
var p = new parse.Parser(data, start);
var tableVersion = p.parseULong();
check.argument(tableVersion === 1, 'Unsupported META table version.');
p.parseULong(); // flags - currently unused and set to 0
p.parseULong(); // tableOffset
var numDataMaps = p.parseULong();
var tags = {};
for (var i = 0; i < numDataMaps; i++) {
var tag = p.parseTag();
var dataOffset = p.parseULong();
var dataLength = p.parseULong();
var text = decode.UTF8(data, start + dataOffset, dataLength);
tags[tag] = text;
}
return tags;
}
function makeMetaTable(tags) {
var numTags = Object.keys(tags).length;
var stringPool = '';
var stringPoolOffset = 16 + numTags * 12;
var result = new table.Table('meta', [
{ name: 'version', type: 'ULONG', value: 1 },
{ name: 'flags', type: 'ULONG', value: 0 },
{ name: 'offset', type: 'ULONG', value: stringPoolOffset },
{ name: 'numTags', type: 'ULONG', value: numTags }
]);
for (var tag in tags) {
var pos = stringPool.length;
stringPool += tags[tag];
result.fields.push({ name: 'tag ' + tag, type: 'TAG', value: tag });
result.fields.push({
name: 'offset ' + tag,
type: 'ULONG',
value: stringPoolOffset + pos
});
result.fields.push({
name: 'length ' + tag,
type: 'ULONG',
value: tags[tag].length
});
}
result.fields.push({
name: 'stringPool',
type: 'CHARARRAY',
value: stringPool
});
return result;
}
var meta = { parse: parseMetaTable, make: makeMetaTable };
// The `sfnt` wrapper provides organization for the tables in the font.
function log2(v) {
return (Math.log(v) / Math.log(2)) | 0;
}
function computeCheckSum(bytes) {
while (bytes.length % 4 !== 0) {
bytes.push(0);
}
var sum = 0;
for (var i = 0; i < bytes.length; i += 4) {
sum +=
(bytes[i] << 24) +
(bytes[i + 1] << 16) +
(bytes[i + 2] << 8) +
bytes[i + 3];
}
sum %= Math.pow(2, 32);
return sum;
}
function makeTableRecord(tag, checkSum, offset, length) {
return new table.Record('Table Record', [
{ name: 'tag', type: 'TAG', value: tag !== undefined ? tag : '' },
{
name: 'checkSum',
type: 'ULONG',
value: checkSum !== undefined ? checkSum : 0
},
{
name: 'offset',
type: 'ULONG',
value: offset !== undefined ? offset : 0
},
{
name: 'length',
type: 'ULONG',
value: length !== undefined ? length : 0
}
]);
}
function makeSfntTable(tables) {
var sfnt = new table.Table('sfnt', [
{ name: 'version', type: 'TAG', value: 'OTTO' },
{ name: 'numTables', type: 'USHORT', value: 0 },
{ name: 'searchRange', type: 'USHORT', value: 0 },
{ name: 'entrySelector', type: 'USHORT', value: 0 },
{ name: 'rangeShift', type: 'USHORT', value: 0 }
]);
sfnt.tables = tables;
sfnt.numTables = tables.length;
var highestPowerOf2 = Math.pow(2, log2(sfnt.numTables));
sfnt.searchRange = 16 * highestPowerOf2;
sfnt.entrySelector = log2(highestPowerOf2);
sfnt.rangeShift = sfnt.numTables * 16 - sfnt.searchRange;
var recordFields = [];
var tableFields = [];
var offset = sfnt.sizeOf() + makeTableRecord().sizeOf() * sfnt.numTables;
while (offset % 4 !== 0) {
offset += 1;
tableFields.push({ name: 'padding', type: 'BYTE', value: 0 });
}
for (var i = 0; i < tables.length; i += 1) {
var t = tables[i];
check.argument(
t.tableName.length === 4,
'Table name' + t.tableName + ' is invalid.'
);
var tableLength = t.sizeOf();
var tableRecord = makeTableRecord(
t.tableName,
computeCheckSum(t.encode()),
offset,
tableLength
);
recordFields.push({
name: tableRecord.tag + ' Table Record',
type: 'RECORD',
value: tableRecord
});
tableFields.push({
name: t.tableName + ' table',
type: 'RECORD',
value: t
});
offset += tableLength;
check.argument(
!isNaN(offset),
'Something went wrong calculating the offset.'
);
while (offset % 4 !== 0) {
offset += 1;
tableFields.push({ name: 'padding', type: 'BYTE', value: 0 });
}
}
// Table records need to be sorted alphabetically.
recordFields.sort(function(r1, r2) {
if (r1.value.tag > r2.value.tag) {
return 1;
} else {
return -1;
}
});
sfnt.fields = sfnt.fields.concat(recordFields);
sfnt.fields = sfnt.fields.concat(tableFields);
return sfnt;
}
// Get the metrics for a character. If the string has more than one character
// this function returns metrics for the first available character.
// You can provide optional fallback metrics if no characters are available.
function metricsForChar(font, chars, notFoundMetrics) {
for (var i = 0; i < chars.length; i += 1) {
var glyphIndex = font.charToGlyphIndex(chars[i]);
if (glyphIndex > 0) {
var glyph = font.glyphs.get(glyphIndex);
return glyph.getMetrics();
}
}
return notFoundMetrics;
}
function average(vs) {
var sum = 0;
for (var i = 0; i < vs.length; i += 1) {
sum += vs[i];
}
return sum / vs.length;
}
// Convert the font object to a SFNT data structure.
// This structure contains all the necessary tables and metadata to create a binary OTF file.
function fontToSfntTable(font) {
var xMins = [];
var yMins = [];
var xMaxs = [];
var yMaxs = [];
var advanceWidths = [];
var leftSideBearings = [];
var rightSideBearings = [];
var firstCharIndex;
var lastCharIndex = 0;
var ulUnicodeRange1 = 0;
var ulUnicodeRange2 = 0;
var ulUnicodeRange3 = 0;
var ulUnicodeRange4 = 0;
for (var i = 0; i < font.glyphs.length; i += 1) {
var glyph = font.glyphs.get(i);
var unicode = glyph.unicode | 0;
if (isNaN(glyph.advanceWidth)) {
throw new Error(
'Glyph ' + glyph.name + ' (' + i + '): advanceWidth is not a number.'
);
}
if (firstCharIndex > unicode || firstCharIndex === undefined) {
// ignore .notdef char
if (unicode > 0) {
firstCharIndex = unicode;
}
}
if (lastCharIndex < unicode) {
lastCharIndex = unicode;
}
var position = os2.getUnicodeRange(unicode);
if (position < 32) {
ulUnicodeRange1 |= 1 << position;
} else if (position < 64) {
ulUnicodeRange2 |= 1 << (position - 32);
} else if (position < 96) {
ulUnicodeRange3 |= 1 << (position - 64);
} else if (position < 123) {
ulUnicodeRange4 |= 1 << (position - 96);
} else {
throw new Error(
'Unicode ranges bits > 123 are reserved for internal usage'
);
}
// Skip non-important characters.
if (glyph.name === '.notdef') {
continue;
}
var metrics = glyph.getMetrics();
xMins.push(metrics.xMin);
yMins.push(metrics.yMin);
xMaxs.push(metrics.xMax);
yMaxs.push(metrics.yMax);
leftSideBearings.push(metrics.leftSideBearing);
rightSideBearings.push(metrics.rightSideBearing);
advanceWidths.push(glyph.advanceWidth);
}
var globals = {
xMin: Math.min.apply(null, xMins),
yMin: Math.min.apply(null, yMins),
xMax: Math.max.apply(null, xMaxs),
yMax: Math.max.apply(null, yMaxs),
advanceWidthMax: Math.max.apply(null, advanceWidths),
advanceWidthAvg: average(advanceWidths),
minLeftSideBearing: Math.min.apply(null, leftSideBearings),
maxLeftSideBearing: Math.max.apply(null, leftSideBearings),
minRightSideBearing: Math.min.apply(null, rightSideBearings)
};
globals.ascender = font.ascender;
globals.descender = font.descender;
var headTable = head.make({
flags: 3, // 00000011 (baseline for font at y=0; left sidebearing point at x=0)
unitsPerEm: font.unitsPerEm,
xMin: globals.xMin,
yMin: globals.yMin,
xMax: globals.xMax,
yMax: globals.yMax,
lowestRecPPEM: 3,
createdTimestamp: font.createdTimestamp
});
var hheaTable = hhea.make({
ascender: globals.ascender,
descender: globals.descender,
advanceWidthMax: globals.advanceWidthMax,
minLeftSideBearing: globals.minLeftSideBearing,
minRightSideBearing: globals.minRightSideBearing,
xMaxExtent: globals.maxLeftSideBearing + (globals.xMax - globals.xMin),
numberOfHMetrics: font.glyphs.length
});
var maxpTable = maxp.make(font.glyphs.length);
var os2Table = os2.make({
xAvgCharWidth: Math.round(globals.advanceWidthAvg),
usWeightClass: font.tables.os2.usWeightClass,
usWidthClass: font.tables.os2.usWidthClass,
usFirstCharIndex: firstCharIndex,
usLastCharIndex: lastCharIndex,
ulUnicodeRange1: ulUnicodeRange1,
ulUnicodeRange2: ulUnicodeRange2,
ulUnicodeRange3: ulUnicodeRange3,
ulUnicodeRange4: ulUnicodeRange4,
fsSelection: font.tables.os2.fsSelection, // REGULAR
// See http://typophile.com/node/13081 for more info on vertical metrics.
// We get metrics for typical characters (such as "x" for xHeight).
// We provide some fallback characters if characters are unavailable: their
// ordering was chosen experimentally.
sTypoAscender: globals.ascender,
sTypoDescender: globals.descender,
sTypoLineGap: 0,
usWinAscent: globals.yMax,
usWinDescent: Math.abs(globals.yMin),
ulCodePageRange1: 1, // FIXME: hard-code Latin 1 support for now
sxHeight: metricsForChar(font, 'xyvw', {
yMax: Math.round(globals.ascender / 2)
}).yMax,
sCapHeight: metricsForChar(font, 'HIKLEFJMNTZBDPRAGOQSUVWXY', globals)
.yMax,
usDefaultChar: font.hasChar(' ') ? 32 : 0, // Use space as the default character, if available.
usBreakChar: font.hasChar(' ') ? 32 : 0 // Use space as the break character, if available.
});
var hmtxTable = hmtx.make(font.glyphs);
var cmapTable = cmap.make(font.glyphs);
var englishFamilyName = font.getEnglishName('fontFamily');
var englishStyleName = font.getEnglishName('fontSubfamily');
var englishFullName = englishFamilyName + ' ' + englishStyleName;
var postScriptName = font.getEnglishName('postScriptName');
if (!postScriptName) {
postScriptName =
englishFamilyName.replace(/\s/g, '') + '-' + englishStyleName;
}
var names = {};
for (var n in font.names) {
names[n] = font.names[n];
}
if (!names.uniqueID) {
names.uniqueID = {
en: font.getEnglishName('manufacturer') + ':' + englishFullName
};
}
if (!names.postScriptName) {
names.postScriptName = { en: postScriptName };
}
if (!names.preferredFamily) {
names.preferredFamily = font.names.fontFamily;
}
if (!names.preferredSubfamily) {
names.preferredSubfamily = font.names.fontSubfamily;
}
var languageTags = [];
var nameTable = _name.make(names, languageTags);
var ltagTable =
languageTags.length > 0 ? ltag.make(languageTags) : undefined;
var postTable = post.make();
var cffTable = cff.make(font.glyphs, {
version: font.getEnglishName('version'),
fullName: englishFullName,
familyName: englishFamilyName,
weightName: englishStyleName,
postScriptName: postScriptName,
unitsPerEm: font.unitsPerEm,
fontBBox: [0, globals.yMin, globals.ascender, globals.advanceWidthMax]
});
var metaTable =
font.metas && Object.keys(font.metas).length > 0
? meta.make(font.metas)
: undefined;
// The order does not matter because makeSfntTable() will sort them.
var tables = [
headTable,
hheaTable,
maxpTable,
os2Table,
nameTable,
cmapTable,
postTable,
cffTable,
hmtxTable
];
if (ltagTable) {
tables.push(ltagTable);
}
// Optional tables
if (font.tables.gsub) {
tables.push(gsub.make(font.tables.gsub));
}
if (metaTable) {
tables.push(metaTable);
}
var sfntTable = makeSfntTable(tables);
// Compute the font's checkSum and store it in head.checkSumAdjustment.
var bytes = sfntTable.encode();
var checkSum = computeCheckSum(bytes);
var tableFields = sfntTable.fields;
var checkSumAdjusted = false;
for (var i$1 = 0; i$1 < tableFields.length; i$1 += 1) {
if (tableFields[i$1].name === 'head table') {
tableFields[i$1].value.checkSumAdjustment = 0xb1b0afba - checkSum;
checkSumAdjusted = true;
break;
}
}
if (!checkSumAdjusted) {
throw new Error('Could not find head table with checkSum to adjust.');
}
return sfntTable;
}
var sfnt = {
make: makeSfntTable,
fontToTable: fontToSfntTable,
computeCheckSum: computeCheckSum
};
// The Layout object is the prototype of Substitution objects, and provides
function searchTag(arr, tag) {
/* jshint bitwise: false */
var imin = 0;
var imax = arr.length - 1;
while (imin <= imax) {
var imid = (imin + imax) >>> 1;
var val = arr[imid].tag;
if (val === tag) {
return imid;
} else if (val < tag) {
imin = imid + 1;
} else {
imax = imid - 1;
}
}
// Not found: return -1-insertion point
return -imin - 1;
}
function binSearch(arr, value) {
/* jshint bitwise: false */
var imin = 0;
var imax = arr.length - 1;
while (imin <= imax) {
var imid = (imin + imax) >>> 1;
var val = arr[imid];
if (val === value) {
return imid;
} else if (val < value) {
imin = imid + 1;
} else {
imax = imid - 1;
}
}
// Not found: return -1-insertion point
return -imin - 1;
}
// binary search in a list of ranges (coverage, class definition)
function searchRange(ranges, value) {
// jshint bitwise: false
var range;
var imin = 0;
var imax = ranges.length - 1;
while (imin <= imax) {
var imid = (imin + imax) >>> 1;
range = ranges[imid];
var start = range.start;
if (start === value) {
return range;
} else if (start < value) {
imin = imid + 1;
} else {
imax = imid - 1;
}
}
if (imin > 0) {
range = ranges[imin - 1];
if (value > range.end) {
return 0;
}
return range;
}
}
/**
* @exports opentype.Layout
* @class
*/
function Layout(font, tableName) {
this.font = font;
this.tableName = tableName;
}
Layout.prototype = {
/**
* Binary search an object by "tag" property
* @instance
* @function searchTag
* @memberof opentype.Layout
* @param {Array} arr
* @param {string} tag
* @return {number}
*/
searchTag: searchTag,
/**
* Binary search in a list of numbers
* @instance
* @function binSearch
* @memberof opentype.Layout
* @param {Array} arr
* @param {number} value
* @return {number}
*/
binSearch: binSearch,
/**
* Get or create the Layout table (GSUB, GPOS etc).
* @param {boolean} create - Whether to create a new one.
* @return {Object} The GSUB or GPOS table.
*/
getTable: function(create) {
var layout = this.font.tables[this.tableName];
if (!layout && create) {
layout = this.font.tables[this.tableName] = this.createDefaultTable();
}
return layout;
},
/**
* Returns all scripts in the substitution table.
* @instance
* @return {Array}
*/
getScriptNames: function() {
var layout = this.getTable();
if (!layout) {
return [];
}
return layout.scripts.map(function(script) {
return script.tag;
});
},
/**
* Returns the best bet for a script name.
* Returns 'DFLT' if it exists.
* If not, returns 'latn' if it exists.
* If neither exist, returns undefined.
*/
getDefaultScriptName: function() {
var layout = this.getTable();
if (!layout) {
return;
}
var hasLatn = false;
for (var i = 0; i < layout.scripts.length; i++) {
var name = layout.scripts[i].tag;
if (name === 'DFLT') {
return name;
}
if (name === 'latn') {
hasLatn = true;
}
}
if (hasLatn) {
return 'latn';
}
},
/**
* Returns all LangSysRecords in the given script.
* @instance
* @param {string} [script='DFLT']
* @param {boolean} create - forces the creation of this script table if it doesn't exist.
* @return {Object} An object with tag and script properties.
*/
getScriptTable: function(script, create) {
var layout = this.getTable(create);
if (layout) {
script = script || 'DFLT';
var scripts = layout.scripts;
var pos = searchTag(layout.scripts, script);
if (pos >= 0) {
return scripts[pos].script;
} else if (create) {
var scr = {
tag: script,
script: {
defaultLangSys: {
reserved: 0,
reqFeatureIndex: 0xffff,
featureIndexes: []
},
langSysRecords: []
}
};
scripts.splice(-1 - pos, 0, scr);
return scr.script;
}
}
},
/**
* Returns a language system table
* @instance
* @param {string} [script='DFLT']
* @param {string} [language='dlft']
* @param {boolean} create - forces the creation of this langSysTable if it doesn't exist.
* @return {Object}
*/
getLangSysTable: function(script, language, create) {
var scriptTable = this.getScriptTable(script, create);
if (scriptTable) {
if (!language || language === 'dflt' || language === 'DFLT') {
return scriptTable.defaultLangSys;
}
var pos = searchTag(scriptTable.langSysRecords, language);
if (pos >= 0) {
return scriptTable.langSysRecords[pos].langSys;
} else if (create) {
var langSysRecord = {
tag: language,
langSys: {
reserved: 0,
reqFeatureIndex: 0xffff,
featureIndexes: []
}
};
scriptTable.langSysRecords.splice(-1 - pos, 0, langSysRecord);
return langSysRecord.langSys;
}
}
},
/**
* Get a specific feature table.
* @instance
* @param {string} [script='DFLT']
* @param {string} [language='dlft']
* @param {string} feature - One of the codes listed at https://www.microsoft.com/typography/OTSPEC/featurelist.htm
* @param {boolean} create - forces the creation of the feature table if it doesn't exist.
* @return {Object}
*/
getFeatureTable: function(script, language, feature, create) {
var langSysTable = this.getLangSysTable(script, language, create);
if (langSysTable) {
var featureRecord;
var featIndexes = langSysTable.featureIndexes;
var allFeatures = this.font.tables[this.tableName].features;
// The FeatureIndex array of indices is in arbitrary order,
// even if allFeatures is sorted alphabetically by feature tag.
for (var i = 0; i < featIndexes.length; i++) {
featureRecord = allFeatures[featIndexes[i]];
if (featureRecord.tag === feature) {
return featureRecord.feature;
}
}
if (create) {
var index = allFeatures.length;
// Automatic ordering of features would require to shift feature indexes in the script list.
check.assert(
index === 0 || feature >= allFeatures[index - 1].tag,
'Features must be added in alphabetical order.'
);
featureRecord = {
tag: feature,
feature: { params: 0, lookupListIndexes: [] }
};
allFeatures.push(featureRecord);
featIndexes.push(index);
return featureRecord.feature;
}
}
},
/**
* Get the lookup tables of a given type for a script/language/feature.
* @instance
* @param {string} [script='DFLT']
* @param {string} [language='dlft']
* @param {string} feature - 4-letter feature code
* @param {number} lookupType - 1 to 9
* @param {boolean} create - forces the creation of the lookup table if it doesn't exist, with no subtables.
* @return {Object[]}
*/
getLookupTables: function(script, language, feature, lookupType, create) {
var featureTable = this.getFeatureTable(
script,
language,
feature,
create
);
var tables = [];
if (featureTable) {
var lookupTable;
var lookupListIndexes = featureTable.lookupListIndexes;
var allLookups = this.font.tables[this.tableName].lookups;
// lookupListIndexes are in no particular order, so use naive search.
for (var i = 0; i < lookupListIndexes.length; i++) {
lookupTable = allLookups[lookupListIndexes[i]];
if (lookupTable.lookupType === lookupType) {
tables.push(lookupTable);
}
}
if (tables.length === 0 && create) {
lookupTable = {
lookupType: lookupType,
lookupFlag: 0,
subtables: [],
markFilteringSet: undefined
};
var index = allLookups.length;
allLookups.push(lookupTable);
lookupListIndexes.push(index);
return [lookupTable];
}
}
return tables;
},
/**
* Find a glyph in a class definition table
* https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#class-definition-table
* @param {object} classDefTable - an OpenType Layout class definition table
* @param {number} glyphIndex - the index of the glyph to find
* @returns {number} -1 if not found
*/
getGlyphClass: function(classDefTable, glyphIndex) {
switch (classDefTable.format) {
case 1:
if (
classDefTable.startGlyph <= glyphIndex &&
glyphIndex < classDefTable.startGlyph + classDefTable.classes.length
) {
return classDefTable.classes[glyphIndex - classDefTable.startGlyph];
}
return 0;
case 2:
var range = searchRange(classDefTable.ranges, glyphIndex);
return range ? range.classId : 0;
}
},
/**
* Find a glyph in a coverage table
* https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#coverage-table
* @param {object} coverageTable - an OpenType Layout coverage table
* @param {number} glyphIndex - the index of the glyph to find
* @returns {number} -1 if not found
*/
getCoverageIndex: function(coverageTable, glyphIndex) {
switch (coverageTable.format) {
case 1:
var index = binSearch(coverageTable.glyphs, glyphIndex);
return index >= 0 ? index : -1;
case 2:
var range = searchRange(coverageTable.ranges, glyphIndex);
return range ? range.index + glyphIndex - range.start : -1;
}
},
/**
* Returns the list of glyph indexes of a coverage table.
* Format 1: the list is stored raw
* Format 2: compact list as range records.
* @instance
* @param {Object} coverageTable
* @return {Array}
*/
expandCoverage: function(coverageTable) {
if (coverageTable.format === 1) {
return coverageTable.glyphs;
} else {
var glyphs = [];
var ranges = coverageTable.ranges;
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
var start = range.start;
var end = range.end;
for (var j = start; j <= end; j++) {
glyphs.push(j);
}
}
return glyphs;
}
}
};
// The Position object provides utility methods to manipulate
/**
* @exports opentype.Position
* @class
* @extends opentype.Layout
* @param {opentype.Font}
* @constructor
*/
function Position(font) {
Layout.call(this, font, 'gpos');
}
Position.prototype = Layout.prototype;
/**
* Init some data for faster and easier access later.
*/
Position.prototype.init = function() {
var script = this.getDefaultScriptName();
this.defaultKerningTables = this.getKerningTables(script);
};
/**
* Find a glyph pair in a list of lookup tables of type 2 and retrieve the xAdvance kerning value.
*
* @param {integer} leftIndex - left glyph index
* @param {integer} rightIndex - right glyph index
* @returns {integer}
*/
Position.prototype.getKerningValue = function(
kerningLookups,
leftIndex,
rightIndex
) {
var this$1 = this;
for (var i = 0; i < kerningLookups.length; i++) {
var subtables = kerningLookups[i].subtables;
for (var j = 0; j < subtables.length; j++) {
var subtable = subtables[j];
var covIndex = this$1.getCoverageIndex(subtable.coverage, leftIndex);
if (covIndex < 0) {
continue;
}
switch (subtable.posFormat) {
case 1:
// Search Pair Adjustment Positioning Format 1
var pairSet = subtable.pairSets[covIndex];
for (var k = 0; k < pairSet.length; k++) {
var pair = pairSet[k];
if (pair.secondGlyph === rightIndex) {
return (pair.value1 && pair.value1.xAdvance) || 0;
}
}
break; // left glyph found, not right glyph - try next subtable
case 2:
// Search Pair Adjustment Positioning Format 2
var class1 = this$1.getGlyphClass(subtable.classDef1, leftIndex);
var class2 = this$1.getGlyphClass(subtable.classDef2, rightIndex);
var pair$1 = subtable.classRecords[class1][class2];
return (pair$1.value1 && pair$1.value1.xAdvance) || 0;
}
}
}
return 0;
};
/**
* List all kerning lookup tables.
*
* @param {string} [script='DFLT'] - use font.position.getDefaultScriptName() for a better default value
* @param {string} [language='dflt']
* @return {object[]} The list of kerning lookup tables (may be empty), or undefined if there is no GPOS table (and we should use the kern table)
*/
Position.prototype.getKerningTables = function(script, language) {
if (this.font.tables.gpos) {
return this.getLookupTables(script, language, 'kern', 2);
}
};
// The Substitution object provides utility methods to manipulate
/**
* @exports opentype.Substitution
* @class
* @extends opentype.Layout
* @param {opentype.Font}
* @constructor
*/
function Substitution(font) {
Layout.call(this, font, 'gsub');
}
// Check if 2 arrays of primitives are equal.
function arraysEqual(ar1, ar2) {
var n = ar1.length;
if (n !== ar2.length) {
return false;
}
for (var i = 0; i < n; i++) {
if (ar1[i] !== ar2[i]) {
return false;
}
}
return true;
}
// Find the first subtable of a lookup table in a particular format.
function getSubstFormat(lookupTable, format, defaultSubtable) {
var subtables = lookupTable.subtables;
for (var i = 0; i < subtables.length; i++) {
var subtable = subtables[i];
if (subtable.substFormat === format) {
return subtable;
}
}
if (defaultSubtable) {
subtables.push(defaultSubtable);
return defaultSubtable;
}
return undefined;
}
Substitution.prototype = Layout.prototype;
/**
* Create a default GSUB table.
* @return {Object} gsub - The GSUB table.
*/
Substitution.prototype.createDefaultTable = function() {
// Generate a default empty GSUB table with just a DFLT script and dflt lang sys.
return {
version: 1,
scripts: [
{
tag: 'DFLT',
script: {
defaultLangSys: {
reserved: 0,
reqFeatureIndex: 0xffff,
featureIndexes: []
},
langSysRecords: []
}
}
],
features: [],
lookups: []
};
};
/**
* List all single substitutions (lookup type 1) for a given script, language, and feature.
* @param {string} [script='DFLT']
* @param {string} [language='dflt']
* @param {string} feature - 4-character feature name ('aalt', 'salt', 'ss01'...)
* @return {Array} substitutions - The list of substitutions.
*/
Substitution.prototype.getSingle = function(feature, script, language) {
var this$1 = this;
var substitutions = [];
var lookupTables = this.getLookupTables(script, language, feature, 1);
for (var idx = 0; idx < lookupTables.length; idx++) {
var subtables = lookupTables[idx].subtables;
for (var i = 0; i < subtables.length; i++) {
var subtable = subtables[i];
var glyphs = this$1.expandCoverage(subtable.coverage);
var j = void 0;
if (subtable.substFormat === 1) {
var delta = subtable.deltaGlyphId;
for (j = 0; j < glyphs.length; j++) {
var glyph = glyphs[j];
substitutions.push({ sub: glyph, by: glyph + delta });
}
} else {
var substitute = subtable.substitute;
for (j = 0; j < glyphs.length; j++) {
substitutions.push({ sub: glyphs[j], by: substitute[j] });
}
}
}
}
return substitutions;
};
/**
* List all alternates (lookup type 3) for a given script, language, and feature.
* @param {string} [script='DFLT']
* @param {string} [language='dflt']
* @param {string} feature - 4-character feature name ('aalt', 'salt'...)
* @return {Array} alternates - The list of alternates
*/
Substitution.prototype.getAlternates = function(feature, script, language) {
var this$1 = this;
var alternates = [];
var lookupTables = this.getLookupTables(script, language, feature, 3);
for (var idx = 0; idx < lookupTables.length; idx++) {
var subtables = lookupTables[idx].subtables;
for (var i = 0; i < subtables.length; i++) {
var subtable = subtables[i];
var glyphs = this$1.expandCoverage(subtable.coverage);
var alternateSets = subtable.alternateSets;
for (var j = 0; j < glyphs.length; j++) {
alternates.push({ sub: glyphs[j], by: alternateSets[j] });
}
}
}
return alternates;
};
/**
* List all ligatures (lookup type 4) for a given script, language, and feature.
* The result is an array of ligature objects like { sub: [ids], by: id }
* @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...)
* @param {string} [script='DFLT']
* @param {string} [language='dflt']
* @return {Array} ligatures - The list of ligatures.
*/
Substitution.prototype.getLigatures = function(feature, script, language) {
var this$1 = this;
var ligatures = [];
var lookupTables = this.getLookupTables(script, language, feature, 4);
for (var idx = 0; idx < lookupTables.length; idx++) {
var subtables = lookupTables[idx].subtables;
for (var i = 0; i < subtables.length; i++) {
var subtable = subtables[i];
var glyphs = this$1.expandCoverage(subtable.coverage);
var ligatureSets = subtable.ligatureSets;
for (var j = 0; j < glyphs.length; j++) {
var startGlyph = glyphs[j];
var ligSet = ligatureSets[j];
for (var k = 0; k < ligSet.length; k++) {
var lig = ligSet[k];
ligatures.push({
sub: [startGlyph].concat(lig.components),
by: lig.ligGlyph
});
}
}
}
}
return ligatures;
};
/**
* Add or modify a single substitution (lookup type 1)
* Format 2, more flexible, is always used.
* @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...)
* @param {Object} substitution - { sub: id, delta: number } for format 1 or { sub: id, by: id } for format 2.
* @param {string} [script='DFLT']
* @param {string} [language='dflt']
*/
Substitution.prototype.addSingle = function(
feature,
substitution,
script,
language
) {
var lookupTable = this.getLookupTables(
script,
language,
feature,
1,
true
)[0];
var subtable = getSubstFormat(lookupTable, 2, {
// lookup type 1 subtable, format 2, coverage format 1
substFormat: 2,
coverage: { format: 1, glyphs: [] },
substitute: []
});
check.assert(
subtable.coverage.format === 1,
'Ligature: unable to modify coverage table format ' +
subtable.coverage.format
);
var coverageGlyph = substitution.sub;
var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph);
if (pos < 0) {
pos = -1 - pos;
subtable.coverage.glyphs.splice(pos, 0, coverageGlyph);
subtable.substitute.splice(pos, 0, 0);
}
subtable.substitute[pos] = substitution.by;
};
/**
* Add or modify an alternate substitution (lookup type 1)
* @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...)
* @param {Object} substitution - { sub: id, by: [ids] }
* @param {string} [script='DFLT']
* @param {string} [language='dflt']
*/
Substitution.prototype.addAlternate = function(
feature,
substitution,
script,
language
) {
var lookupTable = this.getLookupTables(
script,
language,
feature,
3,
true
)[0];
var subtable = getSubstFormat(lookupTable, 1, {
// lookup type 3 subtable, format 1, coverage format 1
substFormat: 1,
coverage: { format: 1, glyphs: [] },
alternateSets: []
});
check.assert(
subtable.coverage.format === 1,
'Ligature: unable to modify coverage table format ' +
subtable.coverage.format
);
var coverageGlyph = substitution.sub;
var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph);
if (pos < 0) {
pos = -1 - pos;
subtable.coverage.glyphs.splice(pos, 0, coverageGlyph);
subtable.alternateSets.splice(pos, 0, 0);
}
subtable.alternateSets[pos] = substitution.by;
};
/**
* Add a ligature (lookup type 4)
* Ligatures with more components must be stored ahead of those with fewer components in order to be found
* @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...)
* @param {Object} ligature - { sub: [ids], by: id }
* @param {string} [script='DFLT']
* @param {string} [language='dflt']
*/
Substitution.prototype.addLigature = function(
feature,
ligature,
script,
language
) {
var lookupTable = this.getLookupTables(
script,
language,
feature,
4,
true
)[0];
var subtable = lookupTable.subtables[0];
if (!subtable) {
subtable = {
// lookup type 4 subtable, format 1, coverage format 1
substFormat: 1,
coverage: { format: 1, glyphs: [] },
ligatureSets: []
};
lookupTable.subtables[0] = subtable;
}
check.assert(
subtable.coverage.format === 1,
'Ligature: unable to modify coverage table format ' +
subtable.coverage.format
);
var coverageGlyph = ligature.sub[0];
var ligComponents = ligature.sub.slice(1);
var ligatureTable = {
ligGlyph: ligature.by,
components: ligComponents
};
var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph);
if (pos >= 0) {
// ligatureSet already exists
var ligatureSet = subtable.ligatureSets[pos];
for (var i = 0; i < ligatureSet.length; i++) {
// If ligature already exists, return.
if (arraysEqual(ligatureSet[i].components, ligComponents)) {
return;
}
}
// ligature does not exist: add it.
ligatureSet.push(ligatureTable);
} else {
// Create a new ligatureSet and add coverage for the first glyph.
pos = -1 - pos;
subtable.coverage.glyphs.splice(pos, 0, coverageGlyph);
subtable.ligatureSets.splice(pos, 0, [ligatureTable]);
}
};
/**
* List all feature data for a given script and language.
* @param {string} feature - 4-letter feature name
* @param {string} [script='DFLT']
* @param {string} [language='dflt']
* @return {Array} substitutions - The list of substitutions.
*/
Substitution.prototype.getFeature = function(feature, script, language) {
if (/ss\d\d/.test(feature)) {
// ss01 - ss20
return this.getSingle(feature, script, language);
}
switch (feature) {
case 'aalt':
case 'salt':
return this.getSingle(feature, script, language).concat(
this.getAlternates(feature, script, language)
);
case 'dlig':
case 'liga':
case 'rlig':
return this.getLigatures(feature, script, language);
}
return undefined;
};
/**
* Add a substitution to a feature for a given script and language.
* @param {string} feature - 4-letter feature name
* @param {Object} sub - the substitution to add (an object like { sub: id or [ids], by: id or [ids] })
* @param {string} [script='DFLT']
* @param {string} [language='dflt']
*/
Substitution.prototype.add = function(feature, sub, script, language) {
if (/ss\d\d/.test(feature)) {
// ss01 - ss20
return this.addSingle(feature, sub, script, language);
}
switch (feature) {
case 'aalt':
case 'salt':
if (typeof sub.by === 'number') {
return this.addSingle(feature, sub, script, language);
}
return this.addAlternate(feature, sub, script, language);
case 'dlig':
case 'liga':
case 'rlig':
return this.addLigature(feature, sub, script, language);
}
return undefined;
};
function isBrowser() {
return typeof window !== 'undefined';
}
function nodeBufferToArrayBuffer(buffer) {
var ab = new ArrayBuffer(buffer.length);
var view = new Uint8Array(ab);
for (var i = 0; i < buffer.length; ++i) {
view[i] = buffer[i];
}
return ab;
}
function arrayBufferToNodeBuffer(ab) {
var buffer = new Buffer(ab.byteLength);
var view = new Uint8Array(ab);
for (var i = 0; i < buffer.length; ++i) {
buffer[i] = view[i];
}
return buffer;
}
function checkArgument(expression, message) {
if (!expression) {
throw message;
}
}
// The `glyf` table describes the glyphs in TrueType outline format.
// Parse the coordinate data for a glyph.
function parseGlyphCoordinate(
p,
flag,
previousValue,
shortVectorBitMask,
sameBitMask
) {
var v;
if ((flag & shortVectorBitMask) > 0) {
// The coordinate is 1 byte long.
v = p.parseByte();
// The `same` bit is re-used for short values to signify the sign of the value.
if ((flag & sameBitMask) === 0) {
v = -v;
}
v = previousValue + v;
} else {
// The coordinate is 2 bytes long.
// If the `same` bit is set, the coordinate is the same as the previous coordinate.
if ((flag & sameBitMask) > 0) {
v = previousValue;
} else {
// Parse the coordinate as a signed 16-bit delta value.
v = previousValue + p.parseShort();
}
}
return v;
}
// Parse a TrueType glyph.
function parseGlyph(glyph, data, start) {
var p = new parse.Parser(data, start);
glyph.numberOfContours = p.parseShort();
glyph._xMin = p.parseShort();
glyph._yMin = p.parseShort();
glyph._xMax = p.parseShort();
glyph._yMax = p.parseShort();
var flags;
var flag;
if (glyph.numberOfContours > 0) {
// This glyph is not a composite.
var endPointIndices = (glyph.endPointIndices = []);
for (var i = 0; i < glyph.numberOfContours; i += 1) {
endPointIndices.push(p.parseUShort());
}
glyph.instructionLength = p.parseUShort();
glyph.instructions = [];
for (var i$1 = 0; i$1 < glyph.instructionLength; i$1 += 1) {
glyph.instructions.push(p.parseByte());
}
var numberOfCoordinates = endPointIndices[endPointIndices.length - 1] + 1;
flags = [];
for (var i$2 = 0; i$2 < numberOfCoordinates; i$2 += 1) {
flag = p.parseByte();
flags.push(flag);
// If bit 3 is set, we repeat this flag n times, where n is the next byte.
if ((flag & 8) > 0) {
var repeatCount = p.parseByte();
for (var j = 0; j < repeatCount; j += 1) {
flags.push(flag);
i$2 += 1;
}
}
}
check.argument(flags.length === numberOfCoordinates, 'Bad flags.');
if (endPointIndices.length > 0) {
var points = [];
var point;
// X/Y coordinates are relative to the previous point, except for the first point which is relative to 0,0.
if (numberOfCoordinates > 0) {
for (var i$3 = 0; i$3 < numberOfCoordinates; i$3 += 1) {
flag = flags[i$3];
point = {};
point.onCurve = !!(flag & 1);
point.lastPointOfContour = endPointIndices.indexOf(i$3) >= 0;
points.push(point);
}
var px = 0;
for (var i$4 = 0; i$4 < numberOfCoordinates; i$4 += 1) {
flag = flags[i$4];
point = points[i$4];
point.x = parseGlyphCoordinate(p, flag, px, 2, 16);
px = point.x;
}
var py = 0;
for (var i$5 = 0; i$5 < numberOfCoordinates; i$5 += 1) {
flag = flags[i$5];
point = points[i$5];
point.y = parseGlyphCoordinate(p, flag, py, 4, 32);
py = point.y;
}
}
glyph.points = points;
} else {
glyph.points = [];
}
} else if (glyph.numberOfContours === 0) {
glyph.points = [];
} else {
glyph.isComposite = true;
glyph.points = [];
glyph.components = [];
var moreComponents = true;
while (moreComponents) {
flags = p.parseUShort();
var component = {
glyphIndex: p.parseUShort(),
xScale: 1,
scale01: 0,
scale10: 0,
yScale: 1,
dx: 0,
dy: 0
};
if ((flags & 1) > 0) {
// The arguments are words
if ((flags & 2) > 0) {
// values are offset
component.dx = p.parseShort();
component.dy = p.parseShort();
} else {
// values are matched points
component.matchedPoints = [p.parseUShort(), p.parseUShort()];
}
} else {
// The arguments are bytes
if ((flags & 2) > 0) {
// values are offset
component.dx = p.parseChar();
component.dy = p.parseChar();
} else {
// values are matched points
component.matchedPoints = [p.parseByte(), p.parseByte()];
}
}
if ((flags & 8) > 0) {
// We have a scale
component.xScale = component.yScale = p.parseF2Dot14();
} else if ((flags & 64) > 0) {
// We have an X / Y scale
component.xScale = p.parseF2Dot14();
component.yScale = p.parseF2Dot14();
} else if ((flags & 128) > 0) {
// We have a 2x2 transformation
component.xScale = p.parseF2Dot14();
component.scale01 = p.parseF2Dot14();
component.scale10 = p.parseF2Dot14();
component.yScale = p.parseF2Dot14();
}
glyph.components.push(component);
moreComponents = !!(flags & 32);
}
if (flags & 0x100) {
// We have instructions
glyph.instructionLength = p.parseUShort();
glyph.instructions = [];
for (var i$6 = 0; i$6 < glyph.instructionLength; i$6 += 1) {
glyph.instructions.push(p.parseByte());
}
}
}
}
// Transform an array of points and return a new array.
function transformPoints(points, transform) {
var newPoints = [];
for (var i = 0; i < points.length; i += 1) {
var pt = points[i];
var newPt = {
x: transform.xScale * pt.x + transform.scale01 * pt.y + transform.dx,
y: transform.scale10 * pt.x + transform.yScale * pt.y + transform.dy,
onCurve: pt.onCurve,
lastPointOfContour: pt.lastPointOfContour
};
newPoints.push(newPt);
}
return newPoints;
}
function getContours(points) {
var contours = [];
var currentContour = [];
for (var i = 0; i < points.length; i += 1) {
var pt = points[i];
currentContour.push(pt);
if (pt.lastPointOfContour) {
contours.push(currentContour);
currentContour = [];
}
}
check.argument(
currentContour.length === 0,
'There are still points left in the current contour.'
);
return contours;
}
// Convert the TrueType glyph outline to a Path.
function getPath(points) {
var p = new Path();
if (!points) {
return p;
}
var contours = getContours(points);
for (var contourIndex = 0; contourIndex < contours.length; ++contourIndex) {
var contour = contours[contourIndex];
var prev = null;
var curr = contour[contour.length - 1];
var next = contour[0];
if (curr.onCurve) {
p.moveTo(curr.x, curr.y);
} else {
if (next.onCurve) {
p.moveTo(next.x, next.y);
} else {
// If both first and last points are off-curve, start at their middle.
var start = {
x: (curr.x + next.x) * 0.5,
y: (curr.y + next.y) * 0.5
};
p.moveTo(start.x, start.y);
}
}
for (var i = 0; i < contour.length; ++i) {
prev = curr;
curr = next;
next = contour[(i + 1) % contour.length];
if (curr.onCurve) {
// This is a straight line.
p.lineTo(curr.x, curr.y);
} else {
var prev2 = prev;
var next2 = next;
if (!prev.onCurve) {
prev2 = { x: (curr.x + prev.x) * 0.5, y: (curr.y + prev.y) * 0.5 };
}
if (!next.onCurve) {
next2 = { x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5 };
}
p.quadraticCurveTo(curr.x, curr.y, next2.x, next2.y);
}
}
p.closePath();
}
return p;
}
function buildPath(glyphs, glyph) {
if (glyph.isComposite) {
for (var j = 0; j < glyph.components.length; j += 1) {
var component = glyph.components[j];
var componentGlyph = glyphs.get(component.glyphIndex);
// Force the ttfGlyphLoader to parse the glyph.
componentGlyph.getPath();
if (componentGlyph.points) {
var transformedPoints = void 0;
if (component.matchedPoints === undefined) {
// component positioned by offset
transformedPoints = transformPoints(
componentGlyph.points,
component
);
} else {
// component positioned by matched points
if (
component.matchedPoints[0] > glyph.points.length - 1 ||
component.matchedPoints[1] > componentGlyph.points.length - 1
) {
throw Error('Matched points out of range in ' + glyph.name);
}
var firstPt = glyph.points[component.matchedPoints[0]];
var secondPt = componentGlyph.points[component.matchedPoints[1]];
var transform = {
xScale: component.xScale,
scale01: component.scale01,
scale10: component.scale10,
yScale: component.yScale,
dx: 0,
dy: 0
};
secondPt = transformPoints([secondPt], transform)[0];
transform.dx = firstPt.x - secondPt.x;
transform.dy = firstPt.y - secondPt.y;
transformedPoints = transformPoints(
componentGlyph.points,
transform
);
}
glyph.points = glyph.points.concat(transformedPoints);
}
}
}
return getPath(glyph.points);
}
// Parse all the glyphs according to the offsets from the `loca` table.
function parseGlyfTable(data, start, loca, font) {
var glyphs = new glyphset.GlyphSet(font);
// The last element of the loca table is invalid.
for (var i = 0; i < loca.length - 1; i += 1) {
var offset = loca[i];
var nextOffset = loca[i + 1];
if (offset !== nextOffset) {
glyphs.push(
i,
glyphset.ttfGlyphLoader(
font,
i,
parseGlyph,
data,
start + offset,
buildPath
)
);
} else {
glyphs.push(i, glyphset.glyphLoader(font, i));
}
}
return glyphs;
}
var glyf = { getPath: getPath, parse: parseGlyfTable };
/* A TrueType font hinting interpreter.
*
* (c) 2017 Axel Kittenberger
*
* This interpreter has been implemented according to this documentation:
* https://developer.apple.com/fonts/TrueType-Reference-Manual/RM05/Chap5.html
*
* According to the documentation F24DOT6 values are used for pixels.
* That means calculation is 1/64 pixel accurate and uses integer operations.
* However, Javascript has floating point operations by default and only
* those are available. One could make a case to simulate the 1/64 accuracy
* exactly by truncating after every division operation
* (for example with << 0) to get pixel exactly results as other TrueType
* implementations. It may make sense since some fonts are pixel optimized
* by hand using DELTAP instructions. The current implementation doesn't
* and rather uses full floating point precision.
*
* xScale, yScale and rotation is currently ignored.
*
* A few non-trivial instructions are missing as I didn't encounter yet
* a font that used them to test a possible implementation.
*
* Some fonts seem to use undocumented features regarding the twilight zone.
* Only some of them are implemented as they were encountered.
*
* The exports.DEBUG statements are removed on the minified distribution file.
*/
var instructionTable;
var exec;
var execGlyph;
var execComponent;
/*
* Creates a hinting object.
*
* There ought to be exactly one
* for each truetype font that is used for hinting.
*/
function Hinting(font) {
// the font this hinting object is for
this.font = font;
this.getCommands = function(hPoints) {
return glyf.getPath(hPoints).commands;
};
// cached states
this._fpgmState = this._prepState = undefined;
// errorState
// 0 ... all okay
// 1 ... had an error in a glyf,
// continue working but stop spamming
// the console
// 2 ... error at prep, stop hinting at this ppem
// 3 ... error at fpeg, stop hinting for this font at all
this._errorState = 0;
}
/*
* Not rounding.
*/
function roundOff(v) {
return v;
}
/*
* Rounding to grid.
*/
function roundToGrid(v) {
//Rounding in TT is supposed to "symmetrical around zero"
return Math.sign(v) * Math.round(Math.abs(v));
}
/*
* Rounding to double grid.
*/
function roundToDoubleGrid(v) {
return Math.sign(v) * Math.round(Math.abs(v * 2)) / 2;
}
/*
* Rounding to half grid.
*/
function roundToHalfGrid(v) {
return Math.sign(v) * (Math.round(Math.abs(v) + 0.5) - 0.5);
}
/*
* Rounding to up to grid.
*/
function roundUpToGrid(v) {
return Math.sign(v) * Math.ceil(Math.abs(v));
}
/*
* Rounding to down to grid.
*/
function roundDownToGrid(v) {
return Math.sign(v) * Math.floor(Math.abs(v));
}
/*
* Super rounding.
*/
var roundSuper = function(v) {
var period = this.srPeriod;
var phase = this.srPhase;
var threshold = this.srThreshold;
var sign = 1;
if (v < 0) {
v = -v;
sign = -1;
}
v += threshold - phase;
v = Math.trunc(v / period) * period;
v += phase;
// according to http://xgridfit.sourceforge.net/round.html
if (v < 0) {
return phase * sign;
}
return v * sign;
};
/*
* Unit vector of x-axis.
*/
var xUnitVector = {
x: 1,
y: 0,
axis: 'x',
// Gets the projected distance between two points.
// o1/o2 ... if true, respective original position is used.
distance: function(p1, p2, o1, o2) {
return (o1 ? p1.xo : p1.x) - (o2 ? p2.xo : p2.x);
},
// Moves point p so the moved position has the same relative
// position to the moved positions of rp1 and rp2 than the
// original positions had.
//
// See APPENDIX on INTERPOLATE at the bottom of this file.
interpolate: function(p, rp1, rp2, pv) {
var do1;
var do2;
var doa1;
var doa2;
var dm1;
var dm2;
var dt;
if (!pv || pv === this) {
do1 = p.xo - rp1.xo;
do2 = p.xo - rp2.xo;
dm1 = rp1.x - rp1.xo;
dm2 = rp2.x - rp2.xo;
doa1 = Math.abs(do1);
doa2 = Math.abs(do2);
dt = doa1 + doa2;
if (dt === 0) {
p.x = p.xo + (dm1 + dm2) / 2;
return;
}
p.x = p.xo + (dm1 * doa2 + dm2 * doa1) / dt;
return;
}
do1 = pv.distance(p, rp1, true, true);
do2 = pv.distance(p, rp2, true, true);
dm1 = pv.distance(rp1, rp1, false, true);
dm2 = pv.distance(rp2, rp2, false, true);
doa1 = Math.abs(do1);
doa2 = Math.abs(do2);
dt = doa1 + doa2;
if (dt === 0) {
xUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true);
return;
}
xUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true);
},
// Slope of line normal to this
normalSlope: Number.NEGATIVE_INFINITY,
// Sets the point 'p' relative to point 'rp'
// by the distance 'd'.
//
// See APPENDIX on SETRELATIVE at the bottom of this file.
//
// p ... point to set
// rp ... reference point
// d ... distance on projection vector
// pv ... projection vector (undefined = this)
// org ... if true, uses the original position of rp as reference.
setRelative: function(p, rp, d, pv, org) {
if (!pv || pv === this) {
p.x = (org ? rp.xo : rp.x) + d;
return;
}
var rpx = org ? rp.xo : rp.x;
var rpy = org ? rp.yo : rp.y;
var rpdx = rpx + d * pv.x;
var rpdy = rpy + d * pv.y;
p.x = rpdx + (p.y - rpdy) / pv.normalSlope;
},
// Slope of vector line.
slope: 0,
// Touches the point p.
touch: function(p) {
p.xTouched = true;
},
// Tests if a point p is touched.
touched: function(p) {
return p.xTouched;
},
// Untouches the point p.
untouch: function(p) {
p.xTouched = false;
}
};
/*
* Unit vector of y-axis.
*/
var yUnitVector = {
x: 0,
y: 1,
axis: 'y',
// Gets the projected distance between two points.
// o1/o2 ... if true, respective original position is used.
distance: function(p1, p2, o1, o2) {
return (o1 ? p1.yo : p1.y) - (o2 ? p2.yo : p2.y);
},
// Moves point p so the moved position has the same relative
// position to the moved positions of rp1 and rp2 than the
// original positions had.
//
// See APPENDIX on INTERPOLATE at the bottom of this file.
interpolate: function(p, rp1, rp2, pv) {
var do1;
var do2;
var doa1;
var doa2;
var dm1;
var dm2;
var dt;
if (!pv || pv === this) {
do1 = p.yo - rp1.yo;
do2 = p.yo - rp2.yo;
dm1 = rp1.y - rp1.yo;
dm2 = rp2.y - rp2.yo;
doa1 = Math.abs(do1);
doa2 = Math.abs(do2);
dt = doa1 + doa2;
if (dt === 0) {
p.y = p.yo + (dm1 + dm2) / 2;
return;
}
p.y = p.yo + (dm1 * doa2 + dm2 * doa1) / dt;
return;
}
do1 = pv.distance(p, rp1, true, true);
do2 = pv.distance(p, rp2, true, true);
dm1 = pv.distance(rp1, rp1, false, true);
dm2 = pv.distance(rp2, rp2, false, true);
doa1 = Math.abs(do1);
doa2 = Math.abs(do2);
dt = doa1 + doa2;
if (dt === 0) {
yUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true);
return;
}
yUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true);
},
// Slope of line normal to this.
normalSlope: 0,
// Sets the point 'p' relative to point 'rp'
// by the distance 'd'
//
// See APPENDIX on SETRELATIVE at the bottom of this file.
//
// p ... point to set
// rp ... reference point
// d ... distance on projection vector
// pv ... projection vector (undefined = this)
// org ... if true, uses the original position of rp as reference.
setRelative: function(p, rp, d, pv, org) {
if (!pv || pv === this) {
p.y = (org ? rp.yo : rp.y) + d;
return;
}
var rpx = org ? rp.xo : rp.x;
var rpy = org ? rp.yo : rp.y;
var rpdx = rpx + d * pv.x;
var rpdy = rpy + d * pv.y;
p.y = rpdy + pv.normalSlope * (p.x - rpdx);
},
// Slope of vector line.
slope: Number.POSITIVE_INFINITY,
// Touches the point p.
touch: function(p) {
p.yTouched = true;
},
// Tests if a point p is touched.
touched: function(p) {
return p.yTouched;
},
// Untouches the point p.
untouch: function(p) {
p.yTouched = false;
}
};
Object.freeze(xUnitVector);
Object.freeze(yUnitVector);
/*
* Creates a unit vector that is not x- or y-axis.
*/
function UnitVector(x, y) {
this.x = x;
this.y = y;
this.axis = undefined;
this.slope = y / x;
this.normalSlope = -x / y;
Object.freeze(this);
}
/*
* Gets the projected distance between two points.
* o1/o2 ... if true, respective original position is used.
*/
UnitVector.prototype.distance = function(p1, p2, o1, o2) {
return (
this.x * xUnitVector.distance(p1, p2, o1, o2) +
this.y * yUnitVector.distance(p1, p2, o1, o2)
);
};
/*
* Moves point p so the moved position has the same relative
* position to the moved positions of rp1 and rp2 than the
* original positions had.
*
* See APPENDIX on INTERPOLATE at the bottom of this file.
*/
UnitVector.prototype.interpolate = function(p, rp1, rp2, pv) {
var dm1;
var dm2;
var do1;
var do2;
var doa1;
var doa2;
var dt;
do1 = pv.distance(p, rp1, true, true);
do2 = pv.distance(p, rp2, true, true);
dm1 = pv.distance(rp1, rp1, false, true);
dm2 = pv.distance(rp2, rp2, false, true);
doa1 = Math.abs(do1);
doa2 = Math.abs(do2);
dt = doa1 + doa2;
if (dt === 0) {
this.setRelative(p, p, (dm1 + dm2) / 2, pv, true);
return;
}
this.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true);
};
/*
* Sets the point 'p' relative to point 'rp'
* by the distance 'd'
*
* See APPENDIX on SETRELATIVE at the bottom of this file.
*
* p ... point to set
* rp ... reference point
* d ... distance on projection vector
* pv ... projection vector (undefined = this)
* org ... if true, uses the original position of rp as reference.
*/
UnitVector.prototype.setRelative = function(p, rp, d, pv, org) {
pv = pv || this;
var rpx = org ? rp.xo : rp.x;
var rpy = org ? rp.yo : rp.y;
var rpdx = rpx + d * pv.x;
var rpdy = rpy + d * pv.y;
var pvns = pv.normalSlope;
var fvs = this.slope;
var px = p.x;
var py = p.y;
p.x = (fvs * px - pvns * rpdx + rpdy - py) / (fvs - pvns);
p.y = fvs * (p.x - px) + py;
};
/*
* Touches the point p.
*/
UnitVector.prototype.touch = function(p) {
p.xTouched = true;
p.yTouched = true;
};
/*
* Returns a unit vector with x/y coordinates.
*/
function getUnitVector(x, y) {
var d = Math.sqrt(x * x + y * y);
x /= d;
y /= d;
if (x === 1 && y === 0) {
return xUnitVector;
} else if (x === 0 && y === 1) {
return yUnitVector;
} else {
return new UnitVector(x, y);
}
}
/*
* Creates a point in the hinting engine.
*/
function HPoint(x, y, lastPointOfContour, onCurve) {
this.x = this.xo = Math.round(x * 64) / 64; // hinted x value and original x-value
this.y = this.yo = Math.round(y * 64) / 64; // hinted y value and original y-value
this.lastPointOfContour = lastPointOfContour;
this.onCurve = onCurve;
this.prevPointOnContour = undefined;
this.nextPointOnContour = undefined;
this.xTouched = false;
this.yTouched = false;
Object.preventExtensions(this);
}
/*
* Returns the next touched point on the contour.
*
* v ... unit vector to test touch axis.
*/
HPoint.prototype.nextTouched = function(v) {
var p = this.nextPointOnContour;
while (!v.touched(p) && p !== this) {
p = p.nextPointOnContour;
}
return p;
};
/*
* Returns the previous touched point on the contour
*
* v ... unit vector to test touch axis.
*/
HPoint.prototype.prevTouched = function(v) {
var p = this.prevPointOnContour;
while (!v.touched(p) && p !== this) {
p = p.prevPointOnContour;
}
return p;
};
/*
* The zero point.
*/
var HPZero = Object.freeze(new HPoint(0, 0));
/*
* The default state of the interpreter.
*
* Note: Freezing the defaultState and then deriving from it
* makes the V8 Javascript engine going awkward,
* so this is avoided, albeit the defaultState shouldn't
* ever change.
*/
var defaultState = {
cvCutIn: 17 / 16, // control value cut in
deltaBase: 9,
deltaShift: 0.125,
loop: 1, // loops some instructions
minDis: 1, // minimum distance
autoFlip: true
};
/*
* The current state of the interpreter.
*
* env ... 'fpgm' or 'prep' or 'glyf'
* prog ... the program
*/
function State(env, prog) {
this.env = env;
this.stack = [];
this.prog = prog;
switch (env) {
case 'glyf':
this.zp0 = this.zp1 = this.zp2 = 1;
this.rp0 = this.rp1 = this.rp2 = 0;
/* fall through */
case 'prep':
this.fv = this.pv = this.dpv = xUnitVector;
this.round = roundToGrid;
}
}
/*
* Executes a glyph program.
*
* This does the hinting for each glyph.
*
* Returns an array of moved points.
*
* glyph: the glyph to hint
* ppem: the size the glyph is rendered for
*/
Hinting.prototype.exec = function(glyph, ppem) {
if (typeof ppem !== 'number') {
throw new Error('Point size is not a number!');
}
// Received a fatal error, don't do any hinting anymore.
if (this._errorState > 2) {
return;
}
var font = this.font;
var prepState = this._prepState;
if (!prepState || prepState.ppem !== ppem) {
var fpgmState = this._fpgmState;
if (!fpgmState) {
// Executes the fpgm state.
// This is used by fonts to define functions.
State.prototype = defaultState;
fpgmState = this._fpgmState = new State('fpgm', font.tables.fpgm);
fpgmState.funcs = [];
fpgmState.font = font;
if (exports.DEBUG) {
console.log('---EXEC FPGM---');
fpgmState.step = -1;
}
try {
exec(fpgmState);
} catch (e) {
console.log('Hinting error in FPGM:' + e);
this._errorState = 3;
return;
}
}
// Executes the prep program for this ppem setting.
// This is used by fonts to set cvt values
// depending on to be rendered font size.
State.prototype = fpgmState;
prepState = this._prepState = new State('prep', font.tables.prep);
prepState.ppem = ppem;
// Creates a copy of the cvt table
// and scales it to the current ppem setting.
var oCvt = font.tables.cvt;
if (oCvt) {
var cvt = (prepState.cvt = new Array(oCvt.length));
var scale = ppem / font.unitsPerEm;
for (var c = 0; c < oCvt.length; c++) {
cvt[c] = oCvt[c] * scale;
}
} else {
prepState.cvt = [];
}
if (exports.DEBUG) {
console.log('---EXEC PREP---');
prepState.step = -1;
}
try {
exec(prepState);
} catch (e) {
if (this._errorState < 2) {
console.log('Hinting error in PREP:' + e);
}
this._errorState = 2;
}
}
if (this._errorState > 1) {
return;
}
try {
return execGlyph(glyph, prepState);
} catch (e) {
if (this._errorState < 1) {
console.log('Hinting error:' + e);
console.log('Note: further hinting errors are silenced');
}
this._errorState = 1;
return undefined;
}
};
/*
* Executes the hinting program for a glyph.
*/
execGlyph = function(glyph, prepState) {
// original point positions
var xScale = prepState.ppem / prepState.font.unitsPerEm;
var yScale = xScale;
var components = glyph.components;
var contours;
var gZone;
var state;
State.prototype = prepState;
if (!components) {
state = new State('glyf', glyph.instructions);
if (exports.DEBUG) {
console.log('---EXEC GLYPH---');
state.step = -1;
}
execComponent(glyph, state, xScale, yScale);
gZone = state.gZone;
} else {
var font = prepState.font;
gZone = [];
contours = [];
for (var i = 0; i < components.length; i++) {
var c = components[i];
var cg = font.glyphs.get(c.glyphIndex);
state = new State('glyf', cg.instructions);
if (exports.DEBUG) {
console.log('---EXEC COMP ' + i + '---');
state.step = -1;
}
execComponent(cg, state, xScale, yScale);
// appends the computed points to the result array
// post processes the component points
var dx = Math.round(c.dx * xScale);
var dy = Math.round(c.dy * yScale);
var gz = state.gZone;
var cc = state.contours;
for (var pi = 0; pi < gz.length; pi++) {
var p = gz[pi];
p.xTouched = p.yTouched = false;
p.xo = p.x = p.x + dx;
p.yo = p.y = p.y + dy;
}
var gLen = gZone.length;
gZone.push.apply(gZone, gz);
for (var j = 0; j < cc.length; j++) {
contours.push(cc[j] + gLen);
}
}
if (glyph.instructions && !state.inhibitGridFit) {
// the composite has instructions on its own
state = new State('glyf', glyph.instructions);
state.gZone = state.z0 = state.z1 = state.z2 = gZone;
state.contours = contours;
// note: HPZero cannot be used here, since
// the point might be modified
gZone.push(
new HPoint(0, 0),
new HPoint(Math.round(glyph.advanceWidth * xScale), 0)
);
if (exports.DEBUG) {
console.log('---EXEC COMPOSITE---');
state.step = -1;
}
exec(state);
gZone.length -= 2;
}
}
return gZone;
};
/*
* Executes the hinting program for a component of a multi-component glyph
* or of the glyph itself for a non-component glyph.
*/
execComponent = function(glyph, state, xScale, yScale) {
var points = glyph.points || [];
var pLen = points.length;
var gZone = (state.gZone = state.z0 = state.z1 = state.z2 = []);
var contours = (state.contours = []);
// Scales the original points and
// makes copies for the hinted points.
var cp; // current point
for (var i = 0; i < pLen; i++) {
cp = points[i];
gZone[i] = new HPoint(
cp.x * xScale,
cp.y * yScale,
cp.lastPointOfContour,
cp.onCurve
);
}
// Chain links the contours.
var sp; // start point
var np; // next point
for (var i$1 = 0; i$1 < pLen; i$1++) {
cp = gZone[i$1];
if (!sp) {
sp = cp;
contours.push(i$1);
}
if (cp.lastPointOfContour) {
cp.nextPointOnContour = sp;
sp.prevPointOnContour = cp;
sp = undefined;
} else {
np = gZone[i$1 + 1];
cp.nextPointOnContour = np;
np.prevPointOnContour = cp;
}
}
if (state.inhibitGridFit) {
return;
}
if (exports.DEBUG) {
console.log('PROCESSING GLYPH', state.stack);
for (var i$2 = 0; i$2 < pLen; i$2++) {
console.log(i$2, gZone[i$2].x, gZone[i$2].y);
}
}
gZone.push(
new HPoint(0, 0),
new HPoint(Math.round(glyph.advanceWidth * xScale), 0)
);
exec(state);
// Removes the extra points.
gZone.length -= 2;
if (exports.DEBUG) {
console.log('FINISHED GLYPH', state.stack);
for (var i$3 = 0; i$3 < pLen; i$3++) {
console.log(i$3, gZone[i$3].x, gZone[i$3].y);
}
}
};
/*
* Executes the program loaded in state.
*/
exec = function(state) {
var prog = state.prog;
if (!prog) {
return;
}
var pLen = prog.length;
var ins;
for (state.ip = 0; state.ip < pLen; state.ip++) {
if (exports.DEBUG) {
state.step++;
}
ins = instructionTable[prog[state.ip]];
if (!ins) {
throw new Error(
'unknown instruction: 0x' + Number(prog[state.ip]).toString(16)
);
}
ins(state);
// very extensive debugging for each step
/*
if (exports.DEBUG) {
var da;
if (state.gZone) {
da = [];
for (let i = 0; i < state.gZone.length; i++)
{
da.push(i + ' ' +
state.gZone[i].x * 64 + ' ' +
state.gZone[i].y * 64 + ' ' +
(state.gZone[i].xTouched ? 'x' : '') +
(state.gZone[i].yTouched ? 'y' : '')
);
}
console.log('GZ', da);
}
if (state.tZone) {
da = [];
for (let i = 0; i < state.tZone.length; i++) {
da.push(i + ' ' +
state.tZone[i].x * 64 + ' ' +
state.tZone[i].y * 64 + ' ' +
(state.tZone[i].xTouched ? 'x' : '') +
(state.tZone[i].yTouched ? 'y' : '')
);
}
console.log('TZ', da);
}
if (state.stack.length > 10) {
console.log(
state.stack.length,
'...', state.stack.slice(state.stack.length - 10)
);
} else {
console.log(state.stack.length, state.stack);
}
}
*/
}
};
/*
* Initializes the twilight zone.
*
* This is only done if a SZPx instruction
* refers to the twilight zone.
*/
function initTZone(state) {
var tZone = (state.tZone = new Array(state.gZone.length));
// no idea if this is actually correct...
for (var i = 0; i < tZone.length; i++) {
tZone[i] = new HPoint(0, 0);
}
}
/*
* Skips the instruction pointer ahead over an IF/ELSE block.
* handleElse .. if true breaks on matching ELSE
*/
function skip(state, handleElse) {
var prog = state.prog;
var ip = state.ip;
var nesting = 1;
var ins;
do {
ins = prog[++ip];
if (ins === 0x58) {
// IF
nesting++;
} else if (ins === 0x59) {
// EIF
nesting--;
} else if (ins === 0x40) {
// NPUSHB
ip += prog[ip + 1] + 1;
} else if (ins === 0x41) {
// NPUSHW
ip += 2 * prog[ip + 1] + 1;
} else if (ins >= 0xb0 && ins <= 0xb7) {
// PUSHB
ip += ins - 0xb0 + 1;
} else if (ins >= 0xb8 && ins <= 0xbf) {
// PUSHW
ip += (ins - 0xb8 + 1) * 2;
} else if (handleElse && nesting === 1 && ins === 0x1b) {
// ELSE
break;
}
} while (nesting > 0);
state.ip = ip;
}
/*----------------------------------------------------------*
* And then a lot of instructions... *
*----------------------------------------------------------*/
// SVTCA[a] Set freedom and projection Vectors To Coordinate Axis
// 0x00-0x01
function SVTCA(v, state) {
if (exports.DEBUG) {
console.log(state.step, 'SVTCA[' + v.axis + ']');
}
state.fv = state.pv = state.dpv = v;
}
// SPVTCA[a] Set Projection Vector to Coordinate Axis
// 0x02-0x03
function SPVTCA(v, state) {
if (exports.DEBUG) {
console.log(state.step, 'SPVTCA[' + v.axis + ']');
}
state.pv = state.dpv = v;
}
// SFVTCA[a] Set Freedom Vector to Coordinate Axis
// 0x04-0x05
function SFVTCA(v, state) {
if (exports.DEBUG) {
console.log(state.step, 'SFVTCA[' + v.axis + ']');
}
state.fv = v;
}
// SPVTL[a] Set Projection Vector To Line
// 0x06-0x07
function SPVTL(a, state) {
var stack = state.stack;
var p2i = stack.pop();
var p1i = stack.pop();
var p2 = state.z2[p2i];
var p1 = state.z1[p1i];
if (exports.DEBUG) {
console.log('SPVTL[' + a + ']', p2i, p1i);
}
var dx;
var dy;
if (!a) {
dx = p1.x - p2.x;
dy = p1.y - p2.y;
} else {
dx = p2.y - p1.y;
dy = p1.x - p2.x;
}
state.pv = state.dpv = getUnitVector(dx, dy);
}
// SFVTL[a] Set Freedom Vector To Line
// 0x08-0x09
function SFVTL(a, state) {
var stack = state.stack;
var p2i = stack.pop();
var p1i = stack.pop();
var p2 = state.z2[p2i];
var p1 = state.z1[p1i];
if (exports.DEBUG) {
console.log('SFVTL[' + a + ']', p2i, p1i);
}
var dx;
var dy;
if (!a) {
dx = p1.x - p2.x;
dy = p1.y - p2.y;
} else {
dx = p2.y - p1.y;
dy = p1.x - p2.x;
}
state.fv = getUnitVector(dx, dy);
}
// SPVFS[] Set Projection Vector From Stack
// 0x0A
function SPVFS(state) {
var stack = state.stack;
var y = stack.pop();
var x = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'SPVFS[]', y, x);
}
state.pv = state.dpv = getUnitVector(x, y);
}
// SFVFS[] Set Freedom Vector From Stack
// 0x0B
function SFVFS(state) {
var stack = state.stack;
var y = stack.pop();
var x = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'SPVFS[]', y, x);
}
state.fv = getUnitVector(x, y);
}
// GPV[] Get Projection Vector
// 0x0C
function GPV(state) {
var stack = state.stack;
var pv = state.pv;
if (exports.DEBUG) {
console.log(state.step, 'GPV[]');
}
stack.push(pv.x * 0x4000);
stack.push(pv.y * 0x4000);
}
// GFV[] Get Freedom Vector
// 0x0C
function GFV(state) {
var stack = state.stack;
var fv = state.fv;
if (exports.DEBUG) {
console.log(state.step, 'GFV[]');
}
stack.push(fv.x * 0x4000);
stack.push(fv.y * 0x4000);
}
// SFVTPV[] Set Freedom Vector To Projection Vector
// 0x0E
function SFVTPV(state) {
state.fv = state.pv;
if (exports.DEBUG) {
console.log(state.step, 'SFVTPV[]');
}
}
// ISECT[] moves point p to the InterSECTion of two lines
// 0x0F
function ISECT(state) {
var stack = state.stack;
var pa0i = stack.pop();
var pa1i = stack.pop();
var pb0i = stack.pop();
var pb1i = stack.pop();
var pi = stack.pop();
var z0 = state.z0;
var z1 = state.z1;
var pa0 = z0[pa0i];
var pa1 = z0[pa1i];
var pb0 = z1[pb0i];
var pb1 = z1[pb1i];
var p = state.z2[pi];
if (exports.DEBUG) {
console.log('ISECT[], ', pa0i, pa1i, pb0i, pb1i, pi);
}
// math from
// en.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line
var x1 = pa0.x;
var y1 = pa0.y;
var x2 = pa1.x;
var y2 = pa1.y;
var x3 = pb0.x;
var y3 = pb0.y;
var x4 = pb1.x;
var y4 = pb1.y;
var div = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
var f1 = x1 * y2 - y1 * x2;
var f2 = x3 * y4 - y3 * x4;
p.x = (f1 * (x3 - x4) - f2 * (x1 - x2)) / div;
p.y = (f1 * (y3 - y4) - f2 * (y1 - y2)) / div;
}
// SRP0[] Set Reference Point 0
// 0x10
function SRP0(state) {
state.rp0 = state.stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'SRP0[]', state.rp0);
}
}
// SRP1[] Set Reference Point 1
// 0x11
function SRP1(state) {
state.rp1 = state.stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'SRP1[]', state.rp1);
}
}
// SRP1[] Set Reference Point 2
// 0x12
function SRP2(state) {
state.rp2 = state.stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'SRP2[]', state.rp2);
}
}
// SZP0[] Set Zone Pointer 0
// 0x13
function SZP0(state) {
var n = state.stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'SZP0[]', n);
}
state.zp0 = n;
switch (n) {
case 0:
if (!state.tZone) {
initTZone(state);
}
state.z0 = state.tZone;
break;
case 1:
state.z0 = state.gZone;
break;
default:
throw new Error('Invalid zone pointer');
}
}
// SZP1[] Set Zone Pointer 1
// 0x14
function SZP1(state) {
var n = state.stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'SZP1[]', n);
}
state.zp1 = n;
switch (n) {
case 0:
if (!state.tZone) {
initTZone(state);
}
state.z1 = state.tZone;
break;
case 1:
state.z1 = state.gZone;
break;
default:
throw new Error('Invalid zone pointer');
}
}
// SZP2[] Set Zone Pointer 2
// 0x15
function SZP2(state) {
var n = state.stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'SZP2[]', n);
}
state.zp2 = n;
switch (n) {
case 0:
if (!state.tZone) {
initTZone(state);
}
state.z2 = state.tZone;
break;
case 1:
state.z2 = state.gZone;
break;
default:
throw new Error('Invalid zone pointer');
}
}
// SZPS[] Set Zone PointerS
// 0x16
function SZPS(state) {
var n = state.stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'SZPS[]', n);
}
state.zp0 = state.zp1 = state.zp2 = n;
switch (n) {
case 0:
if (!state.tZone) {
initTZone(state);
}
state.z0 = state.z1 = state.z2 = state.tZone;
break;
case 1:
state.z0 = state.z1 = state.z2 = state.gZone;
break;
default:
throw new Error('Invalid zone pointer');
}
}
// SLOOP[] Set LOOP variable
// 0x17
function SLOOP(state) {
state.loop = state.stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'SLOOP[]', state.loop);
}
}
// RTG[] Round To Grid
// 0x18
function RTG(state) {
if (exports.DEBUG) {
console.log(state.step, 'RTG[]');
}
state.round = roundToGrid;
}
// RTHG[] Round To Half Grid
// 0x19
function RTHG(state) {
if (exports.DEBUG) {
console.log(state.step, 'RTHG[]');
}
state.round = roundToHalfGrid;
}
// SMD[] Set Minimum Distance
// 0x1A
function SMD(state) {
var d = state.stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'SMD[]', d);
}
state.minDis = d / 0x40;
}
// ELSE[] ELSE clause
// 0x1B
function ELSE(state) {
// This instruction has been reached by executing a then branch
// so it just skips ahead until matching EIF.
//
// In case the IF was negative the IF[] instruction already
// skipped forward over the ELSE[]
if (exports.DEBUG) {
console.log(state.step, 'ELSE[]');
}
skip(state, false);
}
// JMPR[] JuMP Relative
// 0x1C
function JMPR(state) {
var o = state.stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'JMPR[]', o);
}
// A jump by 1 would do nothing.
state.ip += o - 1;
}
// SCVTCI[] Set Control Value Table Cut-In
// 0x1D
function SCVTCI(state) {
var n = state.stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'SCVTCI[]', n);
}
state.cvCutIn = n / 0x40;
}
// DUP[] DUPlicate top stack element
// 0x20
function DUP(state) {
var stack = state.stack;
if (exports.DEBUG) {
console.log(state.step, 'DUP[]');
}
stack.push(stack[stack.length - 1]);
}
// POP[] POP top stack element
// 0x21
function POP(state) {
if (exports.DEBUG) {
console.log(state.step, 'POP[]');
}
state.stack.pop();
}
// CLEAR[] CLEAR the stack
// 0x22
function CLEAR(state) {
if (exports.DEBUG) {
console.log(state.step, 'CLEAR[]');
}
state.stack.length = 0;
}
// SWAP[] SWAP the top two elements on the stack
// 0x23
function SWAP(state) {
var stack = state.stack;
var a = stack.pop();
var b = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'SWAP[]');
}
stack.push(a);
stack.push(b);
}
// DEPTH[] DEPTH of the stack
// 0x24
function DEPTH(state) {
var stack = state.stack;
if (exports.DEBUG) {
console.log(state.step, 'DEPTH[]');
}
stack.push(stack.length);
}
// LOOPCALL[] LOOPCALL function
// 0x2A
function LOOPCALL(state) {
var stack = state.stack;
var fn = stack.pop();
var c = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'LOOPCALL[]', fn, c);
}
// saves callers program
var cip = state.ip;
var cprog = state.prog;
state.prog = state.funcs[fn];
// executes the function
for (var i = 0; i < c; i++) {
exec(state);
if (exports.DEBUG) {
console.log(
++state.step,
i + 1 < c ? 'next loopcall' : 'done loopcall',
i
);
}
}
// restores the callers program
state.ip = cip;
state.prog = cprog;
}
// CALL[] CALL function
// 0x2B
function CALL(state) {
var fn = state.stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'CALL[]', fn);
}
// saves callers program
var cip = state.ip;
var cprog = state.prog;
state.prog = state.funcs[fn];
// executes the function
exec(state);
// restores the callers program
state.ip = cip;
state.prog = cprog;
if (exports.DEBUG) {
console.log(++state.step, 'returning from', fn);
}
}
// CINDEX[] Copy the INDEXed element to the top of the stack
// 0x25
function CINDEX(state) {
var stack = state.stack;
var k = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'CINDEX[]', k);
}
// In case of k == 1, it copies the last element after popping
// thus stack.length - k.
stack.push(stack[stack.length - k]);
}
// MINDEX[] Move the INDEXed element to the top of the stack
// 0x26
function MINDEX(state) {
var stack = state.stack;
var k = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'MINDEX[]', k);
}
stack.push(stack.splice(stack.length - k, 1)[0]);
}
// FDEF[] Function DEFinition
// 0x2C
function FDEF(state) {
if (state.env !== 'fpgm') {
throw new Error('FDEF not allowed here');
}
var stack = state.stack;
var prog = state.prog;
var ip = state.ip;
var fn = stack.pop();
var ipBegin = ip;
if (exports.DEBUG) {
console.log(state.step, 'FDEF[]', fn);
}
while (prog[++ip] !== 0x2d) {}
state.ip = ip;
state.funcs[fn] = prog.slice(ipBegin + 1, ip);
}
// MDAP[a] Move Direct Absolute Point
// 0x2E-0x2F
function MDAP(round, state) {
var pi = state.stack.pop();
var p = state.z0[pi];
var fv = state.fv;
var pv = state.pv;
if (exports.DEBUG) {
console.log(state.step, 'MDAP[' + round + ']', pi);
}
var d = pv.distance(p, HPZero);
if (round) {
d = state.round(d);
}
fv.setRelative(p, HPZero, d, pv);
fv.touch(p);
state.rp0 = state.rp1 = pi;
}
// IUP[a] Interpolate Untouched Points through the outline
// 0x30
function IUP(v, state) {
var z2 = state.z2;
var pLen = z2.length - 2;
var cp;
var pp;
var np;
if (exports.DEBUG) {
console.log(state.step, 'IUP[' + v.axis + ']');
}
for (var i = 0; i < pLen; i++) {
cp = z2[i]; // current point
// if this point has been touched go on
if (v.touched(cp)) {
continue;
}
pp = cp.prevTouched(v);
// no point on the contour has been touched?
if (pp === cp) {
continue;
}
np = cp.nextTouched(v);
if (pp === np) {
// only one point on the contour has been touched
// so simply moves the point like that
v.setRelative(cp, cp, v.distance(pp, pp, false, true), v, true);
}
v.interpolate(cp, pp, np, v);
}
}
// SHP[] SHift Point using reference point
// 0x32-0x33
function SHP(a, state) {
var stack = state.stack;
var rpi = a ? state.rp1 : state.rp2;
var rp = (a ? state.z0 : state.z1)[rpi];
var fv = state.fv;
var pv = state.pv;
var loop = state.loop;
var z2 = state.z2;
while (loop--) {
var pi = stack.pop();
var p = z2[pi];
var d = pv.distance(rp, rp, false, true);
fv.setRelative(p, p, d, pv);
fv.touch(p);
if (exports.DEBUG) {
console.log(
state.step,
(state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') +
'SHP[' +
(a ? 'rp1' : 'rp2') +
']',
pi
);
}
}
state.loop = 1;
}
// SHC[] SHift Contour using reference point
// 0x36-0x37
function SHC(a, state) {
var stack = state.stack;
var rpi = a ? state.rp1 : state.rp2;
var rp = (a ? state.z0 : state.z1)[rpi];
var fv = state.fv;
var pv = state.pv;
var ci = stack.pop();
var sp = state.z2[state.contours[ci]];
var p = sp;
if (exports.DEBUG) {
console.log(state.step, 'SHC[' + a + ']', ci);
}
var d = pv.distance(rp, rp, false, true);
do {
if (p !== rp) {
fv.setRelative(p, p, d, pv);
}
p = p.nextPointOnContour;
} while (p !== sp);
}
// SHZ[] SHift Zone using reference point
// 0x36-0x37
function SHZ(a, state) {
var stack = state.stack;
var rpi = a ? state.rp1 : state.rp2;
var rp = (a ? state.z0 : state.z1)[rpi];
var fv = state.fv;
var pv = state.pv;
var e = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'SHZ[' + a + ']', e);
}
var z;
switch (e) {
case 0:
z = state.tZone;
break;
case 1:
z = state.gZone;
break;
default:
throw new Error('Invalid zone');
}
var p;
var d = pv.distance(rp, rp, false, true);
var pLen = z.length - 2;
for (var i = 0; i < pLen; i++) {
p = z[i];
fv.setRelative(p, p, d, pv);
//if (p !== rp) fv.setRelative(p, p, d, pv);
}
}
// SHPIX[] SHift point by a PIXel amount
// 0x38
function SHPIX(state) {
var stack = state.stack;
var loop = state.loop;
var fv = state.fv;
var d = stack.pop() / 0x40;
var z2 = state.z2;
while (loop--) {
var pi = stack.pop();
var p = z2[pi];
if (exports.DEBUG) {
console.log(
state.step,
(state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') +
'SHPIX[]',
pi,
d
);
}
fv.setRelative(p, p, d);
fv.touch(p);
}
state.loop = 1;
}
// IP[] Interpolate Point
// 0x39
function IP(state) {
var stack = state.stack;
var rp1i = state.rp1;
var rp2i = state.rp2;
var loop = state.loop;
var rp1 = state.z0[rp1i];
var rp2 = state.z1[rp2i];
var fv = state.fv;
var pv = state.dpv;
var z2 = state.z2;
while (loop--) {
var pi = stack.pop();
var p = z2[pi];
if (exports.DEBUG) {
console.log(
state.step,
(state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') + 'IP[]',
pi,
rp1i,
'<->',
rp2i
);
}
fv.interpolate(p, rp1, rp2, pv);
fv.touch(p);
}
state.loop = 1;
}
// MSIRP[a] Move Stack Indirect Relative Point
// 0x3A-0x3B
function MSIRP(a, state) {
var stack = state.stack;
var d = stack.pop() / 64;
var pi = stack.pop();
var p = state.z1[pi];
var rp0 = state.z0[state.rp0];
var fv = state.fv;
var pv = state.pv;
fv.setRelative(p, rp0, d, pv);
fv.touch(p);
if (exports.DEBUG) {
console.log(state.step, 'MSIRP[' + a + ']', d, pi);
}
state.rp1 = state.rp0;
state.rp2 = pi;
if (a) {
state.rp0 = pi;
}
}
// ALIGNRP[] Align to reference point.
// 0x3C
function ALIGNRP(state) {
var stack = state.stack;
var rp0i = state.rp0;
var rp0 = state.z0[rp0i];
var loop = state.loop;
var fv = state.fv;
var pv = state.pv;
var z1 = state.z1;
while (loop--) {
var pi = stack.pop();
var p = z1[pi];
if (exports.DEBUG) {
console.log(
state.step,
(state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') +
'ALIGNRP[]',
pi
);
}
fv.setRelative(p, rp0, 0, pv);
fv.touch(p);
}
state.loop = 1;
}
// RTG[] Round To Double Grid
// 0x3D
function RTDG(state) {
if (exports.DEBUG) {
console.log(state.step, 'RTDG[]');
}
state.round = roundToDoubleGrid;
}
// MIAP[a] Move Indirect Absolute Point
// 0x3E-0x3F
function MIAP(round, state) {
var stack = state.stack;
var n = stack.pop();
var pi = stack.pop();
var p = state.z0[pi];
var fv = state.fv;
var pv = state.pv;
var cv = state.cvt[n];
if (exports.DEBUG) {
console.log(state.step, 'MIAP[' + round + ']', n, '(', cv, ')', pi);
}
var d = pv.distance(p, HPZero);
if (round) {
if (Math.abs(d - cv) < state.cvCutIn) {
d = cv;
}
d = state.round(d);
}
fv.setRelative(p, HPZero, d, pv);
if (state.zp0 === 0) {
p.xo = p.x;
p.yo = p.y;
}
fv.touch(p);
state.rp0 = state.rp1 = pi;
}
// NPUSB[] PUSH N Bytes
// 0x40
function NPUSHB(state) {
var prog = state.prog;
var ip = state.ip;
var stack = state.stack;
var n = prog[++ip];
if (exports.DEBUG) {
console.log(state.step, 'NPUSHB[]', n);
}
for (var i = 0; i < n; i++) {
stack.push(prog[++ip]);
}
state.ip = ip;
}
// NPUSHW[] PUSH N Words
// 0x41
function NPUSHW(state) {
var ip = state.ip;
var prog = state.prog;
var stack = state.stack;
var n = prog[++ip];
if (exports.DEBUG) {
console.log(state.step, 'NPUSHW[]', n);
}
for (var i = 0; i < n; i++) {
var w = (prog[++ip] << 8) | prog[++ip];
if (w & 0x8000) {
w = -((w ^ 0xffff) + 1);
}
stack.push(w);
}
state.ip = ip;
}
// WS[] Write Store
// 0x42
function WS(state) {
var stack = state.stack;
var store = state.store;
if (!store) {
store = state.store = [];
}
var v = stack.pop();
var l = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'WS', v, l);
}
store[l] = v;
}
// RS[] Read Store
// 0x43
function RS(state) {
var stack = state.stack;
var store = state.store;
var l = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'RS', l);
}
var v = (store && store[l]) || 0;
stack.push(v);
}
// WCVTP[] Write Control Value Table in Pixel units
// 0x44
function WCVTP(state) {
var stack = state.stack;
var v = stack.pop();
var l = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'WCVTP', v, l);
}
state.cvt[l] = v / 0x40;
}
// RCVT[] Read Control Value Table entry
// 0x45
function RCVT(state) {
var stack = state.stack;
var cvte = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'RCVT', cvte);
}
stack.push(state.cvt[cvte] * 0x40);
}
// GC[] Get Coordinate projected onto the projection vector
// 0x46-0x47
function GC(a, state) {
var stack = state.stack;
var pi = stack.pop();
var p = state.z2[pi];
if (exports.DEBUG) {
console.log(state.step, 'GC[' + a + ']', pi);
}
stack.push(state.dpv.distance(p, HPZero, a, false) * 0x40);
}
// MD[a] Measure Distance
// 0x49-0x4A
function MD(a, state) {
var stack = state.stack;
var pi2 = stack.pop();
var pi1 = stack.pop();
var p2 = state.z1[pi2];
var p1 = state.z0[pi1];
var d = state.dpv.distance(p1, p2, a, a);
if (exports.DEBUG) {
console.log(state.step, 'MD[' + a + ']', pi2, pi1, '->', d);
}
state.stack.push(Math.round(d * 64));
}
// MPPEM[] Measure Pixels Per EM
// 0x4B
function MPPEM(state) {
if (exports.DEBUG) {
console.log(state.step, 'MPPEM[]');
}
state.stack.push(state.ppem);
}
// FLIPON[] set the auto FLIP Boolean to ON
// 0x4D
function FLIPON(state) {
if (exports.DEBUG) {
console.log(state.step, 'FLIPON[]');
}
state.autoFlip = true;
}
// LT[] Less Than
// 0x50
function LT(state) {
var stack = state.stack;
var e2 = stack.pop();
var e1 = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'LT[]', e2, e1);
}
stack.push(e1 < e2 ? 1 : 0);
}
// LTEQ[] Less Than or EQual
// 0x53
function LTEQ(state) {
var stack = state.stack;
var e2 = stack.pop();
var e1 = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'LTEQ[]', e2, e1);
}
stack.push(e1 <= e2 ? 1 : 0);
}
// GTEQ[] Greater Than
// 0x52
function GT(state) {
var stack = state.stack;
var e2 = stack.pop();
var e1 = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'GT[]', e2, e1);
}
stack.push(e1 > e2 ? 1 : 0);
}
// GTEQ[] Greater Than or EQual
// 0x53
function GTEQ(state) {
var stack = state.stack;
var e2 = stack.pop();
var e1 = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'GTEQ[]', e2, e1);
}
stack.push(e1 >= e2 ? 1 : 0);
}
// EQ[] EQual
// 0x54
function EQ(state) {
var stack = state.stack;
var e2 = stack.pop();
var e1 = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'EQ[]', e2, e1);
}
stack.push(e2 === e1 ? 1 : 0);
}
// NEQ[] Not EQual
// 0x55
function NEQ(state) {
var stack = state.stack;
var e2 = stack.pop();
var e1 = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'NEQ[]', e2, e1);
}
stack.push(e2 !== e1 ? 1 : 0);
}
// ODD[] ODD
// 0x56
function ODD(state) {
var stack = state.stack;
var n = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'ODD[]', n);
}
stack.push(Math.trunc(n) % 2 ? 1 : 0);
}
// EVEN[] EVEN
// 0x57
function EVEN(state) {
var stack = state.stack;
var n = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'EVEN[]', n);
}
stack.push(Math.trunc(n) % 2 ? 0 : 1);
}
// IF[] IF test
// 0x58
function IF(state) {
var test = state.stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'IF[]', test);
}
// if test is true it just continues
// if not the ip is skipped until matching ELSE or EIF
if (!test) {
skip(state, true);
if (exports.DEBUG) {
console.log(state.step, 'EIF[]');
}
}
}
// EIF[] End IF
// 0x59
function EIF(state) {
// this can be reached normally when
// executing an else branch.
// -> just ignore it
if (exports.DEBUG) {
console.log(state.step, 'EIF[]');
}
}
// AND[] logical AND
// 0x5A
function AND(state) {
var stack = state.stack;
var e2 = stack.pop();
var e1 = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'AND[]', e2, e1);
}
stack.push(e2 && e1 ? 1 : 0);
}
// OR[] logical OR
// 0x5B
function OR(state) {
var stack = state.stack;
var e2 = stack.pop();
var e1 = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'OR[]', e2, e1);
}
stack.push(e2 || e1 ? 1 : 0);
}
// NOT[] logical NOT
// 0x5C
function NOT(state) {
var stack = state.stack;
var e = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'NOT[]', e);
}
stack.push(e ? 0 : 1);
}
// DELTAP1[] DELTA exception P1
// DELTAP2[] DELTA exception P2
// DELTAP3[] DELTA exception P3
// 0x5D, 0x71, 0x72
function DELTAP123(b, state) {
var stack = state.stack;
var n = stack.pop();
var fv = state.fv;
var pv = state.pv;
var ppem = state.ppem;
var base = state.deltaBase + (b - 1) * 16;
var ds = state.deltaShift;
var z0 = state.z0;
if (exports.DEBUG) {
console.log(state.step, 'DELTAP[' + b + ']', n, stack);
}
for (var i = 0; i < n; i++) {
var pi = stack.pop();
var arg = stack.pop();
var appem = base + ((arg & 0xf0) >> 4);
if (appem !== ppem) {
continue;
}
var mag = (arg & 0x0f) - 8;
if (mag >= 0) {
mag++;
}
if (exports.DEBUG) {
console.log(state.step, 'DELTAPFIX', pi, 'by', mag * ds);
}
var p = z0[pi];
fv.setRelative(p, p, mag * ds, pv);
}
}
// SDB[] Set Delta Base in the graphics state
// 0x5E
function SDB(state) {
var stack = state.stack;
var n = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'SDB[]', n);
}
state.deltaBase = n;
}
// SDS[] Set Delta Shift in the graphics state
// 0x5F
function SDS(state) {
var stack = state.stack;
var n = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'SDS[]', n);
}
state.deltaShift = Math.pow(0.5, n);
}
// ADD[] ADD
// 0x60
function ADD(state) {
var stack = state.stack;
var n2 = stack.pop();
var n1 = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'ADD[]', n2, n1);
}
stack.push(n1 + n2);
}
// SUB[] SUB
// 0x61
function SUB(state) {
var stack = state.stack;
var n2 = stack.pop();
var n1 = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'SUB[]', n2, n1);
}
stack.push(n1 - n2);
}
// DIV[] DIV
// 0x62
function DIV(state) {
var stack = state.stack;
var n2 = stack.pop();
var n1 = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'DIV[]', n2, n1);
}
stack.push(n1 * 64 / n2);
}
// MUL[] MUL
// 0x63
function MUL(state) {
var stack = state.stack;
var n2 = stack.pop();
var n1 = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'MUL[]', n2, n1);
}
stack.push(n1 * n2 / 64);
}
// ABS[] ABSolute value
// 0x64
function ABS(state) {
var stack = state.stack;
var n = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'ABS[]', n);
}
stack.push(Math.abs(n));
}
// NEG[] NEGate
// 0x65
function NEG(state) {
var stack = state.stack;
var n = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'NEG[]', n);
}
stack.push(-n);
}
// FLOOR[] FLOOR
// 0x66
function FLOOR(state) {
var stack = state.stack;
var n = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'FLOOR[]', n);
}
stack.push(Math.floor(n / 0x40) * 0x40);
}
// CEILING[] CEILING
// 0x67
function CEILING(state) {
var stack = state.stack;
var n = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'CEILING[]', n);
}
stack.push(Math.ceil(n / 0x40) * 0x40);
}
// ROUND[ab] ROUND value
// 0x68-0x6B
function ROUND(dt, state) {
var stack = state.stack;
var n = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'ROUND[]');
}
stack.push(state.round(n / 0x40) * 0x40);
}
// WCVTF[] Write Control Value Table in Funits
// 0x70
function WCVTF(state) {
var stack = state.stack;
var v = stack.pop();
var l = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'WCVTF[]', v, l);
}
state.cvt[l] = v * state.ppem / state.font.unitsPerEm;
}
// DELTAC1[] DELTA exception C1
// DELTAC2[] DELTA exception C2
// DELTAC3[] DELTA exception C3
// 0x73, 0x74, 0x75
function DELTAC123(b, state) {
var stack = state.stack;
var n = stack.pop();
var ppem = state.ppem;
var base = state.deltaBase + (b - 1) * 16;
var ds = state.deltaShift;
if (exports.DEBUG) {
console.log(state.step, 'DELTAC[' + b + ']', n, stack);
}
for (var i = 0; i < n; i++) {
var c = stack.pop();
var arg = stack.pop();
var appem = base + ((arg & 0xf0) >> 4);
if (appem !== ppem) {
continue;
}
var mag = (arg & 0x0f) - 8;
if (mag >= 0) {
mag++;
}
var delta = mag * ds;
if (exports.DEBUG) {
console.log(state.step, 'DELTACFIX', c, 'by', delta);
}
state.cvt[c] += delta;
}
}
// SROUND[] Super ROUND
// 0x76
function SROUND(state) {
var n = state.stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'SROUND[]', n);
}
state.round = roundSuper;
var period;
switch (n & 0xc0) {
case 0x00:
period = 0.5;
break;
case 0x40:
period = 1;
break;
case 0x80:
period = 2;
break;
default:
throw new Error('invalid SROUND value');
}
state.srPeriod = period;
switch (n & 0x30) {
case 0x00:
state.srPhase = 0;
break;
case 0x10:
state.srPhase = 0.25 * period;
break;
case 0x20:
state.srPhase = 0.5 * period;
break;
case 0x30:
state.srPhase = 0.75 * period;
break;
default:
throw new Error('invalid SROUND value');
}
n &= 0x0f;
if (n === 0) {
state.srThreshold = 0;
} else {
state.srThreshold = (n / 8 - 0.5) * period;
}
}
// S45ROUND[] Super ROUND 45 degrees
// 0x77
function S45ROUND(state) {
var n = state.stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'S45ROUND[]', n);
}
state.round = roundSuper;
var period;
switch (n & 0xc0) {
case 0x00:
period = Math.sqrt(2) / 2;
break;
case 0x40:
period = Math.sqrt(2);
break;
case 0x80:
period = 2 * Math.sqrt(2);
break;
default:
throw new Error('invalid S45ROUND value');
}
state.srPeriod = period;
switch (n & 0x30) {
case 0x00:
state.srPhase = 0;
break;
case 0x10:
state.srPhase = 0.25 * period;
break;
case 0x20:
state.srPhase = 0.5 * period;
break;
case 0x30:
state.srPhase = 0.75 * period;
break;
default:
throw new Error('invalid S45ROUND value');
}
n &= 0x0f;
if (n === 0) {
state.srThreshold = 0;
} else {
state.srThreshold = (n / 8 - 0.5) * period;
}
}
// ROFF[] Round Off
// 0x7A
function ROFF(state) {
if (exports.DEBUG) {
console.log(state.step, 'ROFF[]');
}
state.round = roundOff;
}
// RUTG[] Round Up To Grid
// 0x7C
function RUTG(state) {
if (exports.DEBUG) {
console.log(state.step, 'RUTG[]');
}
state.round = roundUpToGrid;
}
// RDTG[] Round Down To Grid
// 0x7D
function RDTG(state) {
if (exports.DEBUG) {
console.log(state.step, 'RDTG[]');
}
state.round = roundDownToGrid;
}
// SCANCTRL[] SCAN conversion ConTRoL
// 0x85
function SCANCTRL(state) {
var n = state.stack.pop();
// ignored by opentype.js
if (exports.DEBUG) {
console.log(state.step, 'SCANCTRL[]', n);
}
}
// SDPVTL[a] Set Dual Projection Vector To Line
// 0x86-0x87
function SDPVTL(a, state) {
var stack = state.stack;
var p2i = stack.pop();
var p1i = stack.pop();
var p2 = state.z2[p2i];
var p1 = state.z1[p1i];
if (exports.DEBUG) {
console.log(state.step, 'SDPVTL[' + a + ']', p2i, p1i);
}
var dx;
var dy;
if (!a) {
dx = p1.x - p2.x;
dy = p1.y - p2.y;
} else {
dx = p2.y - p1.y;
dy = p1.x - p2.x;
}
state.dpv = getUnitVector(dx, dy);
}
// GETINFO[] GET INFOrmation
// 0x88
function GETINFO(state) {
var stack = state.stack;
var sel = stack.pop();
var r = 0;
if (exports.DEBUG) {
console.log(state.step, 'GETINFO[]', sel);
}
// v35 as in no subpixel hinting
if (sel & 0x01) {
r = 35;
}
// TODO rotation and stretch currently not supported
// and thus those GETINFO are always 0.
// opentype.js is always gray scaling
if (sel & 0x20) {
r |= 0x1000;
}
stack.push(r);
}
// ROLL[] ROLL the top three stack elements
// 0x8A
function ROLL(state) {
var stack = state.stack;
var a = stack.pop();
var b = stack.pop();
var c = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'ROLL[]');
}
stack.push(b);
stack.push(a);
stack.push(c);
}
// MAX[] MAXimum of top two stack elements
// 0x8B
function MAX(state) {
var stack = state.stack;
var e2 = stack.pop();
var e1 = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'MAX[]', e2, e1);
}
stack.push(Math.max(e1, e2));
}
// MIN[] MINimum of top two stack elements
// 0x8C
function MIN(state) {
var stack = state.stack;
var e2 = stack.pop();
var e1 = stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'MIN[]', e2, e1);
}
stack.push(Math.min(e1, e2));
}
// SCANTYPE[] SCANTYPE
// 0x8D
function SCANTYPE(state) {
var n = state.stack.pop();
// ignored by opentype.js
if (exports.DEBUG) {
console.log(state.step, 'SCANTYPE[]', n);
}
}
// INSTCTRL[] INSTCTRL
// 0x8D
function INSTCTRL(state) {
var s = state.stack.pop();
var v = state.stack.pop();
if (exports.DEBUG) {
console.log(state.step, 'INSTCTRL[]', s, v);
}
switch (s) {
case 1:
state.inhibitGridFit = !!v;
return;
case 2:
state.ignoreCvt = !!v;
return;
default:
throw new Error('invalid INSTCTRL[] selector');
}
}
// PUSHB[abc] PUSH Bytes
// 0xB0-0xB7
function PUSHB(n, state) {
var stack = state.stack;
var prog = state.prog;
var ip = state.ip;
if (exports.DEBUG) {
console.log(state.step, 'PUSHB[' + n + ']');
}
for (var i = 0; i < n; i++) {
stack.push(prog[++ip]);
}
state.ip = ip;
}
// PUSHW[abc] PUSH Words
// 0xB8-0xBF
function PUSHW(n, state) {
var ip = state.ip;
var prog = state.prog;
var stack = state.stack;
if (exports.DEBUG) {
console.log(state.ip, 'PUSHW[' + n + ']');
}
for (var i = 0; i < n; i++) {
var w = (prog[++ip] << 8) | prog[++ip];
if (w & 0x8000) {
w = -((w ^ 0xffff) + 1);
}
stack.push(w);
}
state.ip = ip;
}
// MDRP[abcde] Move Direct Relative Point
// 0xD0-0xEF
// (if indirect is 0)
//
// and
//
// MIRP[abcde] Move Indirect Relative Point
// 0xE0-0xFF
// (if indirect is 1)
function MDRP_MIRP(indirect, setRp0, keepD, ro, dt, state) {
var stack = state.stack;
var cvte = indirect && stack.pop();
var pi = stack.pop();
var rp0i = state.rp0;
var rp = state.z0[rp0i];
var p = state.z1[pi];
var md = state.minDis;
var fv = state.fv;
var pv = state.dpv;
var od; // original distance
var d; // moving distance
var sign; // sign of distance
var cv;
d = od = pv.distance(p, rp, true, true);
sign = d >= 0 ? 1 : -1; // Math.sign would be 0 in case of 0
// TODO consider autoFlip
d = Math.abs(d);
if (indirect) {
cv = state.cvt[cvte];
if (ro && Math.abs(d - cv) < state.cvCutIn) {
d = cv;
}
}
if (keepD && d < md) {
d = md;
}
if (ro) {
d = state.round(d);
}
fv.setRelative(p, rp, sign * d, pv);
fv.touch(p);
if (exports.DEBUG) {
console.log(
state.step,
(indirect ? 'MIRP[' : 'MDRP[') +
(setRp0 ? 'M' : 'm') +
(keepD ? '>' : '_') +
(ro ? 'R' : '_') +
(dt === 0 ? 'Gr' : dt === 1 ? 'Bl' : dt === 2 ? 'Wh' : '') +
']',
indirect ? cvte + '(' + state.cvt[cvte] + ',' + cv + ')' : '',
pi,
'(d =',
od,
'->',
sign * d,
')'
);
}
state.rp1 = state.rp0;
state.rp2 = pi;
if (setRp0) {
state.rp0 = pi;
}
}
/*
* The instruction table.
*/
instructionTable = [
/* 0x00 */ SVTCA.bind(undefined, yUnitVector),
/* 0x01 */ SVTCA.bind(undefined, xUnitVector),
/* 0x02 */ SPVTCA.bind(undefined, yUnitVector),
/* 0x03 */ SPVTCA.bind(undefined, xUnitVector),
/* 0x04 */ SFVTCA.bind(undefined, yUnitVector),
/* 0x05 */ SFVTCA.bind(undefined, xUnitVector),
/* 0x06 */ SPVTL.bind(undefined, 0),
/* 0x07 */ SPVTL.bind(undefined, 1),
/* 0x08 */ SFVTL.bind(undefined, 0),
/* 0x09 */ SFVTL.bind(undefined, 1),
/* 0x0A */ SPVFS,
/* 0x0B */ SFVFS,
/* 0x0C */ GPV,
/* 0x0D */ GFV,
/* 0x0E */ SFVTPV,
/* 0x0F */ ISECT,
/* 0x10 */ SRP0,
/* 0x11 */ SRP1,
/* 0x12 */ SRP2,
/* 0x13 */ SZP0,
/* 0x14 */ SZP1,
/* 0x15 */ SZP2,
/* 0x16 */ SZPS,
/* 0x17 */ SLOOP,
/* 0x18 */ RTG,
/* 0x19 */ RTHG,
/* 0x1A */ SMD,
/* 0x1B */ ELSE,
/* 0x1C */ JMPR,
/* 0x1D */ SCVTCI,
/* 0x1E */ undefined, // TODO SSWCI
/* 0x1F */ undefined, // TODO SSW
/* 0x20 */ DUP,
/* 0x21 */ POP,
/* 0x22 */ CLEAR,
/* 0x23 */ SWAP,
/* 0x24 */ DEPTH,
/* 0x25 */ CINDEX,
/* 0x26 */ MINDEX,
/* 0x27 */ undefined, // TODO ALIGNPTS
/* 0x28 */ undefined,
/* 0x29 */ undefined, // TODO UTP
/* 0x2A */ LOOPCALL,
/* 0x2B */ CALL,
/* 0x2C */ FDEF,
/* 0x2D */ undefined, // ENDF (eaten by FDEF)
/* 0x2E */ MDAP.bind(undefined, 0),
/* 0x2F */ MDAP.bind(undefined, 1),
/* 0x30 */ IUP.bind(undefined, yUnitVector),
/* 0x31 */ IUP.bind(undefined, xUnitVector),
/* 0x32 */ SHP.bind(undefined, 0),
/* 0x33 */ SHP.bind(undefined, 1),
/* 0x34 */ SHC.bind(undefined, 0),
/* 0x35 */ SHC.bind(undefined, 1),
/* 0x36 */ SHZ.bind(undefined, 0),
/* 0x37 */ SHZ.bind(undefined, 1),
/* 0x38 */ SHPIX,
/* 0x39 */ IP,
/* 0x3A */ MSIRP.bind(undefined, 0),
/* 0x3B */ MSIRP.bind(undefined, 1),
/* 0x3C */ ALIGNRP,
/* 0x3D */ RTDG,
/* 0x3E */ MIAP.bind(undefined, 0),
/* 0x3F */ MIAP.bind(undefined, 1),
/* 0x40 */ NPUSHB,
/* 0x41 */ NPUSHW,
/* 0x42 */ WS,
/* 0x43 */ RS,
/* 0x44 */ WCVTP,
/* 0x45 */ RCVT,
/* 0x46 */ GC.bind(undefined, 0),
/* 0x47 */ GC.bind(undefined, 1),
/* 0x48 */ undefined, // TODO SCFS
/* 0x49 */ MD.bind(undefined, 0),
/* 0x4A */ MD.bind(undefined, 1),
/* 0x4B */ MPPEM,
/* 0x4C */ undefined, // TODO MPS
/* 0x4D */ FLIPON,
/* 0x4E */ undefined, // TODO FLIPOFF
/* 0x4F */ undefined, // TODO DEBUG
/* 0x50 */ LT,
/* 0x51 */ LTEQ,
/* 0x52 */ GT,
/* 0x53 */ GTEQ,
/* 0x54 */ EQ,
/* 0x55 */ NEQ,
/* 0x56 */ ODD,
/* 0x57 */ EVEN,
/* 0x58 */ IF,
/* 0x59 */ EIF,
/* 0x5A */ AND,
/* 0x5B */ OR,
/* 0x5C */ NOT,
/* 0x5D */ DELTAP123.bind(undefined, 1),
/* 0x5E */ SDB,
/* 0x5F */ SDS,
/* 0x60 */ ADD,
/* 0x61 */ SUB,
/* 0x62 */ DIV,
/* 0x63 */ MUL,
/* 0x64 */ ABS,
/* 0x65 */ NEG,
/* 0x66 */ FLOOR,
/* 0x67 */ CEILING,
/* 0x68 */ ROUND.bind(undefined, 0),
/* 0x69 */ ROUND.bind(undefined, 1),
/* 0x6A */ ROUND.bind(undefined, 2),
/* 0x6B */ ROUND.bind(undefined, 3),
/* 0x6C */ undefined, // TODO NROUND[ab]
/* 0x6D */ undefined, // TODO NROUND[ab]
/* 0x6E */ undefined, // TODO NROUND[ab]
/* 0x6F */ undefined, // TODO NROUND[ab]
/* 0x70 */ WCVTF,
/* 0x71 */ DELTAP123.bind(undefined, 2),
/* 0x72 */ DELTAP123.bind(undefined, 3),
/* 0x73 */ DELTAC123.bind(undefined, 1),
/* 0x74 */ DELTAC123.bind(undefined, 2),
/* 0x75 */ DELTAC123.bind(undefined, 3),
/* 0x76 */ SROUND,
/* 0x77 */ S45ROUND,
/* 0x78 */ undefined, // TODO JROT[]
/* 0x79 */ undefined, // TODO JROF[]
/* 0x7A */ ROFF,
/* 0x7B */ undefined,
/* 0x7C */ RUTG,
/* 0x7D */ RDTG,
/* 0x7E */ POP, // actually SANGW, supposed to do only a pop though
/* 0x7F */ POP, // actually AA, supposed to do only a pop though
/* 0x80 */ undefined, // TODO FLIPPT
/* 0x81 */ undefined, // TODO FLIPRGON
/* 0x82 */ undefined, // TODO FLIPRGOFF
/* 0x83 */ undefined,
/* 0x84 */ undefined,
/* 0x85 */ SCANCTRL,
/* 0x86 */ SDPVTL.bind(undefined, 0),
/* 0x87 */ SDPVTL.bind(undefined, 1),
/* 0x88 */ GETINFO,
/* 0x89 */ undefined, // TODO IDEF
/* 0x8A */ ROLL,
/* 0x8B */ MAX,
/* 0x8C */ MIN,
/* 0x8D */ SCANTYPE,
/* 0x8E */ INSTCTRL,
/* 0x8F */ undefined,
/* 0x90 */ undefined,
/* 0x91 */ undefined,
/* 0x92 */ undefined,
/* 0x93 */ undefined,
/* 0x94 */ undefined,
/* 0x95 */ undefined,
/* 0x96 */ undefined,
/* 0x97 */ undefined,
/* 0x98 */ undefined,
/* 0x99 */ undefined,
/* 0x9A */ undefined,
/* 0x9B */ undefined,
/* 0x9C */ undefined,
/* 0x9D */ undefined,
/* 0x9E */ undefined,
/* 0x9F */ undefined,
/* 0xA0 */ undefined,
/* 0xA1 */ undefined,
/* 0xA2 */ undefined,
/* 0xA3 */ undefined,
/* 0xA4 */ undefined,
/* 0xA5 */ undefined,
/* 0xA6 */ undefined,
/* 0xA7 */ undefined,
/* 0xA8 */ undefined,
/* 0xA9 */ undefined,
/* 0xAA */ undefined,
/* 0xAB */ undefined,
/* 0xAC */ undefined,
/* 0xAD */ undefined,
/* 0xAE */ undefined,
/* 0xAF */ undefined,
/* 0xB0 */ PUSHB.bind(undefined, 1),
/* 0xB1 */ PUSHB.bind(undefined, 2),
/* 0xB2 */ PUSHB.bind(undefined, 3),
/* 0xB3 */ PUSHB.bind(undefined, 4),
/* 0xB4 */ PUSHB.bind(undefined, 5),
/* 0xB5 */ PUSHB.bind(undefined, 6),
/* 0xB6 */ PUSHB.bind(undefined, 7),
/* 0xB7 */ PUSHB.bind(undefined, 8),
/* 0xB8 */ PUSHW.bind(undefined, 1),
/* 0xB9 */ PUSHW.bind(undefined, 2),
/* 0xBA */ PUSHW.bind(undefined, 3),
/* 0xBB */ PUSHW.bind(undefined, 4),
/* 0xBC */ PUSHW.bind(undefined, 5),
/* 0xBD */ PUSHW.bind(undefined, 6),
/* 0xBE */ PUSHW.bind(undefined, 7),
/* 0xBF */ PUSHW.bind(undefined, 8),
/* 0xC0 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 0),
/* 0xC1 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 1),
/* 0xC2 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 2),
/* 0xC3 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 3),
/* 0xC4 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 0),
/* 0xC5 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 1),
/* 0xC6 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 2),
/* 0xC7 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 3),
/* 0xC8 */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 0),
/* 0xC9 */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 1),
/* 0xCA */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 2),
/* 0xCB */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 3),
/* 0xCC */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 0),
/* 0xCD */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 1),
/* 0xCE */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 2),
/* 0xCF */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 3),
/* 0xD0 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 0),
/* 0xD1 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 1),
/* 0xD2 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 2),
/* 0xD3 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 3),
/* 0xD4 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 0),
/* 0xD5 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 1),
/* 0xD6 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 2),
/* 0xD7 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 3),
/* 0xD8 */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 0),
/* 0xD9 */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 1),
/* 0xDA */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 2),
/* 0xDB */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 3),
/* 0xDC */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 0),
/* 0xDD */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 1),
/* 0xDE */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 2),
/* 0xDF */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 3),
/* 0xE0 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 0),
/* 0xE1 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 1),
/* 0xE2 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 2),
/* 0xE3 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 3),
/* 0xE4 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 0),
/* 0xE5 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 1),
/* 0xE6 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 2),
/* 0xE7 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 3),
/* 0xE8 */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 0),
/* 0xE9 */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 1),
/* 0xEA */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 2),
/* 0xEB */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 3),
/* 0xEC */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 0),
/* 0xED */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 1),
/* 0xEE */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 2),
/* 0xEF */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 3),
/* 0xF0 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 0),
/* 0xF1 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 1),
/* 0xF2 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 2),
/* 0xF3 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 3),
/* 0xF4 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 0),
/* 0xF5 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 1),
/* 0xF6 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 2),
/* 0xF7 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 3),
/* 0xF8 */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 0),
/* 0xF9 */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 1),
/* 0xFA */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 2),
/* 0xFB */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 3),
/* 0xFC */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 0),
/* 0xFD */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 1),
/* 0xFE */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 2),
/* 0xFF */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 3)
];
/*****************************
Mathematical Considerations
******************************
fv ... refers to freedom vector
pv ... refers to projection vector
rp ... refers to reference point
p ... refers to to point being operated on
d ... refers to distance
SETRELATIVE:
============
case freedom vector == x-axis:
------------------------------
(pv)
.-'
rpd .-'
.-*
d .-'90°'
.-' '
.-' '
*-' ' b
rp '
'
'
p *----------*-------------- (fv)
pm
rpdx = rpx + d * pv.x
rpdy = rpy + d * pv.y
equation of line b
y - rpdy = pvns * (x- rpdx)
y = p.y
x = rpdx + ( p.y - rpdy ) / pvns
case freedom vector == y-axis:
------------------------------
* pm
|\
| \
| \
| \
| \
| \
| \
| \
| \
| \ b
| \
| \
| \ .-' (pv)
| 90° \.-'
| .-'* rpd
| .-'
* *-' d
p rp
rpdx = rpx + d * pv.x
rpdy = rpy + d * pv.y
equation of line b:
pvns ... normal slope to pv
y - rpdy = pvns * (x - rpdx)
x = p.x
y = rpdy + pvns * (p.x - rpdx)
generic case:
-------------
.'(fv)
.'
.* pm
.' !
.' .
.' !
.' . b
.' !
* .
p !
90° . ... (pv)
...-*-'''
...---''' rpd
...---''' d
*--'''
rp
rpdx = rpx + d * pv.x
rpdy = rpy + d * pv.y
equation of line b:
pvns... normal slope to pv
y - rpdy = pvns * (x - rpdx)
equation of freedom vector line:
fvs ... slope of freedom vector (=fy/fx)
y - py = fvs * (x - px)
on pm both equations are true for same x/y
y - rpdy = pvns * (x - rpdx)
y - py = fvs * (x - px)
form to y and set equal:
pvns * (x - rpdx) + rpdy = fvs * (x - px) + py
expand:
pvns * x - pvns * rpdx + rpdy = fvs * x - fvs * px + py
switch:
fvs * x - fvs * px + py = pvns * x - pvns * rpdx + rpdy
solve for x:
fvs * x - pvns * x = fvs * px - pvns * rpdx - py + rpdy
fvs * px - pvns * rpdx + rpdy - py
x = -----------------------------------
fvs - pvns
and:
y = fvs * (x - px) + py
INTERPOLATE:
============
Examples of point interpolation.
The weight of the movement of the reference point gets bigger
the further the other reference point is away, thus the safest
option (that is avoiding 0/0 divisions) is to weight the
original distance of the other point by the sum of both distances.
If the sum of both distances is 0, then move the point by the
arithmetic average of the movement of both reference points.
(+6)
rp1o *---->*rp1
. . (+12)
. . rp2o *---------->* rp2
. . . .
. . . .
. 10 20 . .
|.........|...................| .
. . .
. . (+8) .
po *------>*p .
. . .
. 12 . 24 .
|...........|.......................|
36
-------
(+10)
rp1o *-------->*rp1
. . (-10)
. . rp2 *<---------* rpo2
. . . .
. . . .
. 10 . 30 . .
|.........|.............................|
. .
. (+5) .
po *--->* p .
. . .
. . 20 .
|....|..............|
5 15
-------
(+10)
rp1o *-------->*rp1
. .
. .
rp2o *-------->*rp2
(+10)
po *-------->* p
-------
(+10)
rp1o *-------->*rp1
. .
. .(+30)
rp2o *---------------------------->*rp2
(+25)
po *----------------------->* p
vim: set ts=4 sw=4 expandtab:
*****/
// The Font object
// This code is based on Array.from implementation for strings in https://github.com/mathiasbynens/Array.from
var arrayFromString =
Array.from ||
function(s) {
return (
s.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]?|[^\uD800-\uDFFF]|./g) || []
);
};
/**
* @typedef FontOptions
* @type Object
* @property {Boolean} empty - whether to create a new empty font
* @property {string} familyName
* @property {string} styleName
* @property {string=} fullName
* @property {string=} postScriptName
* @property {string=} designer
* @property {string=} designerURL
* @property {string=} manufacturer
* @property {string=} manufacturerURL
* @property {string=} license
* @property {string=} licenseURL
* @property {string=} version
* @property {string=} description
* @property {string=} copyright
* @property {string=} trademark
* @property {Number} unitsPerEm
* @property {Number} ascender
* @property {Number} descender
* @property {Number} createdTimestamp
* @property {string=} weightClass
* @property {string=} widthClass
* @property {string=} fsSelection
*/
/**
* A Font represents a loaded OpenType font file.
* It contains a set of glyphs and methods to draw text on a drawing context,
* or to get a path representing the text.
* @exports opentype.Font
* @class
* @param {FontOptions}
* @constructor
*/
function Font(options) {
options = options || {};
if (!options.empty) {
// Check that we've provided the minimum set of names.
checkArgument(
options.familyName,
'When creating a new Font object, familyName is required.'
);
checkArgument(
options.styleName,
'When creating a new Font object, styleName is required.'
);
checkArgument(
options.unitsPerEm,
'When creating a new Font object, unitsPerEm is required.'
);
checkArgument(
options.ascender,
'When creating a new Font object, ascender is required.'
);
checkArgument(
options.descender,
'When creating a new Font object, descender is required.'
);
checkArgument(
options.descender < 0,
'Descender should be negative (e.g. -512).'
);
// OS X will complain if the names are empty, so we put a single space everywhere by default.
this.names = {
fontFamily: { en: options.familyName || ' ' },
fontSubfamily: { en: options.styleName || ' ' },
fullName: {
en: options.fullName || options.familyName + ' ' + options.styleName
},
// postScriptName may not contain any whitespace
postScriptName: {
en:
options.postScriptName ||
(options.familyName + options.styleName).replace(/\s/g, '')
},
designer: { en: options.designer || ' ' },
designerURL: { en: options.designerURL || ' ' },
manufacturer: { en: options.manufacturer || ' ' },
manufacturerURL: { en: options.manufacturerURL || ' ' },
license: { en: options.license || ' ' },
licenseURL: { en: options.licenseURL || ' ' },
version: { en: options.version || 'Version 0.1' },
description: { en: options.description || ' ' },
copyright: { en: options.copyright || ' ' },
trademark: { en: options.trademark || ' ' }
};
this.unitsPerEm = options.unitsPerEm || 1000;
this.ascender = options.ascender;
this.descender = options.descender;
this.createdTimestamp = options.createdTimestamp;
this.tables = {
os2: {
usWeightClass: options.weightClass || this.usWeightClasses.MEDIUM,
usWidthClass: options.widthClass || this.usWidthClasses.MEDIUM,
fsSelection: options.fsSelection || this.fsSelectionValues.REGULAR
}
};
}
this.supported = true; // Deprecated: parseBuffer will throw an error if font is not supported.
this.glyphs = new glyphset.GlyphSet(this, options.glyphs || []);
this.encoding = new DefaultEncoding(this);
this.position = new Position(this);
this.substitution = new Substitution(this);
this.tables = this.tables || {};
Object.defineProperty(this, 'hinting', {
get: function() {
if (this._hinting) {
return this._hinting;
}
if (this.outlinesFormat === 'truetype') {
return (this._hinting = new Hinting(this));
}
}
});
}
/**
* Check if the font has a glyph for the given character.
* @param {string}
* @return {Boolean}
*/
Font.prototype.hasChar = function(c) {
return this.encoding.charToGlyphIndex(c) !== null;
};
/**
* Convert the given character to a single glyph index.
* Note that this function assumes that there is a one-to-one mapping between
* the given character and a glyph; for complex scripts this might not be the case.
* @param {string}
* @return {Number}
*/
Font.prototype.charToGlyphIndex = function(s) {
return this.encoding.charToGlyphIndex(s);
};
/**
* Convert the given character to a single Glyph object.
* Note that this function assumes that there is a one-to-one mapping between
* the given character and a glyph; for complex scripts this might not be the case.
* @param {string}
* @return {opentype.Glyph}
*/
Font.prototype.charToGlyph = function(c) {
var glyphIndex = this.charToGlyphIndex(c);
var glyph = this.glyphs.get(glyphIndex);
if (!glyph) {
// .notdef
glyph = this.glyphs.get(0);
}
return glyph;
};
/**
* Convert the given text to a list of Glyph objects.
* Note that there is no strict one-to-one mapping between characters and
* glyphs, so the list of returned glyphs can be larger or smaller than the
* length of the given string.
* @param {string}
* @param {GlyphRenderOptions} [options]
* @return {opentype.Glyph[]}
*/
Font.prototype.stringToGlyphs = function(s, options) {
var this$1 = this;
options = options || this.defaultRenderOptions;
// Get glyph indexes
var chars = arrayFromString(s);
var indexes = [];
for (var i = 0; i < chars.length; i += 1) {
var c = chars[i];
indexes.push(this$1.charToGlyphIndex(c));
}
var length = indexes.length;
// Apply substitutions on glyph indexes
if (options.features) {
var script = options.script || this.substitution.getDefaultScriptName();
var manyToOne = [];
if (options.features.liga) {
manyToOne = manyToOne.concat(
this.substitution.getFeature('liga', script, options.language)
);
}
if (options.features.rlig) {
manyToOne = manyToOne.concat(
this.substitution.getFeature('rlig', script, options.language)
);
}
for (var i$1 = 0; i$1 < length; i$1 += 1) {
for (var j = 0; j < manyToOne.length; j++) {
var ligature = manyToOne[j];
var components = ligature.sub;
var compCount = components.length;
var k = 0;
while (k < compCount && components[k] === indexes[i$1 + k]) {
k++;
}
if (k === compCount) {
indexes.splice(i$1, compCount, ligature.by);
length = length - compCount + 1;
}
}
}
}
// convert glyph indexes to glyph objects
var glyphs = new Array(length);
var notdef = this.glyphs.get(0);
for (var i$2 = 0; i$2 < length; i$2 += 1) {
glyphs[i$2] = this$1.glyphs.get(indexes[i$2]) || notdef;
}
return glyphs;
};
/**
* @param {string}
* @return {Number}
*/
Font.prototype.nameToGlyphIndex = function(name) {
return this.glyphNames.nameToGlyphIndex(name);
};
/**
* @param {string}
* @return {opentype.Glyph}
*/
Font.prototype.nameToGlyph = function(name) {
var glyphIndex = this.nameToGlyphIndex(name);
var glyph = this.glyphs.get(glyphIndex);
if (!glyph) {
// .notdef
glyph = this.glyphs.get(0);
}
return glyph;
};
/**
* @param {Number}
* @return {String}
*/
Font.prototype.glyphIndexToName = function(gid) {
if (!this.glyphNames.glyphIndexToName) {
return '';
}
return this.glyphNames.glyphIndexToName(gid);
};
/**
* Retrieve the value of the kerning pair between the left glyph (or its index)
* and the right glyph (or its index). If no kerning pair is found, return 0.
* The kerning value gets added to the advance width when calculating the spacing
* between glyphs.
* For GPOS kerning, this method uses the default script and language, which covers
* most use cases. To have greater control, use font.position.getKerningValue .
* @param {opentype.Glyph} leftGlyph
* @param {opentype.Glyph} rightGlyph
* @return {Number}
*/
Font.prototype.getKerningValue = function(leftGlyph, rightGlyph) {
leftGlyph = leftGlyph.index || leftGlyph;
rightGlyph = rightGlyph.index || rightGlyph;
var gposKerning = this.position.defaultKerningTables;
if (gposKerning) {
return this.position.getKerningValue(gposKerning, leftGlyph, rightGlyph);
}
// "kern" table
return this.kerningPairs[leftGlyph + ',' + rightGlyph] || 0;
};
/**
* @typedef GlyphRenderOptions
* @type Object
* @property {string} [script] - script used to determine which features to apply. By default, 'DFLT' or 'latn' is used.
* See https://www.microsoft.com/typography/otspec/scripttags.htm
* @property {string} [language='dflt'] - language system used to determine which features to apply.
* See https://www.microsoft.com/typography/developers/opentype/languagetags.aspx
* @property {boolean} [kerning=true] - whether to include kerning values
* @property {object} [features] - OpenType Layout feature tags. Used to enable or disable the features of the given script/language system.
* See https://www.microsoft.com/typography/otspec/featuretags.htm
*/
Font.prototype.defaultRenderOptions = {
kerning: true,
features: {
liga: true,
rlig: true
}
};
/**
* Helper function that invokes the given callback for each glyph in the given text.
* The callback gets `(glyph, x, y, fontSize, options)`.* @param {string} text
* @param {string} text - The text to apply.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
* @param {GlyphRenderOptions=} options
* @param {Function} callback
*/
Font.prototype.forEachGlyph = function(
text,
x,
y,
fontSize,
options,
callback
) {
var this$1 = this;
x = x !== undefined ? x : 0;
y = y !== undefined ? y : 0;
fontSize = fontSize !== undefined ? fontSize : 72;
options = options || this.defaultRenderOptions;
var fontScale = 1 / this.unitsPerEm * fontSize;
var glyphs = this.stringToGlyphs(text, options);
var kerningLookups;
if (options.kerning) {
var script = options.script || this.position.getDefaultScriptName();
kerningLookups = this.position.getKerningTables(script, options.language);
}
for (var i = 0; i < glyphs.length; i += 1) {
var glyph = glyphs[i];
callback.call(this$1, glyph, x, y, fontSize, options);
if (glyph.advanceWidth) {
x += glyph.advanceWidth * fontScale;
}
if (options.kerning && i < glyphs.length - 1) {
// We should apply position adjustment lookups in a more generic way.
// Here we only use the xAdvance value.
var kerningValue = kerningLookups
? this$1.position.getKerningValue(
kerningLookups,
glyph.index,
glyphs[i + 1].index
)
: this$1.getKerningValue(glyph, glyphs[i + 1]);
x += kerningValue * fontScale;
}
if (options.letterSpacing) {
x += options.letterSpacing * fontSize;
} else if (options.tracking) {
x += options.tracking / 1000 * fontSize;
}
}
return x;
};
/**
* Create a Path object that represents the given text.
* @param {string} text - The text to create.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
* @param {GlyphRenderOptions=} options
* @return {opentype.Path}
*/
Font.prototype.getPath = function(text, x, y, fontSize, options) {
var fullPath = new Path();
this.forEachGlyph(text, x, y, fontSize, options, function(
glyph,
gX,
gY,
gFontSize
) {
var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this);
fullPath.extend(glyphPath);
});
return fullPath;
};
/**
* Create an array of Path objects that represent the glyphs of a given text.
* @param {string} text - The text to create.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
* @param {GlyphRenderOptions=} options
* @return {opentype.Path[]}
*/
Font.prototype.getPaths = function(text, x, y, fontSize, options) {
var glyphPaths = [];
this.forEachGlyph(text, x, y, fontSize, options, function(
glyph,
gX,
gY,
gFontSize
) {
var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this);
glyphPaths.push(glyphPath);
});
return glyphPaths;
};
/**
* Returns the advance width of a text.
*
* This is something different than Path.getBoundingBox() as for example a
* suffixed whitespace increases the advanceWidth but not the bounding box
* or an overhanging letter like a calligraphic 'f' might have a quite larger
* bounding box than its advance width.
*
* This corresponds to canvas2dContext.measureText(text).width
*
* @param {string} text - The text to create.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
* @param {GlyphRenderOptions=} options
* @return advance width
*/
Font.prototype.getAdvanceWidth = function(text, fontSize, options) {
return this.forEachGlyph(text, 0, 0, fontSize, options, function() {});
};
/**
* Draw the text on the given drawing context.
* @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
* @param {string} text - The text to create.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
* @param {GlyphRenderOptions=} options
*/
Font.prototype.draw = function(ctx, text, x, y, fontSize, options) {
this.getPath(text, x, y, fontSize, options).draw(ctx);
};
/**
* Draw the points of all glyphs in the text.
* On-curve points will be drawn in blue, off-curve points will be drawn in red.
* @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
* @param {string} text - The text to create.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
* @param {GlyphRenderOptions=} options
*/
Font.prototype.drawPoints = function(ctx, text, x, y, fontSize, options) {
this.forEachGlyph(text, x, y, fontSize, options, function(
glyph,
gX,
gY,
gFontSize
) {
glyph.drawPoints(ctx, gX, gY, gFontSize);
});
};
/**
* Draw lines indicating important font measurements for all glyphs in the text.
* Black lines indicate the origin of the coordinate system (point 0,0).
* Blue lines indicate the glyph bounding box.
* Green line indicates the advance width of the glyph.
* @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
* @param {string} text - The text to create.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
* @param {GlyphRenderOptions=} options
*/
Font.prototype.drawMetrics = function(ctx, text, x, y, fontSize, options) {
this.forEachGlyph(text, x, y, fontSize, options, function(
glyph,
gX,
gY,
gFontSize
) {
glyph.drawMetrics(ctx, gX, gY, gFontSize);
});
};
/**
* @param {string}
* @return {string}
*/
Font.prototype.getEnglishName = function(name) {
var translations = this.names[name];
if (translations) {
return translations.en;
}
};
/**
* Validate
*/
Font.prototype.validate = function() {
var _this = this;
function assert(predicate, message) {}
function assertNamePresent(name) {
var englishName = _this.getEnglishName(name);
assert(
englishName && englishName.trim().length > 0,
'No English ' + name + ' specified.'
);
}
// Identification information
assertNamePresent('fontFamily');
assertNamePresent('weightName');
assertNamePresent('manufacturer');
assertNamePresent('copyright');
assertNamePresent('version');
// Dimension information
assert(this.unitsPerEm > 0, 'No unitsPerEm specified.');
};
/**
* Convert the font object to a SFNT data structure.
* This structure contains all the necessary tables and metadata to create a binary OTF file.
* @return {opentype.Table}
*/
Font.prototype.toTables = function() {
return sfnt.fontToTable(this);
};
/**
* @deprecated Font.toBuffer is deprecated. Use Font.toArrayBuffer instead.
*/
Font.prototype.toBuffer = function() {
console.warn(
'Font.toBuffer is deprecated. Use Font.toArrayBuffer instead.'
);
return this.toArrayBuffer();
};
/**
* Converts a `opentype.Font` into an `ArrayBuffer`
* @return {ArrayBuffer}
*/
Font.prototype.toArrayBuffer = function() {
var sfntTable = this.toTables();
var bytes = sfntTable.encode();
var buffer = new ArrayBuffer(bytes.length);
var intArray = new Uint8Array(buffer);
for (var i = 0; i < bytes.length; i++) {
intArray[i] = bytes[i];
}
return buffer;
};
/**
* Initiate a download of the OpenType font.
*/
Font.prototype.download = function(fileName) {
var familyName = this.getEnglishName('fontFamily');
var styleName = this.getEnglishName('fontSubfamily');
fileName =
fileName || familyName.replace(/\s/g, '') + '-' + styleName + '.otf';
var arrayBuffer = this.toArrayBuffer();
if (isBrowser()) {
window.requestFileSystem =
window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(
window.TEMPORARY,
arrayBuffer.byteLength,
function(fs) {
fs.root.getFile(fileName, { create: true }, function(fileEntry) {
fileEntry.createWriter(function(writer) {
var dataView = new DataView(arrayBuffer);
var blob = new Blob([dataView], { type: 'font/opentype' });
writer.write(blob);
writer.addEventListener(
'writeend',
function() {
// Navigating to the file will download it.
location.href = fileEntry.toURL();
},
false
);
});
});
},
function(err) {
throw new Error(err.name + ': ' + err.message);
}
);
} else {
var fs = _dereq_('fs');
var buffer = arrayBufferToNodeBuffer(arrayBuffer);
fs.writeFileSync(fileName, buffer);
}
};
/**
* @private
*/
Font.prototype.fsSelectionValues = {
ITALIC: 0x001, //1
UNDERSCORE: 0x002, //2
NEGATIVE: 0x004, //4
OUTLINED: 0x008, //8
STRIKEOUT: 0x010, //16
BOLD: 0x020, //32
REGULAR: 0x040, //64
USER_TYPO_METRICS: 0x080, //128
WWS: 0x100, //256
OBLIQUE: 0x200 //512
};
/**
* @private
*/
Font.prototype.usWidthClasses = {
ULTRA_CONDENSED: 1,
EXTRA_CONDENSED: 2,
CONDENSED: 3,
SEMI_CONDENSED: 4,
MEDIUM: 5,
SEMI_EXPANDED: 6,
EXPANDED: 7,
EXTRA_EXPANDED: 8,
ULTRA_EXPANDED: 9
};
/**
* @private
*/
Font.prototype.usWeightClasses = {
THIN: 100,
EXTRA_LIGHT: 200,
LIGHT: 300,
NORMAL: 400,
MEDIUM: 500,
SEMI_BOLD: 600,
BOLD: 700,
EXTRA_BOLD: 800,
BLACK: 900
};
// The `fvar` table stores font variation axes and instances.
function addName(name, names) {
var nameString = JSON.stringify(name);
var nameID = 256;
for (var nameKey in names) {
var n = parseInt(nameKey);
if (!n || n < 256) {
continue;
}
if (JSON.stringify(names[nameKey]) === nameString) {
return n;
}
if (nameID <= n) {
nameID = n + 1;
}
}
names[nameID] = name;
return nameID;
}
function makeFvarAxis(n, axis, names) {
var nameID = addName(axis.name, names);
return [
{ name: 'tag_' + n, type: 'TAG', value: axis.tag },
{ name: 'minValue_' + n, type: 'FIXED', value: axis.minValue << 16 },
{
name: 'defaultValue_' + n,
type: 'FIXED',
value: axis.defaultValue << 16
},
{ name: 'maxValue_' + n, type: 'FIXED', value: axis.maxValue << 16 },
{ name: 'flags_' + n, type: 'USHORT', value: 0 },
{ name: 'nameID_' + n, type: 'USHORT', value: nameID }
];
}
function parseFvarAxis(data, start, names) {
var axis = {};
var p = new parse.Parser(data, start);
axis.tag = p.parseTag();
axis.minValue = p.parseFixed();
axis.defaultValue = p.parseFixed();
axis.maxValue = p.parseFixed();
p.skip('uShort', 1); // reserved for flags; no values defined
axis.name = names[p.parseUShort()] || {};
return axis;
}
function makeFvarInstance(n, inst, axes, names) {
var nameID = addName(inst.name, names);
var fields = [
{ name: 'nameID_' + n, type: 'USHORT', value: nameID },
{ name: 'flags_' + n, type: 'USHORT', value: 0 }
];
for (var i = 0; i < axes.length; ++i) {
var axisTag = axes[i].tag;
fields.push({
name: 'axis_' + n + ' ' + axisTag,
type: 'FIXED',
value: inst.coordinates[axisTag] << 16
});
}
return fields;
}
function parseFvarInstance(data, start, axes, names) {
var inst = {};
var p = new parse.Parser(data, start);
inst.name = names[p.parseUShort()] || {};
p.skip('uShort', 1); // reserved for flags; no values defined
inst.coordinates = {};
for (var i = 0; i < axes.length; ++i) {
inst.coordinates[axes[i].tag] = p.parseFixed();
}
return inst;
}
function makeFvarTable(fvar, names) {
var result = new table.Table('fvar', [
{ name: 'version', type: 'ULONG', value: 0x10000 },
{ name: 'offsetToData', type: 'USHORT', value: 0 },
{ name: 'countSizePairs', type: 'USHORT', value: 2 },
{ name: 'axisCount', type: 'USHORT', value: fvar.axes.length },
{ name: 'axisSize', type: 'USHORT', value: 20 },
{ name: 'instanceCount', type: 'USHORT', value: fvar.instances.length },
{ name: 'instanceSize', type: 'USHORT', value: 4 + fvar.axes.length * 4 }
]);
result.offsetToData = result.sizeOf();
for (var i = 0; i < fvar.axes.length; i++) {
result.fields = result.fields.concat(
makeFvarAxis(i, fvar.axes[i], names)
);
}
for (var j = 0; j < fvar.instances.length; j++) {
result.fields = result.fields.concat(
makeFvarInstance(j, fvar.instances[j], fvar.axes, names)
);
}
return result;
}
function parseFvarTable(data, start, names) {
var p = new parse.Parser(data, start);
var tableVersion = p.parseULong();
check.argument(
tableVersion === 0x00010000,
'Unsupported fvar table version.'
);
var offsetToData = p.parseOffset16();
// Skip countSizePairs.
p.skip('uShort', 1);
var axisCount = p.parseUShort();
var axisSize = p.parseUShort();
var instanceCount = p.parseUShort();
var instanceSize = p.parseUShort();
var axes = [];
for (var i = 0; i < axisCount; i++) {
axes.push(
parseFvarAxis(data, start + offsetToData + i * axisSize, names)
);
}
var instances = [];
var instanceStart = start + offsetToData + axisCount * axisSize;
for (var j = 0; j < instanceCount; j++) {
instances.push(
parseFvarInstance(data, instanceStart + j * instanceSize, axes, names)
);
}
return { axes: axes, instances: instances };
}
var fvar = { make: makeFvarTable, parse: parseFvarTable };
// The `GPOS` table contains kerning pairs, among other things.
var subtableParsers$1 = new Array(10); // subtableParsers[0] is unused
// https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#lookup-type-1-single-adjustment-positioning-subtable
// this = Parser instance
subtableParsers$1[1] = function parseLookup1() {
var start = this.offset + this.relativeOffset;
var posformat = this.parseUShort();
if (posformat === 1) {
return {
posFormat: 1,
coverage: this.parsePointer(Parser.coverage),
value: this.parseValueRecord()
};
} else if (posformat === 2) {
return {
posFormat: 2,
coverage: this.parsePointer(Parser.coverage),
values: this.parseValueRecordList()
};
}
check.assert(
false,
'0x' + start.toString(16) + ': GPOS lookup type 1 format must be 1 or 2.'
);
};
// https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#lookup-type-2-pair-adjustment-positioning-subtable
subtableParsers$1[2] = function parseLookup2() {
var start = this.offset + this.relativeOffset;
var posFormat = this.parseUShort();
check.assert(
posFormat === 1 || posFormat === 2,
'0x' + start.toString(16) + ': GPOS lookup type 2 format must be 1 or 2.'
);
var coverage = this.parsePointer(Parser.coverage);
var valueFormat1 = this.parseUShort();
var valueFormat2 = this.parseUShort();
if (posFormat === 1) {
// Adjustments for Glyph Pairs
return {
posFormat: posFormat,
coverage: coverage,
valueFormat1: valueFormat1,
valueFormat2: valueFormat2,
pairSets: this.parseList(
Parser.pointer(
Parser.list(function() {
return {
// pairValueRecord
secondGlyph: this.parseUShort(),
value1: this.parseValueRecord(valueFormat1),
value2: this.parseValueRecord(valueFormat2)
};
})
)
)
};
} else if (posFormat === 2) {
var classDef1 = this.parsePointer(Parser.classDef);
var classDef2 = this.parsePointer(Parser.classDef);
var class1Count = this.parseUShort();
var class2Count = this.parseUShort();
return {
// Class Pair Adjustment
posFormat: posFormat,
coverage: coverage,
valueFormat1: valueFormat1,
valueFormat2: valueFormat2,
classDef1: classDef1,
classDef2: classDef2,
class1Count: class1Count,
class2Count: class2Count,
classRecords: this.parseList(
class1Count,
Parser.list(class2Count, function() {
return {
value1: this.parseValueRecord(valueFormat1),
value2: this.parseValueRecord(valueFormat2)
};
})
)
};
}
};
subtableParsers$1[3] = function parseLookup3() {
return { error: 'GPOS Lookup 3 not supported' };
};
subtableParsers$1[4] = function parseLookup4() {
return { error: 'GPOS Lookup 4 not supported' };
};
subtableParsers$1[5] = function parseLookup5() {
return { error: 'GPOS Lookup 5 not supported' };
};
subtableParsers$1[6] = function parseLookup6() {
return { error: 'GPOS Lookup 6 not supported' };
};
subtableParsers$1[7] = function parseLookup7() {
return { error: 'GPOS Lookup 7 not supported' };
};
subtableParsers$1[8] = function parseLookup8() {
return { error: 'GPOS Lookup 8 not supported' };
};
subtableParsers$1[9] = function parseLookup9() {
return { error: 'GPOS Lookup 9 not supported' };
};
// https://docs.microsoft.com/en-us/typography/opentype/spec/gpos
function parseGposTable(data, start) {
start = start || 0;
var p = new Parser(data, start);
var tableVersion = p.parseVersion(1);
check.argument(
tableVersion === 1 || tableVersion === 1.1,
'Unsupported GPOS table version ' + tableVersion
);
if (tableVersion === 1) {
return {
version: tableVersion,
scripts: p.parseScriptList(),
features: p.parseFeatureList(),
lookups: p.parseLookupList(subtableParsers$1)
};
} else {
return {
version: tableVersion,
scripts: p.parseScriptList(),
features: p.parseFeatureList(),
lookups: p.parseLookupList(subtableParsers$1),
variations: p.parseFeatureVariationsList()
};
}
}
// GPOS Writing //////////////////////////////////////////////
// NOT SUPPORTED
var subtableMakers$1 = new Array(10);
function makeGposTable(gpos) {
return new table.Table('GPOS', [
{ name: 'version', type: 'ULONG', value: 0x10000 },
{
name: 'scripts',
type: 'TABLE',
value: new table.ScriptList(gpos.scripts)
},
{
name: 'features',
type: 'TABLE',
value: new table.FeatureList(gpos.features)
},
{
name: 'lookups',
type: 'TABLE',
value: new table.LookupList(gpos.lookups, subtableMakers$1)
}
]);
}
var gpos = { parse: parseGposTable, make: makeGposTable };
// The `kern` table contains kerning pairs.
function parseWindowsKernTable(p) {
var pairs = {};
// Skip nTables.
p.skip('uShort');
var subtableVersion = p.parseUShort();
check.argument(
subtableVersion === 0,
'Unsupported kern sub-table version.'
);
// Skip subtableLength, subtableCoverage
p.skip('uShort', 2);
var nPairs = p.parseUShort();
// Skip searchRange, entrySelector, rangeShift.
p.skip('uShort', 3);
for (var i = 0; i < nPairs; i += 1) {
var leftIndex = p.parseUShort();
var rightIndex = p.parseUShort();
var value = p.parseShort();
pairs[leftIndex + ',' + rightIndex] = value;
}
return pairs;
}
function parseMacKernTable(p) {
var pairs = {};
// The Mac kern table stores the version as a fixed (32 bits) but we only loaded the first 16 bits.
// Skip the rest.
p.skip('uShort');
var nTables = p.parseULong();
//check.argument(nTables === 1, 'Only 1 subtable is supported (got ' + nTables + ').');
if (nTables > 1) {
console.warn('Only the first kern subtable is supported.');
}
p.skip('uLong');
var coverage = p.parseUShort();
var subtableVersion = coverage & 0xff;
p.skip('uShort');
if (subtableVersion === 0) {
var nPairs = p.parseUShort();
// Skip searchRange, entrySelector, rangeShift.
p.skip('uShort', 3);
for (var i = 0; i < nPairs; i += 1) {
var leftIndex = p.parseUShort();
var rightIndex = p.parseUShort();
var value = p.parseShort();
pairs[leftIndex + ',' + rightIndex] = value;
}
}
return pairs;
}
// Parse the `kern` table which contains kerning pairs.
function parseKernTable(data, start) {
var p = new parse.Parser(data, start);
var tableVersion = p.parseUShort();
if (tableVersion === 0) {
return parseWindowsKernTable(p);
} else if (tableVersion === 1) {
return parseMacKernTable(p);
} else {
throw new Error('Unsupported kern table version (' + tableVersion + ').');
}
}
var kern = { parse: parseKernTable };
// The `loca` table stores the offsets to the locations of the glyphs in the font.
// Parse the `loca` table. This table stores the offsets to the locations of the glyphs in the font,
// relative to the beginning of the glyphData table.
// The number of glyphs stored in the `loca` table is specified in the `maxp` table (under numGlyphs)
// The loca table has two versions: a short version where offsets are stored as uShorts, and a long
// version where offsets are stored as uLongs. The `head` table specifies which version to use
// (under indexToLocFormat).
function parseLocaTable(data, start, numGlyphs, shortVersion) {
var p = new parse.Parser(data, start);
var parseFn = shortVersion ? p.parseUShort : p.parseULong;
// There is an extra entry after the last index element to compute the length of the last glyph.
// That's why we use numGlyphs + 1.
var glyphOffsets = [];
for (var i = 0; i < numGlyphs + 1; i += 1) {
var glyphOffset = parseFn.call(p);
if (shortVersion) {
// The short table version stores the actual offset divided by 2.
glyphOffset *= 2;
}
glyphOffsets.push(glyphOffset);
}
return glyphOffsets;
}
var loca = { parse: parseLocaTable };
// opentype.js
/**
* The opentype library.
* @namespace opentype
*/
// File loaders /////////////////////////////////////////////////////////
/**
* Loads a font from a file. The callback throws an error message as the first parameter if it fails
* and the font as an ArrayBuffer in the second parameter if it succeeds.
* @param {string} path - The path of the file
* @param {Function} callback - The function to call when the font load completes
*/
function loadFromFile(path, callback) {
var fs = _dereq_('fs');
fs.readFile(path, function(err, buffer) {
if (err) {
return callback(err.message);
}
callback(null, nodeBufferToArrayBuffer(buffer));
});
}
/**
* Loads a font from a URL. The callback throws an error message as the first parameter if it fails
* and the font as an ArrayBuffer in the second parameter if it succeeds.
* @param {string} url - The URL of the font file.
* @param {Function} callback - The function to call when the font load completes
*/
function loadFromUrl(url, callback) {
var request = new XMLHttpRequest();
request.open('get', url, true);
request.responseType = 'arraybuffer';
request.onload = function() {
if (request.response) {
return callback(null, request.response);
} else {
return callback('Font could not be loaded: ' + request.statusText);
}
};
request.onerror = function() {
callback('Font could not be loaded');
};
request.send();
}
// Table Directory Entries //////////////////////////////////////////////
/**
* Parses OpenType table entries.
* @param {DataView}
* @param {Number}
* @return {Object[]}
*/
function parseOpenTypeTableEntries(data, numTables) {
var tableEntries = [];
var p = 12;
for (var i = 0; i < numTables; i += 1) {
var tag = parse.getTag(data, p);
var checksum = parse.getULong(data, p + 4);
var offset = parse.getULong(data, p + 8);
var length = parse.getULong(data, p + 12);
tableEntries.push({
tag: tag,
checksum: checksum,
offset: offset,
length: length,
compression: false
});
p += 16;
}
return tableEntries;
}
/**
* Parses WOFF table entries.
* @param {DataView}
* @param {Number}
* @return {Object[]}
*/
function parseWOFFTableEntries(data, numTables) {
var tableEntries = [];
var p = 44; // offset to the first table directory entry.
for (var i = 0; i < numTables; i += 1) {
var tag = parse.getTag(data, p);
var offset = parse.getULong(data, p + 4);
var compLength = parse.getULong(data, p + 8);
var origLength = parse.getULong(data, p + 12);
var compression = void 0;
if (compLength < origLength) {
compression = 'WOFF';
} else {
compression = false;
}
tableEntries.push({
tag: tag,
offset: offset,
compression: compression,
compressedLength: compLength,
length: origLength
});
p += 20;
}
return tableEntries;
}
/**
* @typedef TableData
* @type Object
* @property {DataView} data - The DataView
* @property {number} offset - The data offset.
*/
/**
* @param {DataView}
* @param {Object}
* @return {TableData}
*/
function uncompressTable(data, tableEntry) {
if (tableEntry.compression === 'WOFF') {
var inBuffer = new Uint8Array(
data.buffer,
tableEntry.offset + 2,
tableEntry.compressedLength - 2
);
var outBuffer = new Uint8Array(tableEntry.length);
tinyInflate(inBuffer, outBuffer);
if (outBuffer.byteLength !== tableEntry.length) {
throw new Error(
'Decompression error: ' +
tableEntry.tag +
" decompressed length doesn't match recorded length"
);
}
var view = new DataView(outBuffer.buffer, 0);
return { data: view, offset: 0 };
} else {
return { data: data, offset: tableEntry.offset };
}
}
// Public API ///////////////////////////////////////////////////////////
/**
* Parse the OpenType file data (as an ArrayBuffer) and return a Font object.
* Throws an error if the font could not be parsed.
* @param {ArrayBuffer}
* @return {opentype.Font}
*/
function parseBuffer(buffer) {
var indexToLocFormat;
var ltagTable;
// Since the constructor can also be called to create new fonts from scratch, we indicate this
// should be an empty font that we'll fill with our own data.
var font = new Font({ empty: true });
// OpenType fonts use big endian byte ordering.
// We can't rely on typed array view types, because they operate with the endianness of the host computer.
// Instead we use DataViews where we can specify endianness.
var data = new DataView(buffer, 0);
var numTables;
var tableEntries = [];
var signature = parse.getTag(data, 0);
if (
signature === String.fromCharCode(0, 1, 0, 0) ||
signature === 'true' ||
signature === 'typ1'
) {
font.outlinesFormat = 'truetype';
numTables = parse.getUShort(data, 4);
tableEntries = parseOpenTypeTableEntries(data, numTables);
} else if (signature === 'OTTO') {
font.outlinesFormat = 'cff';
numTables = parse.getUShort(data, 4);
tableEntries = parseOpenTypeTableEntries(data, numTables);
} else if (signature === 'wOFF') {
var flavor = parse.getTag(data, 4);
if (flavor === String.fromCharCode(0, 1, 0, 0)) {
font.outlinesFormat = 'truetype';
} else if (flavor === 'OTTO') {
font.outlinesFormat = 'cff';
} else {
throw new Error('Unsupported OpenType flavor ' + signature);
}
numTables = parse.getUShort(data, 12);
tableEntries = parseWOFFTableEntries(data, numTables);
} else {
throw new Error('Unsupported OpenType signature ' + signature);
}
var cffTableEntry;
var fvarTableEntry;
var glyfTableEntry;
var gposTableEntry;
var gsubTableEntry;
var hmtxTableEntry;
var kernTableEntry;
var locaTableEntry;
var nameTableEntry;
var metaTableEntry;
var p;
for (var i = 0; i < numTables; i += 1) {
var tableEntry = tableEntries[i];
var table = void 0;
switch (tableEntry.tag) {
case 'cmap':
table = uncompressTable(data, tableEntry);
font.tables.cmap = cmap.parse(table.data, table.offset);
font.encoding = new CmapEncoding(font.tables.cmap);
break;
case 'cvt ':
table = uncompressTable(data, tableEntry);
p = new parse.Parser(table.data, table.offset);
font.tables.cvt = p.parseShortList(tableEntry.length / 2);
break;
case 'fvar':
fvarTableEntry = tableEntry;
break;
case 'fpgm':
table = uncompressTable(data, tableEntry);
p = new parse.Parser(table.data, table.offset);
font.tables.fpgm = p.parseByteList(tableEntry.length);
break;
case 'head':
table = uncompressTable(data, tableEntry);
font.tables.head = head.parse(table.data, table.offset);
font.unitsPerEm = font.tables.head.unitsPerEm;
indexToLocFormat = font.tables.head.indexToLocFormat;
break;
case 'hhea':
table = uncompressTable(data, tableEntry);
font.tables.hhea = hhea.parse(table.data, table.offset);
font.ascender = font.tables.hhea.ascender;
font.descender = font.tables.hhea.descender;
font.numberOfHMetrics = font.tables.hhea.numberOfHMetrics;
break;
case 'hmtx':
hmtxTableEntry = tableEntry;
break;
case 'ltag':
table = uncompressTable(data, tableEntry);
ltagTable = ltag.parse(table.data, table.offset);
break;
case 'maxp':
table = uncompressTable(data, tableEntry);
font.tables.maxp = maxp.parse(table.data, table.offset);
font.numGlyphs = font.tables.maxp.numGlyphs;
break;
case 'name':
nameTableEntry = tableEntry;
break;
case 'OS/2':
table = uncompressTable(data, tableEntry);
font.tables.os2 = os2.parse(table.data, table.offset);
break;
case 'post':
table = uncompressTable(data, tableEntry);
font.tables.post = post.parse(table.data, table.offset);
font.glyphNames = new GlyphNames(font.tables.post);
break;
case 'prep':
table = uncompressTable(data, tableEntry);
p = new parse.Parser(table.data, table.offset);
font.tables.prep = p.parseByteList(tableEntry.length);
break;
case 'glyf':
glyfTableEntry = tableEntry;
break;
case 'loca':
locaTableEntry = tableEntry;
break;
case 'CFF ':
cffTableEntry = tableEntry;
break;
case 'kern':
kernTableEntry = tableEntry;
break;
case 'GPOS':
gposTableEntry = tableEntry;
break;
case 'GSUB':
gsubTableEntry = tableEntry;
break;
case 'meta':
metaTableEntry = tableEntry;
break;
}
}
var nameTable = uncompressTable(data, nameTableEntry);
font.tables.name = _name.parse(nameTable.data, nameTable.offset, ltagTable);
font.names = font.tables.name;
if (glyfTableEntry && locaTableEntry) {
var shortVersion = indexToLocFormat === 0;
var locaTable = uncompressTable(data, locaTableEntry);
var locaOffsets = loca.parse(
locaTable.data,
locaTable.offset,
font.numGlyphs,
shortVersion
);
var glyfTable = uncompressTable(data, glyfTableEntry);
font.glyphs = glyf.parse(
glyfTable.data,
glyfTable.offset,
locaOffsets,
font
);
} else if (cffTableEntry) {
var cffTable = uncompressTable(data, cffTableEntry);
cff.parse(cffTable.data, cffTable.offset, font);
} else {
throw new Error("Font doesn't contain TrueType or CFF outlines.");
}
var hmtxTable = uncompressTable(data, hmtxTableEntry);
hmtx.parse(
hmtxTable.data,
hmtxTable.offset,
font.numberOfHMetrics,
font.numGlyphs,
font.glyphs
);
addGlyphNames(font);
if (kernTableEntry) {
var kernTable = uncompressTable(data, kernTableEntry);
font.kerningPairs = kern.parse(kernTable.data, kernTable.offset);
} else {
font.kerningPairs = {};
}
if (gposTableEntry) {
var gposTable = uncompressTable(data, gposTableEntry);
font.tables.gpos = gpos.parse(gposTable.data, gposTable.offset);
font.position.init();
}
if (gsubTableEntry) {
var gsubTable = uncompressTable(data, gsubTableEntry);
font.tables.gsub = gsub.parse(gsubTable.data, gsubTable.offset);
}
if (fvarTableEntry) {
var fvarTable = uncompressTable(data, fvarTableEntry);
font.tables.fvar = fvar.parse(
fvarTable.data,
fvarTable.offset,
font.names
);
}
if (metaTableEntry) {
var metaTable = uncompressTable(data, metaTableEntry);
font.tables.meta = meta.parse(metaTable.data, metaTable.offset);
font.metas = font.tables.meta;
}
return font;
}
/**
* Asynchronously load the font from a URL or a filesystem. When done, call the callback
* with two arguments `(err, font)`. The `err` will be null on success,
* the `font` is a Font object.
* We use the node.js callback convention so that
* opentype.js can integrate with frameworks like async.js.
* @alias opentype.load
* @param {string} url - The URL of the font to load.
* @param {Function} callback - The callback.
*/
function load(url, callback) {
var isNode$$1 = typeof window === 'undefined';
var loadFn = isNode$$1 ? loadFromFile : loadFromUrl;
loadFn(url, function(err, arrayBuffer) {
if (err) {
return callback(err);
}
var font;
try {
font = parseBuffer(arrayBuffer);
} catch (e) {
return callback(e, null);
}
return callback(null, font);
});
}
/**
* Synchronously load the font from a URL or file.
* When done, returns the font object or throws an error.
* @alias opentype.loadSync
* @param {string} url - The URL of the font to load.
* @return {opentype.Font}
*/
function loadSync(url) {
var fs = _dereq_('fs');
var buffer = fs.readFileSync(url);
return parseBuffer(nodeBufferToArrayBuffer(buffer));
}
exports.Font = Font;
exports.Glyph = Glyph;
exports.Path = Path;
exports.BoundingBox = BoundingBox;
exports._parse = parse;
exports.parse = parseBuffer;
exports.load = load;
exports.loadSync = loadSync;
Object.defineProperty(exports, '__esModule', { value: true });
});
}.call(this, _dereq_('buffer').Buffer));
},
{ buffer: 22, fs: 21 }
],
35: [
function(_dereq_, module, exports) {
(function(process) {
// .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
// backported and transplited with Babel, with backwards-compat fixes
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = parts.length - 1; i >= 0; i--) {
var last = parts[i];
if (last === '.') {
parts.splice(i, 1);
} else if (last === '..') {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
}
// path.resolve([from ...], to)
// posix version
exports.resolve = function() {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = i >= 0 ? arguments[i] : process.cwd();
// Skip empty and invalid entries
if (typeof path !== 'string') {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charAt(0) === '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(
filter(resolvedPath.split('/'), function(p) {
return !!p;
}),
!resolvedAbsolute
).join('/');
return (resolvedAbsolute ? '/' : '') + resolvedPath || '.';
};
// path.normalize(path)
// posix version
exports.normalize = function(path) {
var isAbsolute = exports.isAbsolute(path),
trailingSlash = substr(path, -1) === '/';
// Normalize the path
path = normalizeArray(
filter(path.split('/'), function(p) {
return !!p;
}),
!isAbsolute
).join('/');
if (!path && !isAbsolute) {
path = '.';
}
if (path && trailingSlash) {
path += '/';
}
return (isAbsolute ? '/' : '') + path;
};
// posix version
exports.isAbsolute = function(path) {
return path.charAt(0) === '/';
};
// posix version
exports.join = function() {
var paths = Array.prototype.slice.call(arguments, 0);
return exports.normalize(
filter(paths, function(p, index) {
if (typeof p !== 'string') {
throw new TypeError('Arguments to path.join must be strings');
}
return p;
}).join('/')
);
};
// path.relative(from, to)
// posix version
exports.relative = function(from, to) {
from = exports.resolve(from).substr(1);
to = exports.resolve(to).substr(1);
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}
if (start > end) return [];
return arr.slice(start, end - start + 1);
}
var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
exports.sep = '/';
exports.delimiter = ':';
exports.dirname = function(path) {
if (typeof path !== 'string') path = path + '';
if (path.length === 0) return '.';
var code = path.charCodeAt(0);
var hasRoot = code === 47 /*/*/;
var end = -1;
var matchedSlash = true;
for (var i = path.length - 1; i >= 1; --i) {
code = path.charCodeAt(i);
if (code === 47 /*/*/) {
if (!matchedSlash) {
end = i;
break;
}
} else {
// We saw the first non-path separator
matchedSlash = false;
}
}
if (end === -1) return hasRoot ? '/' : '.';
if (hasRoot && end === 1) {
// return '//';
// Backwards-compat fix:
return '/';
}
return path.slice(0, end);
};
function basename(path) {
if (typeof path !== 'string') path = path + '';
var start = 0;
var end = -1;
var matchedSlash = true;
var i;
for (i = path.length - 1; i >= 0; --i) {
if (path.charCodeAt(i) === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
start = i + 1;
break;
}
} else if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// path component
matchedSlash = false;
end = i + 1;
}
}
if (end === -1) return '';
return path.slice(start, end);
}
// Uses a mixed approach for backwards-compatibility, as ext behavior changed
// in new Node.js versions, so only basename() above is backported here
exports.basename = function(path, ext) {
var f = basename(path);
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
exports.extname = function(path) {
if (typeof path !== 'string') path = path + '';
var startDot = -1;
var startPart = 0;
var end = -1;
var matchedSlash = true;
// Track the state of characters (if any) we see before our first dot and
// after any path separator we find
var preDotState = 0;
for (var i = path.length - 1; i >= 0; --i) {
var code = path.charCodeAt(i);
if (code === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
startPart = i + 1;
break;
}
continue;
}
if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// extension
matchedSlash = false;
end = i + 1;
}
if (code === 46 /*.*/) {
// If this is our first dot, mark it as the start of our extension
if (startDot === -1) startDot = i;
else if (preDotState !== 1) preDotState = 1;
} else if (startDot !== -1) {
// We saw a non-dot and non-path separator before our dot, so we should
// have a good chance at having a non-empty extension
preDotState = -1;
}
}
if (
startDot === -1 ||
end === -1 ||
// We saw a non-dot character immediately before the dot
preDotState === 0 ||
// The (right-most) trimmed path component is exactly '..'
(preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
) {
return '';
}
return path.slice(startDot, end);
};
function filter(xs, f) {
if (xs.filter) return xs.filter(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
if (f(xs[i], i, xs)) res.push(xs[i]);
}
return res;
}
// String.prototype.substr - negative index don't work in IE8
var substr =
'ab'.substr(-1) === 'b'
? function(str, start, len) {
return str.substr(start, len);
}
: function(str, start, len) {
if (start < 0) start = str.length + start;
return str.substr(start, len);
};
}.call(this, _dereq_('_process')));
},
{ _process: 36 }
],
36: [
function(_dereq_, module, exports) {
// shim for using process in browser
var process = (module.exports = {});
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout() {
throw new Error('clearTimeout has not been defined');
}
(function() {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
})();
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if (
(cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) &&
setTimeout
) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if (
(cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) &&
clearTimeout
) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while (len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function(fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function() {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function(name) {
return [];
};
process.binding = function(name) {
throw new Error('process.binding is not supported');
};
process.cwd = function() {
return '/';
};
process.chdir = function(dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() {
return 0;
};
},
{}
],
37: [
function(_dereq_, module, exports) {
(function(self) {
'use strict';
if (self.fetch) {
return;
}
var support = {
searchParams: 'URLSearchParams' in self,
iterable: 'Symbol' in self && 'iterator' in Symbol,
blob:
'FileReader' in self &&
'Blob' in self &&
(function() {
try {
new Blob();
return true;
} catch (e) {
return false;
}
})(),
formData: 'FormData' in self,
arrayBuffer: 'ArrayBuffer' in self
};
if (support.arrayBuffer) {
var viewClasses = [
'[object Int8Array]',
'[object Uint8Array]',
'[object Uint8ClampedArray]',
'[object Int16Array]',
'[object Uint16Array]',
'[object Int32Array]',
'[object Uint32Array]',
'[object Float32Array]',
'[object Float64Array]'
];
var isDataView = function(obj) {
return obj && DataView.prototype.isPrototypeOf(obj);
};
var isArrayBufferView =
ArrayBuffer.isView ||
function(obj) {
return (
obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1
);
};
}
function normalizeName(name) {
if (typeof name !== 'string') {
name = String(name);
}
if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {
throw new TypeError('Invalid character in header field name');
}
return name.toLowerCase();
}
function normalizeValue(value) {
if (typeof value !== 'string') {
value = String(value);
}
return value;
}
// Build a destructive iterator for the value list
function iteratorFor(items) {
var iterator = {
next: function() {
var value = items.shift();
return { done: value === undefined, value: value };
}
};
if (support.iterable) {
iterator[Symbol.iterator] = function() {
return iterator;
};
}
return iterator;
}
function Headers(headers) {
this.map = {};
if (headers instanceof Headers) {
headers.forEach(function(value, name) {
this.append(name, value);
}, this);
} else if (Array.isArray(headers)) {
headers.forEach(function(header) {
this.append(header[0], header[1]);
}, this);
} else if (headers) {
Object.getOwnPropertyNames(headers).forEach(function(name) {
this.append(name, headers[name]);
}, this);
}
}
Headers.prototype.append = function(name, value) {
name = normalizeName(name);
value = normalizeValue(value);
var oldValue = this.map[name];
this.map[name] = oldValue ? oldValue + ',' + value : value;
};
Headers.prototype['delete'] = function(name) {
delete this.map[normalizeName(name)];
};
Headers.prototype.get = function(name) {
name = normalizeName(name);
return this.has(name) ? this.map[name] : null;
};
Headers.prototype.has = function(name) {
return this.map.hasOwnProperty(normalizeName(name));
};
Headers.prototype.set = function(name, value) {
this.map[normalizeName(name)] = normalizeValue(value);
};
Headers.prototype.forEach = function(callback, thisArg) {
for (var name in this.map) {
if (this.map.hasOwnProperty(name)) {
callback.call(thisArg, this.map[name], name, this);
}
}
};
Headers.prototype.keys = function() {
var items = [];
this.forEach(function(value, name) {
items.push(name);
});
return iteratorFor(items);
};
Headers.prototype.values = function() {
var items = [];
this.forEach(function(value) {
items.push(value);
});
return iteratorFor(items);
};
Headers.prototype.entries = function() {
var items = [];
this.forEach(function(value, name) {
items.push([name, value]);
});
return iteratorFor(items);
};
if (support.iterable) {
Headers.prototype[Symbol.iterator] = Headers.prototype.entries;
}
function consumed(body) {
if (body.bodyUsed) {
return Promise.reject(new TypeError('Already read'));
}
body.bodyUsed = true;
}
function fileReaderReady(reader) {
return new Promise(function(resolve, reject) {
reader.onload = function() {
resolve(reader.result);
};
reader.onerror = function() {
reject(reader.error);
};
});
}
function readBlobAsArrayBuffer(blob) {
var reader = new FileReader();
var promise = fileReaderReady(reader);
reader.readAsArrayBuffer(blob);
return promise;
}
function readBlobAsText(blob) {
var reader = new FileReader();
var promise = fileReaderReady(reader);
reader.readAsText(blob);
return promise;
}
function readArrayBufferAsText(buf) {
var view = new Uint8Array(buf);
var chars = new Array(view.length);
for (var i = 0; i < view.length; i++) {
chars[i] = String.fromCharCode(view[i]);
}
return chars.join('');
}
function bufferClone(buf) {
if (buf.slice) {
return buf.slice(0);
} else {
var view = new Uint8Array(buf.byteLength);
view.set(new Uint8Array(buf));
return view.buffer;
}
}
function Body() {
this.bodyUsed = false;
this._initBody = function(body) {
this._bodyInit = body;
if (!body) {
this._bodyText = '';
} else if (typeof body === 'string') {
this._bodyText = body;
} else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
this._bodyBlob = body;
} else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
this._bodyFormData = body;
} else if (
support.searchParams &&
URLSearchParams.prototype.isPrototypeOf(body)
) {
this._bodyText = body.toString();
} else if (support.arrayBuffer && support.blob && isDataView(body)) {
this._bodyArrayBuffer = bufferClone(body.buffer);
// IE 10-11 can't handle a DataView body.
this._bodyInit = new Blob([this._bodyArrayBuffer]);
} else if (
support.arrayBuffer &&
(ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))
) {
this._bodyArrayBuffer = bufferClone(body);
} else {
throw new Error('unsupported BodyInit type');
}
if (!this.headers.get('content-type')) {
if (typeof body === 'string') {
this.headers.set('content-type', 'text/plain;charset=UTF-8');
} else if (this._bodyBlob && this._bodyBlob.type) {
this.headers.set('content-type', this._bodyBlob.type);
} else if (
support.searchParams &&
URLSearchParams.prototype.isPrototypeOf(body)
) {
this.headers.set(
'content-type',
'application/x-www-form-urlencoded;charset=UTF-8'
);
}
}
};
if (support.blob) {
this.blob = function() {
var rejected = consumed(this);
if (rejected) {
return rejected;
}
if (this._bodyBlob) {
return Promise.resolve(this._bodyBlob);
} else if (this._bodyArrayBuffer) {
return Promise.resolve(new Blob([this._bodyArrayBuffer]));
} else if (this._bodyFormData) {
throw new Error('could not read FormData body as blob');
} else {
return Promise.resolve(new Blob([this._bodyText]));
}
};
this.arrayBuffer = function() {
if (this._bodyArrayBuffer) {
return consumed(this) || Promise.resolve(this._bodyArrayBuffer);
} else {
return this.blob().then(readBlobAsArrayBuffer);
}
};
}
this.text = function() {
var rejected = consumed(this);
if (rejected) {
return rejected;
}
if (this._bodyBlob) {
return readBlobAsText(this._bodyBlob);
} else if (this._bodyArrayBuffer) {
return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer));
} else if (this._bodyFormData) {
throw new Error('could not read FormData body as text');
} else {
return Promise.resolve(this._bodyText);
}
};
if (support.formData) {
this.formData = function() {
return this.text().then(decode);
};
}
this.json = function() {
return this.text().then(JSON.parse);
};
return this;
}
// HTTP methods whose capitalization should be normalized
var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];
function normalizeMethod(method) {
var upcased = method.toUpperCase();
return methods.indexOf(upcased) > -1 ? upcased : method;
}
function Request(input, options) {
options = options || {};
var body = options.body;
if (input instanceof Request) {
if (input.bodyUsed) {
throw new TypeError('Already read');
}
this.url = input.url;
this.credentials = input.credentials;
if (!options.headers) {
this.headers = new Headers(input.headers);
}
this.method = input.method;
this.mode = input.mode;
if (!body && input._bodyInit != null) {
body = input._bodyInit;
input.bodyUsed = true;
}
} else {
this.url = String(input);
}
this.credentials = options.credentials || this.credentials || 'omit';
if (options.headers || !this.headers) {
this.headers = new Headers(options.headers);
}
this.method = normalizeMethod(options.method || this.method || 'GET');
this.mode = options.mode || this.mode || null;
this.referrer = null;
if ((this.method === 'GET' || this.method === 'HEAD') && body) {
throw new TypeError('Body not allowed for GET or HEAD requests');
}
this._initBody(body);
}
Request.prototype.clone = function() {
return new Request(this, { body: this._bodyInit });
};
function decode(body) {
var form = new FormData();
body
.trim()
.split('&')
.forEach(function(bytes) {
if (bytes) {
var split = bytes.split('=');
var name = split.shift().replace(/\+/g, ' ');
var value = split.join('=').replace(/\+/g, ' ');
form.append(decodeURIComponent(name), decodeURIComponent(value));
}
});
return form;
}
function parseHeaders(rawHeaders) {
var headers = new Headers();
// Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space
// https://tools.ietf.org/html/rfc7230#section-3.2
var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' ');
preProcessedHeaders.split(/\r?\n/).forEach(function(line) {
var parts = line.split(':');
var key = parts.shift().trim();
if (key) {
var value = parts.join(':').trim();
headers.append(key, value);
}
});
return headers;
}
Body.call(Request.prototype);
function Response(bodyInit, options) {
if (!options) {
options = {};
}
this.type = 'default';
this.status = options.status === undefined ? 200 : options.status;
this.ok = this.status >= 200 && this.status < 300;
this.statusText = 'statusText' in options ? options.statusText : 'OK';
this.headers = new Headers(options.headers);
this.url = options.url || '';
this._initBody(bodyInit);
}
Body.call(Response.prototype);
Response.prototype.clone = function() {
return new Response(this._bodyInit, {
status: this.status,
statusText: this.statusText,
headers: new Headers(this.headers),
url: this.url
});
};
Response.error = function() {
var response = new Response(null, { status: 0, statusText: '' });
response.type = 'error';
return response;
};
var redirectStatuses = [301, 302, 303, 307, 308];
Response.redirect = function(url, status) {
if (redirectStatuses.indexOf(status) === -1) {
throw new RangeError('Invalid status code');
}
return new Response(null, { status: status, headers: { location: url } });
};
self.Headers = Headers;
self.Request = Request;
self.Response = Response;
self.fetch = function(input, init) {
return new Promise(function(resolve, reject) {
var request = new Request(input, init);
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var options = {
status: xhr.status,
statusText: xhr.statusText,
headers: parseHeaders(xhr.getAllResponseHeaders() || '')
};
options.url =
'responseURL' in xhr
? xhr.responseURL
: options.headers.get('X-Request-URL');
var body = 'response' in xhr ? xhr.response : xhr.responseText;
resolve(new Response(body, options));
};
xhr.onerror = function() {
reject(new TypeError('Network request failed'));
};
xhr.ontimeout = function() {
reject(new TypeError('Network request failed'));
};
xhr.open(request.method, request.url, true);
if (request.credentials === 'include') {
xhr.withCredentials = true;
} else if (request.credentials === 'omit') {
xhr.withCredentials = false;
}
if ('responseType' in xhr && support.blob) {
xhr.responseType = 'blob';
}
request.headers.forEach(function(value, name) {
xhr.setRequestHeader(name, value);
});
xhr.send(
typeof request._bodyInit === 'undefined' ? null : request._bodyInit
);
});
};
self.fetch.polyfill = true;
})(typeof self !== 'undefined' ? self : this);
},
{}
],
38: [
function(_dereq_, module, exports) {
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.default = void 0;
var _main = _interopRequireDefault(_dereq_('../core/main'));
var _color_conversion = _interopRequireDefault(
_dereq_('../color/color_conversion')
);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
} /** //stores the original hsb values
* @module Environment
* @submodule Environment
* @for p5
* @requires core
*/
var originalHSB; //stores values for color name exceptions
var colorExceptions = [
{
h: 0,
s: 0,
b: 0.8275,
name: 'gray'
},
{
h: 0,
s: 0,
b: 0.8627,
name: 'gray'
},
{
h: 0,
s: 0,
b: 0.7529,
name: 'gray'
},
{
h: 0.0167,
s: 0.1176,
b: 1,
name: 'light pink'
}
];
//stores values for color names
var colorLookUp = [
{
h: 0,
s: 0,
b: 0,
name: 'black'
},
{
h: 0,
s: 0,
b: 0.5,
name: 'gray'
},
{
h: 0,
s: 0,
b: 1,
name: 'white'
},
{
h: 0,
s: 0.5,
b: 0.5,
name: 'dark maroon'
},
{
h: 0,
s: 0.5,
b: 1,
name: 'salmon pink'
},
{
h: 0,
s: 1,
b: 0,
name: 'black'
},
{
h: 0,
s: 1,
b: 0.5,
name: 'dark red'
},
{
h: 0,
s: 1,
b: 1,
name: 'red'
},
{
h: 5,
s: 0,
b: 1,
name: 'very light peach'
},
{
h: 5,
s: 0.5,
b: 0.5,
name: 'brown'
},
{
h: 5,
s: 0.5,
b: 1,
name: 'peach'
},
{
h: 5,
s: 1,
b: 0.5,
name: 'brick red'
},
{
h: 5,
s: 1,
b: 1,
name: 'crimson'
},
{
h: 10,
s: 0,
b: 1,
name: 'light peach'
},
{
h: 10,
s: 0.5,
b: 0.5,
name: 'brown'
},
{
h: 10,
s: 0.5,
b: 1,
name: 'light orange'
},
{
h: 10,
s: 1,
b: 0.5,
name: 'brown'
},
{
h: 10,
s: 1,
b: 1,
name: 'orange'
},
{
h: 15,
s: 0,
b: 1,
name: 'very light yellow'
},
{
h: 15,
s: 0.5,
b: 0.5,
name: 'olive green'
},
{
h: 15,
s: 0.5,
b: 1,
name: 'light yellow'
},
{
h: 15,
s: 1,
b: 0,
name: 'dark olive green'
},
{
h: 15,
s: 1,
b: 0.5,
name: 'olive green'
},
{
h: 15,
s: 1,
b: 1,
name: 'yellow'
},
{
h: 20,
s: 0,
b: 1,
name: 'very light yellow'
},
{
h: 20,
s: 0.5,
b: 0.5,
name: 'olive green'
},
{
h: 20,
s: 0.5,
b: 1,
name: 'light yellow green'
},
{
h: 20,
s: 1,
b: 0,
name: 'dark olive green'
},
{
h: 20,
s: 1,
b: 0.5,
name: 'dark yellow green'
},
{
h: 20,
s: 1,
b: 1,
name: 'yellow green'
},
{
h: 25,
s: 0.5,
b: 0.5,
name: 'dark yellow green'
},
{
h: 25,
s: 0.5,
b: 1,
name: 'light green'
},
{
h: 25,
s: 1,
b: 0.5,
name: 'dark green'
},
{
h: 25,
s: 1,
b: 1,
name: 'green'
},
{
h: 30,
s: 0.5,
b: 1,
name: 'light green'
},
{
h: 30,
s: 1,
b: 0.5,
name: 'dark green'
},
{
h: 30,
s: 1,
b: 1,
name: 'green'
},
{
h: 35,
s: 0,
b: 0.5,
name: 'light green'
},
{
h: 35,
s: 0,
b: 1,
name: 'very light green'
},
{
h: 35,
s: 0.5,
b: 0.5,
name: 'dark green'
},
{
h: 35,
s: 0.5,
b: 1,
name: 'light green'
},
{
h: 35,
s: 1,
b: 0,
name: 'very dark green'
},
{
h: 35,
s: 1,
b: 0.5,
name: 'dark green'
},
{
h: 35,
s: 1,
b: 1,
name: 'green'
},
{
h: 40,
s: 0,
b: 1,
name: 'very light green'
},
{
h: 40,
s: 0.5,
b: 0.5,
name: 'dark green'
},
{
h: 40,
s: 0.5,
b: 1,
name: 'light green'
},
{
h: 40,
s: 1,
b: 0.5,
name: 'dark green'
},
{
h: 40,
s: 1,
b: 1,
name: 'green'
},
{
h: 45,
s: 0.5,
b: 1,
name: 'light turquoise'
},
{
h: 45,
s: 1,
b: 0.5,
name: 'dark turquoise'
},
{
h: 45,
s: 1,
b: 1,
name: 'turquoise'
},
{
h: 50,
s: 0,
b: 1,
name: 'light sky blue'
},
{
h: 50,
s: 0.5,
b: 0.5,
name: 'dark cyan'
},
{
h: 50,
s: 0.5,
b: 1,
name: 'light cyan'
},
{
h: 50,
s: 1,
b: 0.5,
name: 'dark cyan'
},
{
h: 50,
s: 1,
b: 1,
name: 'cyan'
},
{
h: 55,
s: 0,
b: 1,
name: 'light sky blue'
},
{
h: 55,
s: 0.5,
b: 1,
name: 'light sky blue'
},
{
h: 55,
s: 1,
b: 0.5,
name: 'dark blue'
},
{
h: 55,
s: 1,
b: 1,
name: 'sky blue'
},
{
h: 60,
s: 0,
b: 0.5,
name: 'gray'
},
{
h: 60,
s: 0,
b: 1,
name: 'very light blue'
},
{
h: 60,
s: 0.5,
b: 0.5,
name: 'blue'
},
{
h: 60,
s: 0.5,
b: 1,
name: 'light blue'
},
{
h: 60,
s: 1,
b: 0.5,
name: 'navy blue'
},
{
h: 60,
s: 1,
b: 1,
name: 'blue'
},
{
h: 65,
s: 0,
b: 1,
name: 'lavender'
},
{
h: 65,
s: 0.5,
b: 0.5,
name: 'navy blue'
},
{
h: 65,
s: 0.5,
b: 1,
name: 'light purple'
},
{
h: 65,
s: 1,
b: 0.5,
name: 'dark navy blue'
},
{
h: 65,
s: 1,
b: 1,
name: 'blue'
},
{
h: 70,
s: 0,
b: 1,
name: 'lavender'
},
{
h: 70,
s: 0.5,
b: 0.5,
name: 'navy blue'
},
{
h: 70,
s: 0.5,
b: 1,
name: 'lavender blue'
},
{
h: 70,
s: 1,
b: 0.5,
name: 'dark navy blue'
},
{
h: 70,
s: 1,
b: 1,
name: 'blue'
},
{
h: 75,
s: 0.5,
b: 1,
name: 'lavender'
},
{
h: 75,
s: 1,
b: 0.5,
name: 'dark purple'
},
{
h: 75,
s: 1,
b: 1,
name: 'purple'
},
{
h: 80,
s: 0.5,
b: 1,
name: 'pinkish purple'
},
{
h: 80,
s: 1,
b: 0.5,
name: 'dark purple'
},
{
h: 80,
s: 1,
b: 1,
name: 'purple'
},
{
h: 85,
s: 0,
b: 1,
name: 'light pink'
},
{
h: 85,
s: 0.5,
b: 0.5,
name: 'purple'
},
{
h: 85,
s: 0.5,
b: 1,
name: 'light fuchsia'
},
{
h: 85,
s: 1,
b: 0.5,
name: 'dark fuchsia'
},
{
h: 85,
s: 1,
b: 1,
name: 'fuchsia'
},
{
h: 90,
s: 0.5,
b: 0.5,
name: 'dark fuchsia'
},
{
h: 90,
s: 0.5,
b: 1,
name: 'hot pink'
},
{
h: 90,
s: 1,
b: 0.5,
name: 'dark fuchsia'
},
{
h: 90,
s: 1,
b: 1,
name: 'fuchsia'
},
{
h: 95,
s: 0,
b: 1,
name: 'pink'
},
{
h: 95,
s: 0.5,
b: 1,
name: 'light pink'
},
{
h: 95,
s: 1,
b: 0.5,
name: 'dark magenta'
},
{
h: 95,
s: 1,
b: 1,
name: 'magenta'
}
];
//returns text with color name
function _calculateColor(hsb) {
var colortext;
//round hue
if (hsb[0] !== 0) {
hsb[0] = Math.round(hsb[0] * 100);
var hue = hsb[0].toString().split('');
var last = hue.length - 1;
hue[last] = parseInt(hue[last]);
//if last digit of hue is < 2.5 make it 0
if (hue[last] < 2.5) {
hue[last] = 0;
//if last digit of hue is >= 2.5 and less than 7.5 make it 5
} else if (hue[last] >= 2.5 && hue[last] < 7.5) {
hue[last] = 5;
}
//if hue only has two digits
if (hue.length === 2) {
hue[0] = parseInt(hue[0]);
//if last is greater than 7.5
if (hue[last] >= 7.5) {
//add one to the tens
hue[last] = 0;
hue[0] = hue[0] + 1;
}
hsb[0] = hue[0] * 10 + hue[1];
} else {
if (hue[last] >= 7.5) {
hsb[0] = 10;
} else {
hsb[0] = hue[last];
}
}
}
//map brightness from 0 to 1
hsb[2] = hsb[2] / 255;
//round saturation and brightness
for (var i = hsb.length - 1; i >= 1; i--) {
if (hsb[i] <= 0.25) {
hsb[i] = 0;
} else if (hsb[i] > 0.25 && hsb[i] < 0.75) {
hsb[i] = 0.5;
} else {
hsb[i] = 1;
}
}
//after rounding, if the values are hue 0, saturation 0 and brightness 1
//look at color exceptions which includes several tones from white to gray
if (hsb[0] === 0 && hsb[1] === 0 && hsb[2] === 1) {
//round original hsb values
for (var _i = 2; _i >= 0; _i--) {
originalHSB[_i] = Math.round(originalHSB[_i] * 10000) / 10000;
}
//compare with the values in the colorExceptions array
for (var e = 0; e < colorExceptions.length; e++) {
if (
colorExceptions[e].h === originalHSB[0] &&
colorExceptions[e].s === originalHSB[1] &&
colorExceptions[e].b === originalHSB[2]
) {
colortext = colorExceptions[e].name;
break;
} else {
//if there is no match return white
colortext = 'white';
}
}
} else {
//otherwise, compare with values in colorLookUp
for (var _i2 = 0; _i2 < colorLookUp.length; _i2++) {
if (
colorLookUp[_i2].h === hsb[0] &&
colorLookUp[_i2].s === hsb[1] &&
colorLookUp[_i2].b === hsb[2]
) {
colortext = colorLookUp[_i2].name;
break;
}
}
}
return colortext;
}
//gets rgba and returs a color name
_main.default.prototype._rgbColorName = function(arg) {
//conversts rgba to hsb
var hsb = _color_conversion.default._rgbaToHSBA(arg);
//stores hsb in global variable
originalHSB = hsb;
//calculate color name
return _calculateColor([hsb[0], hsb[1], hsb[2]]);
};
var _default = _main.default;
exports.default = _default;
},
{ '../color/color_conversion': 44, '../core/main': 59 }
],
39: [
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 Environment
* @submodule Environment
* @for p5
* @requires core
*/ var descContainer = '_Description'; //Fallback container
var fallbackDescId = '_fallbackDesc'; //Fallback description
var fallbackTableId = '_fallbackTable'; //Fallback Table
var fallbackTableElId = '_fte_'; //Fallback Table Element
var labelContainer = '_Label'; //Label container
var labelDescId = '_labelDesc'; //Label description
var labelTableId = '_labelTable'; //Label Table
var labelTableElId = '_lte_'; //Label Table Element
/**
* Creates a screen reader accessible description for the canvas.
* The first parameter should be a string with a description of the canvas.
* The second parameter is optional. If specified, it determines how the
* description is displayed.
*
* <code class="language-javascript">describe(text, LABEL)</code> displays
* the description to all users as a <a
* href="https://en.wikipedia.org/wiki/Museum_label" target="_blank">
* tombstone or exhibit label/caption</a> in a
* <code class="language-javascript"><div class="p5Label"></div></code>
* adjacent to the canvas. You can style it as you wish in your CSS.
*
* <code class="language-javascript">describe(text, FALLBACK)</code> makes the
* description accessible to screen-reader users only, in
* <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility" target="_blank">
* a sub DOM inside the canvas element</a>. If a second parameter is not
* specified, by default, the description will only be available to
* screen-reader users.
*
* @method describe
* @param {String} text description of the canvas
* @param {Constant} [display] either LABEL or FALLBACK (Optional)
*
* @example
* <div>
* <code>
* describe('pink square with red heart in the bottom right corner', LABEL);
* background('pink');
* fill('red');
* noStroke();
* ellipse(67, 67, 20, 20);
* ellipse(83, 67, 20, 20);
* triangle(91, 73, 75, 95, 59, 73);
* </code>
* </div>
*
* <div>
* <code>
* 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');
* }
* </code>
* </div>
*
*/ _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.
*
* <code class="language-javascript">describeElement(name, text, LABEL)</code>
* displays the element description to all users as a
* <a href="https://en.wikipedia.org/wiki/Museum_label" target="_blank">
* tombstone or exhibit label/caption</a> in a
* <code class="language-javascript"><div class="p5Label"></div></code>
* adjacent to the canvas. You can style it as you wish in your CSS.
*
* <code class="language-javascript">describeElement(name, text, FALLBACK)</code>
* makes the element description accessible to screen-reader users
* only, in <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility" target="_blank">
* a sub DOM inside the canvas element</a>. 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 (Optional)
*
* @example
* <div>
* <code>
* describe('Heart and yellow circle over pink background', LABEL);
* noStroke();
* background('pink');
* describeElement('Circle', 'Yellow circle in the top left corner', LABEL);
* fill('yellow');
* ellipse(25, 25, 40, 40);
* describeElement('Heart', 'red heart in the bottom right corner', LABEL);
* 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);
* </code>
* </div>
*/
_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 = '<th scope="row">'
.concat(elementName, '</th><td>')
.concat(text, '</td>');
//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 = '<div id="'
.concat(cnvId)
.concat(
descContainer,
'" role="region" aria-label="Canvas Description"><p id="'
)
.concat(cnvId)
.concat(fallbackDescId, '"></p></div>');
if (!this.dummyDOM.querySelector('#'.concat(cnvId, 'accessibleOutput'))) {
//create description container + <p> for fallback description
this.dummyDOM.querySelector('#'.concat(cnvId)).innerHTML = html;
} else {
//create description container + <p> 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 <p> before the table
this.dummyDOM
.querySelector('#' + cnvId + fallbackTableId)
.insertAdjacentHTML(
'beforebegin',
'<p id="'.concat(cnvId + fallbackDescId, '"></p>')
);
}
//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 = '<div id="'
.concat(cnvId)
.concat(labelContainer, '" class="p5Label"><p id="')
.concat(cnvId)
.concat(labelDescId, '"></p></div>');
//if there are no accessible outputs (see textOutput() and gridOutput())
if (
!this.dummyDOM.querySelector('#'.concat(cnvId, 'accessibleOutputLabel'))
) {
//create label container + <p> for label description
this.dummyDOM
.querySelector('#' + cnvId)
.insertAdjacentHTML('afterend', _html);
} else {
//create label container + <p> 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 <p> before the table
this.dummyDOM
.querySelector('#'.concat(cnvId + labelTableId))
.insertAdjacentHTML(
'beforebegin',
'<p id="'.concat(cnvId).concat(labelDescId, '"></p>')
);
}
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 = '<div id="'
.concat(cnvId)
.concat(
descContainer,
'" role="region" aria-label="Canvas Description"><table id="'
)
.concat(cnvId)
.concat(
fallbackTableId,
'"><caption>Canvas elements and their descriptions</caption></table></div>'
);
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',
'<table id="'
.concat(cnvId)
.concat(
fallbackTableId,
'"><caption>Canvas elements and their descriptions</caption></table>'
)
);
}
//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 = '<div id="'
.concat(cnvId)
.concat(labelContainer, '" class="p5Label"><table id="')
.concat(cnvId)
.concat(labelTableId, '"></table></div>');
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',
'<table id="'.concat(cnvId + labelTableId, '"></table>')
);
}
//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': 59 }
],
40: [
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 };
} /** //the functions in this file support updating the grid output
* @module Environment
* @submodule Environment
* @for p5
* @requires core
*/
//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 = '<a href="#'
.concat(idT, 'shape')
.concat(shapeNumber, '">')
.concat(ingredients[x][y].color, ' ')
.concat(x, '</a>');
} else {
fill = '<a href="#'
.concat(idT, 'shape')
.concat(shapeNumber, '">')
.concat(ingredients[x][y].color, ' ')
.concat(x, ' midpoint</a>');
}
//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 = '<tr>';
for (var c in cells[_r]) {
row = row + '<td>';
if (cells[_r][c] !== undefined) {
row = row + cells[_r][c];
}
row = row + '</td>';
}
table = table + row + '</tr>';
}
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 = '<li id="'
.concat(idT, 'shape')
.concat(totalShapes, '">')
.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 + '</li>';
}
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': 59 }
],
41: [
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 Environment
* @submodule Environment
* @for p5
* @requires core
*/ /**
* <code class="language-javascript">textOutput()</code> 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").
*
* <code class="language-javascript">textOutput()</code> and <code class="language-javascript">texOutput(FALLBACK)</code>
* make the output available in <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility" target="_blank">
* a sub DOM inside the canvas element</a> which is accessible to screen readers.
* <code class="language-javascript">textOutput(LABEL)</code> 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 (Optional)
*
* @example
* <div>
* <code>
* textOutput();
* background(148, 196, 0);
* fill(255, 0, 0);
* ellipse(20, 20, 20, 20);
* fill(0, 0, 255);
* rect(50, 50, 50, 50);
* </code>
* </div>
*
*
* <div>
* <code>
* let x = 0;
* function draw() {
* textOutput();
* background(148, 196, 0);
* fill(255, 0, 0);
* ellipse(x, 20, 20, 20);
* fill(0, 0, 255);
* rect(50, 50, 50, 50);
* ellipse(20, 20, 20, 20);
* x += 0.1;
* }
* </code>
* </div>
*
*/ _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');
}
}
};
/**
* <code class="language-javascript">gridOutput()</code> 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.
*
* <code class="language-javascript">gridOutput()</code> and <code class="language-javascript">gridOutput(FALLBACK)</code>
* make the output available in <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility" target="_blank">
* a sub DOM inside the canvas element</a> which is accessible to screen readers.
* <code class="language-javascript">gridOutput(LABEL)</code> 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 (Optional)
*
* @example
* <div>
* <code>
* gridOutput();
* background(148, 196, 0);
* fill(255, 0, 0);
* ellipse(20, 20, 20, 20);
* fill(0, 0, 255);
* rect(50, 50, 50, 50);
* </code>
* </div>
*
*
* <div>
* <code>
* let x = 0;
* function draw() {
* gridOutput();
* background(148, 196, 0);
* fill(255, 0, 0);
* ellipse(x, 20, 20, 20);
* fill(0, 0, 255);
* rect(50, 50, 50, 50);
* ellipse(20, 20, 20, 20);
* x += 0.1;
* }
* </code>
* </div>
*
*/
_main.default.prototype.gridOutput = function(display) {
_main.default._validateParameters('gridOutput', arguments);
//if gridOutput is already true
if (this._accessibleOutputs.grid) {
return;
} else {
//make gridOutput true
this._accessibleOutputs.grid = true;
//create output for fallback
this._createOutput('gridOutput', 'Fallback');
if (display === this.LABEL) {
//make gridOutput label true
this._accessibleOutputs.gridLabel = true;
//create output for label
this._createOutput('gridOutput', 'Label');
}
}
};
//helper function returns true when accessible outputs are true
_main.default.prototype._addAccsOutput = function() {
//if there are no accessible outputs create object with all false
if (!this._accessibleOutputs) {
this._accessibleOutputs = {
text: false,
grid: false,
textLabel: false,
gridLabel: false
};
}
return this._accessibleOutputs.grid || this._accessibleOutputs.text;
};
//helper function that creates html structure for accessible outputs
_main.default.prototype._createOutput = function(type, display) {
var cnvId = this.canvas.id;
//if there are no ingredients create object. this object stores data for the outputs
if (!this.ingredients) {
this.ingredients = {
shapes: {},
colors: { background: 'white', fill: 'white', stroke: 'black' },
pShapes: ''
};
}
//if there is no dummyDOM create it
if (!this.dummyDOM) {
this.dummyDOM = document.getElementById(cnvId).parentNode;
}
var cIdT, container, inner;
var query = '';
if (display === 'Fallback') {
cIdT = cnvId + type;
container = cnvId + 'accessibleOutput';
if (!this.dummyDOM.querySelector('#'.concat(container))) {
//if there is no canvas description (see describe() and describeElement())
if (!this.dummyDOM.querySelector('#'.concat(cnvId, '_Description'))) {
//create html structure inside of canvas
this.dummyDOM.querySelector(
'#'.concat(cnvId)
).innerHTML = '<div id="'.concat(
container,
'" role="region" aria-label="Canvas Outputs"></div>'
);
} else {
//create html structure after canvas description container
this.dummyDOM
.querySelector('#'.concat(cnvId, '_Description'))
.insertAdjacentHTML(
'afterend',
'<div id="'.concat(
container,
'" role="region" aria-label="Canvas Outputs"></div>'
)
);
}
}
} else if (display === 'Label') {
query = display;
cIdT = cnvId + type + display;
container = cnvId + 'accessibleOutput' + display;
if (!this.dummyDOM.querySelector('#'.concat(container))) {
//if there is no canvas description label (see describe() and describeElement())
if (!this.dummyDOM.querySelector('#'.concat(cnvId, '_Label'))) {
//create html structure adjacent to canvas
this.dummyDOM
.querySelector('#'.concat(cnvId))
.insertAdjacentHTML(
'afterend',
'<div id="'.concat(container, '"></div>')
);
} else {
//create html structure after canvas label
this.dummyDOM
.querySelector('#'.concat(cnvId, '_Label'))
.insertAdjacentHTML(
'afterend',
'<div id="'.concat(container, '"></div>')
);
}
}
}
//create an object to store the latest output. this object is used in _updateTextOutput() and _updateGridOutput()
this._accessibleOutputs[cIdT] = {};
if (type === 'textOutput') {
query = '#'.concat(cnvId, 'gridOutput').concat(query); //query is used to check if gridOutput already exists
inner = '<div id="'
.concat(cIdT, '">Text Output<div id="')
.concat(cIdT, 'Summary" aria-label="text output summary"><p id="')
.concat(cIdT, '_summary"></p><ul id="')
.concat(cIdT, '_list"></ul></div><table id="')
.concat(
cIdT,
'_shapeDetails" summary="text output shape details"></table></div>'
);
//if gridOutput already exists
if (this.dummyDOM.querySelector(query)) {
//create textOutput before gridOutput
this.dummyDOM.querySelector(query).insertAdjacentHTML('beforebegin', inner);
} else {
//create output inside of container
this.dummyDOM.querySelector('#'.concat(container)).innerHTML = inner;
}
//store output html elements
this._accessibleOutputs[cIdT].list = this.dummyDOM.querySelector(
'#'.concat(cIdT, '_list')
);
} else if (type === 'gridOutput') {
query = '#'.concat(cnvId, 'textOutput').concat(query); //query is used to check if textOutput already exists
inner = '<div id="'
.concat(cIdT, '">Grid Output<p id="')
.concat(cIdT, '_summary" aria-label="grid output summary"><table id="')
.concat(cIdT, '_map" summary="grid output content"></table><ul id="')
.concat(
cIdT,
'_shapeDetails" aria-label="grid output shape details"></ul></div>'
);
//if textOutput already exists
if (this.dummyDOM.querySelector(query)) {
//create gridOutput after textOutput
this.dummyDOM.querySelector(query).insertAdjacentHTML('afterend', inner);
} else {
//create output inside of container
this.dummyDOM.querySelector('#'.concat(container)).innerHTML = inner;
}
//store output html elements
this._accessibleOutputs[cIdT].map = this.dummyDOM.querySelector(
'#'.concat(cIdT, '_map')
);
}
this._accessibleOutputs[cIdT].shapeDetails = this.dummyDOM.querySelector(
'#'.concat(cIdT, '_shapeDetails')
);
this._accessibleOutputs[cIdT].summary = this.dummyDOM.querySelector(
'#'.concat(cIdT, '_summary')
);
};
//this function is called at the end of setup and draw if using
//accessibleOutputs and calls update functions of outputs
_main.default.prototype._updateAccsOutput = function() {
var cnvId = this.canvas.id;
//if the shapes are not the same as before
if (JSON.stringify(this.ingredients.shapes) !== this.ingredients.pShapes) {
//save current shapes as string in pShapes
this.ingredients.pShapes = JSON.stringify(this.ingredients.shapes);
if (this._accessibleOutputs.text) {
this._updateTextOutput(cnvId + 'textOutput');
}
if (this._accessibleOutputs.grid) {
this._updateGridOutput(cnvId + 'gridOutput');
}
if (this._accessibleOutputs.textLabel) {
this._updateTextOutput(cnvId + 'textOutputLabel');
}
if (this._accessibleOutputs.gridLabel) {
this._updateGridOutput(cnvId + 'gridOutputLabel');
}
}
};
//helper function that resets all ingredients when background is called
//and saves background color name
_main.default.prototype._accsBackground = function(args) {
//save current shapes as string in pShapes
this.ingredients.pShapes = JSON.stringify(this.ingredients.shapes);
//empty shapes JSON
this.ingredients.shapes = {};
//update background different
if (this.ingredients.colors.backgroundRGBA !== args) {
this.ingredients.colors.backgroundRGBA = args;
this.ingredients.colors.background = this._rgbColorName(args);
}
};
//helper function that gets fill and stroke of shapes
_main.default.prototype._accsCanvasColors = function(f, args) {
if (f === 'fill') {
//update fill different
if (this.ingredients.colors.fillRGBA !== args) {
this.ingredients.colors.fillRGBA = args;
this.ingredients.colors.fill = this._rgbColorName(args);
}
} else if (f === 'stroke') {
//update stroke if different
if (this.ingredients.colors.strokeRGBA !== args) {
this.ingredients.colors.strokeRGBA = args;
this.ingredients.colors.stroke = this._rgbColorName(args);
}
}
};
//builds ingredients.shapes used for building outputs
_main.default.prototype._accsOutput = function(f, args) {
if (f === 'ellipse' && args[2] === args[3]) {
f = 'circle';
} else if (f === 'rectangle' && args[2] === args[3]) {
f = 'square';
}
var include = {};
var add = true;
var middle = _getMiddle(f, args);
if (f === 'line') {
//make color stroke
include.color = this.ingredients.colors.stroke;
//get lenght
include.length = Math.round(this.dist(args[0], args[1], args[2], args[3]));
//get position of end points
var p1 = _getPos([args[0], [1]], this.width, this.height);
var p2 = _getPos([args[2], [3]], this.width, this.height);
include.loc = _canvasLocator(middle, this.width, this.height);
if (p1 === p2) {
include.pos = 'at '.concat(p1);
} else {
include.pos = 'from '.concat(p1, ' to ').concat(p2);
}
} else {
if (f === 'point') {
//make color stroke
include.color = this.ingredients.colors.stroke;
} else {
//make color fill
include.color = this.ingredients.colors.fill;
//get area of shape
include.area = _getArea(f, args, this.width, this.height);
}
//get middle of shapes
//calculate position using middle of shape
include.pos = _getPos(middle, this.width, this.height);
//calculate location using middle of shape
include.loc = _canvasLocator(middle, this.width, this.height);
}
//if it is the first time this shape is created
if (!this.ingredients.shapes[f]) {
this.ingredients.shapes[f] = [include];
//if other shapes of this type have been created
} else if (this.ingredients.shapes[f] !== [include]) {
//for every shape of this type
for (var y in this.ingredients.shapes[f]) {
//compare it with current shape and if it already exists make add false
if (
JSON.stringify(this.ingredients.shapes[f][y]) === JSON.stringify(include)
) {
add = false;
}
}
//add shape by pushing it to the end
if (add === true) {
this.ingredients.shapes[f].push(include);
}
}
};
//gets middle point / centroid of shape
function _getMiddle(f, args) {
var x, y;
if (
f === 'rectangle' ||
f === 'ellipse' ||
f === 'arc' ||
f === 'circle' ||
f === 'square'
) {
x = Math.round(args[0] + args[2] / 2);
y = Math.round(args[1] + args[3] / 2);
} else if (f === 'triangle') {
x = (args[0] + args[2] + args[4]) / 3;
y = (args[1] + args[3] + args[5]) / 3;
} else if (f === 'quadrilateral') {
x = (args[0] + args[2] + args[4] + args[6]) / 4;
y = (args[1] + args[3] + args[5] + args[7]) / 4;
} else if (f === 'line') {
x = (args[0] + args[2]) / 2;
y = (args[1] + args[3]) / 2;
} else {
x = args[0];
y = args[1];
}
return [x, y];
}
//gets position of shape in the canvas
function _getPos(args, canvasWidth, canvasHeight) {
if (args[0] < 0.4 * canvasWidth) {
if (args[1] < 0.4 * canvasHeight) {
return 'top left';
} else if (args[1] > 0.6 * canvasHeight) {
return 'bottom left';
} else {
return 'mid left';
}
} else if (args[0] > 0.6 * canvasWidth) {
if (args[1] < 0.4 * canvasHeight) {
return 'top right';
} else if (args[1] > 0.6 * canvasHeight) {
return 'bottom right';
} else {
return 'mid right';
}
} else {
if (args[1] < 0.4 * canvasHeight) {
return 'top middle';
} else if (args[1] > 0.6 * canvasHeight) {
return 'bottom middle';
} else {
return 'middle';
}
}
}
//locates shape in a 10*10 grid
function _canvasLocator(args, canvasWidth, canvasHeight) {
var noRows = 10;
var noCols = 10;
var locX = Math.floor(args[0] / canvasWidth * noRows);
var locY = Math.floor(args[1] / canvasHeight * noCols);
if (locX === noRows) {
locX = locX - 1;
}
if (locY === noCols) {
locY = locY - 1;
}
return {
locX: locX,
locY: locY
};
}
//calculates area of shape
function _getArea(objectType, shapeArgs, canvasWidth, canvasHeight) {
var objectArea = 0;
if (objectType === 'arc') {
// area of full ellipse = PI * horizontal radius * vertical radius.
// therefore, area of arc = difference bet. arc's start and end radians * horizontal radius * vertical radius.
// the below expression is adjusted for negative values and differences in arc's start and end radians over PI*2
var arcSizeInRadians =
((shapeArgs[5] - shapeArgs[4]) % (Math.PI * 2) + Math.PI * 2) %
(Math.PI * 2);
objectArea = arcSizeInRadians * shapeArgs[2] * shapeArgs[3] / 8;
if (shapeArgs[6] === 'open' || shapeArgs[6] === 'chord') {
// when the arc's mode is OPEN or CHORD, we need to account for the area of the triangle that is formed to close the arc
// (Ax( By − Cy) + Bx(Cy − Ay) + Cx(Ay − By ) )/2
var Ax = shapeArgs[0];
var Ay = shapeArgs[1];
var Bx =
shapeArgs[0] + shapeArgs[2] / 2 * Math.cos(shapeArgs[4]).toFixed(2);
var By =
shapeArgs[1] + shapeArgs[3] / 2 * Math.sin(shapeArgs[4]).toFixed(2);
var Cx =
shapeArgs[0] + shapeArgs[2] / 2 * Math.cos(shapeArgs[5]).toFixed(2);
var Cy =
shapeArgs[1] + shapeArgs[3] / 2 * Math.sin(shapeArgs[5]).toFixed(2);
var areaOfExtraTriangle =
Math.abs(Ax * (By - Cy) + Bx * (Cy - Ay) + Cx * (Ay - By)) / 2;
if (arcSizeInRadians > Math.PI) {
objectArea = objectArea + areaOfExtraTriangle;
} else {
objectArea = objectArea - areaOfExtraTriangle;
}
}
} else if (objectType === 'ellipse' || objectType === 'circle') {
objectArea = 3.14 * shapeArgs[2] / 2 * shapeArgs[3] / 2;
} else if (objectType === 'line') {
objectArea = 0;
} else if (objectType === 'point') {
objectArea = 0;
} else if (objectType === 'quadrilateral') {
// ((x4+x1)*(y4-y1)+(x1+x2)*(y1-y2)+(x2+x3)*(y2-y3)+(x3+x4)*(y3-y4))/2
objectArea =
Math.abs(
(shapeArgs[6] + shapeArgs[0]) * (shapeArgs[7] - shapeArgs[1]) +
(shapeArgs[0] + shapeArgs[2]) * (shapeArgs[1] - shapeArgs[3]) +
(shapeArgs[2] + shapeArgs[4]) * (shapeArgs[3] - shapeArgs[5]) +
(shapeArgs[4] + shapeArgs[6]) * (shapeArgs[5] - shapeArgs[7])
) / 2;
} else if (objectType === 'rectangle' || objectType === 'square') {
objectArea = shapeArgs[2] * shapeArgs[3];
} else if (objectType === 'triangle') {
objectArea =
Math.abs(
shapeArgs[0] * (shapeArgs[3] - shapeArgs[5]) +
shapeArgs[2] * (shapeArgs[5] - shapeArgs[1]) +
shapeArgs[4] * (shapeArgs[1] - shapeArgs[3])
) / 2;
// (Ax( By − Cy) + Bx(Cy − Ay) + Cx(Ay − By ))/2
}
return Math.round(objectArea * 100 / (canvasWidth * canvasHeight));
}
var _default = _main.default;
exports.default = _default;
},
{ '../core/main': 59 }
],
42: [
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 };
} /** //the functions in this file support updating the text output
* @module Environment
* @submodule Environment
* @for p5
* @requires core
*/
//updates textOutput
_main.default.prototype._updateTextOutput = function(idT) {
//if html structure is not there yet
if (!this.dummyDOM.querySelector('#'.concat(idT, '_summary'))) {
return;
}
var current = this._accessibleOutputs[idT];
//create shape list
var innerList = _shapeList(idT, this.ingredients.shapes);
//create output summary
var innerSummary = _textSummary(
innerList.numShapes,
this.ingredients.colors.background,
this.width,
this.height
);
//create shape details
var innerShapeDetails = _shapeDetails(idT, this.ingredients.shapes);
//if it is different from current summary
if (innerSummary !== current.summary.innerHTML) {
//update
current.summary.innerHTML = innerSummary;
}
//if it is different from current shape list
if (innerList.listShapes !== current.list.innerHTML) {
//update
current.list.innerHTML = innerList.listShapes;
}
//if it is different from current shape details
if (innerShapeDetails !== current.shapeDetails.innerHTML) {
//update
current.shapeDetails.innerHTML = innerShapeDetails;
}
this._accessibleOutputs[idT] = current;
};
//Builds textOutput summary
function _textSummary(numShapes, background, width, height) {
var text = 'Your output is a, '
.concat(width, ' by ')
.concat(height, ' pixels, ')
.concat(background, ' canvas containing the following');
if (numShapes === 1) {
text = ''.concat(text, ' shape:');
} else {
text = ''.concat(text, ' ').concat(numShapes, ' shapes:');
}
return text;
}
//Builds textOutput table with shape details
function _shapeDetails(idT, ingredients) {
var shapeDetails = '';
var shapeNumber = 0;
//goes trhough every shape type in ingredients
for (var x in ingredients) {
//and for every shape
for (var y in ingredients[x]) {
//it creates a table row
var row = '<tr id="'
.concat(idT, 'shape')
.concat(shapeNumber, '"><th>')
.concat(ingredients[x][y].color, ' ')
.concat(x, '</th>');
if (x === 'line') {
row =
row +
'<td>location = '
.concat(ingredients[x][y].pos, '</td><td>length = ')
.concat(ingredients[x][y].length, ' pixels</td></tr>');
} else {
row = row + '<td>location = '.concat(ingredients[x][y].pos, '</td>');
if (x !== 'point') {
row = row + '<td> area = '.concat(ingredients[x][y].area, '%</td>');
}
row = row + '</tr>';
}
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 = '<li><a href="#'
.concat(idT, 'shape')
.concat(shapeNumber, '">')
.concat(ingredients[x][y].color, ' ')
.concat(x, '</a>');
if (x === 'line') {
_line =
_line +
', '
.concat(ingredients[x][y].pos, ', ')
.concat(ingredients[x][y].length, ' pixels long.</li>');
} 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 + '.</li>';
}
shapeList = shapeList + _line;
shapeNumber++;
}
}
return { numShapes: shapeNumber, listShapes: shapeList };
}
var _default = _main.default;
exports.default = _default;
},
{ '../core/main': 59 }
],
43: [
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/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': 38,
'./accessibility/describe': 39,
'./accessibility/gridOutput': 40,
'./accessibility/outputs': 41,
'./accessibility/textOutput': 42,
'./color/color_conversion': 44,
'./color/creating_reading': 45,
'./color/p5.Color': 46,
'./color/setting': 47,
'./core/constants': 48,
'./core/environment': 49,
'./core/friendly_errors/fes_core': 51,
'./core/friendly_errors/file_errors': 52,
'./core/friendly_errors/stacktrace': 53,
'./core/friendly_errors/validate_params': 54,
'./core/helpers': 55,
'./core/init': 56,
'./core/legacy': 58,
'./core/main': 59,
'./core/p5.Element': 60,
'./core/p5.Graphics': 61,
'./core/p5.Renderer': 62,
'./core/p5.Renderer2D': 63,
'./core/preload': 64,
'./core/rendering': 65,
'./core/shape/2d_primitives': 66,
'./core/shape/attributes': 67,
'./core/shape/curves': 68,
'./core/shape/vertex': 69,
'./core/shim': 70,
'./core/structure': 71,
'./core/transform': 72,
'./data/local_storage.js': 73,
'./data/p5.TypedDict': 74,
'./dom/dom': 75,
'./events/acceleration': 76,
'./events/keyboard': 77,
'./events/mouse': 78,
'./events/touch': 79,
'./image/filters': 80,
'./image/image': 81,
'./image/loading_displaying': 82,
'./image/p5.Image': 83,
'./image/pixels': 84,
'./io/files': 85,
'./io/p5.Table': 86,
'./io/p5.TableRow': 87,
'./io/p5.XML': 88,
'./math/calculation': 89,
'./math/math': 90,
'./math/noise': 91,
'./math/p5.Vector': 92,
'./math/random': 93,
'./math/trigonometry': 94,
'./typography/attributes': 95,
'./typography/loading_displaying': 96,
'./typography/p5.Font': 97,
'./utilities/array_functions': 98,
'./utilities/conversion': 99,
'./utilities/string_functions': 100,
'./utilities/time_date': 101,
'./webgl/3d_primitives': 102,
'./webgl/interaction': 103,
'./webgl/light': 104,
'./webgl/loading': 105,
'./webgl/material': 106,
'./webgl/p5.Camera': 107,
'./webgl/p5.Geometry': 108,
'./webgl/p5.Matrix': 109,
'./webgl/p5.RenderBuffer': 110,
'./webgl/p5.RendererGL': 113,
'./webgl/p5.RendererGL.Immediate': 111,
'./webgl/p5.RendererGL.Retained': 112,
'./webgl/p5.Shader': 114,
'./webgl/p5.Texture': 115,
'./webgl/text': 116
}
],
44: [
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 <http://www.easyrgb.com/en/math.php>.
*
* 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': 59 }
],
45: [
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');
_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 <a href="#/p5.Color">p5.Color</a> object, color components,
* or CSS color
* @return {Number} the alpha value
*
* @example
* <div>
* <code>
* 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);
* </code>
* </div>
*
* @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 <a href="#/p5.Color">p5.Color</a> object, color components,
* or CSS color
* @return {Number} the blue value
* @example
* <div>
* <code>
* 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
* </code>
* </div>
*
* @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 <a href="#/p5.Color">p5.Color</a> object, color components,
* or CSS color
* @return {Number} the brightness value
*
* @example
* <div>
* <code>
* 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);
* </code>
* </div>
*
* <div>
* <code>
* 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);
* </code>
* </div>
*
* @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 <a href="#/p5/colorMode">colorMode()</a>. 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 <a href="#/p5/color">color()</a>, 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
* <div>
* <code>
* let c = color(255, 204, 0);
* fill(c);
* noStroke();
* rect(30, 20, 55, 55);
* </code>
* </div>
*
* <div>
* <code>
* 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);
* </code>
* </div>
*
* <div>
* <code>
* // You can use named SVG & CSS colors
* let c = color('magenta');
* fill(c);
* noStroke();
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div>
* <code>
* // 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);
* </code>
* </div>
*
* <div>
* <code>
* // 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
* </code>
* </div>
*
* <div>
* <code>
* // 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
* </code>
* </div>
*
* <div>
* <code>
* // 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
* </code>
* </div>
*
* <div>
* <code>
* 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);
* </code>
* </div>
*
* @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 <a href="#/p5.Color">p5.Color</a> object, color components,
* or CSS color
* @return {Number} the green value
* @example
* <div>
* <code>
* 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
* </code>
* </div>
*
* @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 <a href="#/p5.Color">p5.Color</a> object, color components,
* or CSS color
* @return {Number} the hue
* @example
* <div>
* <code>
* 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);
* </code>
* </div>
*
* @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 <a href="#/p5/lerp">lerp()</a>,
* 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
* <div>
* <code>
* 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);
* </code>
* </div>
*
* @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 <a href="#/p5.Color">p5.Color</a> object, color components,
* or CSS color
* @return {Number} the lightness
*
* @example
* <div>
* <code>
* 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);
* </code>
* </div>
*
* @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 <a href="#/p5.Color">p5.Color</a> object, color components,
* or CSS color
* @return {Number} the red value
* @example
* <div>
* <code>
* 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
* </code>
* </div>
*
* <div class="norender">
* <code>
* 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
* </code>
* </div>
*
* @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 <a href="#/p5.Color">p5.Color</a> object, color components,
* or CSS color
* @return {Number} the saturation value
* @example
* <div>
* <code>
* 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);
* </code>
* </div>
*
* @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': 48,
'../core/friendly_errors/fes_core': 51,
'../core/friendly_errors/file_errors': 52,
'../core/friendly_errors/validate_params': 54,
'../core/main': 59,
'./p5.Color': 46
}
],
46: [
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 <a href="#/p5/saturation">saturation()</a> 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
* <div>
* <code>
* createCanvas(200, 100);
* let myColor;
* stroke(255);
* myColor = color(100, 100, 250);
* fill(myColor);
* rotate(HALF_PI);
* text(myColor.toString(), 0, -5);
* text(myColor.toString('#rrggbb'), 0, -30);
* text(myColor.toString('rgba%'), 0, -55);
* </code>
* </div>
*
* <div>
* <code>
* let myColor = color(100, 130, 250);
* text(myColor.toString('#rrggbb'), 25, 25);
* </code>
* </div>
*
* @alt
* A canvas with 3 text representation of their color.
*/
_main.default.Color.prototype.toString = function(format) {
var a = this.levels;
var f = this._array;
var alpha = f[3]; // String representation uses normalized alpha
switch (format) {
case '#rrggbb':
return '#'.concat(
a[0] < 16 ? '0'.concat(a[0].toString(16)) : a[0].toString(16),
a[1] < 16 ? '0'.concat(a[1].toString(16)) : a[1].toString(16),
a[2] < 16 ? '0'.concat(a[2].toString(16)) : a[2].toString(16)
);
case '#rrggbbaa':
return '#'.concat(
a[0] < 16 ? '0'.concat(a[0].toString(16)) : a[0].toString(16),
a[1] < 16 ? '0'.concat(a[1].toString(16)) : a[1].toString(16),
a[2] < 16 ? '0'.concat(a[2].toString(16)) : a[2].toString(16),
a[3] < 16 ? '0'.concat(a[2].toString(16)) : a[3].toString(16)
);
case '#rgb':
return '#'.concat(
Math.round(f[0] * 15).toString(16),
Math.round(f[1] * 15).toString(16),
Math.round(f[2] * 15).toString(16)
);
case '#rgba':
return '#'.concat(
Math.round(f[0] * 15).toString(16),
Math.round(f[1] * 15).toString(16),
Math.round(f[2] * 15).toString(16),
Math.round(f[3] * 15).toString(16)
);
case 'rgb':
return 'rgb('.concat(a[0], ', ', a[1], ', ', a[2], ')');
case 'rgb%':
return 'rgb('.concat(
(100 * f[0]).toPrecision(3),
'%, ',
(100 * f[1]).toPrecision(3),
'%, ',
(100 * f[2]).toPrecision(3),
'%)'
);
case 'rgba%':
return 'rgba('.concat(
(100 * f[0]).toPrecision(3),
'%, ',
(100 * f[1]).toPrecision(3),
'%, ',
(100 * f[2]).toPrecision(3),
'%, ',
(100 * f[3]).toPrecision(3),
'%)'
);
case 'hsb':
case 'hsv':
if (!this.hsba)
this.hsba = _color_conversion.default._rgbaToHSBA(this._array);
return 'hsb('.concat(
this.hsba[0] * this.maxes[constants.HSB][0],
', ',
this.hsba[1] * this.maxes[constants.HSB][1],
', ',
this.hsba[2] * this.maxes[constants.HSB][2],
')'
);
case 'hsb%':
case 'hsv%':
if (!this.hsba)
this.hsba = _color_conversion.default._rgbaToHSBA(this._array);
return 'hsb('.concat(
(100 * this.hsba[0]).toPrecision(3),
'%, ',
(100 * this.hsba[1]).toPrecision(3),
'%, ',
(100 * this.hsba[2]).toPrecision(3),
'%)'
);
case 'hsba':
case 'hsva':
if (!this.hsba)
this.hsba = _color_conversion.default._rgbaToHSBA(this._array);
return 'hsba('.concat(
this.hsba[0] * this.maxes[constants.HSB][0],
', ',
this.hsba[1] * this.maxes[constants.HSB][1],
', ',
this.hsba[2] * this.maxes[constants.HSB][2],
', ',
alpha,
')'
);
case 'hsba%':
case 'hsva%':
if (!this.hsba)
this.hsba = _color_conversion.default._rgbaToHSBA(this._array);
return 'hsba('.concat(
(100 * this.hsba[0]).toPrecision(3),
'%, ',
(100 * this.hsba[1]).toPrecision(3),
'%, ',
(100 * this.hsba[2]).toPrecision(3),
'%, ',
(100 * alpha).toPrecision(3),
'%)'
);
case 'hsl':
if (!this.hsla)
this.hsla = _color_conversion.default._rgbaToHSLA(this._array);
return 'hsl('.concat(
this.hsla[0] * this.maxes[constants.HSL][0],
', ',
this.hsla[1] * this.maxes[constants.HSL][1],
', ',
this.hsla[2] * this.maxes[constants.HSL][2],
')'
);
case 'hsl%':
if (!this.hsla)
this.hsla = _color_conversion.default._rgbaToHSLA(this._array);
return 'hsl('.concat(
(100 * this.hsla[0]).toPrecision(3),
'%, ',
(100 * this.hsla[1]).toPrecision(3),
'%, ',
(100 * this.hsla[2]).toPrecision(3),
'%)'
);
case 'hsla':
if (!this.hsla)
this.hsla = _color_conversion.default._rgbaToHSLA(this._array);
return 'hsla('.concat(
this.hsla[0] * this.maxes[constants.HSL][0],
', ',
this.hsla[1] * this.maxes[constants.HSL][1],
', ',
this.hsla[2] * this.maxes[constants.HSL][2],
', ',
alpha,
')'
);
case 'hsla%':
if (!this.hsla)
this.hsla = _color_conversion.default._rgbaToHSLA(this._array);
return 'hsl('.concat(
(100 * this.hsla[0]).toPrecision(3),
'%, ',
(100 * this.hsla[1]).toPrecision(3),
'%, ',
(100 * this.hsla[2]).toPrecision(3),
'%, ',
(100 * alpha).toPrecision(3),
'%)'
);
case 'rgba':
default:
return 'rgba('.concat(a[0], ',', a[1], ',', a[2], ',', alpha, ')');
}
};
/**
* The setRed function sets the red component of a color.
* The range depends on your color mode, in the default RGB mode it's between 0 and 255.
* @method setRed
* @param {Number} red the new red value
* @example
* <div>
* <code>
* let backgroundColor;
*
* function setup() {
* backgroundColor = color(100, 50, 150);
* }
*
* function draw() {
* backgroundColor.setRed(128 + 128 * sin(millis() / 1000));
* background(backgroundColor);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* let backgroundColor = color(100, 50, 150);
* function draw() {
* backgroundColor.setGreen(128 + 128 * sin(millis() / 1000));
* background(backgroundColor);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* let backgroundColor = color(100, 50, 150);
* function draw() {
* backgroundColor.setBlue(128 + 128 * sin(millis() / 1000));
* background(backgroundColor);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* function draw() {
* clear();
* background(200);
* squareColor = color(100, 50, 100);
* squareColor.setAlpha(128 + 128 * sin(millis() / 1000));
* fill(squareColor);
* rect(13, 13, width - 26, height - 26);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* // todo
* </code>
* </div>
*
* @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': 48, '../core/main': 59, './color_conversion': 44 }
],
47: [
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 <a href="#/p5/background">background()</a> function sets the color used
* for the background of the p5.js canvas. The default background is transparent.
* This function is typically used within <a href="#/p5/draw">draw()</a> to clear
* the display window at the beginning of each frame, but it can be used inside
* <a href="#/p5/setup">setup()</a> 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 <a href="#/p5/colorMode">colorMode</a>. (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.<br><br>
*
* 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 <a href="#/p5.Color">p5.Color</a> object can also be provided to set the background color.
*
* A <a href="#/p5.Image">p5.Image</a> can also be provided to set the background image.
*
* @method background
* @param {p5.Color} color any value created by the <a href="#/p5/color">color()</a> function
* @chainable
*
* @example
* <div>
* <code>
* // Grayscale integer value
* background(51);
* </code>
* </div>
*
* <div>
* <code>
* // R, G & B integer values
* background(255, 204, 0);
* </code>
* </div>
*
* <div>
* <code>
* // H, S & B integer values
* colorMode(HSB);
* background(255, 204, 100);
* </code>
* </div>
*
* <div>
* <code>
* // Named SVG/CSS color string
* background('red');
* </code>
* </div>
*
* <div>
* <code>
* // three-digit hexadecimal RGB notation
* background('#fae');
* </code>
* </div>
*
* <div>
* <code>
* // six-digit hexadecimal RGB notation
* background('#222222');
* </code>
* </div>
*
* <div>
* <code>
* // integer RGB notation
* background('rgb(0,255,0)');
* </code>
* </div>
*
* <div>
* <code>
* // integer RGBA notation
* background('rgba(0,255,0, 0.25)');
* </code>
* </div>
*
* <div>
* <code>
* // percentage RGB notation
* background('rgb(100%,0%,10%)');
* </code>
* </div>
*
* <div>
* <code>
* // percentage RGBA notation
* background('rgba(100%,0%,100%,0.5)');
* </code>
* </div>
*
* <div>
* <code>
* // p5 Color object
* background(color(0, 0, 255));
* </code>
* </div>
*
* @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 <a href="#/p5/loadImage">loadImage()</a> or <a href="#/p5/createImage">createImage()</a>,
* 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
* <a href="#/p5/createVideo">createVideo()</a> or <a href="#/p5/createDiv">createDiv()</a>.
* Unlike the main graphics context, pixels in additional graphics areas created
* with <a href="#/p5/createGraphics">createGraphics()</a> can be entirely
* or partially transparent. This function clears everything to make all of
* the pixels 100% transparent.
*
* @method clear
* @chainable
* @example
* <div>
* <code>
* // Clear the screen on mouse press.
* function draw() {
* ellipse(mouseX, mouseY, 20, 20);
* }
* function mousePressed() {
* clear();
* background(128);
* }
* </code>
* </div>
*
* @alt
* small white ellipses are continually drawn at mouse's x and y coordinates.
*/
_main.default.prototype.clear = function() {
this._renderer.clear();
return this;
};
/**
* <a href="#/p5/colorMode">colorMode()</a> changes the way p5.js interprets
* color data. By default, the parameters for <a href="#/p5/fill">fill()</a>,
* <a href="#/p5/stroke">stroke()</a>, <a href="#/p5/background">background()</a>,
* and <a href="#/p5/color">color()</a> 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
* <div>
* <code>
* 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);
* }
* }
* </code>
* </div>
*
* <div>
* <code>
* 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);
* }
* }
* </code>
* </div>
*
* <div>
* <code>
* colorMode(RGB, 255);
* let c = color(127, 255, 0);
* colorMode(RGB, 1);
* let myColor = c._getRed();
* text(myColor, 10, 10, 80, 80);
* </code>
* </div>
*
* <div>
* <code>
* noFill();
* colorMode(RGB, 255, 255, 255, 1);
* background(255);
* strokeWeight(4);
* stroke(255, 0, 10, 0.3);
* ellipse(40, 40, 50, 50);
* ellipse(50, 50, 40, 40);
* </code>
* </div>
*
* @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 <a href="#/p5/colorMode">colorMode()</a>. (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 <a href="#/p5.Color">Color</a> 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
* <div>
* <code>
* // Grayscale integer value
* fill(51);
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div>
* <code>
* // R, G & B integer values
* fill(255, 204, 0);
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div>
* <code>
* // H, S & B integer values
* colorMode(HSB);
* fill(255, 204, 100);
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div>
* <code>
* // Named SVG/CSS color string
* fill('red');
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div>
* <code>
* // three-digit hexadecimal RGB notation
* fill('#fae');
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div>
* <code>
* // six-digit hexadecimal RGB notation
* fill('#222222');
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div>
* <code>
* // integer RGB notation
* fill('rgb(0,255,0)');
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div>
* <code>
* // integer RGBA notation
* fill('rgba(0,255,0, 0.25)');
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div>
* <code>
* // percentage RGB notation
* fill('rgb(100%,0%,10%)');
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div>
* <code>
* // percentage RGBA notation
* fill('rgba(100%,0%,100%,0.5)');
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div>
* <code>
* // p5 Color object
* fill(color(0, 0, 255));
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* @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 <a href="#/p5/noStroke">noStroke()</a> and <a href="#/p5/noFill">noFill()</a> are called,
* nothing will be drawn to the screen.
*
* @method noFill
* @chainable
* @example
* <div>
* <code>
* rect(15, 10, 55, 55);
* noFill();
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div modernizr='webgl'>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(0);
* noFill();
* stroke(100, 100, 240);
* rotateX(frameCount * 0.01);
* rotateY(frameCount * 0.01);
* box(45, 45, 45);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/noStroke">noStroke()</a> and <a href="#/p5/noFill">noFill()</a>
* are called, nothing will be drawn to the screen.
*
* @method noStroke
* @chainable
* @example
* <div>
* <code>
* noStroke();
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div modernizr='webgl'>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(0);
* noStroke();
* fill(240, 150, 150);
* rotateX(frameCount * 0.01);
* rotateY(frameCount * 0.01);
* box(45, 45, 45);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/colorMode">colorMode()</a> (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 <a href="#/p5.Color">Color</a> 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
* <div>
* <code>
* // Grayscale integer value
* strokeWeight(4);
* stroke(51);
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div>
* <code>
* // R, G & B integer values
* stroke(255, 204, 0);
* strokeWeight(4);
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div>
* <code>
* // H, S & B integer values
* colorMode(HSB);
* strokeWeight(4);
* stroke(255, 204, 100);
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div>
* <code>
* // Named SVG/CSS color string
* stroke('red');
* strokeWeight(4);
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div>
* <code>
* // three-digit hexadecimal RGB notation
* stroke('#fae');
* strokeWeight(4);
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div>
* <code>
* // six-digit hexadecimal RGB notation
* stroke('#222222');
* strokeWeight(4);
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div>
* <code>
* // integer RGB notation
* stroke('rgb(0,255,0)');
* strokeWeight(4);
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div>
* <code>
* // integer RGBA notation
* stroke('rgba(0,255,0,0.25)');
* strokeWeight(4);
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div>
* <code>
* // percentage RGB notation
* stroke('rgb(100%,0%,10%)');
* strokeWeight(4);
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div>
* <code>
* // percentage RGBA notation
* stroke('rgba(100%,0%,100%,0.5)');
* strokeWeight(4);
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* <div>
* <code>
* // p5 Color object
* stroke(color(0, 0, 255));
* strokeWeight(4);
* rect(20, 20, 60, 60);
* </code>
* </div>
*
* @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 <a href="#/p5/erase">erase()</a> will subtract from
* the canvas.Erased areas will reveal the web page underneath the canvas.Erasing
* can be canceled with <a href="#/p5/noErase">noErase()</a>.
*
* Drawing done with <a href="#/p5/image">image()</a> and <a href="#/p5/background">
* background()</a> in between <a href="#/p5/erase">erase()</a> and
* <a href="#/p5/noErase">noErase()</a> 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
* <div>
* <code>
* background(100, 100, 250);
* fill(250, 100, 100);
* rect(20, 20, 60, 60);
* erase();
* ellipse(25, 30, 30);
* noErase();
* </code>
* </div>
*
* <div>
* <code>
* background(150, 250, 150);
* fill(100, 100, 250);
* rect(20, 20, 60, 60);
* strokeWeight(5);
* erase(150, 255);
* triangle(50, 10, 70, 50, 90, 10);
* noErase();
* </code>
* </div>
*
* <div>
* <code>
* function setup() {
* smooth();
* createCanvas(100, 100, WEBGL);
* // Make a <p> element and put it behind the canvas
* let p = createP('I am a dom element');
* p.center();
* p.style('font-size', '20px');
* p.style('text-align', 'center');
* p.style('z-index', '-9999');
* }
*
* function draw() {
* background(250, 250, 150);
* fill(15, 195, 185);
* noStroke();
* sphere(30);
* erase();
* rotateY(frameCount * 0.02);
* translate(0, 0, 40);
* torus(15, 5);
* noErase();
* }
* </code>
* </div>
*
* @alt
* 60x60 centered pink rect, purple background. Elliptical area in top-left of rect is erased white.
* 60x60 centered purple rect, mint green background. Triangle in top-right is partially erased with fully erased outline.
* 60x60 centered teal sphere, yellow background. Torus rotating around sphere erases to reveal black text underneath.
*/
_main.default.prototype.erase = function() {
var opacityFill =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 255;
var opacityStroke =
arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 255;
this._renderer.erase(opacityFill, opacityStroke);
return this;
};
/**
* Ends erasing that was started with <a href="#/p5/erase">erase()</a>.
* The <a href="#/p5/fill">fill()</a>, <a href="#/p5/stroke">stroke()</a>, and
* <a href="#/p5/blendMode">blendMode()</a> settings will return to what they were
* prior to calling <a href="#/p5/erase">erase()</a>.
*
* @method noErase
* @chainable
* @example
* <div>
* <code>
* background(235, 145, 15);
* noStroke();
* fill(30, 45, 220);
* rect(30, 10, 10, 80);
* erase();
* ellipse(50, 50, 60);
* noErase();
* rect(70, 10, 10, 80);
* </code>
* </div>
*
* @alt
* Orange background, with two tall blue rectangles. A centered ellipse erased the first blue rect but not the second.
*/
_main.default.prototype.noErase = function() {
this._renderer.noErase();
return this;
};
var _default = _main.default;
exports.default = _default;
},
{ '../core/constants': 48, '../core/main': 59, './p5.Color': 46 }
],
48: [
function(_dereq_, module, exports) {
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.FILL = exports.STROKE = exports.CURVE = exports.BEZIER = exports.QUADRATIC = exports.LINEAR = exports._CTX_MIDDLE = exports._DEFAULT_LEADMULT = exports._DEFAULT_TEXT_FILL = exports.BOLDITALIC = exports.BOLD = exports.ITALIC = exports.NORMAL = exports.BLUR = exports.ERODE = exports.DILATE = exports.POSTERIZE = exports.INVERT = exports.OPAQUE = exports.GRAY = exports.THRESHOLD = exports.BURN = exports.DODGE = exports.SOFT_LIGHT = exports.HARD_LIGHT = exports.OVERLAY = exports.REPLACE = exports.SCREEN = exports.MULTIPLY = exports.EXCLUSION = exports.SUBTRACT = exports.DIFFERENCE = exports.LIGHTEST = exports.DARKEST = exports.ADD = exports.REMOVE = exports.BLEND = exports.UP_ARROW = exports.TAB = exports.SHIFT = exports.RIGHT_ARROW = exports.RETURN = exports.OPTION = exports.LEFT_ARROW = exports.ESCAPE = exports.ENTER = exports.DOWN_ARROW = exports.DELETE = exports.CONTROL = exports.BACKSPACE = exports.ALT = exports.AUTO = exports.HSL = exports.HSB = exports.RGB = exports.MITER = exports.BEVEL = exports.ROUND = exports.SQUARE = exports.PROJECT = exports.PIE = exports.CHORD = exports.OPEN = exports.CLOSE = exports.TESS = exports.QUAD_STRIP = exports.QUADS = exports.TRIANGLE_STRIP = exports.TRIANGLE_FAN = exports.TRIANGLES = exports.LINE_LOOP = exports.LINE_STRIP = exports.LINES = exports.POINTS = exports.BASELINE = exports.BOTTOM = exports.TOP = exports.CENTER = exports.LEFT = exports.RIGHT = exports.RADIUS = exports.CORNERS = exports.CORNER = exports.RAD_TO_DEG = exports.DEG_TO_RAD = exports.RADIANS = exports.DEGREES = exports.TWO_PI = exports.TAU = exports.QUARTER_PI = exports.PI = exports.HALF_PI = exports.WAIT = exports.TEXT = exports.MOVE = exports.HAND = exports.CROSS = exports.ARROW = exports.WEBGL = exports.P2D = void 0;
exports.FALLBACK = exports.LABEL = exports.AXES = exports.GRID = exports._DEFAULT_FILL = exports._DEFAULT_STROKE = exports.PORTRAIT = exports.LANDSCAPE = exports.MIRROR = exports.CLAMP = exports.REPEAT = exports.NEAREST = exports.IMAGE = exports.IMMEDIATE = exports.TEXTURE = void 0; /**
* @module Constants
* @submodule Constants
* @for p5
*/
var _PI = Math.PI;
// GRAPHICS RENDERER
/**
* The default, two-dimensional renderer.
* @property {String} P2D
* @final
*/
var P2D = 'p2d';
/**
* One of the two render modes in p5.js: P2D (default renderer) and WEBGL
* Enables 3D render by introducing the third dimension: Z
* @property {String} WEBGL
* @final
*/ exports.P2D = P2D;
var WEBGL = 'webgl';
// ENVIRONMENT
/**
* @property {String} ARROW
* @final
*/ exports.WEBGL = WEBGL;
var ARROW = 'default';
/**
* @property {String} CROSS
* @final
*/ exports.ARROW = ARROW;
var CROSS = 'crosshair';
/**
* @property {String} HAND
* @final
*/ exports.CROSS = CROSS;
var HAND = 'pointer';
/**
* @property {String} MOVE
* @final
*/ exports.HAND = HAND;
var MOVE = 'move';
/**
* @property {String} TEXT
* @final
*/ exports.MOVE = MOVE;
var TEXT = 'text';
/**
* @property {String} WAIT
* @final
*/ exports.TEXT = TEXT;
var WAIT = 'wait';
// TRIGONOMETRY
/**
* HALF_PI is a mathematical constant with the value
* 1.57079632679489661923. It is half the ratio of the
* circumference of a circle to its diameter. It is useful in
* combination with the trigonometric functions <a href="#/p5/sin">sin()</a> and <a href="#/p5/cos">cos()</a>.
*
* @property {Number} HALF_PI
* @final
*
* @example
* <div><code>
* arc(50, 50, 80, 80, 0, HALF_PI);
* </code></div>
*
* @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 <a href="#/p5/sin">sin()</a> and <a href="#/p5/cos">cos()</a>.
*
* @property {Number} PI
* @final
*
* @example
* <div><code>
* arc(50, 50, 80, 80, 0, PI);
* </code></div>
*
* @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 <a href="#/p5/sin">sin()</a> and <a href="#/p5/cos">cos()</a>.
*
* @property {Number} QUARTER_PI
* @final
*
* @example
* <div><code>
* arc(50, 50, 80, 80, 0, QUARTER_PI);
* </code></div>
*
* @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 <a href="#/p5/sin">sin()</a> and <a href="#/p5/cos">cos()</a>.
*
* @property {Number} TAU
* @final
*
* @example
* <div><code>
* arc(50, 50, 80, 80, 0, TAU);
* </code></div>
*
* @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 <a href="#/p5/sin">sin()</a> and <a href="#/p5/cos">cos()</a>.
*
* @property {Number} TWO_PI
* @final
*
* @example
* <div><code>
* arc(50, 50, 80, 80, 0, TWO_PI);
* </code></div>
*
* @alt
* 80x80 white ellipse shape in center of canvas.
*/ exports.TAU = TAU;
var TWO_PI = _PI * 2;
/**
* Constant to be used with <a href="#/p5/angleMode">angleMode()</a> function, to set the mode which
* p5.js interprates and calculates angles (either DEGREES or RADIANS).
* @property {String} DEGREES
* @final
*
* @example
* <div class='norender'><code>
* function setup() {
* angleMode(DEGREES);
* }
* </code></div>
*/ exports.TWO_PI = TWO_PI;
var DEGREES = 'degrees';
/**
* Constant to be used with <a href="#/p5/angleMode">angleMode()</a> function, to set the mode which
* p5.js interprates and calculates angles (either RADIANS or DEGREES).
* @property {String} RADIANS
* @final
*
* @example
* <div class='norender'><code>
* function setup() {
* angleMode(RADIANS);
* }
* </code></div>
*/ exports.DEGREES = DEGREES;
var RADIANS = 'radians';
exports.RADIANS = RADIANS;
var DEG_TO_RAD = _PI / 180.0;
exports.DEG_TO_RAD = DEG_TO_RAD;
var RAD_TO_DEG = 180.0 / _PI;
// SHAPE
/**
* @property {String} CORNER
* @final
*/ exports.RAD_TO_DEG = RAD_TO_DEG;
var CORNER = 'corner';
/**
* @property {String} CORNERS
* @final
*/ exports.CORNER = CORNER;
var CORNERS = 'corners';
/**
* @property {String} RADIUS
* @final
*/ exports.CORNERS = CORNERS;
var RADIUS = 'radius';
/**
* @property {String} RIGHT
* @final
*/ exports.RADIUS = RADIUS;
var RIGHT = 'right';
/**
* @property {String} LEFT
* @final
*/ exports.RIGHT = RIGHT;
var LEFT = 'left';
/**
* @property {String} CENTER
* @final
*/ exports.LEFT = LEFT;
var CENTER = 'center';
/**
* @property {String} TOP
* @final
*/ exports.CENTER = CENTER;
var TOP = 'top';
/**
* @property {String} BOTTOM
* @final
*/ exports.TOP = TOP;
var BOTTOM = 'bottom';
/**
* @property {String} BASELINE
* @final
* @default alphabetic
*/ exports.BOTTOM = BOTTOM;
var BASELINE = 'alphabetic';
/**
* @property {Number} POINTS
* @final
* @default 0x0000
*/ exports.BASELINE = BASELINE;
var POINTS = 0x0000;
/**
* @property {Number} LINES
* @final
* @default 0x0001
*/ exports.POINTS = POINTS;
var LINES = 0x0001;
/**
* @property {Number} LINE_STRIP
* @final
* @default 0x0003
*/ exports.LINES = LINES;
var LINE_STRIP = 0x0003;
/**
* @property {Number} LINE_LOOP
* @final
* @default 0x0002
*/ exports.LINE_STRIP = LINE_STRIP;
var LINE_LOOP = 0x0002;
/**
* @property {Number} TRIANGLES
* @final
* @default 0x0004
*/ exports.LINE_LOOP = LINE_LOOP;
var TRIANGLES = 0x0004;
/**
* @property {Number} TRIANGLE_FAN
* @final
* @default 0x0006
*/ exports.TRIANGLES = TRIANGLES;
var TRIANGLE_FAN = 0x0006;
/**
* @property {Number} TRIANGLE_STRIP
* @final
* @default 0x0005
*/ exports.TRIANGLE_FAN = TRIANGLE_FAN;
var TRIANGLE_STRIP = 0x0005;
/**
* @property {String} QUADS
* @final
*/ exports.TRIANGLE_STRIP = TRIANGLE_STRIP;
var QUADS = 'quads';
/**
* @property {String} QUAD_STRIP
* @final
* @default quad_strip
*/ exports.QUADS = QUADS;
var QUAD_STRIP = 'quad_strip';
/**
* @property {String} TESS
* @final
* @default tess
*/ exports.QUAD_STRIP = QUAD_STRIP;
var TESS = 'tess';
/**
* @property {String} CLOSE
* @final
*/ exports.TESS = TESS;
var CLOSE = 'close';
/**
* @property {String} OPEN
* @final
*/ exports.CLOSE = CLOSE;
var OPEN = 'open';
/**
* @property {String} CHORD
* @final
*/ exports.OPEN = OPEN;
var CHORD = 'chord';
/**
* @property {String} PIE
* @final
*/ exports.CHORD = CHORD;
var PIE = 'pie';
/**
* @property {String} PROJECT
* @final
* @default square
*/ exports.PIE = PIE;
var PROJECT = 'square'; // PEND: careful this is counterintuitive
/**
* @property {String} SQUARE
* @final
* @default butt
*/ exports.PROJECT = PROJECT;
var SQUARE = 'butt';
/**
* @property {String} ROUND
* @final
*/ exports.SQUARE = SQUARE;
var ROUND = 'round';
/**
* @property {String} BEVEL
* @final
*/ exports.ROUND = ROUND;
var BEVEL = 'bevel';
/**
* @property {String} MITER
* @final
*/ exports.BEVEL = BEVEL;
var MITER = 'miter';
// COLOR
/**
* @property {String} RGB
* @final
*/ exports.MITER = MITER;
var RGB = 'rgb';
/**
* HSB (hue, saturation, brightness) is a type of color model.
* You can learn more about it at
* <a href="https://learnui.design/blog/the-hsb-color-system-practicioners-primer.html">HSB</a>.
*
* @property {String} HSB
* @final
*/ exports.RGB = RGB;
var HSB = 'hsb';
/**
* @property {String} HSL
* @final
*/ exports.HSB = HSB;
var HSL = 'hsl';
// DOM EXTENSION
/**
* AUTO allows us to automatically set the width or height of an element (but not both),
* based on the current height and width of the element. Only one parameter can
* be passed to the <a href="/#/p5.Element/size">size</a> function as AUTO, at a time.
*
* @property {String} AUTO
* @final
*/ exports.HSL = HSL;
var AUTO = 'auto';
/**
* @property {Number} ALT
* @final
*/
// INPUT
exports.AUTO = AUTO;
var ALT = 18;
/**
* @property {Number} BACKSPACE
* @final
*/ exports.ALT = ALT;
var BACKSPACE = 8;
/**
* @property {Number} CONTROL
* @final
*/ exports.BACKSPACE = BACKSPACE;
var CONTROL = 17;
/**
* @property {Number} DELETE
* @final
*/ exports.CONTROL = CONTROL;
var DELETE = 46;
/**
* @property {Number} DOWN_ARROW
* @final
*/ exports.DELETE = DELETE;
var DOWN_ARROW = 40;
/**
* @property {Number} ENTER
* @final
*/ exports.DOWN_ARROW = DOWN_ARROW;
var ENTER = 13;
/**
* @property {Number} ESCAPE
* @final
*/ exports.ENTER = ENTER;
var ESCAPE = 27;
/**
* @property {Number} LEFT_ARROW
* @final
*/ exports.ESCAPE = ESCAPE;
var LEFT_ARROW = 37;
/**
* @property {Number} OPTION
* @final
*/ exports.LEFT_ARROW = LEFT_ARROW;
var OPTION = 18;
/**
* @property {Number} RETURN
* @final
*/ exports.OPTION = OPTION;
var RETURN = 13;
/**
* @property {Number} RIGHT_ARROW
* @final
*/ exports.RETURN = RETURN;
var RIGHT_ARROW = 39;
/**
* @property {Number} SHIFT
* @final
*/ exports.RIGHT_ARROW = RIGHT_ARROW;
var SHIFT = 16;
/**
* @property {Number} TAB
* @final
*/ exports.SHIFT = SHIFT;
var TAB = 9;
/**
* @property {Number} UP_ARROW
* @final
*/ exports.TAB = TAB;
var UP_ARROW = 38;
// RENDERING
/**
* @property {String} BLEND
* @final
* @default source-over
*/ exports.UP_ARROW = UP_ARROW;
var BLEND = 'source-over';
/**
* @property {String} REMOVE
* @final
* @default destination-out
*/ exports.BLEND = BLEND;
var REMOVE = 'destination-out';
/**
* @property {String} ADD
* @final
* @default lighter
*/ exports.REMOVE = REMOVE;
var ADD = 'lighter';
//ADD: 'add', //
//SUBTRACT: 'subtract', //
/**
* @property {String} DARKEST
* @final
*/ exports.ADD = ADD;
var DARKEST = 'darken';
/**
* @property {String} LIGHTEST
* @final
* @default lighten
*/ exports.DARKEST = DARKEST;
var LIGHTEST = 'lighten';
/**
* @property {String} DIFFERENCE
* @final
*/ exports.LIGHTEST = LIGHTEST;
var DIFFERENCE = 'difference';
/**
* @property {String} SUBTRACT
* @final
*/ exports.DIFFERENCE = DIFFERENCE;
var SUBTRACT = 'subtract';
/**
* @property {String} EXCLUSION
* @final
*/ exports.SUBTRACT = SUBTRACT;
var EXCLUSION = 'exclusion';
/**
* @property {String} MULTIPLY
* @final
*/ exports.EXCLUSION = EXCLUSION;
var MULTIPLY = 'multiply';
/**
* @property {String} SCREEN
* @final
*/ exports.MULTIPLY = MULTIPLY;
var SCREEN = 'screen';
/**
* @property {String} REPLACE
* @final
* @default copy
*/ exports.SCREEN = SCREEN;
var REPLACE = 'copy';
/**
* @property {String} OVERLAY
* @final
*/ exports.REPLACE = REPLACE;
var OVERLAY = 'overlay';
/**
* @property {String} HARD_LIGHT
* @final
*/ exports.OVERLAY = OVERLAY;
var HARD_LIGHT = 'hard-light';
/**
* @property {String} SOFT_LIGHT
* @final
*/ exports.HARD_LIGHT = HARD_LIGHT;
var SOFT_LIGHT = 'soft-light';
/**
* @property {String} DODGE
* @final
* @default color-dodge
*/ exports.SOFT_LIGHT = SOFT_LIGHT;
var DODGE = 'color-dodge';
/**
* @property {String} BURN
* @final
* @default color-burn
*/ exports.DODGE = DODGE;
var BURN = 'color-burn';
// FILTERS
/**
* @property {String} THRESHOLD
* @final
*/ exports.BURN = BURN;
var THRESHOLD = 'threshold';
/**
* @property {String} GRAY
* @final
*/ exports.THRESHOLD = THRESHOLD;
var GRAY = 'gray';
/**
* @property {String} OPAQUE
* @final
*/ exports.GRAY = GRAY;
var OPAQUE = 'opaque';
/**
* @property {String} INVERT
* @final
*/ exports.OPAQUE = OPAQUE;
var INVERT = 'invert';
/**
* @property {String} POSTERIZE
* @final
*/ exports.INVERT = INVERT;
var POSTERIZE = 'posterize';
/**
* @property {String} DILATE
* @final
*/ exports.POSTERIZE = POSTERIZE;
var DILATE = 'dilate';
/**
* @property {String} ERODE
* @final
*/ exports.DILATE = DILATE;
var ERODE = 'erode';
/**
* @property {String} BLUR
* @final
*/ exports.ERODE = ERODE;
var BLUR = 'blur';
// TYPOGRAPHY
/**
* @property {String} NORMAL
* @final
*/ exports.BLUR = BLUR;
var NORMAL = 'normal';
/**
* @property {String} ITALIC
* @final
*/ exports.NORMAL = NORMAL;
var ITALIC = 'italic';
/**
* @property {String} BOLD
* @final
*/ exports.ITALIC = ITALIC;
var BOLD = 'bold';
/**
* @property {String} BOLDITALIC
* @final
*/ exports.BOLD = BOLD;
var BOLDITALIC = 'bold italic';
// TYPOGRAPHY-INTERNAL
exports.BOLDITALIC = BOLDITALIC;
var _DEFAULT_TEXT_FILL = '#000000';
exports._DEFAULT_TEXT_FILL = _DEFAULT_TEXT_FILL;
var _DEFAULT_LEADMULT = 1.25;
exports._DEFAULT_LEADMULT = _DEFAULT_LEADMULT;
var _CTX_MIDDLE = 'middle';
// VERTICES
/**
* @property {String} LINEAR
* @final
*/ exports._CTX_MIDDLE = _CTX_MIDDLE;
var LINEAR = 'linear';
/**
* @property {String} QUADRATIC
* @final
*/ exports.LINEAR = LINEAR;
var QUADRATIC = 'quadratic';
/**
* @property {String} BEZIER
* @final
*/ exports.QUADRATIC = QUADRATIC;
var BEZIER = 'bezier';
/**
* @property {String} CURVE
* @final
*/ exports.BEZIER = BEZIER;
var CURVE = 'curve';
// WEBGL DRAWMODES
/**
* @property {String} STROKE
* @final
*/ exports.CURVE = CURVE;
var STROKE = 'stroke';
/**
* @property {String} FILL
* @final
*/ exports.STROKE = STROKE;
var FILL = 'fill';
/**
* @property {String} TEXTURE
* @final
*/ exports.FILL = FILL;
var TEXTURE = 'texture';
/**
* @property {String} IMMEDIATE
* @final
*/ exports.TEXTURE = TEXTURE;
var IMMEDIATE = 'immediate';
// WEBGL TEXTURE MODE
// NORMAL already exists for typography
/**
* @property {String} IMAGE
* @final
*/ exports.IMMEDIATE = IMMEDIATE;
var IMAGE = 'image';
// WEBGL TEXTURE WRAP AND FILTERING
// LINEAR already exists above
/**
* @property {String} NEAREST
* @final
*/ exports.IMAGE = IMAGE;
var NEAREST = 'nearest';
/**
* @property {String} REPEAT
* @final
*/ exports.NEAREST = NEAREST;
var REPEAT = 'repeat';
/**
* @property {String} CLAMP
* @final
*/ exports.REPEAT = REPEAT;
var CLAMP = 'clamp';
/**
* @property {String} MIRROR
* @final
*/ exports.CLAMP = CLAMP;
var MIRROR = 'mirror';
// DEVICE-ORIENTATION
/**
* @property {String} LANDSCAPE
* @final
*/ exports.MIRROR = MIRROR;
var LANDSCAPE = 'landscape';
/**
* @property {String} PORTRAIT
* @final
*/ exports.LANDSCAPE = LANDSCAPE;
var PORTRAIT = 'portrait';
// DEFAULTS
exports.PORTRAIT = PORTRAIT;
var _DEFAULT_STROKE = '#000000';
exports._DEFAULT_STROKE = _DEFAULT_STROKE;
var _DEFAULT_FILL = '#FFFFFF';
/**
* @property {String} GRID
* @final
*/ exports._DEFAULT_FILL = _DEFAULT_FILL;
var GRID = 'grid';
/**
* @property {String} AXES
* @final
*/ exports.GRID = GRID;
var AXES = 'axes';
/**
* @property {String} LABEL
* @final
*/ exports.AXES = AXES;
var LABEL = 'label';
/**
* @property {String} FALLBACK
* @final
*/ exports.LABEL = LABEL;
var FALLBACK = 'fallback';
exports.FALLBACK = FALLBACK;
},
{}
],
49: [
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 C = _interopRequireWildcard(_dereq_('./constants'));
function _getRequireWildcardCache() {
if (typeof WeakMap !== 'function') return null;
var cache = new WeakMap();
_getRequireWildcardCache = function _getRequireWildcardCache() {
return cache;
};
return cache;
}
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
}
if (obj === null || (_typeof(obj) !== 'object' && typeof obj !== 'function')) {
return { default: obj };
}
var cache = _getRequireWildcardCache();
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* @module Environment
* @submodule Environment
* @for p5
* @requires core
* @requires constants
*/ var standardCursors = [C.ARROW, C.CROSS, C.HAND, C.MOVE, C.TEXT, C.WAIT];
_main.default.prototype._frameRate = 0;
_main.default.prototype._lastFrameTime = window.performance.now();
_main.default.prototype._targetFrameRate = 60;
var _windowPrint = window.print;
/**
* The <a href="#/p5/print">print()</a> function writes to the console area of
* your browser. This function is often helpful for looking at the data a program
* is producing. This function creates a new line of text for each call to
* the function. Individual elements can be separated with quotes ("") and joined
* with the addition operator (+).
*
* Note that calling print() without any arguments invokes the window.print()
* function which opens the browser's print dialog. To print a blank line
* to console you can write print('\n').
*
* @method print
* @param {Any} contents any combination of Number, String, Object, Boolean,
* Array to print
* @example
* <div><code class='norender'>
* let x = 10;
* print('The value of x is ' + x);
* // prints "The value of x is 10"
* </code></div>
*
* @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 <a href="#/p5/frameCount">frameCount</a> contains the
* number of frames that have been displayed since the program started. Inside
* <a href="#/p5/setup">setup()</a> the value is 0, after the first iteration
* of draw it is 1, etc.
*
* @property {Integer} frameCount
* @readOnly
* @example
* <div><code>
* function setup() {
* frameRate(30);
* textSize(30);
* textAlign(CENTER);
* }
*
* function draw() {
* background(200);
* text(frameCount, width / 2, height / 2);
* }
* </code></div>
*
* @alt
* numbers rapidly counting upward with frame count set to 30.
*/
_main.default.prototype.frameCount = 0;
/**
* The system variable <a href="#/p5/deltaTime">deltaTime</a> 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
* <div><code>
* 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);
* }
* </code></div>
*
* @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
* <div><code>
* // 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);
* }
* }
* </code></div>
*
* @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
* <div><code>
* // Move the mouse across the quadrants
* // to see the cursor change
* function draw() {
* line(width / 2, 0, width / 2, height);
* line(0, height / 2, width, height / 2);
* if (mouseX < 50 && mouseY < 50) {
* cursor(CROSS);
* } else if (mouseX > 50 && mouseY < 50) {
* cursor('progress');
* } else if (mouseX > 50 && mouseY > 50) {
* cursor('https://avatars0.githubusercontent.com/u/1617169?s=16');
* } else {
* cursor('grab');
* }
* }
* </code></div>
*
* @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
* <a href="#/p5/setup">setup()</a> 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 <a href="#/p5/frameRate">frameRate()</a> 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 <a href="#/p5/getFrameRate">getFrameRate()</a>.
*
* Calling <a href="#/p5/frameRate">frameRate()</a> 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
*
* <div><code>
* 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; // Move Rectangle
*
* 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);
* }
* </code></div>
*
* @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 <a href="#/p5/setup">setup()</a> is
* recommended. The default rate is 60 frames per second.
*
* Calling <a href="#/p5/frameRate">frameRate()</a> 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
* <div><code>
* function setup() {
* noCursor();
* }
*
* function draw() {
* background(200);
* ellipse(mouseX, mouseY, 10, 10);
* }
* </code></div>
*
* @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 <a href="#/p5/pixelDensity">pixelDensity</a>. 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
* <div class="norender"><code>
* createCanvas(displayWidth, displayHeight);
* </code></div>
*
* @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 <a href="#/p5/pixelDensity">pixelDensity</a>. 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
* <div class="norender"><code>
* createCanvas(displayWidth, displayHeight);
* </code></div>
*
* @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
* <div class="norender"><code>
* createCanvas(windowWidth, windowHeight);
* </code></div>
*
* @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
* <div class="norender"><code>
* createCanvas(windowWidth, windowHeight);
* </code></div>
*
* @alt
* This example does not render anything.
*/
_main.default.prototype.windowHeight = getWindowHeight();
/**
* The <a href="#/p5/windowResized">windowResized()</a> 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
* <div class="norender"><code>
* function setup() {
* createCanvas(windowWidth, windowHeight);
* }
*
* function draw() {
* background(0, 100, 200);
* }
*
* function windowResized() {
* resizeCanvas(windowWidth, windowHeight);
* }
* </code></div>
* @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 <a href="#/p5/createCanvas">createCanvas()</a> 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
* <a href="#/p5/createCanvas">createCanvas()</a> 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 <a href="#/p5/createCanvas">createCanvas()</a> 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
* <a href="#/p5/createCanvas">createCanvas()</a> 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
* <div>
* <code>
* // 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);
* }
* }
* </code>
* </div>
*
* @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 <a href="#/p5/pixelDensity">pixelDensity()</a> 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
* <div>
* <code>
* function setup() {
* pixelDensity(1);
* createCanvas(100, 100);
* background(200);
* ellipse(width / 2, height / 2, 50, 50);
* }
* </code>
* </div>
*
* <div>
* <code>
* function setup() {
* pixelDensity(3.0);
* createCanvas(100, 100);
* background(200);
* ellipse(width / 2, height / 2, 50, 50);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* function setup() {
* let density = displayDensity();
* pixelDensity(density);
* createCanvas(100, 100);
* background(200);
* ellipse(width / 2, height / 2, 50, 50);
* }
* </code>
* </div>
*
* @alt
* 50x50 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.
* @method getURL
* @return {String} url
* @example
* <div>
* <code>
* let url;
* let x = 100;
*
* function setup() {
* fill(0);
* noStroke();
* url = getURL();
* }
*
* function draw() {
* background(200);
* text(url, x, height / 2);
* x--;
* }
* </code>
* </div>
*
* @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.
* @method getURLPath
* @return {String[]} path components
* @example
* <div class='norender'><code>
* function setup() {
* let urlPath = getURLPath();
* for (let i = 0; i < urlPath.length; i++) {
* text(urlPath[i], 10, i * 20 + 20);
* }
* }
* </code></div>
*
* @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.
* @method getURLParams
* @return {Object} URL params
* @example
* <div class='norender notest'>
* <code>
* // Example: http://p5js.org?year=2014&month=May&day=15
*
* function setup() {
* let params = getURLParams();
* text(params.day, 10, 20);
* text(params.month, 10, 40);
* text(params.year, 10, 60);
* }
* </code>
* </div>
*
* @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': 48, './main': 59 }
],
50: [
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;
},
{}
],
51: [
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
);
};
/**
* 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 the function to link
*
* @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
*
* @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];
}
// 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 {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 })
);
};
/**
* 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.
* @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 if the various functions such as setup, draw, preload have been
* defined with capitalization mistakes
* @method checkForUserDefinedFunctions
* @private
* @param {*} context The current default context. It's 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]
}
);
report(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.
*
* @method handleMisspelling
* @private
* @param {String} errSym the symbol to whose spelling to check
* @param {Error} error the ReferenceError object
*
* @returns {Boolean} a boolean value indicating if this error was likely due
* to a mis-spelling
*/
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.
report(
msg,
matchedSymbols.length === 1 ? matchedSymbols[0].name : undefined
);
return true;
}
return false;
};
/**
* prints a friendly stacktrace which only includes user-written functions
* and is easier for newcomers to understand
* @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. It also uses this processed stack to figure out if the error
* error happened internally within the library, and if the error was due to
* a non-loadX() method being used in preload
* "Internally" here means that the error 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 indicating if the error happened internally
* friendlyStack: the simplified stacktrace, with internal details filtered
*/
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
) {
report(
(0, _internationalization.translator)('fes.wrongPreload', {
func: func,
location: locationObj
? (0, _internationalization.translator)('fes.location', locationObj)
: '',
error: error.message
}),
'preload'
);
} else {
// Library error
report(
(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];
};
/**
* The main function for handling global errors. Called when an error
* happens and is responsible for detecting the type of error that
* has happened and showing the appropriate message
*
* @method fesErrorMonitor
* @private
* @param {*} e The 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': {
var url =
'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Errors/Illegal_character#What_went_wrong';
report(
(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';
report(
(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';
report(
(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) {
report(
(0, _internationalization.translator)(
'fes.globalErrors.type.notfuncObj',
translationObj
)
);
} else {
report(
(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': 48,
'../internationalization': 57,
'../main': 59,
'./browser_errors': 50
}
],
52: [
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
*
* This file contains the part of the FES responsible for dealing with
* file load errors
*/ 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': 57, '../main': 59 }
],
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 };
} /** // 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.
* @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', '<anonymous>'].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(/<anonymous function(: (\w+))?>/, '$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': 59 }
],
54: [
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': 48,
'../internationalization': 57,
'../main': 59
}
],
55: [
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': 48 }
],
56: [
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': 59, './internationalization': 57 }
],
57: [
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 };
}
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 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(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;
};
exports.initialize = initialize;
},
{
'../../translations': 118,
'../../translations/dev': undefined,
i18next: 30,
'i18next-browser-languagedetector': 27
}
],
58: [
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': 59 }
],
59: [
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 <a href="#/p5/preload">preload()</a>,
* <a href="#/p5/setup">setup()</a>, and/or
* <a href="#/p5/draw">draw()</a> 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 <a href="#/p5/preload">preload()</a>,
* <a href="#/p5/setup">setup()</a>, and/or <a href="#/p5/draw">draw()</a> 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 <a href="#/p5/setup">setup()</a>, the <a href="#/p5/preload">preload()</a> function is used to handle
* asynchronous loading of external files in a blocking way. If a preload
* function is defined, <a href="#/p5/setup">setup()</a> will wait until any load calls within have
* finished. Nothing besides load calls (<a href="#/p5/loadImage">loadImage</a>, <a href="#/p5/loadJSON">loadJSON</a>, <a href="#/p5/loadFont">loadFont</a>,
* <a href="#/p5/loadStrings">loadStrings</a>, etc.) should be inside the preload function. If asynchronous
* loading is preferred, the load methods can instead be called in <a href="#/p5/setup">setup()</a>
* 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 <a href="http://bit.ly/2kQ6Nio">here</a>.
*
* @method preload
* @example
* <div><code>
* 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);
* }
* </code></div>
*
* @alt
* nothing displayed
*
*/
/**
* The <a href="#/p5/setup">setup()</a> 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 <a href="#/p5/setup">setup()</a> function for each program and it shouldn't
* be called again after its initial execution.
*
* Note: Variables declared within <a href="#/p5/setup">setup()</a> are not accessible within other
* functions, including <a href="#/p5/draw">draw()</a>.
*
* @method setup
* @example
* <div><code>
* let a = 0;
*
* function setup() {
* background(0);
* noStroke();
* fill(102);
* }
*
* function draw() {
* rect(a++ % width, 10, 2, 80);
* }
* </code></div>
*
* @alt
* nothing displayed
*
*/
/**
* Called directly after <a href="#/p5/setup">setup()</a>, the <a href="#/p5/draw">draw()</a> function continuously executes
* the lines of code contained inside its block until the program is stopped
* or <a href="#/p5/noLoop">noLoop()</a> is called. Note if <a href="#/p5/noLoop">noLoop()</a> is called in <a href="#/p5/setup">setup()</a>, <a href="#/p5/draw">draw()</a> will
* still be executed once before stopping. <a href="#/p5/draw">draw()</a> is called automatically and
* should never be called explicitly.
*
* It should always be controlled with <a href="#/p5/noLoop">noLoop()</a>, <a href="#/p5/redraw">redraw()</a> and <a href="#/p5/loop">loop()</a>. After
* <a href="#/p5/noLoop">noLoop()</a> stops the code in <a href="#/p5/draw">draw()</a> from executing, <a href="#/p5/redraw">redraw()</a> causes the
* code inside <a href="#/p5/draw">draw()</a> to execute once, and <a href="#/p5/loop">loop()</a> will cause the code
* inside <a href="#/p5/draw">draw()</a> to resume executing continuously.
*
* The number of times <a href="#/p5/draw">draw()</a> executes in each second may be controlled with
* the <a href="#/p5/frameRate">frameRate()</a> function.
*
* There can only be one <a href="#/p5/draw">draw()</a> function for each sketch, and <a href="#/p5/draw">draw()</a> must
* exist if you want the code to run continuously, or to process events such
* as <a href="#/p5/mousePressed">mousePressed()</a>. Sometimes, you might have an empty call to <a href="#/p5/draw">draw()</a> 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 <a href="#/p5/draw">draw()</a> call. If any transformations are performed
* within <a href="#/p5/draw">draw()</a> (ex: scale, rotate, translate), their effects will be
* undone at the beginning of <a href="#/p5/draw">draw()</a>, so transformations will not accumulate
* over time. On the other hand, styling applied (ex: fill, stroke, etc) will
* remain in effect.
*
* @method draw
* @example
* <div><code>
* let yPos = 0;
* function setup() {
* // setup() runs once
* frameRate(30);
* }
* function draw() {
* // draw() loops forever, until stopped
* background(204);
* yPos = yPos - 1;
* if (yPos < 0) {
* yPos = height;
* }
* line(0, yPos, width, yPos);
* }
* </code></div>
*
* @alt
* nothing displayed
*
*/
//////////////////////////////////////////////
// PRIVATE p5 PROPERTIES AND METHODS
//////////////////////////////////////////////
this._accessibleOutputs = {
text: false,
grid: false,
textLabel: false,
gridLabel: false
};
this._setupDone = 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;
// 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();
_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._lastFrameTime = window.performance.now();
context._setup();
context._draw();
}
}
};
this._decrementPreload = function() {
var context = this._isGlobal ? window : this;
if (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;
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();
// 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._lastFrameTime = 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._lastFrameTime;
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(matrixs and stack)
_this.redraw();
_this._frameRate = 1000.0 / (now - _this._lastFrameTime);
_this.deltaTime = now - _this._lastFrameTime;
_this._setProperty('deltaTime', _this.deltaTime);
_this._lastFrameTime = 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
* <div class='norender'><code>
* function draw() {
* ellipse(50, 50, 10, 10);
* }
*
* function mousePressed() {
* remove(); // remove whole sketch on mouse press
* }
* </code></div>
*
* @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 <a href='https://github.com/processing/p5.js/wiki/Optimizing-p5.js-Code-for-Performance#disable-the-friendly-error-system-fes'>
* disabling the friendly error system</a>.
*
* @property {Boolean} disableFriendlyErrors
* @example
* <div class="norender notest"><code>
* p5.disableFriendlyErrors = true;
*
* function setup() {
* createCanvas(100, 50);
* }
* </code></div>
*/
p5.disableFriendlyErrors = false;
// attach constants to p5 prototype
for (var k in constants) {
p5.prototype[k] = constants[k];
}
// functions that cause preload to wait
// more can be added by using registerPreloadMethod(func)
p5.prototype._preloadMethods = {
loadJSON: p5.prototype,
loadImage: p5.prototype,
loadStrings: p5.prototype,
loadXML: p5.prototype,
loadBytes: p5.prototype,
loadTable: p5.prototype,
loadFont: p5.prototype,
loadModel: p5.prototype,
loadShader: p5.prototype
};
p5.prototype._registeredMethods = { init: [], pre: [], post: [], remove: [] };
p5.prototype._registeredPreloadMethods = {};
var _default = p5;
exports.default = _default;
},
{ './constants': 48, './shim': 70 }
],
60: [
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 DOM
* @submodule DOM
* @for p5.Element
*/ /**
* Base class for all elements added to a sketch, including canvas,
* graphics buffers, and other HTML elements. It is not called directly, but <a href="#/p5.Element">p5.Element</a>
* objects are created by calling <a href="#/p5/createCanvas">createCanvas</a>, <a href="#/p5/createGraphics">createGraphics</a>,
* <a href="#/p5/createDiv">createDiv</a>, <a href="#/p5/createImg">createImg</a>, <a href="#/p5/createInput">createInput</a>, etc.
*
* @class p5.Element
* @constructor
* @param {String} elt DOM node that is wrapped
* @param {p5} [pInst] pointer to p5 instance
*/ _main.default.Element = function(elt, pInst) {
/**
* Underlying HTML element. All normal HTML methods can be called on this.
* @example
* <div>
* <code>
* function setup() {
* let c = createCanvas(50, 50);
* c.elt.style.border = '5px solid red';
* }
*
* function draw() {
* background(220);
* }
* </code>
* </div>
*
* @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 <a href="#/p5.Element">p5.Element</a>. If no arguments given, parent node is returned.
* For more ways to position the canvas, see the
* <a href='https://github.com/processing/p5.js/wiki/Positioning-your-canvas'>
* positioning the canvas</a> wiki page.
*
* @method parent
* @param {String|p5.Element|Object} parent the ID, DOM node, or <a href="#/p5.Element">p5.Element</a>
* of desired parent element
* @chainable
*
* @example
* <div class="norender notest"><code>
* // Add the following comment to html file.
* // <div id="myContainer"></div>
*
* // The js code
* let cnv = createCanvas(100, 100);
* cnv.parent('myContainer');
* </code></div>
*
* <div class='norender'><code>
* let div0 = createDiv('this is the parent');
* let div1 = createDiv('this is the child');
* div1.parent(div0); // use p5.Element
* </code></div>
*
* <div class='norender'><code>
* let div0 = createDiv('this is the parent');
* div0.id('apples');
* let div1 = createDiv('this is the child');
* div1.parent('apples'); // use id
* </code></div>
*
* <div class='norender notest'><code>
* let elt = document.getElementById('myParentDiv');
* let div1 = createDiv('this is the child');
* div1.parent(elt); // use element from page
* </code></div>
*
* @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 <a href="#/p5.Element/class">.class()</a> function can be used
* to identify multiple elements with the same class name.
*
* @method id
* @param {String} id ID of the element
* @chainable
*
* @example
* <div class='norender'><code>
* function setup() {
* let cnv = createCanvas(100, 100);
* // Assigns a CSS selector ID to
* // the canvas element.
* cnv.id('mycanvas');
* }
* </code></div>
*
* @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
* <div class='norender'><code>
* function setup() {
* let cnv = createCanvas(100, 100);
* // Assigns a CSS selector class 'small'
* // to the canvas element.
* cnv.class('small');
* }
* </code></div>
*
* @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 .<a href="#/p5.Element/mousePressed">mousePressed()</a> 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
* <div class='norender'><code>
* 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);
* }
* </code></div>
*
* @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 .<a href="#/p5.Element/doubleClicked">doubleClicked()</a> 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
* <div class='norender'><code>
* 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);
* }
* </code></div>
*
* @alt
* no display.
*/
_main.default.Element.prototype.doubleClicked = function(fxn) {
_main.default.Element._adjustListener('dblclick', fxn, this);
return this;
};
/**
* The <a href="#/p5.Element/mouseWheel">mouseWheel()</a> 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
* <div class='norender'><code>
* 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;
* }
* }
* </code></div>
*
* @alt
* no display.
*/
_main.default.Element.prototype.mouseWheel = function(fxn) {
_main.default.Element._adjustListener('wheel', fxn, this);
return this;
};
/**
* The <a href="#/p5.Element/mouseReleased">mouseReleased()</a> 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
* <div class='norender'><code>
* 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);
* }
* </code></div>
*
* @alt
* no display.
*/
_main.default.Element.prototype.mouseReleased = function(fxn) {
_main.default.Element._adjustListener('mouseup', fxn, this);
return this;
};
/**
* The .<a href="#/p5.Element/mouseClicked">mouseClicked()</a> 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
* <div class="norender">
* <code>
* 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);
* }
* </code>
* </div>
*
* @alt
* no display.
*/
_main.default.Element.prototype.mouseClicked = function(fxn) {
_main.default.Element._adjustListener('click', fxn, this);
return this;
};
/**
* The .<a href="#/p5.Element/mouseMoved">mouseMoved()</a> 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
* <div class='norender'><code>
* 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;
* }
* }
* </code></div>
*
* @alt
* no display.
*/
_main.default.Element.prototype.mouseMoved = function(fxn) {
_main.default.Element._adjustListener('mousemove', fxn, this);
return this;
};
/**
* The .<a href="#/p5.Element/mouseOver">mouseOver()</a> 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
* <div class='norender'><code>
* 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;
* }
* }
* </code></div>
*
* @alt
* no display.
*/
_main.default.Element.prototype.mouseOver = function(fxn) {
_main.default.Element._adjustListener('mouseover', fxn, this);
return this;
};
/**
* The .<a href="#/p5.Element/mouseOut">mouseOut()</a> 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
* <div class='norender'><code>
* 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;
* }
* }
* </code></div>
*
* @alt
* no display.
*/
_main.default.Element.prototype.mouseOut = function(fxn) {
_main.default.Element._adjustListener('mouseout', fxn, this);
return this;
};
/**
* The .<a href="#/p5.Element/touchStarted">touchStarted()</a> 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
* <div class='norender'><code>
* 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);
* }
* </code></div>
*
* @alt
* no display.
*/
_main.default.Element.prototype.touchStarted = function(fxn) {
_main.default.Element._adjustListener('touchstart', fxn, this);
return this;
};
/**
* The .<a href="#/p5.Element/touchMoved">touchMoved()</a> 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
* <div class='norender'><code>
* 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);
* }
* </code></div>
*
* @alt
* no display.
*/
_main.default.Element.prototype.touchMoved = function(fxn) {
_main.default.Element._adjustListener('touchmove', fxn, this);
return this;
};
/**
* The .<a href="#/p5.Element/touchEnded">touchEnded()</a> 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
* <div class='norender'><code>
* 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);
* }
* </code></div>
*
* @alt
* no display.
*/
_main.default.Element.prototype.touchEnded = function(fxn) {
_main.default.Element._adjustListener('touchend', fxn, this);
return this;
};
/**
* The .<a href="#/p5.Element/dragOver">dragOver()</a> 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
* <div><code>
* // 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);
* }
* </code></div>
* @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
* <div><code>
* // 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);
* }
* </code></div>
* @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': 59 }
],
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'));
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 <a href='#/p5/draw'>draw()</a> will copy the behavior
* of the standard canvas.
*
* @method reset
* @example
*
* <div><code>
* 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();
* }
* </code></div>
*
* @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
* <div class='norender'><code>
* let bg;
* function setup() {
* bg = createCanvas(100, 100);
* bg.background(0);
* image(bg, 0, 0);
* bg.remove();
* }
* </code></div>
*
* <div><code>
* let bg;
* function setup() {
* pixelDensity(1);
* createCanvas(100, 100);
* stroke(255);
* fill(0);
*
* // create and draw the background image
* bg = createGraphics(100, 100);
* bg.background(200);
* bg.ellipse(50, 50, 80, 80);
* }
* function draw() {
* let t = millis() / 1000;
* // draw the background
* if (bg) {
* image(bg, frameCount % 100, 0);
* image(bg, frameCount % 100 - 100, 0);
* }
* // draw the foreground
* let p = p5.Vector.fromAngle(t, 35).add(50, 50);
* ellipse(p.x, p.y, 30);
* }
* function mouseClicked() {
* // remove the background
* if (bg) {
* bg.remove();
* bg = null;
* }
* }
* </code></div>
*
* @alt
* no image
* a multi-colored circle moving back and forth over a scrolling background.
*/
_main.default.Graphics.prototype.remove = function() {
if (this.elt.parentNode) {
this.elt.parentNode.removeChild(this.elt);
}
var idx = this._pInst._elements.indexOf(this);
if (idx !== -1) {
this._pInst._elements.splice(idx, 1);
}
for (var elt_ev in this._events) {
this.elt.removeEventListener(elt_ev, this._events[elt_ev]);
}
};
var _default = _main.default.Graphics;
exports.default = _default;
},
{ './constants': 48, './main': 59 }
],
62: [
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_('../core/constants'));
function _getRequireWildcardCache() {
if (typeof WeakMap !== 'function') return null;
var cache = new WeakMap();
_getRequireWildcardCache = function _getRequireWildcardCache() {
return cache;
};
return cache;
}
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
}
if (obj === null || (_typeof(obj) !== 'object' && typeof obj !== 'function')) {
return { default: obj };
}
var cache = _getRequireWildcardCache();
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _typeof(obj) {
if (typeof Symbol === 'function' && 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);
}
/**
* Main graphics and rendering context, as well as the base API
* implementation for p5.js "core". To be used as the superclass for
* Renderer2D and Renderer3D classes, respectively.
*
* @class p5.Renderer
* @constructor
* @extends p5.Element
* @param {String} elt DOM node that is wrapped
* @param {p5} [pInst] pointer to p5 instance
* @param {Boolean} [isMainCanvas] whether we're using it as main canvas
*/
_main.default.Renderer = function(elt, pInst, isMainCanvas) {
_main.default.Element.call(this, elt, pInst);
this.canvas = elt;
this._pixelsState = pInst;
if (isMainCanvas) {
this._isMainCanvas = true;
// for pixel method sharing with pimage
this._pInst._setProperty('_curElement', this);
this._pInst._setProperty('canvas', this.canvas);
this._pInst._setProperty('width', this.width);
this._pInst._setProperty('height', this.height);
} else {
// hide if offscreen buffer by default
this.canvas.style.display = 'none';
this._styles = []; // non-main elt styles stored in p5.Renderer
}
this._textSize = 12;
this._textLeading = 15;
this._textFont = 'sans-serif';
this._textStyle = constants.NORMAL;
this._textAscent = null;
this._textDescent = null;
this._textAlign = constants.LEFT;
this._textBaseline = constants.BASELINE;
this._rectMode = constants.CORNER;
this._ellipseMode = constants.CENTER;
this._curveTightness = 0;
this._imageMode = constants.CORNER;
this._tint = null;
this._doStroke = true;
this._doFill = true;
this._strokeSet = false;
this._fillSet = false;
};
_main.default.Renderer.prototype = Object.create(_main.default.Element.prototype);
// the renderer should return a 'style' object that it wishes to
// store on the push stack.
_main.default.Renderer.prototype.push = function() {
return {
properties: {
_doStroke: this._doStroke,
_strokeSet: this._strokeSet,
_doFill: this._doFill,
_fillSet: this._fillSet,
_tint: this._tint,
_imageMode: this._imageMode,
_rectMode: this._rectMode,
_ellipseMode: this._ellipseMode,
_textFont: this._textFont,
_textLeading: this._textLeading,
_textSize: this._textSize,
_textAlign: this._textAlign,
_textBaseline: this._textBaseline,
_textStyle: this._textStyle
}
};
};
// a pop() operation is in progress
// the renderer is passed the 'style' object that it returned
// from its push() method.
_main.default.Renderer.prototype.pop = function(style) {
if (style.properties) {
// copy the style properties back into the renderer
Object.assign(this, style.properties);
}
};
/**
* Resize our canvas element.
*/
_main.default.Renderer.prototype.resize = function(w, h) {
this.width = w;
this.height = h;
this.elt.width = w * this._pInst._pixelDensity;
this.elt.height = h * this._pInst._pixelDensity;
this.elt.style.width = ''.concat(w, 'px');
this.elt.style.height = ''.concat(h, 'px');
if (this._isMainCanvas) {
this._pInst._setProperty('width', this.width);
this._pInst._setProperty('height', this.height);
}
};
_main.default.Renderer.prototype.get = function(x, y, w, h) {
var pixelsState = this._pixelsState;
var pd = pixelsState._pixelDensity;
var canvas = this.canvas;
if (typeof x === 'undefined' && typeof y === 'undefined') {
// get()
x = y = 0;
w = pixelsState.width;
h = pixelsState.height;
} else {
x *= pd;
y *= pd;
if (typeof w === 'undefined' && typeof h === 'undefined') {
// get(x,y)
if (x < 0 || y < 0 || x >= canvas.width || y >= canvas.height) {
return [0, 0, 0, 0];
}
return this._getPixel(x, y);
}
// get(x,y,w,h)
}
var region = new _main.default.Image(w, h);
region.canvas
.getContext('2d')
.drawImage(canvas, x, y, w * pd, h * pd, 0, 0, w, h);
return region;
};
_main.default.Renderer.prototype.textLeading = function(l) {
if (typeof l === 'number') {
this._setProperty('_textLeading', l);
return this._pInst;
}
return this._textLeading;
};
_main.default.Renderer.prototype.textSize = function(s) {
if (typeof s === 'number') {
this._setProperty('_textSize', s);
this._setProperty('_textLeading', s * constants._DEFAULT_LEADMULT);
return this._applyTextProperties();
}
return this._textSize;
};
_main.default.Renderer.prototype.textStyle = function(s) {
if (s) {
if (
s === constants.NORMAL ||
s === constants.ITALIC ||
s === constants.BOLD ||
s === constants.BOLDITALIC
) {
this._setProperty('_textStyle', s);
}
return this._applyTextProperties();
}
return this._textStyle;
};
_main.default.Renderer.prototype.textAscent = function() {
if (this._textAscent === null) {
this._updateTextMetrics();
}
return this._textAscent;
};
_main.default.Renderer.prototype.textDescent = function() {
if (this._textDescent === null) {
this._updateTextMetrics();
}
return this._textDescent;
};
_main.default.Renderer.prototype.textAlign = function(h, v) {
if (typeof h !== 'undefined') {
this._setProperty('_textAlign', h);
if (typeof v !== 'undefined') {
this._setProperty('_textBaseline', v);
}
return this._applyTextProperties();
} else {
return {
horizontal: this._textAlign,
vertical: this._textBaseline
};
}
};
_main.default.Renderer.prototype.text = function(str, x, y, maxWidth, maxHeight) {
var p = this._pInst;
var cars;
var n;
var ii;
var jj;
var line;
var testLine;
var testWidth;
var words;
var totalHeight;
var shiftedY;
var finalMaxHeight = Number.MAX_VALUE;
if (!(this._doFill || this._doStroke)) {
return;
}
if (typeof str === 'undefined') {
return;
} else if (typeof str !== 'string') {
str = str.toString();
}
str = str.replace(/(\t)/g, ' ');
cars = str.split('\n');
if (typeof maxWidth !== 'undefined') {
totalHeight = 0;
for (ii = 0; ii < cars.length; ii++) {
line = '';
words = cars[ii].split(' ');
for (n = 0; n < words.length; n++) {
testLine = ''.concat(line + words[n], ' ');
testWidth = this.textWidth(testLine);
if (testWidth > maxWidth) {
var currentWord = words[n];
for (var index = 0; index < currentWord.length; index++) {
testLine = ''.concat(line + currentWord[index]);
testWidth = this.textWidth(testLine);
if (testWidth > maxWidth && line.length > 0) {
line = ''.concat(currentWord[index]);
totalHeight += p.textLeading();
} else {
line = testLine;
}
}
line = ''.concat(line, ' ');
} else {
line = testLine;
}
}
if (ii < cars.length - 1) {
totalHeight += p.textLeading();
}
}
if (this._rectMode === constants.CENTER) {
x -= maxWidth / 2;
y -= maxHeight / 2;
}
switch (this._textAlign) {
case constants.CENTER:
x += maxWidth / 2;
break;
case constants.RIGHT:
x += maxWidth;
break;
}
var baselineHacked = false;
if (typeof maxHeight !== 'undefined') {
switch (this._textBaseline) {
case constants.BOTTOM:
shiftedY = y + (maxHeight - totalHeight);
y = Math.max(shiftedY, y);
break;
case constants.CENTER:
shiftedY = y + (maxHeight - totalHeight) / 2;
y = Math.max(shiftedY, y);
break;
case constants.BASELINE:
baselineHacked = true;
this._textBaseline = constants.TOP;
break;
}
// remember the max-allowed y-position for any line (fix to #928)
finalMaxHeight = y + maxHeight - p.textAscent();
}
for (ii = 0; ii < cars.length; ii++) {
line = '';
words = cars[ii].split(' ');
for (n = 0; n < words.length; n++) {
testLine = ''.concat(line + words[n], ' ');
testWidth = this.textWidth(testLine);
if (testWidth > maxWidth) {
var _currentWord = words[n];
for (var _index = 0; _index < _currentWord.length; _index++) {
testLine = ''.concat(line + _currentWord[_index]);
testWidth = this.textWidth(testLine);
if (testWidth > maxWidth && line.length > 0) {
var lastChar = line.slice(-1);
var shouldAddHyphen = lastChar !== '\n' && lastChar !== ' ';
line = ''.concat(line).concat(shouldAddHyphen ? '-' : '');
this._renderText(p, line, x, y, finalMaxHeight);
y += p.textLeading();
line = ''.concat(_currentWord[_index]);
} else {
line = testLine;
}
}
line = ''.concat(line, ' ');
} else {
line = testLine;
}
}
this._renderText(p, line, x, y, finalMaxHeight);
y += p.textLeading();
if (baselineHacked) {
this._textBaseline = constants.BASELINE;
}
}
} else {
// Offset to account for vertically centering multiple lines of text - no
// need to adjust anything for vertical align top or baseline
var offset = 0;
var vAlign = p.textAlign().vertical;
if (vAlign === constants.CENTER) {
offset = (cars.length - 1) * p.textLeading() / 2;
} else if (vAlign === constants.BOTTOM) {
offset = (cars.length - 1) * p.textLeading();
}
for (jj = 0; jj < cars.length; jj++) {
this._renderText(p, cars[jj], x, y - offset, finalMaxHeight);
y += p.textLeading();
}
}
return p;
};
_main.default.Renderer.prototype._applyDefaults = function() {
return this;
};
/**
* Helper fxn to check font type (system or otf)
*/
_main.default.Renderer.prototype._isOpenType = function() {
var f =
arguments.length > 0 && arguments[0] !== undefined
? arguments[0]
: this._textFont;
return _typeof(f) === 'object' && f.font && f.font.supported;
};
_main.default.Renderer.prototype._updateTextMetrics = function() {
if (this._isOpenType()) {
this._setProperty('_textAscent', this._textFont._textAscent());
this._setProperty('_textDescent', this._textFont._textDescent());
return this;
}
// Adapted from http://stackoverflow.com/a/25355178
var text = document.createElement('span');
text.style.fontFamily = this._textFont;
text.style.fontSize = ''.concat(this._textSize, 'px');
text.innerHTML = 'ABCjgq|';
var block = document.createElement('div');
block.style.display = 'inline-block';
block.style.width = '1px';
block.style.height = '0px';
var container = document.createElement('div');
container.appendChild(text);
container.appendChild(block);
container.style.height = '0px';
container.style.overflow = 'hidden';
document.body.appendChild(container);
block.style.verticalAlign = 'baseline';
var blockOffset = calculateOffset(block);
var textOffset = calculateOffset(text);
var ascent = blockOffset[1] - textOffset[1];
block.style.verticalAlign = 'bottom';
blockOffset = calculateOffset(block);
textOffset = calculateOffset(text);
var height = blockOffset[1] - textOffset[1];
var descent = height - ascent;
document.body.removeChild(container);
this._setProperty('_textAscent', ascent);
this._setProperty('_textDescent', descent);
return this;
};
/**
* Helper fxn to measure ascent and descent.
* Adapted from http://stackoverflow.com/a/25355178
*/
function calculateOffset(object) {
var currentLeft = 0,
currentTop = 0;
if (object.offsetParent) {
do {
currentLeft += object.offsetLeft;
currentTop += object.offsetTop;
} while ((object = object.offsetParent));
} else {
currentLeft += object.offsetLeft;
currentTop += object.offsetTop;
}
return [currentLeft, currentTop];
}
var _default = _main.default.Renderer;
exports.default = _default;
},
{ '../core/constants': 48, './main': 59 }
],
63: [
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 _filters = _interopRequireDefault(_dereq_('../image/filters'));
_dereq_('./p5.Renderer');
function _getRequireWildcardCache() {
if (typeof WeakMap !== 'function') return null;
var cache = new WeakMap();
_getRequireWildcardCache = function _getRequireWildcardCache() {
return cache;
};
return cache;
}
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
}
if (obj === null || (_typeof(obj) !== 'object' && typeof obj !== 'function')) {
return { default: obj };
}
var cache = _getRequireWildcardCache();
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* p5.Renderer2D
* The 2D graphics canvas renderer class.
* extends p5.Renderer
*/
var styleEmpty = 'rgba(0,0,0,0)';
// const alphaThreshold = 0.00125; // minimum visible
_main.default.Renderer2D = function(elt, pInst, isMainCanvas) {
_main.default.Renderer.call(this, elt, pInst, isMainCanvas);
this.drawingContext = this.canvas.getContext('2d');
this._pInst._setProperty('drawingContext', this.drawingContext);
return this;
};
_main.default.Renderer2D.prototype = Object.create(
_main.default.Renderer.prototype
);
_main.default.Renderer2D.prototype._applyDefaults = function() {
this._cachedFillStyle = this._cachedStrokeStyle = undefined;
this._cachedBlendMode = constants.BLEND;
this._setFill(constants._DEFAULT_FILL);
this._setStroke(constants._DEFAULT_STROKE);
this.drawingContext.lineCap = constants.ROUND;
this.drawingContext.font = 'normal 12px sans-serif';
};
_main.default.Renderer2D.prototype.resize = function(w, h) {
_main.default.Renderer.prototype.resize.call(this, w, h);
this.drawingContext.scale(this._pInst._pixelDensity, this._pInst._pixelDensity);
};
//////////////////////////////////////////////
// COLOR | Setting
//////////////////////////////////////////////
_main.default.Renderer2D.prototype.background = function() {
this.drawingContext.save();
this.resetMatrix();
if (
(arguments.length <= 0 ? undefined : arguments[0]) instanceof
_main.default.Image
) {
this._pInst.image(
arguments.length <= 0 ? undefined : arguments[0],
0,
0,
this.width,
this.height
);
} else {
var _this$_pInst;
var curFill = this._getFill();
// create background rect
var color = (_this$_pInst = this._pInst).color.apply(_this$_pInst, arguments);
//accessible Outputs
if (this._pInst._addAccsOutput()) {
this._pInst._accsBackground(color.levels);
}
var newFill = color.toString();
this._setFill(newFill);
if (this._isErasing) {
this.blendMode(this._cachedBlendMode);
}
this.drawingContext.fillRect(0, 0, this.width, this.height);
// reset fill
this._setFill(curFill);
if (this._isErasing) {
this._pInst.erase();
}
}
this.drawingContext.restore();
};
_main.default.Renderer2D.prototype.clear = function() {
this.drawingContext.save();
this.resetMatrix();
this.drawingContext.clearRect(0, 0, this.width, this.height);
this.drawingContext.restore();
};
_main.default.Renderer2D.prototype.fill = function() {
var _this$_pInst2;
var color = (_this$_pInst2 = this._pInst).color.apply(_this$_pInst2, arguments);
this._setFill(color.toString());
//accessible Outputs
if (this._pInst._addAccsOutput()) {
this._pInst._accsCanvasColors('fill', color.levels);
}
};
_main.default.Renderer2D.prototype.stroke = function() {
var _this$_pInst3;
var color = (_this$_pInst3 = this._pInst).color.apply(_this$_pInst3, arguments);
this._setStroke(color.toString());
//accessible Outputs
if (this._pInst._addAccsOutput()) {
this._pInst._accsCanvasColors('stroke', color.levels);
}
};
_main.default.Renderer2D.prototype.erase = function(opacityFill, opacityStroke) {
if (!this._isErasing) {
// cache the fill style
this._cachedFillStyle = this.drawingContext.fillStyle;
var newFill = this._pInst.color(255, opacityFill).toString();
this.drawingContext.fillStyle = newFill;
//cache the stroke style
this._cachedStrokeStyle = this.drawingContext.strokeStyle;
var newStroke = this._pInst.color(255, opacityStroke).toString();
this.drawingContext.strokeStyle = newStroke;
//cache blendMode
var tempBlendMode = this._cachedBlendMode;
this.blendMode(constants.REMOVE);
this._cachedBlendMode = tempBlendMode;
this._isErasing = true;
}
};
_main.default.Renderer2D.prototype.noErase = function() {
if (this._isErasing) {
this.drawingContext.fillStyle = this._cachedFillStyle;
this.drawingContext.strokeStyle = this._cachedStrokeStyle;
this.blendMode(this._cachedBlendMode);
this._isErasing = false;
}
};
//////////////////////////////////////////////
// IMAGE | Loading & Displaying
//////////////////////////////////////////////
_main.default.Renderer2D.prototype.image = function(
img,
sx,
sy,
sWidth,
sHeight,
dx,
dy,
dWidth,
dHeight
) {
var cnv;
if (img.gifProperties) {
img._animateGif(this._pInst);
}
try {
if (this._tint) {
if (
_main.default.MediaElement &&
img instanceof _main.default.MediaElement
) {
img.loadPixels();
}
if (img.canvas) {
cnv = this._getTintedImageCanvas(img);
}
}
if (!cnv) {
cnv = img.canvas || img.elt;
}
var s = 1;
if (img.width && img.width > 0) {
s = cnv.width / img.width;
}
if (this._isErasing) {
this.blendMode(this._cachedBlendMode);
}
this.drawingContext.drawImage(
cnv,
s * sx,
s * sy,
s * sWidth,
s * sHeight,
dx,
dy,
dWidth,
dHeight
);
if (this._isErasing) {
this._pInst.erase();
}
} catch (e) {
if (e.name !== 'NS_ERROR_NOT_AVAILABLE') {
throw e;
}
}
};
_main.default.Renderer2D.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._tint[0] / 255;
newPixels[i + 1] = g * this._tint[1] / 255;
newPixels[i + 2] = b * this._tint[2] / 255;
newPixels[i + 3] = a * this._tint[3] / 255;
}
tmpCtx.putImageData(id, 0, 0);
return tmpCanvas;
};
//////////////////////////////////////////////
// IMAGE | Pixels
//////////////////////////////////////////////
_main.default.Renderer2D.prototype.blendMode = function(mode) {
if (mode === constants.SUBTRACT) {
console.warn('blendMode(SUBTRACT) only works in WEBGL mode.');
} else if (
mode === constants.BLEND ||
mode === constants.REMOVE ||
mode === constants.DARKEST ||
mode === constants.LIGHTEST ||
mode === constants.DIFFERENCE ||
mode === constants.MULTIPLY ||
mode === constants.EXCLUSION ||
mode === constants.SCREEN ||
mode === constants.REPLACE ||
mode === constants.OVERLAY ||
mode === constants.HARD_LIGHT ||
mode === constants.SOFT_LIGHT ||
mode === constants.DODGE ||
mode === constants.BURN ||
mode === constants.ADD
) {
this._cachedBlendMode = mode;
this.drawingContext.globalCompositeOperation = mode;
} else {
throw new Error('Mode '.concat(mode, ' not recognized.'));
}
};
_main.default.Renderer2D.prototype.blend = function() {
var currBlend = this.drawingContext.globalCompositeOperation;
for (
var _len = arguments.length, args = new Array(_len), _key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
var blendMode = args[args.length - 1];
var copyArgs = Array.prototype.slice.call(args, 0, args.length - 1);
this.drawingContext.globalCompositeOperation = blendMode;
_main.default.prototype.copy.apply(this, copyArgs);
this.drawingContext.globalCompositeOperation = currBlend;
};
// p5.Renderer2D.prototype.get = p5.Renderer.prototype.get;
// .get() is not overridden
// x,y are canvas-relative (pre-scaled by _pixelDensity)
_main.default.Renderer2D.prototype._getPixel = function(x, y) {
var imageData, index;
imageData = this.drawingContext.getImageData(x, y, 1, 1).data;
index = 0;
return [
imageData[index + 0],
imageData[index + 1],
imageData[index + 2],
imageData[index + 3]
];
};
_main.default.Renderer2D.prototype.loadPixels = function() {
var pixelsState = this._pixelsState; // if called by p5.Image
var pd = pixelsState._pixelDensity;
var w = this.width * pd;
var h = this.height * pd;
var imageData = this.drawingContext.getImageData(0, 0, w, h);
// @todo this should actually set pixels per object, so diff buffers can
// have diff pixel arrays.
pixelsState._setProperty('imageData', imageData);
pixelsState._setProperty('pixels', imageData.data);
};
_main.default.Renderer2D.prototype.set = function(x, y, imgOrCol) {
// round down to get integer numbers
x = Math.floor(x);
y = Math.floor(y);
var pixelsState = this._pixelsState;
if (imgOrCol instanceof _main.default.Image) {
this.drawingContext.save();
this.drawingContext.setTransform(1, 0, 0, 1, 0, 0);
this.drawingContext.scale(
pixelsState._pixelDensity,
pixelsState._pixelDensity
);
this.drawingContext.clearRect(x, y, imgOrCol.width, imgOrCol.height);
this.drawingContext.drawImage(imgOrCol.canvas, x, y);
this.drawingContext.restore();
} else {
var r = 0,
g = 0,
b = 0,
a = 0;
var idx =
4 *
(y * pixelsState._pixelDensity * (this.width * pixelsState._pixelDensity) +
x * pixelsState._pixelDensity);
if (!pixelsState.imageData) {
pixelsState.loadPixels.call(pixelsState);
}
if (typeof imgOrCol === 'number') {
if (idx < pixelsState.pixels.length) {
r = imgOrCol;
g = imgOrCol;
b = imgOrCol;
a = 255;
//this.updatePixels.call(this);
}
} else if (imgOrCol instanceof Array) {
if (imgOrCol.length < 4) {
throw new Error('pixel array must be of the form [R, G, B, A]');
}
if (idx < pixelsState.pixels.length) {
r = imgOrCol[0];
g = imgOrCol[1];
b = imgOrCol[2];
a = imgOrCol[3];
//this.updatePixels.call(this);
}
} else if (imgOrCol instanceof _main.default.Color) {
if (idx < pixelsState.pixels.length) {
r = imgOrCol.levels[0];
g = imgOrCol.levels[1];
b = imgOrCol.levels[2];
a = imgOrCol.levels[3];
//this.updatePixels.call(this);
}
}
// loop over pixelDensity * pixelDensity
for (var i = 0; i < pixelsState._pixelDensity; i++) {
for (var j = 0; j < pixelsState._pixelDensity; j++) {
// loop over
idx =
4 *
((y * pixelsState._pixelDensity + j) *
this.width *
pixelsState._pixelDensity +
(x * pixelsState._pixelDensity + i));
pixelsState.pixels[idx] = r;
pixelsState.pixels[idx + 1] = g;
pixelsState.pixels[idx + 2] = b;
pixelsState.pixels[idx + 3] = a;
}
}
}
};
_main.default.Renderer2D.prototype.updatePixels = function(x, y, w, h) {
var pixelsState = this._pixelsState;
var pd = pixelsState._pixelDensity;
if (x === undefined && y === undefined && w === undefined && h === undefined) {
x = 0;
y = 0;
w = this.width;
h = this.height;
}
x *= pd;
y *= pd;
w *= pd;
h *= pd;
if (this.gifProperties) {
this.gifProperties.frames[this.gifProperties.displayIndex].image =
pixelsState.imageData;
}
this.drawingContext.putImageData(pixelsState.imageData, x, y, 0, 0, w, h);
};
//////////////////////////////////////////////
// SHAPE | 2D Primitives
//////////////////////////////////////////////
/**
* Generate a cubic Bezier representing an arc on the unit circle of total
* angle `size` radians, beginning `start` radians above the x-axis. Up to
* four of these curves are combined to make a full arc.
*
* See www.joecridge.me/bezier.pdf for an explanation of the method.
*/
_main.default.Renderer2D.prototype._acuteArcToBezier = function _acuteArcToBezier(
start,
size
) {
// Evaluate constants.
var alpha = size / 2.0,
cos_alpha = Math.cos(alpha),
sin_alpha = Math.sin(alpha),
cot_alpha = 1.0 / Math.tan(alpha),
// This is how far the arc needs to be rotated.
phi = start + alpha,
cos_phi = Math.cos(phi),
sin_phi = Math.sin(phi),
lambda = (4.0 - cos_alpha) / 3.0,
mu = sin_alpha + (cos_alpha - lambda) * cot_alpha;
// Return rotated waypoints.
return {
ax: Math.cos(start).toFixed(7),
ay: Math.sin(start).toFixed(7),
bx: (lambda * cos_phi + mu * sin_phi).toFixed(7),
by: (lambda * sin_phi - mu * cos_phi).toFixed(7),
cx: (lambda * cos_phi - mu * sin_phi).toFixed(7),
cy: (lambda * sin_phi + mu * cos_phi).toFixed(7),
dx: Math.cos(start + size).toFixed(7),
dy: Math.sin(start + size).toFixed(7)
};
};
/*
* This function requires that:
*
* 0 <= start < TWO_PI
*
* start <= stop < start + TWO_PI
*/
_main.default.Renderer2D.prototype.arc = function(x, y, w, h, start, stop, mode) {
var ctx = this.drawingContext;
var rx = w / 2.0;
var ry = h / 2.0;
var epsilon = 0.00001; // Smallest visible angle on displays up to 4K.
var arcToDraw = 0;
var curves = [];
x += rx;
y += ry;
// Create curves
while (stop - start >= epsilon) {
arcToDraw = Math.min(stop - start, constants.HALF_PI);
curves.push(this._acuteArcToBezier(start, arcToDraw));
start += arcToDraw;
}
// Fill curves
if (this._doFill) {
ctx.beginPath();
curves.forEach(function(curve, index) {
if (index === 0) {
ctx.moveTo(x + curve.ax * rx, y + curve.ay * ry);
}
// prettier-ignore
ctx.bezierCurveTo(x + curve.bx * rx, y + curve.by * ry,
x + curve.cx * rx, y + curve.cy * ry,
x + curve.dx * rx, y + curve.dy * ry);
});
if (mode === constants.PIE || mode == null) {
ctx.lineTo(x, y);
}
ctx.closePath();
ctx.fill();
}
// Stroke curves
if (this._doStroke) {
ctx.beginPath();
curves.forEach(function(curve, index) {
if (index === 0) {
ctx.moveTo(x + curve.ax * rx, y + curve.ay * ry);
}
// prettier-ignore
ctx.bezierCurveTo(x + curve.bx * rx, y + curve.by * ry,
x + curve.cx * rx, y + curve.cy * ry,
x + curve.dx * rx, y + curve.dy * ry);
});
if (mode === constants.PIE) {
ctx.lineTo(x, y);
ctx.closePath();
} else if (mode === constants.CHORD) {
ctx.closePath();
}
ctx.stroke();
}
return this;
};
_main.default.Renderer2D.prototype.ellipse = function(args) {
var ctx = this.drawingContext;
var doFill = this._doFill,
doStroke = this._doStroke;
var x = parseFloat(args[0]),
y = parseFloat(args[1]),
w = parseFloat(args[2]),
h = parseFloat(args[3]);
if (doFill && !doStroke) {
if (this._getFill() === styleEmpty) {
return this;
}
} else if (!doFill && doStroke) {
if (this._getStroke() === styleEmpty) {
return this;
}
}
var kappa = 0.5522847498,
// control point offset horizontal
ox = w / 2 * kappa,
// control point offset vertical
oy = h / 2 * kappa,
// x-end
xe = x + w,
// y-end
ye = y + h,
// x-middle
xm = x + w / 2,
ym = y + h / 2; // y-middle
ctx.beginPath();
ctx.moveTo(x, ym);
ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
if (doFill) {
ctx.fill();
}
if (doStroke) {
ctx.stroke();
}
};
_main.default.Renderer2D.prototype.line = function(x1, y1, x2, y2) {
var ctx = this.drawingContext;
if (!this._doStroke) {
return this;
} else if (this._getStroke() === styleEmpty) {
return this;
}
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
return this;
};
_main.default.Renderer2D.prototype.point = function(x, y) {
var ctx = this.drawingContext;
if (!this._doStroke) {
return this;
} else if (this._getStroke() === styleEmpty) {
return this;
}
var s = this._getStroke();
var f = this._getFill();
x = Math.round(x);
y = Math.round(y);
// swapping fill color to stroke and back after for correct point rendering
this._setFill(s);
if (ctx.lineWidth > 1) {
ctx.beginPath();
ctx.arc(x, y, ctx.lineWidth / 2, 0, constants.TWO_PI, false);
ctx.fill();
} else {
ctx.fillRect(x, y, 1, 1);
}
this._setFill(f);
};
_main.default.Renderer2D.prototype.quad = function(
x1,
y1,
x2,
y2,
x3,
y3,
x4,
y4
) {
var ctx = this.drawingContext;
var doFill = this._doFill,
doStroke = this._doStroke;
if (doFill && !doStroke) {
if (this._getFill() === styleEmpty) {
return this;
}
} else if (!doFill && doStroke) {
if (this._getStroke() === styleEmpty) {
return this;
}
}
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.lineTo(x3, y3);
ctx.lineTo(x4, y4);
ctx.closePath();
if (doFill) {
ctx.fill();
}
if (doStroke) {
ctx.stroke();
}
return this;
};
_main.default.Renderer2D.prototype.rect = function(args) {
var x = args[0];
var y = args[1];
var w = args[2];
var h = args[3];
var tl = args[4];
var tr = args[5];
var br = args[6];
var bl = args[7];
var ctx = this.drawingContext;
var doFill = this._doFill,
doStroke = this._doStroke;
if (doFill && !doStroke) {
if (this._getFill() === styleEmpty) {
return this;
}
} else if (!doFill && doStroke) {
if (this._getStroke() === styleEmpty) {
return this;
}
}
ctx.beginPath();
if (typeof tl === 'undefined') {
// No rounded corners
ctx.rect(x, y, w, h);
} else {
// At least one rounded corner
// Set defaults when not specified
if (typeof tr === 'undefined') {
tr = tl;
}
if (typeof br === 'undefined') {
br = tr;
}
if (typeof bl === 'undefined') {
bl = br;
}
// corner rounding must always be positive
var absW = Math.abs(w);
var absH = Math.abs(h);
var hw = absW / 2;
var hh = absH / 2;
// Clip radii
if (absW < 2 * tl) {
tl = hw;
}
if (absH < 2 * tl) {
tl = hh;
}
if (absW < 2 * tr) {
tr = hw;
}
if (absH < 2 * tr) {
tr = hh;
}
if (absW < 2 * br) {
br = hw;
}
if (absH < 2 * br) {
br = hh;
}
if (absW < 2 * bl) {
bl = hw;
}
if (absH < 2 * bl) {
bl = hh;
}
// Draw shape
ctx.beginPath();
ctx.moveTo(x + tl, y);
ctx.arcTo(x + w, y, x + w, y + h, tr);
ctx.arcTo(x + w, y + h, x, y + h, br);
ctx.arcTo(x, y + h, x, y, bl);
ctx.arcTo(x, y, x + w, y, tl);
ctx.closePath();
}
if (this._doFill) {
ctx.fill();
}
if (this._doStroke) {
ctx.stroke();
}
return this;
};
_main.default.Renderer2D.prototype.triangle = function(args) {
var ctx = this.drawingContext;
var doFill = this._doFill,
doStroke = this._doStroke;
var x1 = args[0],
y1 = args[1];
var x2 = args[2],
y2 = args[3];
var x3 = args[4],
y3 = args[5];
if (doFill && !doStroke) {
if (this._getFill() === styleEmpty) {
return this;
}
} else if (!doFill && doStroke) {
if (this._getStroke() === styleEmpty) {
return this;
}
}
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.lineTo(x3, y3);
ctx.closePath();
if (doFill) {
ctx.fill();
}
if (doStroke) {
ctx.stroke();
}
};
_main.default.Renderer2D.prototype.endShape = function(
mode,
vertices,
isCurve,
isBezier,
isQuadratic,
isContour,
shapeKind
) {
if (vertices.length === 0) {
return this;
}
if (!this._doStroke && !this._doFill) {
return this;
}
var closeShape = mode === constants.CLOSE;
var v;
if (closeShape && !isContour) {
vertices.push(vertices[0]);
}
var i, j;
var numVerts = vertices.length;
if (isCurve && (shapeKind === constants.POLYGON || shapeKind === null)) {
if (numVerts > 3) {
var b = [],
s = 1 - this._curveTightness;
this.drawingContext.beginPath();
this.drawingContext.moveTo(vertices[1][0], vertices[1][1]);
for (i = 1; i + 2 < numVerts; i++) {
v = vertices[i];
b[0] = [v[0], v[1]];
b[1] = [
v[0] + (s * vertices[i + 1][0] - s * vertices[i - 1][0]) / 6,
v[1] + (s * vertices[i + 1][1] - s * vertices[i - 1][1]) / 6
];
b[2] = [
vertices[i + 1][0] + (s * vertices[i][0] - s * vertices[i + 2][0]) / 6,
vertices[i + 1][1] + (s * vertices[i][1] - s * vertices[i + 2][1]) / 6
];
b[3] = [vertices[i + 1][0], vertices[i + 1][1]];
this.drawingContext.bezierCurveTo(
b[1][0],
b[1][1],
b[2][0],
b[2][1],
b[3][0],
b[3][1]
);
}
if (closeShape) {
this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]);
}
this._doFillStrokeClose(closeShape);
}
} else if (
isBezier &&
(shapeKind === constants.POLYGON || shapeKind === null)
) {
this.drawingContext.beginPath();
for (i = 0; i < numVerts; i++) {
if (vertices[i].isVert) {
if (vertices[i].moveTo) {
this.drawingContext.moveTo(vertices[i][0], vertices[i][1]);
} else {
this.drawingContext.lineTo(vertices[i][0], vertices[i][1]);
}
} else {
this.drawingContext.bezierCurveTo(
vertices[i][0],
vertices[i][1],
vertices[i][2],
vertices[i][3],
vertices[i][4],
vertices[i][5]
);
}
}
this._doFillStrokeClose(closeShape);
} else if (
isQuadratic &&
(shapeKind === constants.POLYGON || shapeKind === null)
) {
this.drawingContext.beginPath();
for (i = 0; i < numVerts; i++) {
if (vertices[i].isVert) {
if (vertices[i].moveTo) {
this.drawingContext.moveTo(vertices[i][0], vertices[i][1]);
} else {
this.drawingContext.lineTo(vertices[i][0], vertices[i][1]);
}
} else {
this.drawingContext.quadraticCurveTo(
vertices[i][0],
vertices[i][1],
vertices[i][2],
vertices[i][3]
);
}
}
this._doFillStrokeClose(closeShape);
} else {
if (shapeKind === constants.POINTS) {
for (i = 0; i < numVerts; i++) {
v = vertices[i];
if (this._doStroke) {
this._pInst.stroke(v[6]);
}
this._pInst.point(v[0], v[1]);
}
} else if (shapeKind === constants.LINES) {
for (i = 0; i + 1 < numVerts; i += 2) {
v = vertices[i];
if (this._doStroke) {
this._pInst.stroke(vertices[i + 1][6]);
}
this._pInst.line(v[0], v[1], vertices[i + 1][0], vertices[i + 1][1]);
}
} else if (shapeKind === constants.TRIANGLES) {
for (i = 0; i + 2 < numVerts; i += 3) {
v = vertices[i];
this.drawingContext.beginPath();
this.drawingContext.moveTo(v[0], v[1]);
this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]);
this.drawingContext.lineTo(vertices[i + 2][0], vertices[i + 2][1]);
this.drawingContext.closePath();
if (this._doFill) {
this._pInst.fill(vertices[i + 2][5]);
this.drawingContext.fill();
}
if (this._doStroke) {
this._pInst.stroke(vertices[i + 2][6]);
this.drawingContext.stroke();
}
}
} else if (shapeKind === constants.TRIANGLE_STRIP) {
for (i = 0; i + 1 < numVerts; i++) {
v = vertices[i];
this.drawingContext.beginPath();
this.drawingContext.moveTo(vertices[i + 1][0], vertices[i + 1][1]);
this.drawingContext.lineTo(v[0], v[1]);
if (this._doStroke) {
this._pInst.stroke(vertices[i + 1][6]);
}
if (this._doFill) {
this._pInst.fill(vertices[i + 1][5]);
}
if (i + 2 < numVerts) {
this.drawingContext.lineTo(vertices[i + 2][0], vertices[i + 2][1]);
if (this._doStroke) {
this._pInst.stroke(vertices[i + 2][6]);
}
if (this._doFill) {
this._pInst.fill(vertices[i + 2][5]);
}
}
this._doFillStrokeClose(closeShape);
}
} else if (shapeKind === constants.TRIANGLE_FAN) {
if (numVerts > 2) {
// For performance reasons, try to batch as many of the
// fill and stroke calls as possible.
this.drawingContext.beginPath();
for (i = 2; i < numVerts; i++) {
v = vertices[i];
this.drawingContext.moveTo(vertices[0][0], vertices[0][1]);
this.drawingContext.lineTo(vertices[i - 1][0], vertices[i - 1][1]);
this.drawingContext.lineTo(v[0], v[1]);
this.drawingContext.lineTo(vertices[0][0], vertices[0][1]);
// If the next colour is going to be different, stroke / fill now
if (i < numVerts - 1) {
if (
(this._doFill && v[5] !== vertices[i + 1][5]) ||
(this._doStroke && v[6] !== vertices[i + 1][6])
) {
if (this._doFill) {
this._pInst.fill(v[5]);
this.drawingContext.fill();
this._pInst.fill(vertices[i + 1][5]);
}
if (this._doStroke) {
this._pInst.stroke(v[6]);
this.drawingContext.stroke();
this._pInst.stroke(vertices[i + 1][6]);
}
this.drawingContext.closePath();
this.drawingContext.beginPath(); // Begin the next one
}
}
}
this._doFillStrokeClose(closeShape);
}
} else if (shapeKind === constants.QUADS) {
for (i = 0; i + 3 < numVerts; i += 4) {
v = vertices[i];
this.drawingContext.beginPath();
this.drawingContext.moveTo(v[0], v[1]);
for (j = 1; j < 4; j++) {
this.drawingContext.lineTo(vertices[i + j][0], vertices[i + j][1]);
}
this.drawingContext.lineTo(v[0], v[1]);
if (this._doFill) {
this._pInst.fill(vertices[i + 3][5]);
}
if (this._doStroke) {
this._pInst.stroke(vertices[i + 3][6]);
}
this._doFillStrokeClose(closeShape);
}
} else if (shapeKind === constants.QUAD_STRIP) {
if (numVerts > 3) {
for (i = 0; i + 1 < numVerts; i += 2) {
v = vertices[i];
this.drawingContext.beginPath();
if (i + 3 < numVerts) {
this.drawingContext.moveTo(vertices[i + 2][0], vertices[i + 2][1]);
this.drawingContext.lineTo(v[0], v[1]);
this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]);
this.drawingContext.lineTo(vertices[i + 3][0], vertices[i + 3][1]);
if (this._doFill) {
this._pInst.fill(vertices[i + 3][5]);
}
if (this._doStroke) {
this._pInst.stroke(vertices[i + 3][6]);
}
} else {
this.drawingContext.moveTo(v[0], v[1]);
this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]);
}
this._doFillStrokeClose(closeShape);
}
}
} else {
this.drawingContext.beginPath();
this.drawingContext.moveTo(vertices[0][0], vertices[0][1]);
for (i = 1; i < numVerts; i++) {
v = vertices[i];
if (v.isVert) {
if (v.moveTo) {
this.drawingContext.moveTo(v[0], v[1]);
} else {
this.drawingContext.lineTo(v[0], v[1]);
}
}
}
this._doFillStrokeClose(closeShape);
}
}
isCurve = false;
isBezier = false;
isQuadratic = false;
isContour = false;
if (closeShape) {
vertices.pop();
}
return this;
};
//////////////////////////////////////////////
// SHAPE | Attributes
//////////////////////////////////////////////
_main.default.Renderer2D.prototype.strokeCap = function(cap) {
if (
cap === constants.ROUND ||
cap === constants.SQUARE ||
cap === constants.PROJECT
) {
this.drawingContext.lineCap = cap;
}
return this;
};
_main.default.Renderer2D.prototype.strokeJoin = function(join) {
if (
join === constants.ROUND ||
join === constants.BEVEL ||
join === constants.MITER
) {
this.drawingContext.lineJoin = join;
}
return this;
};
_main.default.Renderer2D.prototype.strokeWeight = function(w) {
if (typeof w === 'undefined' || w === 0) {
// hack because lineWidth 0 doesn't work
this.drawingContext.lineWidth = 0.0001;
} else {
this.drawingContext.lineWidth = w;
}
return this;
};
_main.default.Renderer2D.prototype._getFill = function() {
if (!this._cachedFillStyle) {
this._cachedFillStyle = this.drawingContext.fillStyle;
}
return this._cachedFillStyle;
};
_main.default.Renderer2D.prototype._setFill = function(fillStyle) {
if (fillStyle !== this._cachedFillStyle) {
this.drawingContext.fillStyle = fillStyle;
this._cachedFillStyle = fillStyle;
}
};
_main.default.Renderer2D.prototype._getStroke = function() {
if (!this._cachedStrokeStyle) {
this._cachedStrokeStyle = this.drawingContext.strokeStyle;
}
return this._cachedStrokeStyle;
};
_main.default.Renderer2D.prototype._setStroke = function(strokeStyle) {
if (strokeStyle !== this._cachedStrokeStyle) {
this.drawingContext.strokeStyle = strokeStyle;
this._cachedStrokeStyle = strokeStyle;
}
};
//////////////////////////////////////////////
// SHAPE | Curves
//////////////////////////////////////////////
_main.default.Renderer2D.prototype.bezier = function(
x1,
y1,
x2,
y2,
x3,
y3,
x4,
y4
) {
this._pInst.beginShape();
this._pInst.vertex(x1, y1);
this._pInst.bezierVertex(x2, y2, x3, y3, x4, y4);
this._pInst.endShape();
return this;
};
_main.default.Renderer2D.prototype.curve = function(
x1,
y1,
x2,
y2,
x3,
y3,
x4,
y4
) {
this._pInst.beginShape();
this._pInst.curveVertex(x1, y1);
this._pInst.curveVertex(x2, y2);
this._pInst.curveVertex(x3, y3);
this._pInst.curveVertex(x4, y4);
this._pInst.endShape();
return this;
};
//////////////////////////////////////////////
// SHAPE | Vertex
//////////////////////////////////////////////
_main.default.Renderer2D.prototype._doFillStrokeClose = function(closeShape) {
if (closeShape) {
this.drawingContext.closePath();
}
if (this._doFill) {
this.drawingContext.fill();
}
if (this._doStroke) {
this.drawingContext.stroke();
}
};
//////////////////////////////////////////////
// TRANSFORM
//////////////////////////////////////////////
_main.default.Renderer2D.prototype.applyMatrix = function(a, b, c, d, e, f) {
this.drawingContext.transform(a, b, c, d, e, f);
};
_main.default.Renderer2D.prototype.resetMatrix = function() {
this.drawingContext.setTransform(1, 0, 0, 1, 0, 0);
this.drawingContext.scale(this._pInst._pixelDensity, this._pInst._pixelDensity);
return this;
};
_main.default.Renderer2D.prototype.rotate = function(rad) {
this.drawingContext.rotate(rad);
};
_main.default.Renderer2D.prototype.scale = function(x, y) {
this.drawingContext.scale(x, y);
return this;
};
_main.default.Renderer2D.prototype.translate = function(x, y) {
// support passing a vector as the 1st parameter
if (x instanceof _main.default.Vector) {
y = x.y;
x = x.x;
}
this.drawingContext.translate(x, y);
return this;
};
//////////////////////////////////////////////
// TYPOGRAPHY
//
//////////////////////////////////////////////
_main.default.Renderer2D.prototype.text = function(
str,
x,
y,
maxWidth,
maxHeight
) {
var baselineHacked;
// baselineHacked: (HACK)
// A temporary fix to conform to Processing's implementation
// of BASELINE vertical alignment in a bounding box
if (typeof maxWidth !== 'undefined') {
if (this.drawingContext.textBaseline === constants.BASELINE) {
baselineHacked = true;
this.drawingContext.textBaseline = constants.TOP;
}
}
var p = _main.default.Renderer.prototype.text.apply(this, arguments);
if (baselineHacked) {
this.drawingContext.textBaseline = constants.BASELINE;
}
return p;
};
_main.default.Renderer2D.prototype._renderText = function(p, line, x, y, maxY) {
if (y >= maxY) {
return; // don't render lines beyond our maxY position
}
p.push(); // fix to #803
if (!this._isOpenType()) {
// a system/browser font
// no stroke unless specified by user
if (this._doStroke && this._strokeSet) {
this.drawingContext.strokeText(line, x, y);
}
if (this._doFill) {
// if fill hasn't been set by user, use default text fill
if (!this._fillSet) {
this._setFill(constants._DEFAULT_TEXT_FILL);
}
this.drawingContext.fillText(line, x, y);
}
} else {
// an opentype font, let it handle the rendering
this._textFont._renderPath(line, x, y, { renderer: this });
}
p.pop();
return p;
};
_main.default.Renderer2D.prototype.textWidth = function(s) {
if (this._isOpenType()) {
return this._textFont._textWidth(s, this._textSize);
}
return this.drawingContext.measureText(s).width;
};
_main.default.Renderer2D.prototype._applyTextProperties = function() {
var font;
var p = this._pInst;
this._setProperty('_textAscent', null);
this._setProperty('_textDescent', null);
font = this._textFont;
if (this._isOpenType()) {
font = this._textFont.font.familyName;
this._setProperty('_textStyle', this._textFont.font.styleName);
}
this.drawingContext.font = ''
.concat(this._textStyle || 'normal', ' ')
.concat(this._textSize || 12, 'px ')
.concat(font || 'sans-serif');
this.drawingContext.textAlign = this._textAlign;
if (this._textBaseline === constants.CENTER) {
this.drawingContext.textBaseline = constants._CTX_MIDDLE;
} else {
this.drawingContext.textBaseline = this._textBaseline;
}
return p;
};
//////////////////////////////////////////////
// STRUCTURE
//////////////////////////////////////////////
// a push() operation is in progress.
// the renderer should return a 'style' object that it wishes to
// store on the push stack.
// derived renderers should call the base class' push() method
// to fetch the base style object.
_main.default.Renderer2D.prototype.push = function() {
this.drawingContext.save();
// get the base renderer style
return _main.default.Renderer.prototype.push.apply(this);
};
// a pop() operation is in progress
// the renderer is passed the 'style' object that it returned
// from its push() method.
// derived renderers should pass this object to their base
// class' pop method
_main.default.Renderer2D.prototype.pop = function(style) {
this.drawingContext.restore();
// Re-cache the fill / stroke state
this._cachedFillStyle = this.drawingContext.fillStyle;
this._cachedStrokeStyle = this.drawingContext.strokeStyle;
_main.default.Renderer.prototype.pop.call(this, style);
};
var _default = _main.default.Renderer2D;
exports.default = _default;
},
{ '../image/filters': 80, './constants': 48, './main': 59, './p5.Renderer': 62 }
],
64: [
function(_dereq_, module, exports) {
'use strict';
var _main = _interopRequireDefault(_dereq_('./main'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
_main.default.prototype._promisePreloads = [
/* Example object
{
target: p5.prototype, // The target object to have the method modified
method: 'loadXAsync', // The name of the preload function to wrap
addCallbacks: true, // Whether to automatically handle the p5 callbacks
legacyPreloadSetup: { // Optional object to generate a legacy-style preload
method: 'loadX', // The name of the legacy preload function to generate
createBaseObject: function() {
return {};
} // An optional function to create the base object for the legacy preload.
}
}
*/
];
_main.default.prototype.registerPromisePreload = function(setup) {
_main.default.prototype._promisePreloads.push(setup);
};
var initialSetupRan = false;
_main.default.prototype._setupPromisePreloads = function() {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (
var _iterator = this._promisePreloads[Symbol.iterator](), _step;
!(_iteratorNormalCompletion = (_step = _iterator.next()).done);
_iteratorNormalCompletion = true
) {
var preloadSetup = _step.value;
var thisValue = this;
var method = preloadSetup.method,
addCallbacks = preloadSetup.addCallbacks,
legacyPreloadSetup = preloadSetup.legacyPreloadSetup;
// Get the target object that the preload gets assigned to by default,
// that is the current object.
var target = preloadSetup.target || this;
var sourceFunction = target[method].bind(target);
// If the target is the p5 prototype, then only set it up on the first run per page
if (target === _main.default.prototype) {
if (initialSetupRan) {
continue;
}
thisValue = null;
sourceFunction = target[method];
}
// Replace the original method with a wrapped version
target[method] = this._wrapPromisePreload(
thisValue,
sourceFunction,
addCallbacks
);
// If a legacy preload is required
if (legacyPreloadSetup) {
// What is the name for this legacy preload
var legacyMethod = legacyPreloadSetup.method;
// Wrap the already wrapped Promise-returning method with the legacy setup
target[legacyMethod] = this._legacyPreloadGenerator(
thisValue,
legacyPreloadSetup,
target[method]
);
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
initialSetupRan = true;
};
_main.default.prototype._wrapPromisePreload = function(
thisValue,
fn,
addCallbacks
) {
var replacementFunction = function replacementFunction() {
var _this = this;
// Uses the current preload counting mechanism for now.
this._incrementPreload();
// A variable for the callback function if specified
var callback = null;
// A variable for the errorCallback function if specified
var errorCallback = null;
for (
var _len = arguments.length, args = new Array(_len), _key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
if (addCallbacks) {
// Loop from the end of the args array, pulling up to two functions off of
// the end and putting them in fns
for (var i = args.length - 1; i >= 0 && !errorCallback; i--) {
if (typeof args[i] !== 'function') {
break;
}
errorCallback = callback;
callback = args.pop();
}
}
// Call the underlying funciton and pass it to Promise.resolve,
// so that even if it didn't return a promise we can still
// act on the result as if it did.
var promise = Promise.resolve(fn.apply(this, args));
// Add the optional callbacks
if (callback) {
promise.then(callback);
}
if (errorCallback) {
promise.catch(errorCallback);
}
// Decrement the preload counter only if the promise resolved
promise.then(function() {
return _this._decrementPreload();
});
// Return the original promise so that neither callback changes the result.
return promise;
};
if (thisValue) {
replacementFunction = replacementFunction.bind(thisValue);
}
return replacementFunction;
};
var objectCreator = function objectCreator() {
return {};
};
_main.default.prototype._legacyPreloadGenerator = function(
thisValue,
legacyPreloadSetup,
fn
) {
// Create a function that will generate an object before the preload is
// launched. For example, if the object should be an array or be an instance
// of a specific class.
var baseValueGenerator = legacyPreloadSetup.createBaseObject || objectCreator;
var returnedFunction = function returnedFunction() {
var _this2 = this;
// Our then clause needs to run before setup, so we also increment the preload counter
this._incrementPreload();
// Generate the return value based on the generator.
var returnValue = baseValueGenerator.apply(this, arguments);
// Run the original wrapper
fn.apply(this, arguments).then(function(data) {
// Copy each key from the resolved value into returnValue
Object.assign(returnValue, data);
// Decrement the preload counter, to allow setup to continue.
_this2._decrementPreload();
});
return returnValue;
};
if (thisValue) {
returnedFunction = returnedFunction.bind(thisValue);
}
return returnedFunction;
};
},
{ './main': 59 }
],
65: [
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'));
_dereq_('./p5.Graphics');
_dereq_('./p5.Renderer2D');
_dereq_('../webgl/p5.RendererGL');
function _getRequireWildcardCache() {
if (typeof WeakMap !== 'function') return null;
var cache = new WeakMap();
_getRequireWildcardCache = function _getRequireWildcardCache() {
return cache;
};
return cache;
}
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
}
if (obj === null || (_typeof(obj) !== 'object' && typeof obj !== 'function')) {
return { default: obj };
}
var cache = _getRequireWildcardCache();
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _typeof(obj) {
if (typeof Symbol === 'function' && 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);
}
var defaultId = 'defaultCanvas0'; // this gets set again in createCanvas
var defaultClass = 'p5Canvas';
/**
* Creates a canvas element in the document, and sets the dimensions of it
* in pixels. This method should be called only once at the start of setup.
* Calling <a href="#/p5/createCanvas">createCanvas</a> more than once in a
* sketch will result in very unpredictable behavior. If you want more than
* one drawing canvas you could use <a href="#/p5/createGraphics">createGraphics</a>
* (hidden by default but it can be shown).
*
* Important note: in 2D mode (i.e. when `p5.Renderer` is not set) the origin (0,0)
* is positioned at the top left of the screen. In 3D mode (i.e. when `p5.Renderer`
* is set to `WEBGL`), the origin is positioned at the center of the canvas.
* See [this issue](https://github.com/processing/p5.js/issues/1545) for more information.
*
* The system variables width and height are set by the parameters passed to this
* function. If <a href="#/p5/createCanvas">createCanvas()</a> is not used, the
* window will be given a default size of 100x100 pixels.
*
* For more ways to position the canvas, see the
* <a href='https://github.com/processing/p5.js/wiki/Positioning-your-canvas'>
* positioning the canvas</a> wiki page.
*
* @method createCanvas
* @param {Number} w width of the canvas
* @param {Number} h height of the canvas
* @param {Constant} [renderer] either P2D or WEBGL
* @return {p5.Renderer}
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 50);
* background(153);
* line(0, 0, width, height);
* }
* </code>
* </div>
*
* @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
* <div class="norender"><code>
* function setup() {
* createCanvas(windowWidth, windowHeight);
* }
*
* function draw() {
* background(0, 100, 200);
* }
*
* function windowResized() {
* resizeCanvas(windowWidth, windowHeight);
* }
* </code></div>
*
* @alt
* No image displayed.
*/
_main.default.prototype.resizeCanvas = function(w, h, noRedraw) {
_main.default._validateParameters('resizeCanvas', arguments);
if (this._renderer) {
// save canvas properties
var props = {};
for (var key in this.drawingContext) {
var val = this.drawingContext[key];
if (_typeof(val) !== 'object' && typeof val !== 'function') {
props[key] = val;
}
}
this._renderer.resize(w, h);
this.width = w;
this.height = h;
// reset canvas properties
for (var savedKey in props) {
try {
this.drawingContext[savedKey] = props[savedKey];
} catch (err) {
// ignore read-only property errors
}
}
if (!noRedraw) {
this.redraw();
}
}
//accessible Outputs
if (this._addAccsOutput()) {
this._updateAccsOutput();
}
};
/**
* Removes the default canvas for a p5 sketch that doesn't require a canvas
* @method noCanvas
* @example
* <div>
* <code>
* function setup() {
* noCanvas();
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* let pg;
* function setup() {
* createCanvas(100, 100);
* pg = createGraphics(100, 100);
* }
*
* function draw() {
* background(200);
* pg.background(100);
* pg.noStroke();
* pg.ellipse(pg.width / 2, pg.height / 2, 50, 50);
* image(pg, 50, 50);
* image(pg, 0, 0, 50, 50);
* }
* </code>
* </div>
*
* @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):
* <ul>
* <li><code>BLEND</code> - linear interpolation of colours: C =
* A\*factor + B. <b>This is the default blending mode.</b></li>
* <li><code>ADD</code> - sum of A and B</li>
* <li><code>DARKEST</code> - only the darkest colour succeeds: C =
* min(A\*factor, B).</li>
* <li><code>LIGHTEST</code> - only the lightest colour succeeds: C =
* max(A\*factor, B).</li>
* <li><code>DIFFERENCE</code> - subtract colors from underlying image.</li>
* <li><code>EXCLUSION</code> - similar to <code>DIFFERENCE</code>, but less
* extreme.</li>
* <li><code>MULTIPLY</code> - multiply the colors, result will always be
* darker.</li>
* <li><code>SCREEN</code> - opposite multiply, uses inverse values of the
* colors.</li>
* <li><code>REPLACE</code> - the pixels entirely replace the others and
* don't utilize alpha (transparency) values.</li>
* <li><code>REMOVE</code> - removes pixels from B with the alpha strength of A.</li>
* <li><code>OVERLAY</code> - mix of <code>MULTIPLY</code> and <code>SCREEN
* </code>. Multiplies dark values, and screens light values. <em>(2D)</em></li>
* <li><code>HARD_LIGHT</code> - <code>SCREEN</code> when greater than 50%
* gray, <code>MULTIPLY</code> when lower. <em>(2D)</em></li>
* <li><code>SOFT_LIGHT</code> - mix of <code>DARKEST</code> and
* <code>LIGHTEST</code>. Works like <code>OVERLAY</code>, but not as harsh. <em>(2D)</em>
* </li>
* <li><code>DODGE</code> - lightens light tones and increases contrast,
* ignores darks. <em>(2D)</em></li>
* <li><code>BURN</code> - darker areas are applied, increasing contrast,
* ignores lights. <em>(2D)</em></li>
* <li><code>SUBTRACT</code> - remainder of A and B <em>(3D)</em></li>
* </ul>
*
* <em>(2D)</em> indicates that this blend mode <b>only</b> works in the 2D renderer.<br>
* <em>(3D)</em> indicates that this blend mode <b>only</b> 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
* <div>
* <code>
* blendMode(LIGHTEST);
* strokeWeight(30);
* stroke(80, 150, 255);
* line(25, 25, 75, 75);
* stroke(255, 50, 50);
* line(75, 25, 25, 75);
* </code>
* </div>
*
* <div>
* <code>
* blendMode(MULTIPLY);
* strokeWeight(30);
* stroke(80, 150, 255);
* line(25, 25, 75, 75);
* stroke(255, 50, 50);
* line(75, 25, 25, 75);
* </code>
* </div>
*
* @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
* <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D">
* reference for the native canvas API</a> for possible drawing functions you can call.
*
* @property drawingContext
* @example
* <div>
* <code>
* function setup() {
* drawingContext.shadowOffsetX = 5;
* drawingContext.shadowOffsetY = -5;
* drawingContext.shadowBlur = 10;
* drawingContext.shadowColor = 'black';
* background(200);
* ellipse(width / 2, height / 2, 50, 50);
* }
* </code>
* </div>
*
* @alt
* white ellipse with shadow blur effect around edges
*/ var _default = _main.default;
exports.default = _default;
},
{
'../webgl/p5.RendererGL': 113,
'./constants': 48,
'./main': 59,
'./p5.Graphics': 61,
'./p5.Renderer2D': 63
}
],
66: [
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 <a href="#/p5/ellipseMode">ellipseMode()</a> 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
* <div>
* <code>
* 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);
* </code>
* </div>
*
* <div>
* <code>
* arc(50, 50, 80, 80, 0, PI + QUARTER_PI);
* </code>
* </div>
*
* <div>
* <code>
* arc(50, 50, 80, 80, 0, PI + QUARTER_PI, OPEN);
* </code>
* </div>
*
* <div>
* <code>
* arc(50, 50, 80, 80, 0, PI + QUARTER_PI, CHORD);
* </code>
* </div>
*
* <div>
* <code>
* arc(50, 50, 80, 80, 0, PI + QUARTER_PI, PIE);
* </code>
* </div>
*
* @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
);
//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 <a href="#/p5/ellipseMode">ellipseMode()</a> 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
* <div>
* <code>
* ellipse(56, 46, 55, 55);
* </code>
* </div>
*
* @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
* <div>
* <code>
* // Draw a circle at location (30, 30) with a diameter of 20.
* circle(30, 30, 20);
* </code>
* </div>
*
* @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]);
//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 <a href="#/p5/strokeWeight">
* strokeWeight()</a> function. A line cannot be filled, therefore the <a
* href="#/p5/fill">fill()</a> function will not affect the color of a line. So to
* color a line, use the <a href="#/p5/stroke">stroke()</a> 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
* <div>
* <code>
* line(30, 20, 85, 75);
* </code>
* </div>
*
* <div>
* <code>
* line(30, 20, 85, 20);
* stroke(126);
* line(85, 20, 85, 75);
* stroke(255);
* line(85, 75, 30, 75);
* </code>
* </div>
*
* @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);
}
//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 <a href="#/p5/stroke">stroke()</a> function. The size of the point
* can be changed with the <a href="#/p5/strokeWeight">strokeWeight()</a> 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
* <div>
* <code>
* point(30, 20);
* point(85, 20);
* point(85, 75);
* point(30, 75);
* </code>
* </div>
*
* <div>
* <code>
* 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);
* </code>
* </div>
*
* <div>
* <code>
* let a = createVector(10, 10);
* point(a);
* let b = createVector(10, 20);
* point(b);
* point(createVector(20, 10));
* point(createVector(20, 20));
* </code>
* </div>
*
* @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);
//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
* @chainable
* @example
* <div>
* <code>
* quad(38, 31, 86, 20, 69, 63, 30, 76);
* </code>
* </div>
*
* @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);
//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 <a href="#/p5/rectMode">rectMode()</a> 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
* <div>
* <code>
* // Draw a rectangle at location (30, 20) with a width and height of 55.
* rect(30, 20, 55, 55);
* </code>
* </div>
*
* <div>
* <code>
* // Draw a rectangle with rounded corners, each having a radius of 20.
* rect(30, 20, 55, 55, 20);
* </code>
* </div>
*
* <div>
* <code>
* // 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);
* </code>
* </div>
*
* @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 <a
* href="#/p5/rectMode">rectMode()</a> 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
* <div>
* <code>
* // Draw a square at location (30, 20) with a side size of 55.
* square(30, 20, 55);
* </code>
* </div>
*
* <div>
* <code>
* // Draw a square with rounded corners, each having a radius of 20.
* square(30, 20, 55, 20);
* </code>
* </div>
*
* <div>
* <code>
* // 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);
* </code>
* </div>
*
* @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);
//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
* <div>
* <code>
* triangle(30, 75, 58, 20, 86, 75);
* </code>
* </div>
*
*@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);
}
//accessible outputs
if (this._accessibleOutputs.grid || this._accessibleOutputs.text) {
this._accsOutput('triangle', args);
}
return this;
};
var _default = _main.default;
exports.default = _default;
},
{
'../constants': 48,
'../friendly_errors/fes_core': 51,
'../friendly_errors/file_errors': 52,
'../friendly_errors/validate_params': 54,
'../helpers': 55,
'../main': 59
}
],
67: [
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 <a href="#/p5/ellipse">ellipse()</a>,
* <a href="#/p5/circle">circle()</a> and <a href="#/p5/arc">arc()</a> 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
* <div>
* <code>
* // Example showing RADIUS and CENTER ellipsemode with 2 overlaying ellipses
* ellipseMode(RADIUS);
* fill(255);
* ellipse(50, 50, 30, 30); // Outer white ellipse
* ellipseMode(CENTER);
* fill(100);
* ellipse(50, 50, 30, 30); // Inner gray ellipse
* </code>
* </div>
*
* <div>
* <code>
* // Example showing CORNER and CORNERS ellipseMode with 2 overlaying ellipses
* ellipseMode(CORNER);
* fill(255);
* ellipse(25, 25, 50, 50); // Outer white ellipse
* ellipseMode(CORNERS);
* fill(100);
* ellipse(25, 25, 50, 50); // Inner gray ellipse
* </code>
* </div>
*
* @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 <a href="#/p5/smooth">smooth()</a> is
* active by default in 2D mode, so it is necessary to call <a href="#/p5/noSmooth">noSmooth()</a> to disable
* smoothing of geometry, images, and fonts. In 3D mode, <a href="#/p5/noSmooth">noSmooth()</a> is enabled
* by default, so it is necessary to call <a href="#/p5/smooth">smooth()</a> if you would like
* smooth (antialiased) edges on your geometry.
*
* @method noSmooth
* @chainable
* @example
* <div>
* <code>
* background(0);
* noStroke();
* smooth();
* ellipse(30, 48, 36, 36);
* noSmooth();
* ellipse(70, 48, 36, 36);
* </code>
* </div>
*
* @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 <a href="#/p5/rect">rect()</a> 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 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 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
* <div>
* <code>
* rectMode(CORNER);
* fill(255);
* rect(25, 25, 50, 50); // Draw white rectangle using CORNER mode
*
* rectMode(CORNERS);
* fill(100);
* rect(25, 25, 50, 50); // Draw gray rectangle using CORNERS mode
* </code>
* </div>
*
* <div>
* <code>
* rectMode(RADIUS);
* fill(255);
* rect(50, 50, 30, 30); // Draw white rectangle using RADIUS mode
*
* rectMode(CENTER);
* fill(100);
* rect(50, 50, 30, 30); // Draw gray rectangle using CENTER mode
* </code>
* </div>
*
* @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. <a href="#/p5/smooth">smooth()</a> will also
* improve image quality of resized images. Note that <a href="#/p5/smooth">smooth()</a> is active by
* default in 2D mode; <a href="#/p5/noSmooth">noSmooth()</a> can be used to disable smoothing of geometry,
* images, and fonts. In 3D mode, <a href="#/p5/noSmooth">noSmooth()</a> is enabled
* by default, so it is necessary to call <a href="#/p5/smooth">smooth()</a> if you would like
* smooth (antialiased) edges on your geometry.
*
* @method smooth
* @chainable
* @example
* <div>
* <code>
* background(0);
* noStroke();
* smooth();
* ellipse(30, 48, 36, 36);
* noSmooth();
* ellipse(70, 48, 36, 36);
* </code>
* </div>
*
* @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
* <div>
* <code>
* // Example of different strokeCaps
* strokeWeight(12.0);
* strokeCap(ROUND);
* line(20, 30, 80, 30);
* strokeCap(SQUARE);
* line(20, 50, 80, 50);
* strokeCap(PROJECT);
* line(20, 70, 80, 70);
* </code>
* </div>
*
* @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
* <div>
* <code>
* // Example of MITER type of joints
* noFill();
* strokeWeight(10.0);
* strokeJoin(MITER);
* beginShape();
* vertex(35, 20);
* vertex(65, 50);
* vertex(35, 80);
* endShape();
* </code>
* </div>
*
* <div>
* <code>
* // Example of BEVEL type of joints
* noFill();
* strokeWeight(10.0);
* strokeJoin(BEVEL);
* beginShape();
* vertex(35, 20);
* vertex(65, 50);
* vertex(35, 80);
* endShape();
* </code>
* </div>
*
* <div>
* <code>
* // Example of ROUND type of joints
* noFill();
* strokeWeight(10.0);
* strokeJoin(ROUND);
* beginShape();
* vertex(35, 20);
* vertex(65, 50);
* vertex(35, 80);
* endShape();
* </code>
* </div>
*
* @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
* <div>
* <code>
* // Example of different stroke weights
* strokeWeight(1); // Default
* line(20, 20, 80, 20);
* strokeWeight(4); // Thicker
* line(20, 40, 80, 40);
* strokeWeight(10); // Beastly
* line(20, 70, 80, 70);
* </code>
* </div>
*
* @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': 48, '../main': 59 }
],
68: [
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 <a href="#/p5/curve">curve()</a>.
*
* @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
* <div>
* <code>
* noFill();
* stroke(255, 102, 0);
* line(85, 20, 10, 10);
* line(90, 90, 15, 80);
* stroke(0, 0, 0);
* bezier(85, 20, 10, 10, 90, 90, 15, 80);
* </code>
* </div>
*
* <div>
* <code>
* background(0, 0, 0);
* noFill();
* stroke(255);
* bezier(250, 250, 0, 100, 100, 0, 100, 0, 0, 0, 100, 0);
* </code>
* </div>
*
* @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
* <div modernizr='webgl'>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* noFill();
* bezierDetail(5);
* }
*
* function draw() {
* background(200);
* // prettier-ignore
* bezier(-40, -40, 0,
* 90, -40, 0,
* -90, 40, 0,
* 40, 40, 0);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* 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);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* 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);
* }
* </code>
* </div>
*
* <div>
* <code>
* 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);
* }
* </code>
* </div>
*
* @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. <br /><br />
* Longer curves can be created by putting a series of <a href="#/p5/curve">curve()</a> functions
* together or using <a href="#/p5/curveVertex">curveVertex()</a>. An additional function called
* <a href="#/p5/curveTightness">curveTightness()</a> provides control for the visual quality of the curve.
* The <a href="#/p5/curve">curve()</a> 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
* <div>
* <code>
* noFill();
* stroke(255, 102, 0);
* curve(5, 26, 5, 26, 73, 24, 73, 61);
* stroke(0);
* curve(5, 26, 73, 24, 73, 61, 15, 65);
* stroke(255, 102, 0);
* curve(73, 24, 73, 61, 15, 65, 15, 65);
* </code>
* </div>
*
* <div>
* <code>
* // Define the curve points as JavaScript objects
* let p1 = { x: 5, y: 26 };
* let p2 = { x: 73, y: 24 };
* let p3 = { x: 73, y: 61 };
* let p4 = { x: 15, y: 65 };
* noFill();
* stroke(255, 102, 0);
* curve(p1.x, p1.y, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
* stroke(0);
* curve(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y);
* stroke(255, 102, 0);
* curve(p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, p4.x, p4.y);
* </code>
* </div>
*
* <div>
* <code>
* noFill();
* stroke(255, 102, 0);
* curve(5, 26, 0, 5, 26, 0, 73, 24, 0, 73, 61, 0);
* stroke(0);
* curve(5, 26, 0, 73, 24, 0, 73, 61, 0, 15, 65, 0);
* stroke(255, 102, 0);
* curve(73, 24, 0, 73, 61, 0, 15, 65, 0, 15, 65, 0);
* </code>
* </div>
*
* @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
* <div modernizr='webgl'>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* curveDetail(5);
* }
* function draw() {
* background(200);
*
* curve(250, 600, 0, -30, 40, 0, 30, 30, 0, -250, 600, 0);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/curve">curve()</a>
* and <a href="#/p5/curveVertex">curveVertex()</a>.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
* <div>
* <code>
* // 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();
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* 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);
* }
* </code>
* </div>
*
*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
* <div>
* <code>
* 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);
* }
* </code>
* </div>
*
* @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': 51,
'../friendly_errors/file_errors': 52,
'../friendly_errors/validate_params': 54,
'../main': 59
}
],
69: [
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 <a href="#/p5/beginContour">beginContour()</a> and
* <a href="#/p5/endContour">endContour()</a> functions to create negative shapes
* within shapes such as the center of the letter 'O'. <a href="#/p5/beginContour">beginContour()</a>
* begins recording vertices for the shape and <a href="#/p5/endContour">endContour()</a> 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 <a href="#/p5/beginShape">beginShape()</a>/<a href="#/p5/endShape">endShape()</a> pair and
* transformations such as <a href="#/p5/translate">translate()</a>, <a href="#/p5/rotate">rotate()</a>, and <a href="#/p5/scale">scale()</a> do not work
* within a <a href="#/p5/beginContour">beginContour()</a>/<a href="#/p5/endContour">endContour()</a> pair. It is also not possible to use
* other shapes, such as <a href="#/p5/ellipse">ellipse()</a> or <a href="#/p5/rect">rect()</a> within.
*
* @method beginContour
* @chainable
* @example
* <div>
* <code>
* translate(50, 50);
* stroke(255, 0, 0);
* beginShape();
* // Exterior part of shape, clockwise winding
* vertex(-40, -40);
* vertex(40, -40);
* vertex(40, 40);
* vertex(-40, 40);
* // Interior part of shape, counter-clockwise winding
* beginContour();
* vertex(-20, -20);
* vertex(-20, 20);
* vertex(20, 20);
* vertex(20, -20);
* endContour();
* endShape(CLOSE);
* </code>
* </div>
*
* @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 <a href="#/p5/beginShape">beginShape()</a> and <a href="#/p5/endShape">endShape()</a> functions allow creating more
* complex forms. <a href="#/p5/beginShape">beginShape()</a> begins recording vertices for a shape and
* <a href="#/p5/endShape">endShape()</a> 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 <a href="#/p5/beginShape">beginShape()</a> are POINTS, LINES, TRIANGLES,
* TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, QUAD_STRIP, and TESS (WebGL only). After calling the
* <a href="#/p5/beginShape">beginShape()</a> function, a series of <a href="#/p5/vertex">vertex()</a> commands must follow. To stop
* drawing the shape, call <a href="#/p5/endShape">endShape()</a>. Each shape will be outlined with the
* current stroke color and filled with the fill color.
*
* Transformations such as <a href="#/p5/translate">translate()</a>, <a href="#/p5/rotate">rotate()</a>, and <a href="#/p5/scale">scale()</a> do not work
* within <a href="#/p5/beginShape">beginShape()</a>. It is also not possible to use other shapes, such as
* <a href="#/p5/ellipse">ellipse()</a> or <a href="#/p5/rect">rect()</a> within <a href="#/p5/beginShape">beginShape()</a>.
*
* @method beginShape
* @param {Constant} [kind] either POINTS, LINES, TRIANGLES, TRIANGLE_FAN
* TRIANGLE_STRIP, QUADS, QUAD_STRIP or TESS
* @chainable
* @example
* <div>
* <code>
* beginShape();
* vertex(30, 20);
* vertex(85, 20);
* vertex(85, 75);
* vertex(30, 75);
* endShape(CLOSE);
* </code>
* </div>
*
* <div>
* <code>
* beginShape(POINTS);
* vertex(30, 20);
* vertex(85, 20);
* vertex(85, 75);
* vertex(30, 75);
* endShape();
* </code>
* </div>
*
* <div>
* <code>
* beginShape(LINES);
* vertex(30, 20);
* vertex(85, 20);
* vertex(85, 75);
* vertex(30, 75);
* endShape();
* </code>
* </div>
*
* <div>
* <code>
* noFill();
* beginShape();
* vertex(30, 20);
* vertex(85, 20);
* vertex(85, 75);
* vertex(30, 75);
* endShape();
* </code>
* </div>
*
* <div>
* <code>
* noFill();
* beginShape();
* vertex(30, 20);
* vertex(85, 20);
* vertex(85, 75);
* vertex(30, 75);
* endShape(CLOSE);
* </code>
* </div>
*
* <div>
* <code>
* beginShape(TRIANGLES);
* vertex(30, 75);
* vertex(40, 20);
* vertex(50, 75);
* vertex(60, 20);
* vertex(70, 75);
* vertex(80, 20);
* endShape();
* </code>
* </div>
*
* <div>
* <code>
* beginShape(TRIANGLE_STRIP);
* vertex(30, 75);
* vertex(40, 20);
* vertex(50, 75);
* vertex(60, 20);
* vertex(70, 75);
* vertex(80, 20);
* vertex(90, 75);
* endShape();
* </code>
* </div>
*
* <div>
* <code>
* beginShape(TRIANGLE_FAN);
* vertex(57.5, 50);
* vertex(57.5, 15);
* vertex(92, 50);
* vertex(57.5, 85);
* vertex(22, 50);
* vertex(57.5, 15);
* endShape();
* </code>
* </div>
*
* <div>
* <code>
* beginShape(QUADS);
* vertex(30, 20);
* vertex(30, 75);
* vertex(50, 75);
* vertex(50, 20);
* vertex(65, 20);
* vertex(65, 75);
* vertex(85, 75);
* vertex(85, 20);
* endShape();
* </code>
* </div>
*
* <div>
* <code>
* beginShape(QUAD_STRIP);
* vertex(30, 20);
* vertex(30, 75);
* vertex(50, 20);
* vertex(50, 75);
* vertex(65, 20);
* vertex(65, 75);
* vertex(85, 20);
* vertex(85, 75);
* endShape();
* </code>
* </div>
*
* <div>
* <code>
* beginShape();
* vertex(20, 20);
* vertex(40, 20);
* vertex(40, 40);
* vertex(60, 40);
* vertex(60, 60);
* vertex(20, 60);
* endShape(CLOSE);
* </code>
* </div>
*
* @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 <a href="#/p5/beginShape">beginShape()</a>
* call, it must be prefaced with a call to <a href="#/p5/vertex">vertex()</a> to set the first anchor
* point. This function must be used between <a href="#/p5/beginShape">beginShape()</a> and <a href="#/p5/endShape">endShape()</a>
* and only when there is no MODE or POINTS parameter specified to
* <a href="#/p5/beginShape">beginShape()</a>.
*
* @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
* <div>
* <code>
* noFill();
* beginShape();
* vertex(30, 20);
* bezierVertex(80, 0, 80, 75, 30, 75);
* endShape();
* </code>
* </div>
*
* <div>
* <code>
* beginShape();
* vertex(30, 20);
* bezierVertex(80, 0, 80, 75, 30, 75);
* bezierVertex(50, 80, 60, 25, 30, 20);
* endShape();
* </code>
* </div>
*
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* setAttributes('antialias', true);
* }
* function draw() {
* orbitControl();
* background(50);
* strokeWeight(4);
* stroke(255);
* point(-25, 30);
* point(25, 30);
* point(25, -30);
* point(-25, -30);
*
* strokeWeight(1);
* noFill();
*
* beginShape();
* vertex(-25, 30);
* bezierVertex(25, 30, 25, -30, -25, -30);
* endShape();
*
* beginShape();
* vertex(-25, 30, 20);
* bezierVertex(25, 30, 20, 25, -30, 20, -25, -30, 20);
* endShape();
* }
* </code>
* </div>
*
* @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 <a href="#/p5/beginShape">beginShape()</a> and <a href="#/p5/endShape">endShape()</a> and only when there
* is no MODE parameter specified to <a href="#/p5/beginShape">beginShape()</a>.
* 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
* <div>
* <code>
* strokeWeight(5);
* point(84, 91);
* point(68, 19);
* point(21, 17);
* point(32, 91);
* strokeWeight(1);
*
* noFill();
* beginShape();
* curveVertex(84, 91);
* curveVertex(84, 91);
* curveVertex(68, 19);
* curveVertex(21, 17);
* curveVertex(32, 91);
* curveVertex(32, 91);
* endShape();
* </code>
* </div>
*
* @alt
* Upside-down u-shape line, mid canvas. left point extends beyond canvas view.
*/
/**
* @method curveVertex
* @param {Number} x
* @param {Number} y
* @param {Number} [z] z-coordinate of the vertex (for WebGL mode)
* @chainable
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* setAttributes('antialias', true);
* }
* function draw() {
* orbitControl();
* background(50);
* strokeWeight(4);
* stroke(255);
*
* point(-25, 25);
* point(-25, 25);
* point(-25, -25);
* point(25, -25);
* point(25, 25);
* point(25, 25);
*
* strokeWeight(1);
* noFill();
*
* beginShape();
* curveVertex(-25, 25);
* curveVertex(-25, 25);
* curveVertex(-25, -25);
* curveVertex(25, -25);
* curveVertex(25, 25);
* curveVertex(25, 25);
* endShape();
*
* beginShape();
* curveVertex(-25, 25, 20);
* curveVertex(-25, 25, 20);
* curveVertex(-25, -25, 20);
* curveVertex(25, -25, 20);
* curveVertex(25, 25, 20);
* curveVertex(25, 25, 20);
* endShape();
* }
* </code>
* </div>
*
* @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 <a href="#/p5/beginContour">beginContour()</a> and <a href="#/p5/endContour">endContour()</a> functions to create negative
* shapes within shapes such as the center of the letter 'O'. <a href="#/p5/beginContour">beginContour()</a>
* begins recording vertices for the shape and <a href="#/p5/endContour">endContour()</a> 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 <a href="#/p5/beginShape">beginShape()</a>/<a href="#/p5/endShape">endShape()</a> pair and
* transformations such as <a href="#/p5/translate">translate()</a>, <a href="#/p5/rotate">rotate()</a>, and <a href="#/p5/scale">scale()</a> do not work
* within a <a href="#/p5/beginContour">beginContour()</a>/<a href="#/p5/endContour">endContour()</a> pair. It is also not possible to use
* other shapes, such as <a href="#/p5/ellipse">ellipse()</a> or <a href="#/p5/rect">rect()</a> within.
*
* @method endContour
* @chainable
* @example
* <div>
* <code>
* translate(50, 50);
* stroke(255, 0, 0);
* beginShape();
* // Exterior part of shape, clockwise winding
* vertex(-40, -40);
* vertex(40, -40);
* vertex(40, 40);
* vertex(-40, 40);
* // Interior part of shape, counter-clockwise winding
* beginContour();
* vertex(-20, -20);
* vertex(-20, 20);
* vertex(20, 20);
* vertex(20, -20);
* endContour();
* endShape(CLOSE);
* </code>
* </div>
*
* @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 <a href="#/p5/endShape">endShape()</a> function is the companion to <a href="#/p5/beginShape">beginShape()</a> and may only be
* called after <a href="#/p5/beginShape">beginShape()</a>. When <a href="#/p5/endshape">endShape()</a> is called, all of image data
* defined since the previous call to <a href="#/p5/beginShape">beginShape()</a> 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
* <div>
* <code>
* noFill();
*
* beginShape();
* vertex(20, 20);
* vertex(45, 20);
* vertex(45, 80);
* endShape(CLOSE);
*
* beginShape();
* vertex(50, 20);
* vertex(75, 20);
* vertex(75, 80);
* endShape();
* </code>
* </div>
*
* @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 <a href="#/p5/beginShape">beginShape()</a> call, it
* must be prefaced with a call to <a href="#/p5/vertex">vertex()</a> 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 <a href="#/p5/beginShape">beginShape()</a> and <a href="#/p5/endShape">endShape()</a>
* and only when there is no MODE or POINTS parameter specified to
* <a href="#/p5/beginShape">beginShape()</a>.
*
* @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
* <div>
* <code>
* strokeWeight(5);
* point(20, 20);
* point(80, 20);
* point(50, 50);
*
* noFill();
* strokeWeight(1);
* beginShape();
* vertex(20, 20);
* quadraticVertex(80, 20, 50, 50);
* endShape();
* </code>
* </div>
*
* <div>
* <code>
* strokeWeight(5);
* point(20, 20);
* point(80, 20);
* point(50, 50);
*
* point(20, 80);
* point(80, 80);
* point(80, 60);
*
* noFill();
* strokeWeight(1);
* beginShape();
* vertex(20, 20);
* quadraticVertex(80, 20, 50, 50);
* quadraticVertex(20, 80, 80, 80);
* vertex(80, 60);
* endShape();
* </code>
* </div>
*
* @alt
* arched-shaped black line with 4 pixel thick stroke weight.
* backwards s-shaped black line with 4 pixel thick stroke weight.
*/
/**
* @method quadraticVertex
* @param {Number} cx
* @param {Number} cy
* @param {Number} cz z-coordinate for the control point (for WebGL mode)
* @param {Number} x3
* @param {Number} y3
* @param {Number} z3 z-coordinate for the anchor point (for WebGL mode)
* @chainable
*
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* setAttributes('antialias', true);
* }
* function draw() {
* orbitControl();
* background(50);
* strokeWeight(4);
* stroke(255);
*
* point(-35, -35);
* point(35, -35);
* point(0, 0);
* point(-35, 35);
* point(35, 35);
* point(35, 10);
*
* strokeWeight(1);
* noFill();
*
* beginShape();
* vertex(-35, -35);
* quadraticVertex(35, -35, 0, 0);
* quadraticVertex(-35, 35, 35, 35);
* vertex(35, 10);
* endShape();
*
* beginShape();
* vertex(-35, -35, 20);
* quadraticVertex(35, -35, 20, 0, 0, 20);
* quadraticVertex(-35, 35, 20, 35, 35, 20);
* vertex(35, 10, 20);
* endShape();
* }
* </code>
* </div>
*
* @alt
* backwards s-shaped black line with the same s-shaped line in postive 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. <a href="#/p5/vertex">vertex()</a>
* is used to specify the vertex coordinates for points, lines, triangles,
* quads, and polygons. It is used exclusively within the <a href="#/p5/beginShape">beginShape()</a> and
* <a href="#/p5/endShape">endShape()</a> functions.
*
* @method vertex
* @param {Number} x x-coordinate of the vertex
* @param {Number} y y-coordinate of the vertex
* @chainable
* @example
* <div>
* <code>
* strokeWeight(3);
* beginShape(POINTS);
* vertex(30, 20);
* vertex(85, 20);
* vertex(85, 75);
* vertex(30, 75);
* endShape();
* </code>
* </div>
*
* <div>
* <code>
* createCanvas(100, 100, WEBGL);
* background(240, 240, 240);
* fill(237, 34, 93);
* noStroke();
* beginShape();
* vertex(0, 35);
* vertex(35, 0);
* vertex(0, -35);
* vertex(-35, 0);
* endShape();
* </code>
* </div>
*
* <div>
* <code>
* createCanvas(100, 100, WEBGL);
* background(240, 240, 240);
* fill(237, 34, 93);
* noStroke();
* beginShape();
* vertex(-10, 10);
* vertex(0, 35);
* vertex(10, 10);
* vertex(35, 0);
* vertex(10, -8);
* vertex(0, -35);
* vertex(-10, -8);
* vertex(-35, 0);
* endShape();
* </code>
* </div>
*
* <div>
* <code>
* strokeWeight(3);
* stroke(237, 34, 93);
* beginShape(LINES);
* vertex(10, 35);
* vertex(90, 35);
* vertex(10, 65);
* vertex(90, 65);
* vertex(35, 10);
* vertex(35, 90);
* vertex(65, 10);
* vertex(65, 90);
* endShape();
* </code>
* </div>
*
* <div>
* <code>
* // 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();
* }
* </code>
* </div>
* @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': 48, '../main': 59 }
],
70: [
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
});
}
})();
},
{}
],
71: [
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 <a href="#/p5/draw">draw()</a>.
* If <a href="#/p5/loop">loop()</a> is called, the code in <a href="#/p5/draw">draw()</a>
* begins to run continuously again. If using <a href="#/p5/noLoop">noLoop()</a>
* in <a href="#/p5/setup">setup()</a>, it should be the last line inside the block.
*
* When <a href="#/p5/noLoop">noLoop()</a> is used, it's not possible to manipulate
* or access the screen inside event handling functions such as
* <a href="#/p5/mousePressed">mousePressed()</a> or
* <a href="#/p5/keyPressed">keyPressed()</a>. Instead, use those functions to
* call <a href="#/p5/redraw">redraw()</a> or <a href="#/p5/loop">loop()</a>,
* which will run <a href="#/p5/draw">draw()</a>, which can update the screen
* properly. This means that when <a href="#/p5/noLoop">noLoop()</a> has been
* called, no drawing can happen, and functions like <a href="#/p5/saveFrame">saveFrame()</a>
* or <a href="#/p5/loadPixels">loadPixels()</a> may not be used.
*
* Note that if the sketch is resized, <a href="#/p5/redraw">redraw()</a> will
* be called to update the sketch, even after <a href="#/p5/noLoop">noLoop()</a>
* has been specified. Otherwise, the sketch would enter an odd state until
* <a href="#/p5/loop">loop()</a> was called.
*
* Use <a href="#/p5/isLooping">isLooping()</a> to check current state of loop().
*
* @method noLoop
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100);
* background(200);
* noLoop();
* }
* function draw() {
* line(10, 10, 90, 90);
* }
* </code>
* </div>
*
* <div>
* <code>
* 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();
* }
* </code>
* </div>
*
* @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 <a href="#/p5/draw">draw()</a> loop may be stopped by calling
* <a href="#/p5/noLoop">noLoop()</a>. In that case, the <a href="#/p5/draw">draw()</a>
* loop can be resumed with loop().
*
* Avoid calling loop() from inside setup().
*
* Use <a href="#/p5/isLooping">isLooping()</a> to check current state of loop().
*
* @method loop
* @example
* <div>
* <code>
* 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();
* }
* </code>
* </div>
*
* @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 <a href="#/p5/draw">draw()</a> continuously,
* executing the code within it. If the sketch is stopped with
* <a href="#/p5/noLoop">noLoop()</a> or resumed with <a href="#/p5/loop">loop()</a>,
* isLooping() returns the current state for use within custom event handlers.
*
* @method isLooping
* @example
* <div>
* <code>
* let checkbox, button, colBG, colFill;
*
* function setup() {
* createCanvas(100, 100);
*
* button = createButton('Colorize if loop()');
* button.position(0, 120);
* button.mousePressed(changeBG);
*
* checkbox = createCheckbox('loop()', true);
* checkbox.changed(checkLoop);
*
* colBG = color(0);
* colFill = color(255);
* }
*
* function changeBG() {
* if (isLooping()) {
* colBG = color(random(255), random(255), random(255));
* colFill = color(random(255), random(255), random(255));
* }
* }
*
* function checkLoop() {
* if (this.checked()) {
* loop();
* } else {
* noLoop();
* }
* }
*
* function draw() {
* background(colBG);
* fill(colFill);
* ellipse(frameCount % width, height / 2, 50);
* }
* </code>
* </div>
*
* @alt
* Ellipse moves slowly from left. Checkbox toggles loop()/noLoop().
* Button colorizes sketch if isLooping().
*
*/
_main.default.prototype.isLooping = function() {
return this._loop;
};
/**
* The <a href="#/p5/push">push()</a> function saves the current drawing style
* settings and transformations, while <a href="#/p5/pop">pop()</a> 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 <a href="#/p5/push">push()</a>, it builds on
* the current style and transform information. The <a href="#/p5/push">push()</a>
* and <a href="#/p5/pop">pop()</a> functions can be embedded to provide more
* control. (See the second example for a demonstration.)
*
* <a href="#/p5/push">push()</a> stores information related to the current transformation state
* and style settings controlled by the following functions:
* <a href="#/p5/fill">fill()</a>,
* <a href="#/p5/noFill">noFill()</a>,
* <a href="#/p5/noStroke">noStroke()</a>,
* <a href="#/p5/stroke">stroke()</a>,
* <a href="#/p5/tint">tint()</a>,
* <a href="#/p5/noTint">noTint()</a>,
* <a href="#/p5/strokeWeight">strokeWeight()</a>,
* <a href="#/p5/strokeCap">strokeCap()</a>,
* <a href="#/p5/strokeJoin">strokeJoin()</a>,
* <a href="#/p5/imageMode">imageMode()</a>,
* <a href="#/p5/rectMode">rectMode()</a>,
* <a href="#/p5/ellipseMode">ellipseMode()</a>,
* <a href="#/p5/colorMode">colorMode()</a>,
* <a href="#/p5/textAlign">textAlign()</a>,
* <a href="#/p5/textFont">textFont()</a>,
* <a href="#/p5/textSize">textSize()</a>,
* <a href="#/p5/textLeading">textLeading()</a>,
* <a href="#/p5/applyMatrix">applyMatrix()</a>,
* <a href="#/p5/resetMatrix">resetMatrix()</a>,
* <a href="#/p5/rotate">rotate()</a>,
* <a href="#/p5/scale">scale()</a>,
* <a href="#/p5/shearX">shearX()</a>,
* <a href="#/p5/shearY">shearY()</a>,
* <a href="#/p5/translate">translate()</a>,
* <a href="#/p5/noiseSeed">noiseSeed()</a>.
*
* In WEBGL mode additional style settings are stored. These are controlled by the
* following functions: <a href="#/p5/setCamera">setCamera()</a>,
* <a href="#/p5/ambientLight">ambientLight()</a>,
* <a href="#/p5/directionalLight">directionalLight()</a>,
* <a href="#/p5/pointLight">pointLight()</a>, <a href="#/p5/texture">texture()</a>,
* <a href="#/p5/specularMaterial">specularMaterial()</a>,
* <a href="#/p5/shininess">shininess()</a>,
* <a href="#/p5/normalMaterial">normalMaterial()</a>
* and <a href="#/p5/shader">shader()</a>.
*
* @method push
* @example
* <div>
* <code>
* 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
* </code>
* </div>
*
* <div>
* <code>
* 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
* </code>
* </div>
*
* @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 <a href="#/p5/push">push()</a> function saves the current drawing style
* settings and transformations, while <a href="#/p5/pop">pop()</a> 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 <a href="#/p5/push">push()</a>, it
* builds on the current style and transform information. The <a href="#/p5/push">push()</a>
* and <a href="#/p5/pop">pop()</a> functions can be embedded to provide more
* control. (See the second example for a demonstration.)
*
* <a href="#/p5/push">push()</a> stores information related to the current transformation state
* and style settings controlled by the following functions:
* <a href="#/p5/fill">fill()</a>,
* <a href="#/p5/noFill">noFill()</a>,
* <a href="#/p5/noStroke">noStroke()</a>,
* <a href="#/p5/stroke">stroke()</a>,
* <a href="#/p5/tint">tint()</a>,
* <a href="#/p5/noTint">noTint()</a>,
* <a href="#/p5/strokeWeight">strokeWeight()</a>,
* <a href="#/p5/strokeCap">strokeCap()</a>,
* <a href="#/p5/strokeJoin">strokeJoin()</a>,
* <a href="#/p5/imageMode">imageMode()</a>,
* <a href="#/p5/rectMode">rectMode()</a>,
* <a href="#/p5/ellipseMode">ellipseMode()</a>,
* <a href="#/p5/colorMode">colorMode()</a>,
* <a href="#/p5/textAlign">textAlign()</a>,
* <a href="#/p5/textFont">textFont()</a>,
* <a href="#/p5/textSize">textSize()</a>,
* <a href="#/p5/textLeading">textLeading()</a>,
* <a href="#/p5/applyMatrix">applyMatrix()</a>,
* <a href="#/p5/resetMatrix">resetMatrix()</a>,
* <a href="#/p5/rotate">rotate()</a>,
* <a href="#/p5/scale">scale()</a>,
* <a href="#/p5/shearX">shearX()</a>,
* <a href="#/p5/shearY">shearY()</a>,
* <a href="#/p5/translate">translate()</a>,
* <a href="#/p5/noiseSeed">noiseSeed()</a>.
*
* In WEBGL mode additional style settings are stored. These are controlled by
* the following functions:
* <a href="#/p5/setCamera">setCamera()</a>,
* <a href="#/p5/ambientLight">ambientLight()</a>,
* <a href="#/p5/directionalLight">directionalLight()</a>,
* <a href="#/p5/pointLight">pointLight()</a>,
* <a href="#/p5/texture">texture()</a>,
* <a href="#/p5/specularMaterial">specularMaterial()</a>,
* <a href="#/p5/shininess">shininess()</a>,
* <a href="#/p5/normalMaterial">normalMaterial()</a> and
* <a href="#/p5/shader">shader()</a>.
*
* @method pop
* @example
* <div>
* <code>
* 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
* </code>
* </div>
*
* <div>
* <code>
* 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
* </code>
* </div>
*
* @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 <a href="#/p5/draw">draw()</a> one time. This
* function allows the program to update the display window only when necessary,
* for example when an event registered by <a href="#/p5/mousePressed">mousePressed()</a>
* or <a href="#/p5/keyPressed">keyPressed()</a> occurs.
*
* In structuring a program, it only makes sense to call <a href="#/p5/redraw">redraw()</a>
* within events such as <a href="#/p5/mousePressed">mousePressed()</a>. This
* is because <a href="#/p5/redraw">redraw()</a> does not run
* <a href="#/p5/draw">draw()</a> immediately (it only sets a flag that indicates
* an update is needed).
*
* The <a href="#/p5/redraw">redraw()</a> function does not work properly when
* called inside <a href="#/p5/draw">draw()</a>.To enable/disable animations,
* use <a href="#/p5/loop">loop()</a> and <a href="#/p5/noLoop">noLoop()</a>.
*
* 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
* <div><code>
* let x = 0;
*
* function setup() {
* createCanvas(100, 100);
* noLoop();
* }
*
* function draw() {
* background(204);
* line(x, 0, x, height);
* }
*
* function mousePressed() {
* x += 1;
* redraw();
* }
* </code>
* </div>
*
* <div class='norender'>
* <code>
* let x = 0;
*
* function setup() {
* createCanvas(100, 100);
* noLoop();
* }
*
* function draw() {
* background(204);
* x += 1;
* line(x, 0, x, height);
* }
*
* function mousePressed() {
* redraw(5);
* }
* </code>
* </div>
*
* @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
* <a target="blank" href="https://www.youtube.com/watch?v=Su792jEauZg&feature=youtu.be">
* Dan Shiffman's Coding Train video tutorial</a> or this
* <a target="blank" href="https://github.com/processing/p5.js/wiki/p5.js-overview#instantiation--namespace">tutorial page</a>
* 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
* <div class='norender'><code>
* 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
* </code></div>
*
* @alt
* white rectangle on black background
*/ var _default = _main.default;
exports.default = _default;
},
{ './main': 59 }
],
72: [
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 <a href="https://en.wikipedia.org/wiki/Transformation_matrix">
* Wikipedia</a>.
*
* The naming of the arguments here follows the naming of the <a href=
* "https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-transform">
* WHATWG specification</a> and corresponds to a
* transformation matrix of the
* form:
*
* > <img style="max-width: 150px" src="assets/transformation-matrix.png"
* alt="The transformation matrix used when applyMatrix is called"/>
*
* @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
* <div>
* <code>
* function setup() {
* frameRate(10);
* rectMode(CENTER);
* }
*
* function draw() {
* let step = frameCount % 20;
* background(200);
* // Equivalent to translate(x, y);
* applyMatrix(1, 0, 0, 1, 40 + step, 50);
* rect(0, 0, 50, 50);
* }
* </code>
* </div>
*
* <div>
* <code>
* function setup() {
* frameRate(10);
* rectMode(CENTER);
* }
*
* function draw() {
* let step = frameCount % 20;
* background(200);
* translate(50, 50);
* // Equivalent to scale(x, y);
* applyMatrix(1 / step, 0, 0, 1 / step, 0, 0);
* rect(0, 0, 50, 50);
* }
* </code>
* </div>
*
* <div>
* <code>
* function setup() {
* frameRate(10);
* rectMode(CENTER);
* }
*
* function draw() {
* let step = frameCount % 20;
* let angle = map(step, 0, 20, 0, TWO_PI);
* let cos_a = cos(angle);
* let sin_a = sin(angle);
* background(200);
* translate(50, 50);
* // Equivalent to rotate(angle);
* applyMatrix(cos_a, sin_a, -sin_a, cos_a, 0, 0);
* rect(0, 0, 50, 50);
* }
* </code>
* </div>
*
* <div>
* <code>
* function setup() {
* frameRate(10);
* rectMode(CENTER);
* }
*
* function draw() {
* let step = frameCount % 20;
* let angle = map(step, 0, 20, -PI / 4, PI / 4);
* background(200);
* translate(50, 50);
* // equivalent to shearX(angle);
* let shear_factor = 1 / tan(PI / 2 - angle);
* applyMatrix(1, 0, shear_factor, 1, 0, 0);
* rect(0, 0, 50, 50);
* }
* </code>
* </div>
*
* <div modernizr='webgl'>
* <code>
* 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);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* translate(50, 50);
* applyMatrix(0.5, 0.5, -0.5, 0.5, 0, 0);
* rect(0, 0, 20, 20);
* // Note that the translate is also reset.
* resetMatrix();
* rect(0, 0, 20, 20);
* </code>
* </div>
*
* @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 <a href="#/p5/angleMode">angleMode</a>, 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 <a href="#/p5/draw">draw()</a> begins again.
*
* Technically, <a href="#/p5/rotate">rotate()</a> multiplies the current transformation matrix
* by a rotation matrix. This function can be further controlled by
* the <a href="#/p5/push">push()</a> and <a href="#/p5/pop">pop()</a>.
*
* @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
* <div>
* <code>
* translate(width / 2, height / 2);
* rotate(PI / 3.0);
* rect(-26, -26, 52, 52);
* </code>
* </div>
*
* @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 <a href="#/p5/draw">draw()</a> begins again.
*
* @method rotateX
* @param {Number} angle the angle of rotation, specified in radians
* or degrees, depending on current angleMode
* @chainable
* @example
* <div modernizr='webgl'>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
* function draw() {
* background(255);
* rotateX(millis() / 1000);
* box();
* }
* </code>
* </div>
*
* @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 <a href="#/p5/draw">draw()</a> begins again.
*
* @method rotateY
* @param {Number} angle the angle of rotation, specified in radians
* or degrees, depending on current angleMode
* @chainable
* @example
* <div modernizr='webgl'>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
* function draw() {
* background(255);
* rotateY(millis() / 1000);
* box();
* }
* </code>
* </div>
*
* @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 <a href="#/p5/draw">draw()</a> begins again.
*
* @method rotateZ
* @param {Number} angle the angle of rotation, specified in radians
* or degrees, depending on current angleMode
* @chainable
* @example
* <div modernizr='webgl'>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
* function draw() {
* background(255);
* rotateZ(millis() / 1000);
* box();
* }
* </code>
* </div>
*
* @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 <a href="#/p5/scale">scale()</a> is called
* within <a href="#/p5/draw">draw()</a>, 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 <a href="#/p5/push">push()</a> and <a href="#/p5/pop">pop()</a>.
*
* @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
* <div>
* <code>
* rect(30, 20, 50, 50);
* scale(0.5);
* rect(30, 20, 50, 50);
* </code>
* </div>
*
* <div>
* <code>
* rect(30, 20, 50, 50);
* scale(0.5, 1.3);
* rect(30, 20, 50, 50);
* </code>
* </div>
*
* @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 <a href="#/p5/shearX">shearX()</a> is called within the <a href="#/p5/draw">draw()</a>,
* the transformation is reset when the loop begins again.
*
* Technically, <a href="#/p5/shearX">shearX()</a> multiplies the current
* transformation matrix by a rotation matrix. This function can be further
* controlled by the <a href="#/p5/push">push()</a> and <a href="#/p5/pop">pop()</a> functions.
*
* @method shearX
* @param {Number} angle angle of shear specified in radians or degrees,
* depending on current angleMode
* @chainable
* @example
* <div>
* <code>
* translate(width / 4, height / 4);
* shearX(PI / 4.0);
* rect(0, 0, 30, 30);
* </code>
* </div>
*
* @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
* <a href="#/p5/shearY">shearY()</a> is called within the <a href="#/p5/draw">draw()</a>, the transformation is reset when
* the loop begins again.
*
* Technically, <a href="#/p5/shearY">shearY()</a> multiplies the current transformation matrix by a
* rotation matrix. This function can be further controlled by the
* <a href="#/p5/push">push()</a> and <a href="#/p5/pop">pop()</a> functions.
*
* @method shearY
* @param {Number} angle angle of shear specified in radians or degrees,
* depending on current angleMode
* @chainable
* @example
* <div>
* <code>
* translate(width / 4, height / 4);
* shearY(PI / 4.0);
* rect(0, 0, 30, 30);
* </code>
* </div>
*
* @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 <a href="#/p5/translate">translate()</a> is called within <a href="#/p5/draw">draw()</a>, the
* transformation is reset when the loop begins again. This function can be
* further controlled by using <a href="#/p5/push">push()</a> and <a href="#/p5/pop">pop()</a>.
*
* @method translate
* @param {Number} x left/right translation
* @param {Number} y up/down translation
* @param {Number} [z] forward/backward translation (webgl only)
* @chainable
* @example
* <div>
* <code>
* translate(30, 20);
* rect(0, 0, 55, 55);
* </code>
* </div>
*
* <div>
* <code>
* rect(0, 0, 55, 55); // Draw rect at original 0,0
* translate(30, 20);
* rect(0, 0, 55, 55); // Draw rect at new 0,0
* translate(14, 14);
* rect(0, 0, 55, 55); // Draw rect at new 0,0
* </code>
* </div>
*
* <div>
* <code>
* function draw() {
* background(200);
* rectMode(CENTER);
* translate(width / 2, height / 2);
* translate(p5.Vector.fromAngle(millis() / 1000, 40));
* rect(0, 0, 20, 20);
* }
* </code>
* </div>
*
* @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': 59 }
],
73: [
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 <a href="#/p5/getItem">getItem</a>.
*
* 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
* <div><code>
* // 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);
* }
* </code></div>
*
* @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
* <div><code>
* // 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);
* }
* </code></div>
*
* @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 = 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
* <div class="norender">
* <code>
* 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
* }
* </code></div>
*/
_main.default.prototype.clearStorage = function() {
localStorage.clear();
};
/**
*
* Removes an item that was stored with storeItem()
*
* @method removeItem
* @param {String} key
* @for p5
*
* @example
* <div class="norender">
* <code>
* 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
* }
* </code></div>
*/
_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': 59 }
],
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 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
* <div class="norender">
* <code>
* 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
* }
* </code></div>
*/ /**
* @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 <a href="#/p5.NumberDict">p5.NumberDict</a> using the key-value pair
* or object you provide.
*
* @method createNumberDict
* @for p5
* @param {Number} key
* @param {Number} value
* @return {p5.NumberDict}
*
* @example
* <div class="norender">
* <code>
* 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
* }
* </code></div>
*/
/**
* @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
* <div class="norender">
* <code>
* function setup() {
* let myDictionary = createNumberDict(1, 10);
* myDictionary.create(2, 20);
* myDictionary.create(3, 30);
* print(myDictionary.size()); // logs 3 to the console
* }
* </code></div>
*/
_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
* <div class="norender">
* <code>
* function setup() {
* let myDictionary = createStringDict('p5', 'js');
* print(myDictionary.hasKey('p5')); // logs true to console
* }
* </code></div>
*/
_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
* <div class="norender">
* <code>
* function setup() {
* let myDictionary = createStringDict('p5', 'js');
* let myValue = myDictionary.get('p5');
* print(myValue === 'js'); // logs true to console
* }
* </code></div>
*/
_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
* <div class="norender">
* <code>
* function setup() {
* let myDictionary = createStringDict('p5', 'js');
* myDictionary.set('p5', 'JS');
* myDictionary.print(); // logs "key: p5 - value: JS" to console
* }
* </code></div>
*/
_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
* <div class="norender">
* <code>
* function setup() {
* let myDictionary = createStringDict('p5', 'js');
* myDictionary.create('happy', 'coding');
* myDictionary.print();
* // above logs "key: p5 - value: js, key: happy - value: coding" to console
* }
* </code></div>
*/
/**
* @method create
* @param {Object} obj key/value pair
*/
_main.default.TypedDict.prototype.create = function(key, value) {
if (key instanceof Object && typeof value === 'undefined') {
this._addObj(key);
} else if (typeof key !== 'undefined') {
this.set(key, value);
} else {
console.log(
'In order to create a new Dictionary entry you must pass ' +
'an object or a key, value pair'
);
}
};
/**
* Removes all previously stored key-value pairs from the Dictionary.
*
* @method clear
* @example
* <div class="norender">
* <code>
* function setup() {
* let myDictionary = createStringDict('p5', 'js');
* print(myDictionary.hasKey('p5')); // prints 'true'
* myDictionary.clear();
* print(myDictionary.hasKey('p5')); // prints 'false'
* }
* </code>
* </div>
*/
_main.default.TypedDict.prototype.clear = function() {
this.data = {};
};
/**
* Removes the key-value pair stored at the given key from the Dictionary.
*
* @method remove
* @param {Number|String} key for the pair to remove
*
* @example
* <div class="norender">
* <code>
* function setup() {
* let myDictionary = createStringDict('p5', 'js');
* myDictionary.create('happy', 'coding');
* myDictionary.print();
* // above logs "key: p5 - value: js, key: happy - value: coding" to console
* myDictionary.remove('p5');
* myDictionary.print();
* // above logs "key: happy value: coding" to console
* }
* </code></div>
*/
_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
* <div class="norender">
* <code>
* function setup() {
* let myDictionary = createStringDict('p5', 'js');
* myDictionary.create('happy', 'coding');
* myDictionary.print();
* // above logs "key: p5 - value: js, key: happy - value: coding" to console
* }
* </code>
* </div>
*/
_main.default.TypedDict.prototype.print = function() {
for (var item in this.data) {
console.log('key:'.concat(item, ' value:').concat(this.data[item]));
}
};
/**
* Converts the Dictionary into a CSV file for local download.
*
* @method saveTable
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100);
* background(200);
* text('click here to save', 10, 10, 70, 80);
* }
*
* function mousePressed() {
* if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {
* createStringDict({
* john: 1940,
* paul: 1942,
* george: 1943,
* ringo: 1940
* }).saveTable('beatles');
* }
* }
* </code>
* </div>
*/
_main.default.TypedDict.prototype.saveTable = function(filename) {
var output = '';
for (var key in this.data) {
output += ''.concat(key, ',').concat(this.data[key], '\n');
}
var blob = new Blob([output], { type: 'text/csv' });
_main.default.prototype.downloadFile(blob, filename || 'mycsv', 'csv');
};
/**
* Converts the Dictionary into a JSON file for local download.
*
* @method saveJSON
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100);
* background(200);
* text('click here to save', 10, 10, 70, 80);
* }
*
* function mousePressed() {
* if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {
* createStringDict({
* john: 1940,
* paul: 1942,
* george: 1943,
* ringo: 1940
* }).saveJSON('beatles');
* }
* }
* </code>
* </div>
*/
_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
* <div class='norender'>
* <code>
* function setup() {
* let myDictionary = createNumberDict(2, 5);
* myDictionary.add(2, 2);
* print(myDictionary.get(2)); // logs 7 to console.
* }
* </code></div>
*
*/
_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
* <div class='norender'>
* <code>
* function setup() {
* let myDictionary = createNumberDict(2, 5);
* myDictionary.sub(2, 2);
* print(myDictionary.get(2)); // logs 3 to console.
* }
* </code></div>
*
*/
_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
* <div class='norender'>
* <code>
* function setup() {
* let myDictionary = createNumberDict(2, 4);
* myDictionary.mult(2, 2);
* print(myDictionary.get(2)); // logs 8 to console.
* }
* </code></div>
*
*/
_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
* <div class='norender'>
* <code>
* function setup() {
* let myDictionary = createNumberDict(2, 8);
* myDictionary.div(2, 2);
* print(myDictionary.get(2)); // logs 4 to console.
* }
* </code></div>
*
*/
_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
* <div class='norender'>
* <code>
* function setup() {
* let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });
* let lowestValue = myDictionary.minValue(); // value is -10
* print(lowestValue);
* }
* </code></div>
*/
_main.default.NumberDict.prototype.minValue = function() {
return this._valueTest(1);
};
/**
* Return the highest number currently stored in the Dictionary.
*
* @method maxValue
* @return {Number}
* @example
* <div class='norender'>
* <code>
* function setup() {
* let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });
* let highestValue = myDictionary.maxValue(); // value is 3
* print(highestValue);
* }
* </code></div>
*/
_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
* <div class='norender'>
* <code>
* function setup() {
* let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });
* let lowestKey = myDictionary.minKey(); // value is 1.2
* print(lowestKey);
* }
* </code></div>
*/
_main.default.NumberDict.prototype.minKey = function() {
return this._keyTest(1);
};
/**
* Return the highest key currently used in the Dictionary.
*
* @method maxKey
* @return {Number}
* @example
* <div class='norender'>
* <code>
* function setup() {
* let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });
* let highestKey = myDictionary.maxKey(); // value is 4
* print(highestKey);
* }
* </code></div>
*/
_main.default.NumberDict.prototype.maxKey = function() {
return this._keyTest(-1);
};
var _default = _main.default.TypedDict;
exports.default = _default;
},
{ '../core/main': 59 }
],
75: [
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 <a href="#/p5.Element">p5.Element</a>.
* 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, <a href="#/p5.Element">p5.Element</a>, or
* HTML element to search within
* @return {p5.Element|null} <a href="#/p5.Element">p5.Element</a> containing node found
* @example
* <div><code>
* function setup() {
* createCanvas(50, 50);
* background(30);
* // move canvas down and right
* select('canvas').position(10, 30);
* }
* </code></div>
*
* <div class="norender"><code>
* // 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
* </code></div>
*/
_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 <a href="#/p5.Element">p5.Element</a>s 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, <a href="#/p5.Element">p5.Element</a>
* , or HTML element to search within
* @return {p5.Element[]} Array of <a href="#/p5.Element">p5.Element</a>s containing nodes found
* @example
* <div class='norender'><code>
* 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);
* }
* }
* </code></div>
* <div class='norender'><code>
* // 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);
* </code></div>
*/
_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 <a href="#/p5/createCanvas">createCanvas</a> or <a href="#/p5/createGraphics">createGraphics</a>.
* Event handlers are removed, and element is removed from the DOM.
* @method removeElements
* @example
* <div class='norender'><code>
* 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
* }
* </code></div>
*/
_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 .<a href="#/p5.Element/changed">changed()</a> 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
* <div><code>
* let sel;
*
* function setup() {
* textAlign(CENTER);
* background(200);
* sel = createSelect();
* sel.position(10, 10);
* sel.option('pear');
* sel.option('kiwi');
* sel.option('grape');
* sel.changed(mySelectEvent);
* }
*
* function mySelectEvent() {
* let item = sel.value();
* background(200);
* text("it's a " + item + '!', 50, 50);
* }
* </code></div>
*
* <div><code>
* let checkbox;
* let cnv;
*
* function setup() {
* checkbox = createCheckbox(' fill');
* checkbox.changed(changeFill);
* cnv = createCanvas(100, 100);
* cnv.position(0, 30);
* noFill();
* }
*
* function draw() {
* background(200);
* ellipse(50, 50, 50, 50);
* }
*
* function changeFill() {
* if (checkbox.checked()) {
* fill(0);
* } else {
* noFill();
* }
* }
* </code></div>
*
* @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 .<a href="#/p5.Element/input">input()</a> 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
* <div class='norender'><code>
* // Open your console to see the output
* function setup() {
* let inp = createInput('');
* inp.input(myInputEvent);
* }
*
* function myInputEvent() {
* console.log('you are typing: ', this.value());
* }
* </code></div>
*
* @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 <a href="#/p5.Element">p5.Element</a> holding created node
* @example
* <div class='norender'><code>
* createDiv('this is some text');
* </code></div>
*/
_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 <a href="#/p5.Element">p5.Element</a> holding created node
* @example
* <div class='norender'><code>
* createP('this is some text');
* </code></div>
*/
_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 <a href="#/p5.Element">p5.Element</a> holding created node
* @example
* <div class='norender'><code>
* createSpan('this is some text');
* </code></div>
*/
_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 <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Img#Attributes">alternate text</a> 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 <a href="#/p5.Element">p5.Element</a> holding created node
* @example
* <div class='norender'><code>
* createImg(
* 'https://p5js.org/assets/img/asterisk-01.png',
* 'the p5 magenta asterisk'
* );
* </code></div>
*/
/**
* @method createImg
* @param {String} src
* @param {String} alt
* @param {String} crossOrigin <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes">crossOrigin property</a> 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 <a href="#/p5.Element">p5.Element</a> as argument
* @return {p5.Element} pointer to <a href="#/p5.Element">p5.Element</a> 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 <a href="#/p5.Element">p5.Element</a> holding created node
* @example
* <div class='norender'><code>
* createA('http://p5js.org/', 'this is a link');
* </code></div>
*/
_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 <a href="#/p5.Element">p5.Element</a> holding created node
* @example
* <div><code>
* 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);
* }
* </code></div>
*
* <div><code>
* let slider;
* function setup() {
* colorMode(HSB);
* slider = createSlider(0, 360, 60, 40);
* slider.position(10, 10);
* slider.style('width', '80px');
* }
*
* function draw() {
* let val = slider.value();
* background(val, 100, 100, 1);
* }
* </code></div>
*/
_main.default.prototype.createSlider = function(min, max, value, step) {
_main.default._validateParameters('createSlider', arguments);
var elt = document.createElement('input');
elt.type = 'range';
elt.min = min;
elt.max = max;
if (step === 0) {
elt.step = 0.000000000000000001; // smallest valid step
} else if (step) {
elt.step = step;
}
if (typeof value === 'number') elt.value = value;
return addElement(elt, this);
};
/**
* Creates a `<button></button>` element in the DOM.
* Use .size() to set the display size of the button.
* Use .mousePressed() to specify behavior on press.
*
* @method createButton
* @param {String} label label displayed on the button
* @param {String} [value] value of the button
* @return {p5.Element} pointer to <a href="#/p5.Element">p5.Element</a> holding created node
* @example
* <div class='norender'><code>
* let button;
* function setup() {
* createCanvas(100, 100);
* background(0);
* button = createButton('click me');
* button.position(19, 19);
* button.mousePressed(changeBG);
* }
*
* function changeBG() {
* let val = random(255);
* background(val);
* }
* </code></div>
*/
_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 <a href="#/p5.Element">p5.Element</a> holding created node
* @example
* <div class='norender'><code>
* let checkbox;
*
* function setup() {
* checkbox = createCheckbox('label', false);
* checkbox.changed(myCheckedEvent);
* }
*
* function myCheckedEvent() {
* if (this.checked()) {
* console.log('Checking!');
* } else {
* console.log('Unchecking!');
* }
* }
* </code></div>
*/
_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 <a href="#/p5.Element">p5.Element</a> 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 <a href="#/p5.Element">p5.Element</a>
* - `.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
* <div><code>
* let sel;
*
* function setup() {
* textAlign(CENTER);
* background(200);
* sel = createSelect();
* sel.position(10, 10);
* sel.option('pear');
* sel.option('kiwi');
* sel.option('grape');
* sel.selected('kiwi');
* sel.changed(mySelectEvent);
* }
*
* function mySelectEvent() {
* let item = sel.value();
* background(200);
* text('It is a ' + item + '!', 50, 50);
* }
* </code></div>
*
* <div><code>
* let sel;
*
* function setup() {
* textAlign(CENTER);
* background(200);
* sel = createSelect();
* sel.position(10, 10);
* sel.option('oil');
* sel.option('milk');
* sel.option('bread');
* sel.disable('milk');
* }
* </code></div>
*/
/**
* @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 <a href="#/p5.Element/">p5.Element</a>.
* - `.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 <a href="#/p5.Element">p5.Element</a> holding created node
* @example
* <div><code>
* let radio;
*
* function setup() {
* radio = createRadio();
* radio.option('black');
* radio.option('white');
* radio.option('gray');
* radio.style('width', '60px');
* textAlign(CENTER);
* fill(255, 0, 0);
* }
*
* function draw() {
* let val = radio.value();
* background(val);
* text(val, width / 2, height / 2);
* }
* </code></div>
* <div><code>
* let radio;
*
* function setup() {
* radio = createRadio();
* radio.option(1, 'apple');
* radio.option(2, 'bread');
* radio.option(3, 'juice');
* radio.style('width', '30px');
* textAlign(CENTER);
* }
*
* function draw() {
* background(200);
* let val = radio.value();
* if (val) {
* text('item cost is $' + val, width / 2, height / 2);
* }
* }
* </code></div>
*/
/**
* @method createRadio
* @param {String} name
* @return {p5.Element} pointer to <a href="#/p5.Element">p5.Element</a> holding created node
*/
/**
* @method createRadio
* @return {p5.Element} pointer to <a href="#/p5.Element">p5.Element</a> holding created node
*/
_main.default.prototype.createRadio = function() {
// Creates a div, adds each option as an individual input inside it.
// If already given with a containerEl, will search for all input[radio]
// it, create a p5.Element out of it, add options to it and return the p5.Element.
var radioElement;
var name;
var arg0 = arguments[0];
// If existing radio Element is provided as argument 0
if (arg0 instanceof HTMLDivElement || arg0 instanceof HTMLSpanElement) {
radioElement = arg0;
if (typeof arguments[1] === 'string') name = arguments[1];
} else {
if (typeof arg0 === 'string') name = arg0;
radioElement = document.createElement('div');
}
this.elt = radioElement;
var self = addElement(radioElement, this);
self._name = name || 'radioOption';
// setup member functions
var isRadioInput = function isRadioInput(el) {
return el instanceof HTMLInputElement && el.type === 'radio';
};
var isNextLabel = function isNextLabel(el) {
return el.nextElementSibling instanceof HTMLLabelElement;
};
self._getOptionsArray = function() {
return Array.from(this.elt.children).filter(isRadioInput);
};
self.option = function(value, label) {
// return an option with this value, create if not exists.
var optionEl;
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (
var _iterator2 = self._getOptionsArray()[Symbol.iterator](), _step2;
!(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done);
_iteratorNormalCompletion2 = true
) {
var option = _step2.value;
if (option.value === value) {
optionEl = option;
break;
}
}
// Create a new option, add it to radioElement and return it.
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
if (optionEl === undefined) {
optionEl = document.createElement('input');
optionEl.setAttribute('type', 'radio');
optionEl.setAttribute('value', value);
this.elt.appendChild(optionEl);
}
// Check if label element exists, else create it
var labelElement;
if (!isNextLabel(optionEl)) {
labelElement = document.createElement('label');
optionEl.insertAdjacentElement('afterend', labelElement);
} else {
labelElement = optionEl.nextElementSibling;
}
labelElement.innerHTML = label === undefined ? value : label;
optionEl.setAttribute('name', self._name);
return optionEl;
};
self.remove = function(value) {
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (
var _iterator3 = self._getOptionsArray()[Symbol.iterator](), _step3;
!(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done);
_iteratorNormalCompletion3 = true
) {
var optionEl = _step3.value;
if (optionEl.value === value) {
if (isNextLabel(optionEl)) optionEl.nextElementSibling.remove();
optionEl.remove();
return;
}
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
};
self.value = function() {
var result = '';
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = undefined;
try {
for (
var _iterator4 = self._getOptionsArray()[Symbol.iterator](), _step4;
!(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done);
_iteratorNormalCompletion4 = true
) {
var option = _step4.value;
if (option.checked) {
result = option.value;
break;
}
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
return result;
};
self.selected = function(value) {
var result = null;
if (value === undefined) {
var _iteratorNormalCompletion5 = true;
var _didIteratorError5 = false;
var _iteratorError5 = undefined;
try {
for (
var _iterator5 = self._getOptionsArray()[Symbol.iterator](), _step5;
!(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done);
_iteratorNormalCompletion5 = true
) {
var option = _step5.value;
if (option.checked) {
result = option;
break;
}
}
} catch (err) {
_didIteratorError5 = true;
_iteratorError5 = err;
} finally {
try {
if (!_iteratorNormalCompletion5 && _iterator5.return != null) {
_iterator5.return();
}
} finally {
if (_didIteratorError5) {
throw _iteratorError5;
}
}
}
} else {
var _iteratorNormalCompletion6 = true;
var _didIteratorError6 = false;
var _iteratorError6 = undefined;
try {
for (
var _iterator6 = self._getOptionsArray()[Symbol.iterator](), _step6;
!(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done);
_iteratorNormalCompletion6 = true
) {
var _option = _step6.value;
if (_option.value === value) {
_option.setAttribute('checked', true);
result = _option;
}
}
} catch (err) {
_didIteratorError6 = true;
_iteratorError6 = err;
} finally {
try {
if (!_iteratorNormalCompletion6 && _iterator6.return != null) {
_iterator6.return();
}
} finally {
if (_didIteratorError6) {
throw _iteratorError6;
}
}
}
}
return result;
};
self.disable = function() {
var shouldDisable =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
var _iteratorNormalCompletion7 = true;
var _didIteratorError7 = false;
var _iteratorError7 = undefined;
try {
for (
var _iterator7 = self._getOptionsArray()[Symbol.iterator](), _step7;
!(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done);
_iteratorNormalCompletion7 = true
) {
var radioInput = _step7.value;
radioInput.setAttribute('disabled', shouldDisable);
}
} catch (err) {
_didIteratorError7 = true;
_iteratorError7 = err;
} finally {
try {
if (!_iteratorNormalCompletion7 && _iterator7.return != null) {
_iterator7.return();
}
} finally {
if (_didIteratorError7) {
throw _iteratorError7;
}
}
}
};
return self;
};
/**
* Creates a colorPicker element in the DOM for color input.
* The .value() method will return a hex string (#rrggbb) of the color.
* The .color() method will return a p5.Color object with the current chosen color.
*
* @method createColorPicker
* @param {String|p5.Color} [value] default color of element
* @return {p5.Element} pointer to <a href="#/p5.Element">p5.Element</a> holding created node
* @example
* <div><code>
* let colorPicker;
* function setup() {
* createCanvas(100, 100);
* colorPicker = createColorPicker('#ed225d');
* colorPicker.position(0, height + 5);
* }
*
* function draw() {
* background(colorPicker.color());
* }
* </code></div>
* <div><code>
* 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());
* }
* </code></div>
*/
_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 .<a href="#/p5.Element/size">size()</a> 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 <a href="#/p5.Element">p5.Element</a> holding created node
* @example
* <div class='norender'><code>
* function setup() {
* let inp = createInput('');
* inp.input(myInputEvent);
* }
*
* function myInputEvent() {
* console.log('you are typing: ', this.value());
* }
* </code></div>
*/
/**
* @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 <a href="#/p5.Element">p5.Element</a> holding created DOM element
* @example
* <div><code>
* let input;
* let img;
*
* function setup() {
* input = createFileInput(handleFile);
* input.position(0, 0);
* }
*
* function draw() {
* background(255);
* if (img) {
* image(img, 0, 0, width, height);
* }
* }
*
* function handleFile(file) {
* print(file);
* if (file.type === 'image') {
* img = createImg(file.data, '');
* img.hide();
* } else {
* img = null;
* }
* }
* </code></div>
*/
_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 .<a href="#/p5.Element/hide">hide()</a>
* and drawn into canvas using <a href="#/p5/image">image()</a>. 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 <a href='https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats'>this
* page</a> 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 <a href="#/p5.Element">p5.Element</a>
* @example
* <div><code>
* 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);
* }
* </code></div>
*/
_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 <a href='https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats'>this
* page for further information about supported formats</a>.
*
* @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 <a href="#/p5.Element">p5.Element</a>
* @example
* <div><code>
* 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);
* }
* </code></div>
*/
_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 .<a href="#/p5.Element/hide">hide()</a>.
* The feed can be drawn onto the canvas using <a href="#/p5/image">image()</a>.
* 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 <a href='http://w3c.github.io/mediacapture-main/getusermedia.html#media-track-constraints'>
* W3C spec</a> for possible properties. Note that not all of these are supported
* by all browsers.
*
* <em>Security note</em>: A new browser security specification requires that
* getUserMedia, which is behind <a href="#/p5/createCapture">createCapture()</a>,
* only works when you're running the code locally, or on HTTPS. Learn more
* <a href='http://stackoverflow.com/questions/34197653/getusermedia-in-chrome-47-without-using-https'>here</a>
* and <a href='https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia'>here</a>.
*
* @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 <a href="#/p5.Element">p5.Element</a>
* @example
* <div class='norender notest'>
* <code>
* let capture;
*
* function setup() {
* createCanvas(480, 480);
* capture = createCapture(VIDEO);
* capture.hide();
* }
*
* function draw() {
* image(capture, 0, 0, width, width * capture.height / capture.width);
* filter(INVERT);
* }
* </code>
* </div>
*
* <div class='norender notest'>
* <code>
* function setup() {
* createCanvas(480, 120);
* let constraints = {
* video: {
* mandatory: {
* minWidth: 1280,
* minHeight: 720
* },
* optional: [{ maxFrameRate: 10 }]
* },
* audio: true
* };
* createCapture(constraints, function(stream) {
* console.log(stream);
* });
* }
* </code>
* </div>
* <div class='norender notest'>
* <code>
* let capture;
*
* function setup() {
* createCanvas(640, 480);
* capture = createCapture(VIDEO);
* }
* function draw() {
* background(0);
* if (capture.loadedmetadata) {
* let c = capture.get(0, 0, 100, 100);
* image(c, 0, 0);
* }
* }
* </code>
* </div>
*/
_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 <a href="#/p5.Element">p5.Element</a> holding created node
* @example
* <div class='norender'><code>
* createElement('h2', 'im an h2 p5.element!');
* </code></div>
*/
_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
* <div class='norender'><code>
* let div = createDiv('div');
* div.addClass('myClass');
* </code></div>
*/
_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
* <div class='norender'><code>
* // 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');
* }
* </code></div>
*/
_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
* <div class='norender'><code>
* let div;
*
* function setup() {
* div = createDiv('div');
* div.addClass('show');
* }
*
* function mousePressed() {
* if (div.hasClass('show')) {
* div.addClass('show');
* } else {
* div.removeClass('show');
* }
* }
* </code></div>
*/
_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
* <div class='norender'><code>
* let div;
*
* function setup() {
* div = createDiv('div');
* div.addClass('show');
* }
*
* function mousePressed() {
* div.toggleClass('show');
* }
* </code></div>
*/
_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 <a href="#/p5.Element">p5.Element</a>.
* If no argument is specified, an array of children DOM nodes is returned.
*
* @method child
* @returns {Node[]} an array of child nodes
* @example
* <div class='norender'><code>
* let div0 = createDiv('this is the parent');
* let div1 = createDiv('this is the child');
* div0.child(div1); // use p5.Element
* </code></div>
* <div class='norender'><code>
* let div0 = createDiv('this is the parent');
* let div1 = createDiv('this is the child');
* div1.id('apples');
* div0.child('apples'); // use id
* </code></div>
* <div class='norender notest'><code>
* // 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
* </code></div>
*/
/**
* @method child
* @param {String|p5.Element} [child] the ID, DOM node, or <a href="#/p5.Element">p5.Element</a>
* 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
* <div><code>
* function setup() {
* let div = createDiv('').size(10, 10);
* div.style('background-color', 'orange');
* div.center();
* }
* </code></div>
*/
_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
* <div class='norender'><code>
* let div = createDiv('').size(100, 100);
* div.html('hi');
* </code></div>
* <div class='norender'><code>
* let div = createDiv('Hello ').size(100, 100);
* div.html('World', true);
* </code></div>
*/
/**
* @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 <a target="_blank"
* href="https://developer.mozilla.org/en-US/docs/Web/CSS/position">positioning scheme</a>.
* 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
* <div><code class='norender'>
* 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);
* }
* </code></div>
* <div><code class='norender'>
* 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');
* }
* </code></div>
*/
/**
* @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
* <div><code class='norender'>
* let myDiv = createDiv('I like pandas.');
* myDiv.style('font-size', '18px');
* myDiv.style('color', '#ff0000');
* </code></div>
* <div><code class='norender'>
* let col = color(25, 23, 200, 50);
* let button = createButton('button');
* button.style('background-color', col);
* button.position(10, 10);
* </code></div>
* <div><code class='norender'>
* let myDiv;
* function setup() {
* background(200);
* myDiv = createDiv('I like gray.');
* myDiv.position(20, 20);
* }
*
* function draw() {
* myDiv.style('font-size', mouseX + 'px');
* }
* </code></div>
*/
/**
* @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
* <div class='norender'><code>
* let myDiv = createDiv('I like pandas.');
* myDiv.attribute('align', 'center');
* </code></div>
*/
/**
* @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
* <div><code>
* let button;
* let checkbox;
*
* function setup() {
* checkbox = createCheckbox('enable', true);
* checkbox.changed(enableButton);
* button = createButton('button');
* button.position(10, 10);
* }
*
* function enableButton() {
* if (this.checked()) {
* // Re-enable the button
* button.removeAttribute('disabled');
* } else {
* // Disable the button
* button.attribute('disabled', '');
* }
* }
* </code></div>
*/
_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
* <div class='norender'><code>
* // gets the value
* let inp;
* function setup() {
* inp = createInput('');
* }
*
* function mousePressed() {
* print(inp.value());
* }
* </code></div>
* <div class='norender'><code>
* // sets the value
* let inp;
* function setup() {
* inp = createInput('myValue');
* }
*
* function mousePressed() {
* inp.value('myValue');
* }
* </code></div>
*/
/**
* @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
* <div class='norender'><code>
* let div = createDiv('div');
* div.style('display', 'none');
* div.show(); // turns display to block
* </code></div>
*/
_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
* <div class='norender'><code>
* let div = createDiv('this is a div');
* div.hide();
* </code></div>
*/
_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
* <div class='norender'><code>
* 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);
* }
* );
* </code></div>
*/
/**
* @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
* <div class='norender'><code>
* let myDiv = createDiv('this is some text');
* myDiv.remove();
* </code></div>
*/
_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
* <a href="https://developer.mozilla.org/en-US/docs/Web/Events/drop">drop</a> event.
* The callback will thus be provided the original
* <a href="https://developer.mozilla.org/en-US/docs/Web/API/DragEvent">DragEvent</a>.
* 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
* <div><code>
* function setup() {
* let c = createCanvas(100, 100);
* background(200);
* textAlign(CENTER);
* text('drop file', width / 2, height / 2);
* c.drop(gotFile);
* }
*
* function gotFile(file) {
* background(200);
* text('received file:', width / 2, height / 2);
* text(file.name, width / 2, height / 2 + 50);
* }
* </code></div>
*
* <div><code>
* let img;
*
* function setup() {
* let c = createCanvas(100, 100);
* background(200);
* textAlign(CENTER);
* text('drop image', width / 2, height / 2);
* c.drop(gotFile);
* }
*
* function draw() {
* if (img) {
* image(img, 0, 0, width, height);
* }
* }
*
* function gotFile(file) {
* img = createImg(file.data, '').hide();
* }
* </code></div>
*
* @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 <a href="#/p5.Element">p5.Element</a> to handle audio and video. In addition to the methods
* of <a href="#/p5.Element">p5.Element</a>, it also contains methods for controlling media. It is not
* called directly, but <a href="#/p5.MediaElement">p5.MediaElement</a>s are created by calling <a href="#/p5/createVideo">createVideo</a>,
* <a href="#/p5/createAudio">createAudio</a>, and <a href="#/p5/createCapture">createCapture</a>.
*
* @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
* <div><code>
* 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);
* }
* }
* </code></div>
*/
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
* <div><code>
* 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);
* }
* }
* </code></div>
*/
_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') {
_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
* <div><code>
* //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);
* }
* }
* }
* </code></div>
*/
_main.default.MediaElement.prototype.stop = function() {
this.elt.pause();
this.elt.currentTime = 0;
return this;
};
/**
* Pauses an HTML5 media element.
*
* @method pause
* @chainable
* @example
* <div><code>
* //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);
* }
* }
* }
* </code></div>
*/
_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
* <div><code>
* //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);
* }
* }
* }
* </code></div>
*/
_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
* <div><code>
* //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);
* }
* }
* }
* </code></div>
*/
_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() {
return _main.default._friendlyAutoplayError(_this2.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
* <div><code>
* 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);
* }
* </code></div>
*
* <div><code>
* 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();
* }
* </code></div>
*
* @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
* <div><code>
* 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);
* }
* </code></div>
* <div><code>
* let audio;
* let counter = 0;
*
* function loaded() {
* audio.play();
* }
*
* function setup() {
* audio = createAudio('assets/lucky_dragons.mp3', loaded);
* textAlign(CENTER);
* }
*
* function draw() {
* if (counter === 0) {
* background(0, 255, 0);
* text('volume(0.9)', width / 2, height / 2);
* } else if (counter === 1) {
* background(255, 255, 0);
* text('volume(0.5)', width / 2, height / 2);
* } else if (counter === 2) {
* background(255, 0, 0);
* text('volume(0.1)', width / 2, height / 2);
* }
* }
*
* function mousePressed() {
* counter++;
* if (counter === 0) {
* audio.volume(0.9);
* } else if (counter === 1) {
* audio.volume(0.5);
* } else if (counter === 2) {
* audio.volume(0.1);
* } else {
* counter = 0;
* audio.volume(0.9);
* }
* }
* </code>
* </div>
*/
/**
* @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
* <div class='norender notest'><code>
* //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();
* }
* </code></div>
*/
/**
* @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
* <div><code>
* 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;
* }
* }
* </code></div>
*/
/**
* @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
* <div><code>
* 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);
* }
* </code></div>
*/
_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
* <div><code>
* function setup() {
* let audioEl = createAudio('assets/beat.mp3');
* audioEl.showControls();
* audioEl.onended(sayDone);
* }
*
* function sayDone(elt) {
* alert('done playing ' + elt.src);
* }
* </code></div>
*/
_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
* <div><code>
* 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);
* }
* </code></div>
*/
_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
* <div><code>
* 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);
* }
* </code></div>
*/
_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
* <div><code>
* //
* //
* function setup() {
* createCanvas(200, 200);
*
* let audioEl = createAudio('assets/beat.mp3');
* audioEl.showControls();
*
* // schedule three calls to changeBackground
* 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));
* audioEl.addCue(5.0, changeBackground, color(255, 255, 0));
* }
*
* function changeBackground(val) {
* background(val);
* }
* </code></div>
*/
_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
* <div><code>
* let audioEl, id1, id2;
* function setup() {
* background(255, 255, 255);
* audioEl = createAudio('assets/beat.mp3');
* audioEl.showControls();
* // schedule five calls to changeBackground
* id1 = 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));
* id2 = audioEl.addCue(4.2, changeBackground, color(255, 255, 0));
* text('Click to remove first and last Cue!', 10, 25, 70, 80);
* }
* function mousePressed() {
* audioEl.removeCue(id1);
* audioEl.removeCue(id2);
* }
* function changeBackground(val) {
* background(val);
* }
* </code></div>
*/
_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
* <div><code>
* 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);
* }
* </code></div>
*/
_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': 59 }
],
76: [
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
* <div>
* <code>
* // Move a touchscreen device to register
* // acceleration changes.
* function draw() {
* background(220, 50);
* fill('magenta');
* ellipse(width / 2, height / 2, accelerationX);
* }
* </code>
* </div>
* @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
* <div>
* <code>
* // Move a touchscreen device to register
* // acceleration changes.
* function draw() {
* background(220, 50);
* fill('magenta');
* ellipse(width / 2, height / 2, accelerationY);
* }
* </code>
* </div>
* @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
* <div>
* <code>
* // Move a touchscreen device to register
* // acceleration changes.
* function draw() {
* background(220, 50);
* fill('magenta');
* ellipse(width / 2, height / 2, accelerationZ);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/angleMode">
* angleMode()</a> 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
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(200);
* //rotateZ(radians(rotationZ));
* rotateX(radians(rotationX));
* //rotateY(radians(rotationY));
* box(200, 200, 200);
* }
* </code>
* </div>
* @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 <a href="#/p5/angleMode">
* angleMode()</a> 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
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(200);
* //rotateZ(radians(rotationZ));
* //rotateX(radians(rotationX));
* rotateY(radians(rotationY));
* box(200, 200, 200);
* }
* </code>
* </div>
* @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 <a href="#/p5/angleMode">
* angleMode()</a> 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
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(200);
* rotateZ(radians(rotationZ));
* //rotateX(radians(rotationX));
* //rotateY(radians(rotationY));
* box(200, 200, 200);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/angleMode"> angleMode()</a> 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
* <div class='norender'>
* <code>
* // 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);
* </code>
* </div>
*
* @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 <a href="#/p5/angleMode"> angleMode()</a> 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
* <div class='norender'>
* <code>
* // 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);
* </code>
* </div>
*
* @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 <a href="#/p5/angleMode"> angleMode()</a> 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
* <div class='norender'>
* <code>
* // 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);
* </code>
* </div>
*
* @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 <a href="#/p5/deviceTurned">deviceTurned()</a>
* method is stored in the turnAxis variable. The turnAxis variable is only defined within
* the scope of deviceTurned().
* @property {String} turnAxis
* @readOnly
* @example
* <div>
* <code>
* // 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;
* }
* }
* }
* </code>
* </div>
*
* @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 <a href="#/p5/setMoveThreshold">setMoveThreshold()</a> function is used to set the movement threshold for
* the <a href="#/p5/deviceMoved">deviceMoved()</a> function. The default threshold is set to 0.5.
*
* @method setMoveThreshold
* @param {number} value The threshold value
* @example
* <div class="norender">
* <code>
* // 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);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/setShakeThreshold">setShakeThreshold()</a> function is used to set the movement threshold for
* the <a href="#/p5/deviceShaken">deviceShaken()</a> function. The default threshold is set to 30.
*
* @method setShakeThreshold
* @param {number} value The threshold value
* @example
* <div class="norender">
* <code>
* // 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);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/deviceMoved">deviceMoved()</a> 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 <a href="https://p5js.org/reference/#/p5/setMoveThreshold">setMoveThreshold()</a>.
*
* @method deviceMoved
* @example
* <div class="norender">
* <code>
* // 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;
* }
* }
* </code>
* </div>
*
* @alt
* 50x50 black rect in center of canvas. turns white on mobile when device moves
*/
/**
* The <a href="#/p5/deviceTurned">deviceTurned()</a> function is called when the device rotates by
* more than 90 degrees continuously.
*
* The axis that triggers the <a href="#/p5/deviceTurned">deviceTurned()</a> method is stored in the turnAxis
* variable. The <a href="#/p5/deviceTurned">deviceTurned()</a> 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
* <div class="norender">
* <code>
* // 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;
* }
* }
* </code>
* </div>
* <div>
* <code>
* // 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;
* }
* }
* }
* </code>
* </div>
*
* @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 <a href="#/p5/deviceShaken">deviceShaken()</a> 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 <a href="https://p5js.org/reference/#/p5/setShakeThreshold">setShakeThreshold()</a>.
*
* @method deviceShaken
* @example
* <div class="norender">
* <code>
* // 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;
* }
* }
* </code>
* </div>
*
* @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 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': 48, '../core/main': 59 }
],
77: [
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 <a href="#/p5/keyIsPressed">keyIsPressed</a> is true if any key is pressed
* and false if no keys are pressed.
*
* @property {Boolean} keyIsPressed
* @readOnly
* @example
* <div>
* <code>
* function draw() {
* if (keyIsPressed === true) {
* fill(0);
* } else {
* fill(255);
* }
* rect(25, 25, 50, 50);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/keyTyped">keyTyped()</a>. For non-ASCII keys, use the <a href="#/p5/keyCode">keyCode</a>
* variable.
*
* @property {String} key
* @readOnly
* @example
* <div><code>
* // 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.
* }
* </code></div>
*
* @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: <a href="http://keycode.info/">keycode.info</a>.
*
* @property {Integer} keyCode
* @readOnly
* @example
* <div><code>
* let fillVal = 126;
* function draw() {
* fill(fillVal);
* rect(25, 25, 50, 50);
* }
*
* function keyPressed() {
* if (keyCode === UP_ARROW) {
* fillVal = 255;
* } else if (keyCode === DOWN_ARROW) {
* fillVal = 0;
* }
* }
* </code></div>
* <div><code>
* function draw() {}
* function keyPressed() {
* background('yellow');
* text(`${key} ${keyCode}`, 10, 40);
* print(key, ' ', keyCode);
* }
* </code></div>
* @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 <a href="#/p5/keyPressed">keyPressed()</a> function is called once every time a key is pressed. The
* keyCode for the key that was pressed is stored in the <a href="#/p5/keyCode">keyCode</a> 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 <a href="#/p5/keyTyped">keyTyped()</a> 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 <a href="#/p5/keyTyped">keyTyped()</a> (and <a href="#/p5/keyReleased">keyReleased()</a> as well). The
* rate of repeat is set by the operating system and how each computer is
* configured.<br><br>
* 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
* <div>
* <code>
* let value = 0;
* function draw() {
* fill(value);
* rect(25, 25, 50, 50);
* }
* function keyPressed() {
* if (value === 0) {
* value = 255;
* } else {
* value = 0;
* }
* }
* </code>
* </div>
* <div>
* <code>
* 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;
* }
* }
* </code>
* </div>
* <div class="norender">
* <code>
* function keyPressed() {
* // Do something
* return false; // prevent any default behaviour
* }
* </code>
* </div>
*
* @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 context = this._isGlobal ? window : this;
if (typeof context.keyPressed === 'function' && !e.charCode) {
var executeDefault = context.keyPressed(e);
if (executeDefault === false) {
e.preventDefault();
}
}
};
/**
* The <a href="#/p5/keyReleased">keyReleased()</a> function is called once every time a key is released.
* See <a href="#/p5/key">key</a> and <a href="#/p5/keyCode">keyCode</a> for more information.<br><br>
* 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
* <div>
* <code>
* 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
* }
* </code>
* </div>
*
* @alt
* black rect center. turns white when key pressed and black when pressed again
*/
_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 <a href="#/p5/keyTyped">keyTyped()</a> 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 <a href="#/p5/keyPressed">keyPressed()</a> 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 <a href="#/p5/keyTyped">keyTyped()</a> (and <a href="#/p5/keyReleased">keyReleased()</a> as well). The
* rate of repeat is set by the operating system and how each computer is
* configured.<br><br>
* 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
* <div>
* <code>
* 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;
* }
* </code>
* </div>
*
* @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', 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 <a href="#/p5/keyIsDown">keyIsDown()</a> 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 <a href="#/p5/keyCode">keyCode</a> names listed
* <a href="http://p5js.org/reference/#p5/keyCode">here</a>.
*
* @method keyIsDown
* @param {Number} code The key to check for.
* @return {Boolean} whether key is down or not
* @example
* <div><code>
* 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);
* }
* </code></div>
*
* <div><code>
* 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);
* }
* </code></div>
*
* @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': 59 }
],
78: [
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
* <div class="notest">
* <code>
* 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);
* }
* </code>
* </div>
* @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
* <div class="notest">
* <code>
* 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);
* }
* </code>
* </div>
* @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
* <div>
* <code>
* // Move the mouse across the canvas
* function draw() {
* background(244, 248, 252);
* line(mouseX, 0, mouseX, 100);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* // Move the mouse across the canvas
* function draw() {
* background(244, 248, 252);
* line(0, mouseY, 100, mouseY);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* // 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);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* 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);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* 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);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* 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);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* 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);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* 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);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* function draw() {
* background(237, 34, 93);
* fill(0);
*
* if (mouseIsPressed) {
* if (mouseButton === LEFT) {
* ellipse(50, 50, 50, 50);
* }
* if (mouseButton === RIGHT) {
* rect(25, 25, 50, 50);
* }
* if (mouseButton === CENTER) {
* triangle(23, 75, 50, 20, 78, 75);
* }
* }
*
* print(mouseButton);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* function draw() {
* background(237, 34, 93);
* fill(0);
*
* if (mouseIsPressed) {
* ellipse(50, 50, 50, 50);
* } else {
* rect(25, 25, 50, 50);
* }
*
* print(mouseIsPressed);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/mouseMoved">mouseMoved()</a> function is called every time the mouse moves and a mouse
* button is not pressed.<br><br>
* 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
* <div>
* <code>
* // 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;
* }
* }
* </code>
* </div>
*
* <div class="norender">
* <code>
* function mouseMoved() {
* ellipse(mouseX, mouseY, 5, 5);
* // prevent default
* return false;
* }
* </code>
* </div>
*
* <div class="norender">
* <code>
* // returns a MouseEvent object
* // as a callback argument
* function mouseMoved(event) {
* console.log(event);
* }
* </code>
* </div>
*
* @alt
* black 50x50 rect becomes lighter with mouse movements until white then resets
* no image displayed
*/
/**
* The <a href="#/p5/mouseDragged">mouseDragged()</a> function is called once every time the mouse moves and
* a mouse button is pressed. If no <a href="#/p5/mouseDragged">mouseDragged()</a> function is defined, the
* <a href="#/p5/touchMoved">touchMoved()</a> function will be called instead if it is defined.<br><br>
* 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
* <div>
* <code>
* // 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;
* }
* }
* </code>
* </div>
*
* <div class="norender">
* <code>
* function mouseDragged() {
* ellipse(mouseX, mouseY, 5, 5);
* // prevent default
* return false;
* }
* </code>
* </div>
*
* <div class="norender">
* <code>
* // returns a MouseEvent object
* // as a callback argument
* function mouseDragged(event) {
* console.log(event);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/mousePressed">mousePressed()</a> 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
* <a href="#/p5/mousePressed">mousePressed()</a> function is defined, the <a href="#/p5/touchStarted">touchStarted()</a> function will be
* called instead if it is defined.<br><br>
* 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
* <div>
* <code>
* // 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;
* }
* }
* </code>
* </div>
*
* <div class="norender">
* <code>
* function mousePressed() {
* ellipse(mouseX, mouseY, 5, 5);
* // prevent default
* return false;
* }
* </code>
* </div>
*
* <div class="norender">
* <code>
* // returns a MouseEvent object
* // as a callback argument
* function mousePressed(event) {
* console.log(event);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/mouseReleased">mouseReleased()</a> function is called every time a mouse button is
* released. If no <a href="#/p5/mouseReleased">mouseReleased()</a> function is defined, the <a href="#/p5/touchEnded">touchEnded()</a>
* function will be called instead if it is defined.<br><br>
* 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
* <div>
* <code>
* // 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;
* }
* }
* </code>
* </div>
*
* <div class="norender">
* <code>
* function mouseReleased() {
* ellipse(mouseX, mouseY, 5, 5);
* // prevent default
* return false;
* }
* </code>
* </div>
*
* <div class="norender">
* <code>
* // returns a MouseEvent object
* // as a callback argument
* function mouseReleased(event) {
* console.log(event);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/mouseClicked">mouseClicked()</a> function is called once after a mouse button has been
* pressed and then released.<br><br>
* 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 <a href="#/p5/mousePressed">mousePressed()</a> or <a href="#/p5/mouseReleased">mouseReleased()</a>.<br><br>
* 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
* <div>
* <code>
* // 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;
* }
* }
* </code>
* </div>
*
* <div class="norender">
* <code>
* function mouseClicked() {
* ellipse(mouseX, mouseY, 5, 5);
* // prevent default
* return false;
* }
* </code>
* </div>
*
* <div class="norender">
* <code>
* // returns a MouseEvent object
* // as a callback argument
* function mouseClicked(event) {
* console.log(event);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/doubleClicked">doubleClicked()</a> 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
* <div>
* <code>
* // 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;
* }
* }
* </code>
* </div>
*
* <div class="norender">
* <code>
* function doubleClicked() {
* ellipse(mouseX, mouseY, 5, 5);
* // prevent default
* return false;
* }
* </code>
* </div>
*
* <div class="norender">
* <code>
* // returns a MouseEvent object
* // as a callback argument
* function doubleClicked(event) {
* console.log(event);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/mouseWheel">mouseWheel()</a> is executed every time a vertical mouse wheel
* event is detected either triggered by an actual mouse wheel or by a
* touchpad.<br><br>
* 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).<br><br>
* 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.<br><br>
* 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
* <div>
* <code>
* 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;
* }
* </code>
* </div>
*
* @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 <a href="#/p5/requestPointerLock">requestPointerLock()</a>
* locks the pointer to its current position and makes it invisible.
* Use <a href="#/p5/movedX">movedX</a> and <a href="#/p5/movedY">movedY</a> 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
* <div class="notest">
* <code>
* 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);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/exitPointerLock">exitPointerLock()</a>
* exits a previously triggered <a href="#/p5/requestPointerLock">pointer Lock</a>
* for example to make ui elements usable etc
*
* @method exitPointerLock
* @example
* <div class="notest">
* <code>
* //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;
* }
* }
* </code>
* </div>
*
* @alt
* cursor gets locked / unlocked on mouse-click
*/
_main.default.prototype.exitPointerLock = function() {
document.exitPointerLock();
};
var _default = _main.default;
exports.default = _default;
},
{ '../core/constants': 48, '../core/main': 59 }
],
79: [
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
* <div>
* <code>
* // 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);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/touchStarted">touchStarted()</a> function is defined, the <a href="#/p5/mousePressed">mousePressed()</a>
* function will be called instead if it is defined.<br><br>
* 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
* <div>
* <code>
* // 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;
* }
* }
* </code>
* </div>
*
* <div class="norender">
* <code>
* function touchStarted() {
* ellipse(mouseX, mouseY, 5, 5);
* // prevent default
* return false;
* }
* </code>
* </div>
*
* <div class="norender">
* <code>
* // returns a TouchEvent object
* // as a callback argument
* function touchStarted(event) {
* console.log(event);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/touchMoved">touchMoved()</a> function is called every time a touch move is registered.
* If no <a href="#/p5/touchMoved">touchMoved()</a> function is defined, the <a href="#/p5/mouseDragged">mouseDragged()</a> function will
* be called instead if it is defined.<br><br>
* 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
* <div>
* <code>
* // 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;
* }
* }
* </code>
* </div>
*
* <div class="norender">
* <code>
* function touchMoved() {
* ellipse(mouseX, mouseY, 5, 5);
* // prevent default
* return false;
* }
* </code>
* </div>
*
* <div class="norender">
* <code>
* // returns a TouchEvent object
* // as a callback argument
* function touchMoved(event) {
* console.log(event);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/touchEnded">touchEnded()</a> function is called every time a touch ends. If no
* <a href="#/p5/touchEnded">touchEnded()</a> function is defined, the <a href="#/p5/mouseReleased">mouseReleased()</a> function will be
* called instead if it is defined.<br><br>
* 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
* <div>
* <code>
* // 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;
* }
* }
* </code>
* </div>
*
* <div class="norender">
* <code>
* function touchEnded() {
* ellipse(mouseX, mouseY, 5, 5);
* // prevent default
* return false;
* }
* </code>
* </div>
*
* <div class="norender">
* <code>
* // returns a TouchEvent object
* // as a callback argument
* function touchEnded(event) {
* console.log(event);
* }
* </code>
* </div>
*
* @alt
* 50x50 black rect turns white with touch.
* no image displayed
*/
_main.default.prototype._ontouchend = function(e) {
this._setProperty('mouseIsPressed', false);
this._updateTouchCoords(e);
this._updateNextMouseCoords(e);
var context = this._isGlobal ? window : this;
var executeDefault;
if (typeof context.touchEnded === 'function') {
executeDefault = context.touchEnded(e);
if (executeDefault === false) {
e.preventDefault();
}
} else if (typeof context.mouseReleased === 'function') {
executeDefault = context.mouseReleased(e);
if (executeDefault === false) {
e.preventDefault();
}
}
};
var _default = _main.default;
exports.default = _default;
},
{ '../core/main': 59 }
],
80: [
function(_dereq_, module, exports) {
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.default = void 0; /*global ImageData:false */
/**
* This module defines the filters for use with image buffers.
*
* This module is basically a collection of functions stored in an object
* as opposed to modules. The functions are destructive, modifying
* the passed in canvas rather than creating a copy.
*
* Generally speaking users of this module will use the Filters.apply method
* on a canvas to create an effect.
*
* A number of functions are borrowed/adapted from
* http://www.html5rocks.com/en/tutorials/canvas/imagefilters/
* or the java processing implementation.
*/
var Filters = {};
/*
* Helper functions
*/
/**
* Returns the pixel buffer for a canvas
*
* @private
*
* @param {Canvas|ImageData} canvas the canvas to get pixels from
* @return {Uint8ClampedArray} a one-dimensional array containing
* the data in thc RGBA order, with integer
* values between 0 and 255
*/
Filters._toPixels = function(canvas) {
if (canvas instanceof ImageData) {
return canvas.data;
} else {
return canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height)
.data;
}
};
/**
* Returns a 32 bit number containing ARGB data at ith pixel in the
* 1D array containing pixels data.
*
* @private
*
* @param {Uint8ClampedArray} data array returned by _toPixels()
* @param {Integer} i index of a 1D Image Array
* @return {Integer} 32 bit integer value representing
* ARGB value.
*/
Filters._getARGB = function(data, i) {
var offset = i * 4;
return (
((data[offset + 3] << 24) & 0xff000000) |
((data[offset] << 16) & 0x00ff0000) |
((data[offset + 1] << 8) & 0x0000ff00) |
(data[offset + 2] & 0x000000ff)
);
};
/**
* Modifies pixels RGBA values to values contained in the data object.
*
* @private
*
* @param {Uint8ClampedArray} pixels array returned by _toPixels()
* @param {Int32Array} data source 1D array where each value
* represents ARGB values
*/
Filters._setPixels = function(pixels, data) {
var offset = 0;
for (var i = 0, al = pixels.length; i < al; i++) {
offset = i * 4;
pixels[offset + 0] = (data[i] & 0x00ff0000) >>> 16;
pixels[offset + 1] = (data[i] & 0x0000ff00) >>> 8;
pixels[offset + 2] = data[i] & 0x000000ff;
pixels[offset + 3] = (data[i] & 0xff000000) >>> 24;
}
};
/**
* Returns the ImageData object for a canvas
* https://developer.mozilla.org/en-US/docs/Web/API/ImageData
*
* @private
*
* @param {Canvas|ImageData} canvas canvas to get image data from
* @return {ImageData} Holder of pixel data (and width and
* height) for a canvas
*/
Filters._toImageData = function(canvas) {
if (canvas instanceof ImageData) {
return canvas;
} else {
return canvas
.getContext('2d')
.getImageData(0, 0, canvas.width, canvas.height);
}
};
/**
* Returns a blank ImageData object.
*
* @private
*
* @param {Integer} width
* @param {Integer} height
* @return {ImageData}
*/
Filters._createImageData = function(width, height) {
Filters._tmpCanvas = document.createElement('canvas');
Filters._tmpCtx = Filters._tmpCanvas.getContext('2d');
return this._tmpCtx.createImageData(width, height);
};
/**
* Applys a filter function to a canvas.
*
* The difference between this and the actual filter functions defined below
* is that the filter functions generally modify the pixel buffer but do
* not actually put that data back to the canvas (where it would actually
* update what is visible). By contrast this method does make the changes
* actually visible in the canvas.
*
* The apply method is the method that callers of this module would generally
* use. It has been separated from the actual filters to support an advanced
* use case of creating a filter chain that executes without actually updating
* the canvas in between everystep.
*
* @private
* @param {HTMLCanvasElement} canvas [description]
* @param {function(ImageData,Object)} func [description]
* @param {Object} filterParam [description]
*/
Filters.apply = function(canvas, func, filterParam) {
var pixelsState = canvas.getContext('2d');
var imageData = pixelsState.getImageData(0, 0, canvas.width, canvas.height);
//Filters can either return a new ImageData object, or just modify
//the one they received.
var newImageData = func(imageData, filterParam);
if (newImageData instanceof ImageData) {
pixelsState.putImageData(
newImageData,
0,
0,
0,
0,
canvas.width,
canvas.height
);
} else {
pixelsState.putImageData(imageData, 0, 0, 0, 0, canvas.width, canvas.height);
}
};
/*
* Filters
*/
/**
* Converts the image to black and white pixels depending if they are above or
* below the threshold defined by the level parameter. The parameter must be
* between 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used.
*
* Borrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/
*
* @private
* @param {Canvas} canvas
* @param {Float} level
*/
Filters.threshold = function(canvas, level) {
var pixels = Filters._toPixels(canvas);
if (level === undefined) {
level = 0.5;
}
var thresh = Math.floor(level * 255);
for (var i = 0; i < pixels.length; i += 4) {
var r = pixels[i];
var g = pixels[i + 1];
var b = pixels[i + 2];
var gray = 0.2126 * r + 0.7152 * g + 0.0722 * b;
var val = void 0;
if (gray >= thresh) {
val = 255;
} else {
val = 0;
}
pixels[i] = pixels[i + 1] = pixels[i + 2] = val;
}
};
/**
* Converts any colors in the image to grayscale equivalents.
* No parameter is used.
*
* Borrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/
*
* @private
* @param {Canvas} canvas
*/
Filters.gray = function(canvas) {
var pixels = Filters._toPixels(canvas);
for (var i = 0; i < pixels.length; i += 4) {
var r = pixels[i];
var g = pixels[i + 1];
var b = pixels[i + 2];
// CIE luminance for RGB
var gray = 0.2126 * r + 0.7152 * g + 0.0722 * b;
pixels[i] = pixels[i + 1] = pixels[i + 2] = gray;
}
};
/**
* Sets the alpha channel to entirely opaque. No parameter is used.
*
* @private
* @param {Canvas} canvas
*/
Filters.opaque = function(canvas) {
var pixels = Filters._toPixels(canvas);
for (var i = 0; i < pixels.length; i += 4) {
pixels[i + 3] = 255;
}
return pixels;
};
/**
* Sets each pixel to its inverse value. No parameter is used.
* @private
* @param {Canvas} canvas
*/
Filters.invert = function(canvas) {
var pixels = Filters._toPixels(canvas);
for (var i = 0; i < pixels.length; i += 4) {
pixels[i] = 255 - pixels[i];
pixels[i + 1] = 255 - pixels[i + 1];
pixels[i + 2] = 255 - pixels[i + 2];
}
};
/**
* Limits each channel of the image to the number of colors specified as
* the parameter. The parameter can be set to values between 2 and 255, but
* results are most noticeable in the lower ranges.
*
* Adapted from java based processing implementation
*
* @private
* @param {Canvas} canvas
* @param {Integer} level
*/
Filters.posterize = function(canvas, level) {
var pixels = Filters._toPixels(canvas);
if (level < 2 || level > 255) {
throw new Error(
'Level must be greater than 2 and less than 255 for posterize'
);
}
var levels1 = level - 1;
for (var i = 0; i < pixels.length; i += 4) {
var rlevel = pixels[i];
var glevel = pixels[i + 1];
var blevel = pixels[i + 2];
pixels[i] = ((rlevel * level) >> 8) * 255 / levels1;
pixels[i + 1] = ((glevel * level) >> 8) * 255 / levels1;
pixels[i + 2] = ((blevel * level) >> 8) * 255 / levels1;
}
};
/**
* reduces the bright areas in an image
* @private
* @param {Canvas} canvas
*/
Filters.dilate = function(canvas) {
var pixels = Filters._toPixels(canvas);
var currIdx = 0;
var maxIdx = pixels.length ? pixels.length / 4 : 0;
var out = new Int32Array(maxIdx);
var currRowIdx, maxRowIdx, colOrig, colOut, currLum;
var idxRight, idxLeft, idxUp, idxDown;
var colRight, colLeft, colUp, colDown;
var lumRight, lumLeft, lumUp, lumDown;
while (currIdx < maxIdx) {
currRowIdx = currIdx;
maxRowIdx = currIdx + canvas.width;
while (currIdx < maxRowIdx) {
colOrig = colOut = Filters._getARGB(pixels, currIdx);
idxLeft = currIdx - 1;
idxRight = currIdx + 1;
idxUp = currIdx - canvas.width;
idxDown = currIdx + canvas.width;
if (idxLeft < currRowIdx) {
idxLeft = currIdx;
}
if (idxRight >= maxRowIdx) {
idxRight = currIdx;
}
if (idxUp < 0) {
idxUp = 0;
}
if (idxDown >= maxIdx) {
idxDown = currIdx;
}
colUp = Filters._getARGB(pixels, idxUp);
colLeft = Filters._getARGB(pixels, idxLeft);
colDown = Filters._getARGB(pixels, idxDown);
colRight = Filters._getARGB(pixels, idxRight);
//compute luminance
currLum =
77 * ((colOrig >> 16) & 0xff) +
151 * ((colOrig >> 8) & 0xff) +
28 * (colOrig & 0xff);
lumLeft =
77 * ((colLeft >> 16) & 0xff) +
151 * ((colLeft >> 8) & 0xff) +
28 * (colLeft & 0xff);
lumRight =
77 * ((colRight >> 16) & 0xff) +
151 * ((colRight >> 8) & 0xff) +
28 * (colRight & 0xff);
lumUp =
77 * ((colUp >> 16) & 0xff) +
151 * ((colUp >> 8) & 0xff) +
28 * (colUp & 0xff);
lumDown =
77 * ((colDown >> 16) & 0xff) +
151 * ((colDown >> 8) & 0xff) +
28 * (colDown & 0xff);
if (lumLeft > currLum) {
colOut = colLeft;
currLum = lumLeft;
}
if (lumRight > currLum) {
colOut = colRight;
currLum = lumRight;
}
if (lumUp > currLum) {
colOut = colUp;
currLum = lumUp;
}
if (lumDown > currLum) {
colOut = colDown;
currLum = lumDown;
}
out[currIdx++] = colOut;
}
}
Filters._setPixels(pixels, out);
};
/**
* increases the bright areas in an image
* @private
* @param {Canvas} canvas
*/
Filters.erode = function(canvas) {
var pixels = Filters._toPixels(canvas);
var currIdx = 0;
var maxIdx = pixels.length ? pixels.length / 4 : 0;
var out = new Int32Array(maxIdx);
var currRowIdx, maxRowIdx, colOrig, colOut, currLum;
var idxRight, idxLeft, idxUp, idxDown;
var colRight, colLeft, colUp, colDown;
var lumRight, lumLeft, lumUp, lumDown;
while (currIdx < maxIdx) {
currRowIdx = currIdx;
maxRowIdx = currIdx + canvas.width;
while (currIdx < maxRowIdx) {
colOrig = colOut = Filters._getARGB(pixels, currIdx);
idxLeft = currIdx - 1;
idxRight = currIdx + 1;
idxUp = currIdx - canvas.width;
idxDown = currIdx + canvas.width;
if (idxLeft < currRowIdx) {
idxLeft = currIdx;
}
if (idxRight >= maxRowIdx) {
idxRight = currIdx;
}
if (idxUp < 0) {
idxUp = 0;
}
if (idxDown >= maxIdx) {
idxDown = currIdx;
}
colUp = Filters._getARGB(pixels, idxUp);
colLeft = Filters._getARGB(pixels, idxLeft);
colDown = Filters._getARGB(pixels, idxDown);
colRight = Filters._getARGB(pixels, idxRight);
//compute luminance
currLum =
77 * ((colOrig >> 16) & 0xff) +
151 * ((colOrig >> 8) & 0xff) +
28 * (colOrig & 0xff);
lumLeft =
77 * ((colLeft >> 16) & 0xff) +
151 * ((colLeft >> 8) & 0xff) +
28 * (colLeft & 0xff);
lumRight =
77 * ((colRight >> 16) & 0xff) +
151 * ((colRight >> 8) & 0xff) +
28 * (colRight & 0xff);
lumUp =
77 * ((colUp >> 16) & 0xff) +
151 * ((colUp >> 8) & 0xff) +
28 * (colUp & 0xff);
lumDown =
77 * ((colDown >> 16) & 0xff) +
151 * ((colDown >> 8) & 0xff) +
28 * (colDown & 0xff);
if (lumLeft < currLum) {
colOut = colLeft;
currLum = lumLeft;
}
if (lumRight < currLum) {
colOut = colRight;
currLum = lumRight;
}
if (lumUp < currLum) {
colOut = colUp;
currLum = lumUp;
}
if (lumDown < currLum) {
colOut = colDown;
currLum = lumDown;
}
out[currIdx++] = colOut;
}
}
Filters._setPixels(pixels, out);
};
// BLUR
// internal kernel stuff for the gaussian blur filter
var blurRadius;
var blurKernelSize;
var blurKernel;
var blurMult;
/*
* Port of https://github.com/processing/processing/blob/
* main/core/src/processing/core/PImage.java#L1250
*
* Optimized code for building the blur kernel.
* further optimized blur code (approx. 15% for radius=20)
* bigger speed gains for larger radii (~30%)
* added support for various image types (ALPHA, RGB, ARGB)
* [toxi 050728]
*/
function buildBlurKernel(r) {
var radius = (r * 3.5) | 0;
radius = radius < 1 ? 1 : radius < 248 ? radius : 248;
if (blurRadius !== radius) {
blurRadius = radius;
blurKernelSize = (1 + blurRadius) << 1;
blurKernel = new Int32Array(blurKernelSize);
blurMult = new Array(blurKernelSize);
for (var l = 0; l < blurKernelSize; l++) {
blurMult[l] = new Int32Array(256);
}
var bk, bki;
var bm, bmi;
for (var i = 1, radiusi = radius - 1; i < radius; i++) {
blurKernel[radius + i] = blurKernel[radiusi] = bki = radiusi * radiusi;
bm = blurMult[radius + i];
bmi = blurMult[radiusi--];
for (var j = 0; j < 256; j++) {
bm[j] = bmi[j] = bki * j;
}
}
bk = blurKernel[radius] = radius * radius;
bm = blurMult[radius];
for (var k = 0; k < 256; k++) {
bm[k] = bk * k;
}
}
}
// Port of https://github.com/processing/processing/blob/
// main/core/src/processing/core/PImage.java#L1433
function blurARGB(canvas, radius) {
var pixels = Filters._toPixels(canvas);
var width = canvas.width;
var height = canvas.height;
var numPackedPixels = width * height;
var argb = new Int32Array(numPackedPixels);
for (var j = 0; j < numPackedPixels; j++) {
argb[j] = Filters._getARGB(pixels, j);
}
var sum, cr, cg, cb, ca;
var read, ri, ym, ymi, bk0;
var a2 = new Int32Array(numPackedPixels);
var r2 = new Int32Array(numPackedPixels);
var g2 = new Int32Array(numPackedPixels);
var b2 = new Int32Array(numPackedPixels);
var yi = 0;
buildBlurKernel(radius);
var x, y, i;
var bm;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
cb = cg = cr = ca = sum = 0;
read = x - blurRadius;
if (read < 0) {
bk0 = -read;
read = 0;
} else {
if (read >= width) {
break;
}
bk0 = 0;
}
for (i = bk0; i < blurKernelSize; i++) {
if (read >= width) {
break;
}
var c = argb[read + yi];
bm = blurMult[i];
ca += bm[(c & -16777216) >>> 24];
cr += bm[(c & 16711680) >> 16];
cg += bm[(c & 65280) >> 8];
cb += bm[c & 255];
sum += blurKernel[i];
read++;
}
ri = yi + x;
a2[ri] = ca / sum;
r2[ri] = cr / sum;
g2[ri] = cg / sum;
b2[ri] = cb / sum;
}
yi += width;
}
yi = 0;
ym = -blurRadius;
ymi = ym * width;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
cb = cg = cr = ca = sum = 0;
if (ym < 0) {
bk0 = ri = -ym;
read = x;
} else {
if (ym >= height) {
break;
}
bk0 = 0;
ri = ym;
read = x + ymi;
}
for (i = bk0; i < blurKernelSize; i++) {
if (ri >= height) {
break;
}
bm = blurMult[i];
ca += bm[a2[read]];
cr += bm[r2[read]];
cg += bm[g2[read]];
cb += bm[b2[read]];
sum += blurKernel[i];
ri++;
read += width;
}
argb[x + yi] =
((ca / sum) << 24) | ((cr / sum) << 16) | ((cg / sum) << 8) | (cb / sum);
}
yi += width;
ymi += width;
ym++;
}
Filters._setPixels(pixels, argb);
}
Filters.blur = function(canvas, radius) {
blurARGB(canvas, radius);
};
var _default = Filters;
exports.default = _default;
},
{}
],
81: [
function(_dereq_, module, exports) {
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.default = void 0;
var _main = _interopRequireDefault(_dereq_('../core/main'));
var _omggif = _interopRequireDefault(_dereq_('omggif'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
function _nonIterableSpread() {
throw new TypeError('Invalid attempt to spread non-iterable instance');
}
function _iterableToArray(iter) {
if (
Symbol.iterator in Object(iter) ||
Object.prototype.toString.call(iter) === '[object Arguments]'
)
return Array.from(iter);
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
arr2[i] = arr[i];
}
return arr2;
}
}
/**
* Creates a new <a href="#/p5.Image">p5.Image</a> (the datatype for storing images). This provides a
* fresh buffer of pixels to play with. Set the size of the buffer with the
* width and height parameters.
*
* .<a href="#/p5.Image/pixels">pixels</a> gives access to an array containing the values for all the pixels
* in the display window.
* These values are numbers. This array is the size (including an appropriate
* factor for the <a href="#/p5/pixelDensity">pixelDensity</a>) 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. See .<a href="#/p5.Image/pixels">pixels</a> for
* more info. It may also be simpler to use <a href="#/p5.Image/set">set()</a> or <a href="#/p5.Image/get">get()</a>.
*
* Before accessing the pixels of an image, the data must loaded with the
* <a href="#/p5.Image/loadPixels">loadPixels()</a> function. After the array data has been modified, the
* <a href="#/p5.Image/updatePixels">updatePixels()</a> function must be run to update the changes.
*
* @method createImage
* @param {Integer} width width in pixels
* @param {Integer} height height in pixels
* @return {p5.Image} the <a href="#/p5.Image">p5.Image</a> object
* @example
* <div>
* <code>
* let img = createImage(66, 66);
* img.loadPixels();
* for (let i = 0; i < img.width; i++) {
* for (let j = 0; j < img.height; j++) {
* img.set(i, j, color(0, 90, 102));
* }
* }
* img.updatePixels();
* image(img, 17, 17);
* </code>
* </div>
*
* <div>
* <code>
* let img = createImage(66, 66);
* img.loadPixels();
* for (let i = 0; i < img.width; i++) {
* for (let j = 0; j < img.height; j++) {
* img.set(i, j, color(0, 90, 102, (i % img.width) * 2));
* }
* }
* img.updatePixels();
* image(img, 17, 17);
* image(img, 34, 34);
* </code>
* </div>
*
* <div>
* <code>
* let pink = color(255, 102, 204);
* let img = createImage(66, 66);
* img.loadPixels();
* let d = pixelDensity();
* let halfImage = 4 * (img.width * d) * (img.height / 2 * d);
* for (let i = 0; i < halfImage; i += 4) {
* img.pixels[i] = red(pink);
* img.pixels[i + 1] = green(pink);
* img.pixels[i + 2] = blue(pink);
* img.pixels[i + 3] = alpha(pink);
* }
* img.updatePixels();
* image(img, 17, 17);
* </code>
* </div>
*
* @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
* <div class='norender notest'><code>
* function setup() {
* let c = createCanvas(100, 100);
* background(255, 0, 0);
* saveCanvas(c, 'myCanvas', 'jpg');
* }
* </code></div>
* <div class='norender notest'><code>
* // 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();
* }
* </code></div>
*
* @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 <a href="#/p5.Image/saveFrames">saveFrames()</a> will only save the first 15 frames of an animation.
* To export longer animations, you might look into a library like
* <a href="https://github.com/spite/ccapture.js/">ccapture.js</a>.
*
* @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
* <div><code>
* function draw() {
* background(mouseX);
* }
*
* function mousePressed() {
* saveFrames('out', 'png', 1, 25, data => {
* print(data);
* });
* }
</code></div>
*
* @alt
* canvas background goes from light to dark with mouse x.
*/
_main.default.prototype.saveFrames = function(
fName,
ext,
_duration,
_fps,
callback
) {
_main.default._validateParameters('saveFrames', arguments);
var duration = _duration || 3;
duration = _main.default.prototype.constrain(duration, 0, 15);
duration = duration * 1000;
var fps = _fps || 15;
fps = _main.default.prototype.constrain(fps, 0, 22);
var count = 0;
var makeFrame = _main.default.prototype._makeFrame;
var cnv = this._curElement.elt;
var frames = [];
var frameFactory = setInterval(function() {
frames.push(makeFrame(fName + count, ext, cnv));
count++;
}, 1000 / fps);
setTimeout(function() {
clearInterval(frameFactory);
if (callback) {
callback(frames);
} else {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (
var _iterator = frames[Symbol.iterator](), _step;
!(_iteratorNormalCompletion = (_step = _iterator.next()).done);
_iteratorNormalCompletion = true
) {
var f = _step.value;
_main.default.prototype.downloadFile(f.imageData, f.filename, f.ext);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
frames = []; // clear frames
}, duration + 0.01);
};
_main.default.prototype._makeFrame = function(filename, extension, _cnv) {
var cnv;
if (this) {
cnv = this._curElement.elt;
} else {
cnv = _cnv;
}
var mimeType;
if (!extension) {
extension = 'png';
mimeType = 'image/png';
} else {
switch (extension.toLowerCase()) {
case 'png':
mimeType = 'image/png';
break;
case 'jpeg':
mimeType = 'image/jpeg';
break;
case 'jpg':
mimeType = 'image/jpeg';
break;
default:
mimeType = 'image/png';
break;
}
}
var downloadMime = 'image/octet-stream';
var imageData = cnv.toDataURL(mimeType);
imageData = imageData.replace(mimeType, downloadMime);
var thisFrame = {};
thisFrame.imageData = imageData;
thisFrame.filename = filename;
thisFrame.ext = extension;
return thisFrame;
};
var _default = _main.default;
exports.default = _default;
},
{ '../core/main': 59, omggif: 33 }
],
82: [
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 _filters = _interopRequireDefault(_dereq_('./filters'));
var _helpers = _interopRequireDefault(_dereq_('../core/helpers'));
var constants = _interopRequireWildcard(_dereq_('../core/constants'));
var _omggif = _interopRequireDefault(_dereq_('omggif'));
_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 Image
* @submodule Loading & Displaying
* @for p5
* @requires core
*/ /**
* Loads an image from a path and creates a <a href="#/p5.Image">p5.Image</a> from it.
*
* The image may not be immediately available for rendering.
* If you want to ensure that the image is ready before doing
* anything with it, place the <a href="#/p5/loadImage">loadImage()</a> call in <a href="#/p5/preload">preload()</a>.
* You may also supply a callback function to handle the image when it's ready.
*
* The path to the image should be relative to the HTML file
* that links in your sketch. Loading an image from a URL or other
* remote location may be blocked due to your browser's built-in
* security.
* You can also pass in a string of a base64 encoded image as an alternative to the file path.
* Remember to add "data:image/png;base64," in front of the string.
*
* @method loadImage
* @param {String} path Path of the image to be loaded
* @param {function(p5.Image)} [successCallback] Function to be called once
* the image is loaded. Will be passed the
* <a href="#/p5.Image">p5.Image</a>.
* @param {function(Event)} [failureCallback] called with event error if
* the image fails to load.
* @return {p5.Image} the <a href="#/p5.Image">p5.Image</a> object
* @example
* <div>
* <code>
* let img;
* function preload() {
* img = loadImage('assets/laDefense.jpg');
* }
* function setup() {
* image(img, 0, 0);
* }
* </code>
* </div>
* <div>
* <code>
* function setup() {
* // here we use a callback to display the image after loading
* loadImage('assets/laDefense.jpg', img => {
* image(img, 0, 0);
* });
* }
* </code>
* </div>
*
* @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<N), should contain integer for loop number
//this is changed to more usable values for us
//to repeat forever, loopCount = null
//everything else is just the number of loops
var loopLimit = gifReader.loopCount();
if (loopLimit === null) {
loopLimit = 1;
} else if (loopLimit === 0) {
loopLimit = null;
}
// we used the pImg for painting and saving during load
// so we have to reset it to the first frame
pImg.drawingContext.putImageData(frames[0].image, 0, 0);
pImg.gifProperties = {
displayIndex: 0,
loopLimit: loopLimit,
loopCount: 0,
frames: frames,
numFrames: numFrames,
playing: true,
timeDisplayed: 0,
lastChangeTime: 0
};
}
if (typeof successCallback === 'function') {
successCallback(pImg);
}
finishCallback();
}
/**
* Validates clipping params. Per drawImage spec sWidth and sHight cannot be
* negative or greater than image intrinsic width and height
* @private
* @param {Number} sVal
* @param {Number} iVal
* @returns {Number}
* @private
*/
function _sAssign(sVal, iVal) {
if (sVal > 0 && sVal < iVal) {
return sVal;
} else {
return iVal;
}
}
/**
* 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:
* <img src="assets/drawImage.png"></img>
*
* @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
* <div>
* <code>
* 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);
* }
* </code>
* </div>
* <div>
* <code>
* 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);
* }
* </code>
* </div>
* <div>
* <code>
* function setup() {
* // Here, we use a callback to display the image after loading
* loadImage('assets/laDefense.jpg', img => {
* image(img, 0, 0);
* });
* }
* </code>
* </div>
* <div>
* <code>
* 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);
* }
* </code>
* </div>
* @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 <a href="#/p5/colorMode">colorMode()</a>).
*
* The value for the gray parameter must be less than or equal to the current
* maximum value as specified by <a href="#/p5/colorMode">colorMode()</a>. 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
* <div>
* <code>
* let img;
* function preload() {
* img = loadImage('assets/laDefense.jpg');
* }
* function setup() {
* image(img, 0, 0);
* tint(0, 153, 204); // Tint blue
* image(img, 50, 0);
* }
* </code>
* </div>
*
* <div>
* <code>
* let img;
* function preload() {
* img = loadImage('assets/laDefense.jpg');
* }
* function setup() {
* image(img, 0, 0);
* tint(0, 153, 204, 126); // Tint blue and set transparency
* image(img, 50, 0);
* }
* </code>
* </div>
*
* <div>
* <code>
* let img;
* function preload() {
* img = loadImage('assets/laDefense.jpg');
* }
* function setup() {
* image(img, 0, 0);
* tint(255, 126); // Apply transparency without changing color
* image(img, 50, 0);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
* function setup() {
* tint(0, 153, 204); // Tint blue
* image(img, 0, 0);
* noTint(); // Disable tint
* image(img, 50, 0);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/image">image()</a> are interpreted.
* The default mode is imageMode(CORNER), which interprets the second and
* third parameters of <a href="#/p5/image">image()</a> 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 <a href="#/p5/image">image()</a>
* 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 <a href="#/p5/image">image()</a>
* 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
*
* <div>
* <code>
* let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
* function setup() {
* imageMode(CORNER);
* image(img, 10, 10, 50, 50);
* }
* </code>
* </div>
*
* <div>
* <code>
* let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
* function setup() {
* imageMode(CORNERS);
* image(img, 10, 10, 90, 40);
* }
* </code>
* </div>
*
* <div>
* <code>
* let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
* function setup() {
* imageMode(CENTER);
* image(img, 50, 50, 80, 80);
* }
* </code>
* </div>
*
* @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': 48,
'../core/friendly_errors/fes_core': 51,
'../core/friendly_errors/file_errors': 52,
'../core/friendly_errors/validate_params': 54,
'../core/helpers': 55,
'../core/main': 59,
'./filters': 80,
omggif: 33
}
],
83: [
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 <a href="#/p5.Image">p5.Image</a> class and P5 methods for
* drawing images to the main display canvas.
*/ /*
* Class methods
*/ /**
* Creates a new <a href="#/p5.Image">p5.Image</a>. A <a href="#/p5.Image">p5.Image</a> 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
* <a href="#/p5/loadImage">loadImage()</a> function. The <a href="#/p5.Image">p5.Image</a> class contains fields for the width and
* height of the image, as well as an array called <a href="#/p5.Image/pixels">pixels[]</a> 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 <a href="#/p5.Image/pixels">pixels[]</a> array, be sure to use the <a href="#/p5.Image/loadPixels">loadPixels()</a> method on
* the image to make sure that the pixel data is properly loaded.
* @example
* <div><code>
* 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);
* }
* </code></div>
*
* @class p5.Image
* @constructor
* @param {Number} width
* @param {Number} height
*/ _main.default.Image = function(width, height) {
/**
* Image width.
* @property {Number} width
* @readOnly
* @example
* <div><code>
* 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);
* }
* }
* </code></div>
*
* @alt
* rocky mountains in top and horizontal lines in corresponding colors in bottom.
*
*/ this.width = width;
/**
* Image height.
* @property {Number} height
* @readOnly
* @example
* <div><code>
* 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);
* }
* }
* </code></div>
*
* @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 <a href="#/p5.Image/loadPixels">loadPixels()</a>
* function. After the array data has been modified, the <a href="#/p5.Image/updatePixels">updatePixels()</a>
* function must be run to update the changes.
* @property {Number[]} pixels
* @example
* <div>
* <code>
* let img = createImage(66, 66);
* img.loadPixels();
* for (let i = 0; i < img.width; i++) {
* for (let j = 0; j < img.height; j++) {
* img.set(i, j, color(0, 90, 102));
* }
* }
* img.updatePixels();
* image(img, 17, 17);
* </code>
* </div>
* <div>
* <code>
* let pink = color(255, 102, 204);
* let img = createImage(66, 66);
* img.loadPixels();
* for (let i = 0; i < 4 * (width * height / 2); i += 4) {
* img.pixels[i] = red(pink);
* img.pixels[i + 1] = green(pink);
* img.pixels[i + 2] = blue(pink);
* img.pixels[i + 3] = alpha(pink);
* }
* img.updatePixels();
* image(img, 17, 17);
* </code>
* </div>
*
* @alt
* 66x66 turquoise rect in center of canvas
* 66x66 pink rect in center of canvas
*
*/
this.pixels = [];
};
/**
* Helper function for animating GIF-based images with time
*/
_main.default.Image.prototype._animateGif = function(pInst) {
var props = this.gifProperties;
var curTime = pInst._lastFrameTime + pInst.deltaTime;
if (props.lastChangeTime === 0) {
props.lastChangeTime = curTime;
}
if (props.playing) {
props.timeDisplayed = curTime - props.lastChangeTime;
var curDelay = props.frames[props.displayIndex].delay;
if (props.timeDisplayed >= curDelay) {
//GIF is bound to 'realtime' so can skip frames
var skips = Math.floor(props.timeDisplayed / curDelay);
props.timeDisplayed = 0;
props.lastChangeTime = curTime;
props.displayIndex += skips;
props.loopCount = Math.floor(props.displayIndex / props.numFrames);
if (props.loopLimit !== null && props.loopCount >= props.loopLimit) {
props.playing = false;
} else {
var ind = props.displayIndex % props.numFrames;
this.drawingContext.putImageData(props.frames[ind].image, 0, 0);
props.displayIndex = ind;
this.setModified(true);
}
}
}
};
/**
* Helper fxn for sharing pixel methods
*/
_main.default.Image.prototype._setProperty = function(prop, value) {
this[prop] = value;
this.setModified(true);
};
/**
* Loads the pixels data for this image into the [pixels] attribute.
*
* @method loadPixels
* @example
* <div><code>
* let myImage;
* let halfImage;
*
* function preload() {
* myImage = loadImage('assets/rockies.jpg');
* }
*
* function setup() {
* myImage.loadPixels();
* halfImage = 4 * myImage.width * myImage.height / 2;
* for (let i = 0; i < halfImage; i++) {
* myImage.pixels[i + halfImage] = myImage.pixels[i];
* }
* myImage.updatePixels();
* }
*
* function draw() {
* image(myImage, 0, 0, width, height);
* }
* </code></div>
*
* @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
* <div><code>
* let myImage;
* let halfImage;
*
* function preload() {
* myImage = loadImage('assets/rockies.jpg');
* }
*
* function setup() {
* myImage.loadPixels();
* halfImage = 4 * myImage.width * myImage.height / 2;
* for (let i = 0; i < halfImage; i++) {
* myImage.pixels[i + halfImage] = myImage.pixels[i];
* }
* myImage.updatePixels();
* }
*
* function draw() {
* image(myImage, 0, 0, width, height);
* }
* </code></div>
*
* @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 <a href="#/p5.Image">p5.Image</a>
* 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 <a href="#/p5.Image">p5.Image</a>
* @example
* <div><code>
* 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
* </code></div>
*
* @alt
* image of rocky mountains with 50x50 green rect in front
*/
/**
* @method get
* @return {p5.Image} the whole <a href="#/p5.Image">p5.Image</a>
*/
/**
* @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 <a href="#/p5.Image">p5.Image</a>.
*
* Note that for a large number of pixels this will
* be slower than directly manipulating the pixels array
* and then calling <a href="#/p5.Image/updatePixels">updatePixels()</a>.
*
* @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 <a href="#/p5.Color">p5.Color</a> | image to copy
* @example
* <div>
* <code>
* let img = createImage(66, 66);
* img.loadPixels();
* for (let i = 0; i < img.width; i++) {
* for (let j = 0; j < img.height; j++) {
* img.set(i, j, color(0, 90, 102, (i % img.width) * 2));
* }
* }
* img.updatePixels();
* image(img, 17, 17);
* image(img, 34, 34);
* </code>
* </div>
*
* @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
* <div><code>
* let img;
*
* function preload() {
* img = loadImage('assets/rockies.jpg');
* }
* function draw() {
* image(img, 0, 0);
* }
*
* function mousePressed() {
* img.resize(50, 100);
* }
* </code></div>
*
* @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
* <div><code>
* 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);
* }
* </code></div>
*
* @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
* <div><code>
* let photo, maskImage;
* function preload() {
* photo = loadImage('assets/rockies.jpg');
* maskImage = loadImage('assets/mask2.png');
* }
*
* function setup() {
* createCanvas(100, 100);
* photo.mask(maskImage);
* image(photo, 0, 0);
* }
* </code></div>
*
* @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.
// - Use other channels of an image. p5 uses the
// blue channel (which feels kind of arbitrary). Note: at the
// moment this method does not match native processing's original
// functionality exactly.
_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';
_main.default.Image.prototype.copy.apply(this, copyArgs);
this.drawingContext.globalCompositeOperation = currBlend;
this.setModified(true);
};
/**
* Applies an image filter to a <a href="#/p5.Image">p5.Image</a>
*
* @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
* <div><code>
* let photo1;
* let photo2;
*
* function preload() {
* photo1 = loadImage('assets/rockies.jpg');
* photo2 = loadImage('assets/rockies.jpg');
* }
*
* function setup() {
* photo2.filter(GRAY);
* image(photo1, 0, 0);
* image(photo2, width / 2, 0);
* }
* </code></div>
*
* @alt
* 2 images of rocky mountains left one in color, right in black and white
*/
_main.default.Image.prototype.filter = function(operation, value) {
_filters.default.apply(this.canvas, _filters.default[operation], value);
this.setModified(true);
};
/**
* Copies a region of pixels from one image to another, using a specified
* blend mode to do the operation.
*
* @method blend
* @param {p5.Image} srcImage source image
* @param {Integer} sx X coordinate of the source's upper left corner
* @param {Integer} sy Y coordinate of the source's upper left corner
* @param {Integer} sw source image width
* @param {Integer} sh source image height
* @param {Integer} dx X coordinate of the destination's upper left corner
* @param {Integer} dy Y coordinate of the destination's upper left corner
* @param {Integer} dw destination image width
* @param {Integer} dh destination image height
* @param {Constant} blendMode the blend mode. either
* BLEND, DARKEST, LIGHTEST, DIFFERENCE,
* MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,
* SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.
*
* Available blend modes are: normal | multiply | screen | overlay |
* darken | lighten | color-dodge | color-burn | hard-light |
* soft-light | difference | exclusion | hue | saturation |
* color | luminosity
*
* http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/
* @example
* <div><code>
* let mountains;
* let bricks;
*
* function preload() {
* mountains = loadImage('assets/rockies.jpg');
* bricks = loadImage('assets/bricks_third.jpg');
* }
*
* function setup() {
* mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, ADD);
* image(mountains, 0, 0);
* image(bricks, 0, 0);
* }
* </code></div>
* <div><code>
* let mountains;
* let bricks;
*
* function preload() {
* mountains = loadImage('assets/rockies.jpg');
* bricks = loadImage('assets/bricks_third.jpg');
* }
*
* function setup() {
* mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);
* image(mountains, 0, 0);
* image(bricks, 0, 0);
* }
* </code></div>
* <div><code>
* let mountains;
* let bricks;
*
* function preload() {
* mountains = loadImage('assets/rockies.jpg');
* bricks = loadImage('assets/bricks_third.jpg');
* }
*
* function setup() {
* mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);
* image(mountains, 0, 0);
* image(bricks, 0, 0);
* }
* </code></div>
*
* @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
*<br><br>
* 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
* <div><code>
* let photo;
*
* function preload() {
* photo = loadImage('assets/rockies.jpg');
* }
*
* function draw() {
* image(photo, 0, 0);
* }
*
* function keyTyped() {
* if (key === 's') {
* photo.save('photo', 'png');
* }
* }
* </code></div>
*
* @alt
* image of rocky mountains.
*/
_main.default.Image.prototype.save = function(filename, extension) {
if (this.gifProperties) {
_main.default.prototype.saveGif(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
* <div><code>
* 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();
* }
* </code></div>
* @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
* <div><code>
* let gif;
*
* function preload() {
* gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif');
* }
*
* function draw() {
* let frame = gif.getCurrentFrame();
* image(gif, 0, 0);
* text(frame, 10, 90);
* }
* </code></div>
* @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
* <div><code>
* 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);
* }
* </code></div>
* @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
* <div><code>
* 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);
* }
* </code></div>
* @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
* <a href="#/p5.Image/pause">pause()</a>
*
* @method play
* @example
* <div><code>
* let gif;
*
* function preload() {
* gif = loadImage('assets/nancy-liang-wind-loop-forever.gif');
* }
*
* function draw() {
* background(255);
* image(gif, 0, 0);
* }
*
* function mousePressed() {
* gif.pause();
* }
*
* function mouseReleased() {
* gif.play();
* }
* </code></div>
* @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
* <div><code>
* let gif;
*
* function preload() {
* gif = loadImage('assets/nancy-liang-wind-loop-forever.gif');
* }
*
* function draw() {
* background(255);
* image(gif, 0, 0);
* }
*
* function mousePressed() {
* gif.pause();
* }
*
* function mouseReleased() {
* gif.play();
* }
* </code></div>
* @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
* <div><code>
* let gifFast, gifSlow;
*
* function preload() {
* gifFast = loadImage('assets/arnott-wallace-eye-loop-forever.gif');
* gifSlow = loadImage('assets/arnott-wallace-eye-loop-forever.gif');
* }
*
* function setup() {
* gifFast.resize(width / 2, height / 2);
* gifSlow.resize(width / 2, height / 2);
*
* //Change the delay here
* gifFast.delay(10);
* gifSlow.delay(100);
* }
*
* function draw() {
* background(255);
* image(gifFast, 0, 0);
* image(gifSlow, width / 2, 0);
* }
* </code></div>
* @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': 59, './filters': 80 }
],
84: [
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
*/ /**
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
* /Global_Objects/Uint8ClampedArray' target='_blank'>Uint8ClampedArray</a>
* 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 <a href="#/p5/pixelDensity">pixelDensity</a>) 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 <a href="#/p5/set">set()</a> will automatically take care of
* setting all the appropriate values in <a href="#/p5/pixels">pixels[]</a> 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 <a href="#/p5/loadPixels">loadPixels()</a>
* function. After the array data has been modified, the <a href="#/p5/updatePixels">updatePixels()</a>
* 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 <a href="#/p5/slice">slice()</a> or
* <a href="#/p5/arrayCopy">arrayCopy()</a> do not
* work.
*
* @property {Number[]} pixels
* @example
* <div>
* <code>
* let pink = color(255, 102, 204);
* loadPixels();
* let d = pixelDensity();
* let halfImage = 4 * (width * d) * (height / 2 * d);
* for (let i = 0; i < halfImage; i += 4) {
* pixels[i] = red(pink);
* pixels[i + 1] = green(pink);
* pixels[i + 2] = blue(pink);
* pixels[i + 3] = alpha(pink);
* }
* updatePixels();
* </code>
* </div>
*
* @alt
* top half of canvas pink, bottom grey
*/ _main.default.prototype.pixels = []; /**
* Copies a region of pixels from one image to another, using a specified
* blend mode to do the operation.
*
* @method blend
* @param {p5.Image} srcImage source image
* @param {Integer} sx X coordinate of the source's upper left corner
* @param {Integer} sy Y coordinate of the source's upper left corner
* @param {Integer} sw source image width
* @param {Integer} sh source image height
* @param {Integer} dx X coordinate of the destination's upper left corner
* @param {Integer} dy Y coordinate of the destination's upper left corner
* @param {Integer} dw destination image width
* @param {Integer} dh destination image height
* @param {Constant} blendMode the blend mode. either
* BLEND, DARKEST, LIGHTEST, DIFFERENCE,
* MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,
* SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.
*
* @example
* <div><code>
* let img0;
* let img1;
*
* function preload() {
* img0 = loadImage('assets/rockies.jpg');
* img1 = loadImage('assets/bricks_third.jpg');
* }
*
* function setup() {
* background(img0);
* image(img1, 0, 0);
* blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);
* }
* </code></div>
* <div><code>
* let img0;
* let img1;
*
* function preload() {
* img0 = loadImage('assets/rockies.jpg');
* img1 = loadImage('assets/bricks_third.jpg');
* }
*
* function setup() {
* background(img0);
* image(img1, 0, 0);
* blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);
* }
* </code></div>
* <div><code>
* let img0;
* let img1;
*
* function preload() {
* img0 = loadImage('assets/rockies.jpg');
* img1 = loadImage('assets/bricks_third.jpg');
* }
*
* function setup() {
* background(img0);
* image(img1, 0, 0);
* blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, ADD);
* }
* </code></div>
*
* @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
* <div><code>
* let img;
*
* function preload() {
* img = loadImage('assets/rockies.jpg');
* }
*
* function setup() {
* background(img);
* copy(img, 7, 22, 10, 10, 35, 25, 50, 50);
* stroke(255);
* noFill();
* // Rectangle shows area being copied
* rect(7, 22, 10, 10);
* }
* </code></div>
*
* @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 <a href="https://github.com/aferriss/p5jsShaderExamples"
* target='_blank'>selection of shader examples</a> 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
* <div>
* <code>
* let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
* function setup() {
* image(img, 0, 0);
* filter(THRESHOLD);
* }
* </code>
* </div>
*
* <div>
* <code>
* let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
* function setup() {
* image(img, 0, 0);
* filter(GRAY);
* }
* </code>
* </div>
*
* <div>
* <code>
* let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
* function setup() {
* image(img, 0, 0);
* filter(OPAQUE);
* }
* </code>
* </div>
*
* <div>
* <code>
* let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
* function setup() {
* image(img, 0, 0);
* filter(INVERT);
* }
* </code>
* </div>
*
* <div>
* <code>
* let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
* function setup() {
* image(img, 0, 0);
* filter(POSTERIZE, 3);
* }
* </code>
* </div>
*
* <div>
* <code>
* let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
* function setup() {
* image(img, 0, 0);
* filter(DILATE);
* }
* </code>
* </div>
*
* <div>
* <code>
* let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
* function setup() {
* image(img, 0, 0);
* filter(BLUR, 3);
* }
* </code>
* </div>
*
* <div>
* <code>
* let img;
* function preload() {
* img = loadImage('assets/bricks.jpg');
* }
* function setup() {
* image(img, 0, 0);
* filter(ERODE);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/imageMode">imageMode()</a>.
*
* Getting the color of a single pixel with get(x, y) is easy, but not as fast
* as grabbing the data directly from <a href="#/p5/pixels">pixels[]</a>. The equivalent statement to
* get(x, y) using <a href="#/p5/pixels">pixels[]</a> 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 <a href="#/p5/pixels">pixels[]</a> for more information.
*
* If you want to extract an array of colors or a subimage from an p5.Image object,
* take a look at <a href="#/p5.Image/get">p5.Image.get()</a>
*
* @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 <a href="#/p5.Image">p5.Image</a>
* @example
* <div>
* <code>
* let img;
* function preload() {
* img = loadImage('assets/rockies.jpg');
* }
* function setup() {
* image(img, 0, 0);
* let c = get();
* image(c, width / 2, 0);
* }
* </code>
* </div>
*
* <div>
* <code>
* let img;
* function preload() {
* img = loadImage('assets/rockies.jpg');
* }
* function setup() {
* image(img, 0, 0);
* let c = get(50, 90);
* fill(c);
* noStroke();
* rect(25, 25, 50, 50);
* }
* </code>
* </div>
*
* @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 <a href="#/p5.Image">p5.Image</a>
*/
/**
* @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 <a href="#/p5/pixels">pixels[]</a> array. This
* function must always be called before reading from or writing to <a href="#/p5/pixels">pixels[]</a>.
* Note that only changes made with <a href="#/p5/set">set()</a> or direct manipulation of <a href="#/p5/pixels">pixels[]</a>
* will occur.
*
* @method loadPixels
* @example
* <div>
* <code>
* 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();
* }
* </code>
* </div>
*
* @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 <a href="#/p5.Color">p5.Color</a> 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 <a href="#/p5/imageMode">imageMode()</a>.
*
* After using <a href="#/p5/set">set()</a>, you must call <a href="#/p5/updatePixels">updatePixels()</a> for your changes to appear.
* This should be called once all pixels have been set, and must be called before
* calling .<a href="#/p5/get">get()</a> 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 <a href="#/p5/pixels">pixels[]</a>. Setting the <a href="#/p5/pixels">pixels[]</a>
* 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 <a href="#/p5/pixels">pixels[]</a> 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 <a href="#/p5.Color">p5.Color</a> object | a <a href="#/p5.Image">p5.Image</a> to copy
* @example
* <div>
* <code>
* let black = color(0);
* set(30, 20, black);
* set(85, 20, black);
* set(85, 75, black);
* set(30, 75, black);
* updatePixels();
* </code>
* </div>
*
* <div>
* <code>
* for (let i = 30; i < width - 15; i++) {
* for (let j = 20; j < height - 25; j++) {
* let c = color(204 - j, 153 - i, 0);
* set(i, j, c);
* }
* }
* updatePixels();
* </code>
* </div>
*
* <div>
* <code>
* let img;
* function preload() {
* img = loadImage('assets/rockies.jpg');
* }
*
* function setup() {
* set(0, 0, img);
* updatePixels();
* line(0, 0, width, height);
* line(0, height, width, 0);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/pixels">pixels[]</a> array.
* Use in conjunction with <a href="#/p5/loadPixels">loadPixels()</a>. If you're only reading pixels from
* the array, there's no need to call <a href="#/p5/updatePixels">updatePixels()</a> — updating is only
* necessary to apply changes. <a href="#/p5/updatePixels">updatePixels()</a> should be called anytime the
* pixels array is manipulated or <a href="#/p5/set">set()</a> is called, and only changes made with
* <a href="#/p5/set">set()</a> or direct changes to <a href="#/p5/pixels">pixels[]</a> 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
* <div>
* <code>
* 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();
* }
* </code>
* </div>
* @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': 46, '../core/main': 59, './filters': 80 }
],
85: [
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 <a href="https://github.com/camsong/
* fetch-jsonp">here</a>.
*
* 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
* <a href="#/p5/loadJSON">loadJSON()</a> 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 <a href="#/p5/loadJSON">loadJSON()</a> inside <a href="#/p5/preload">preload()</a> guarantees to complete the
* operation before <a href="#/p5/setup">setup()</a> and <a href="#/p5/draw">draw()</a> are called.
*
* <div><code>
* // 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);
* }
* </code></div>
*
* Outside of preload(), you may supply a callback function to handle the
* object:
* <div><code>
* 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);
* }
* </code></div>
*
* @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 <a href="#/p5/loadStrings">loadStrings()</a>
* 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 <a href="#/p5/preload">preload()</a> guarantees to complete the
* operation before <a href="#/p5/setup">setup()</a> and <a href="#/p5/draw">draw()</a> are called.
*
* <div><code>
* let result;
* function preload() {
* result = loadStrings('assets/test.txt');
* }
* function setup() {
* background(200);
* text(random(result), 10, 10, 80, 80);
* }
* </code></div>
*
* Outside of preload(), you may supply a callback function to handle the
* object:
*
* <div><code>
* function setup() {
* loadStrings('assets/test.txt', pickString);
* }
*
* function pickString(result) {
* background(200);
* text(random(result), 10, 10, 80, 80);
* }
* </code></div>
*
* @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/);
// 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 <a href="#/p5.Table">p5.Table</a> 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 <a href="#/p5/loadTable">loadTable()</a> inside <a href="#/p5/preload">preload()</a>
* guarantees to complete the operation before <a href="#/p5/setup">setup()</a> and <a href="#/p5/draw">draw()</a> are called.
* Outside of <a href="#/p5/preload">preload()</a>, 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
* <a href="#/p5/loadTable">loadTable()</a> completes. On success, the
* <a href="#/p5.Table">Table</a> 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} <a href="#/p5.Table">Table</a> object containing data
*
* @example
* <div class='norender'>
* <code>
* // 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));
* }
* }
* </code>
* </div>
*
* @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';
}
}
}
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 <a href="#/p5/loadXML">loadXML()</a> inside <a href="#/p5/preload">preload()</a>
* guarantees to complete the operation before <a href="#/p5/setup">setup()</a> and <a href="#/p5/draw">draw()</a> are called.
*
* Outside of <a href="#/p5/preload">preload()</a>, 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 <a href="#/p5/loadXML">loadXML()</a>
* 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
* <div class='norender'><code>
* // The following short XML file called "mammals.xml" is parsed
* // in the code below.
* //
* // <?xml version="1.0"?>
* // <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
* </code></div>
*
* @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 <a href="#/p5/loadBytes">loadBytes()</a>
* 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
* <div class='norender'><code>
* 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));
* }
* }
* </code></div>
*
* @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 <code>httpDo(path, 'GET')</code>. 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
* <a href="#/p5/httpGet">httpGet()</a> 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
* <div class='norender'><code>
* // 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();
* }
* </code></div>
*/
/**
* @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 <code>httpDo(path, 'POST')</code>.
*
* @method httpPost
* @param {String} path name of the file or url to load
* @param {String} [datatype] "json", "jsonp", "xml", or "text".
* If omitted, <a href="#/p5/httpPost">httpPost()</a> will guess.
* @param {Object|Boolean} [data] param data passed sent with request
* @param {function} [callback] function to be executed after
* <a href="#/p5/httpPost">httpPost()</a> 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
* <div>
* <code>
* // 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);
* });
* }
* </code>
* </div>
*
* <div><code>
* 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);
* }
* );
* }
* </code></div>
*/
/**
* @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.<br><br>
* 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
* <a href="#/p5/httpGet">httpGet()</a> 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
* <div>
* <code>
* // 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;
* }
* }
* </code>
* </div>
*/
/**
* @method httpDo
* @param {String} path
* @param {Object} options Request object options as documented in the
* "fetch" API
* <a href="https://developer.mozilla.org/en/docs/Web/API/Fetch_API">reference</a>
* @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
* <div>
* <code>
* 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) {
* const writer = createWriter('squares.txt');
* for (let i = 0; i < 10; i++) {
* writer.print(i * i);
* }
* writer.close();
* writer.clear();
* }
* }
* </code>
* </div>
*/
_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
* <div class="norender notest">
* <code>
* // 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();
* </code>
* </div>
* <div class='norender notest'>
* <code>
* // 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();
* </code>
* </div>
* <div class='norender notest'>
* <code>
* // 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();
* </code>
* </div>
* <div>
* <code>
* 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();
* }
* </code>
* </div>
*/
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
* <div class='norender notest'>
* <code>
* // 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();
* </code>
* </div>
* <div class='norender notest'>
* <code>
* let writer;
*
* function setup() {
* createCanvas(400, 400);
* // create a PrintWriter
* writer = createWriter('newFile.txt');
* }
*
* function draw() {
* writer.print([mouseX, mouseY]);
* }
*
* function mouseClicked() {
* writer.close();
* }
* </code>
* </div>
*/
this.print = function(data) {
this.content += ''.concat(data, '\n');
};
/**
* Clears the data already written to the PrintWriter object
* @method clear
* @example
* <div class ="norender notest"><code>
* // create writer object
* let writer = createWriter('newFile.txt');
* writer.write(['clear me']);
* // clear writer object here
* writer.clear();
* // close writer
* writer.close();
* </code></div>
* <div>
* <code>
* function setup() {
* button = createButton('CLEAR ME');
* button.position(21, 40);
* button.mousePressed(createFile);
* }
*
* function createFile() {
* let writer = createWriter('newFile.txt');
* writer.write(['clear me']);
* writer.clear();
* writer.close();
* }
* </code>
* </div>
*
*/
this.clear = function() {
this.content = '';
};
/**
* Closes the PrintWriter
* @method close
* @example
* <div class="norender notest">
* <code>
* // create a file called 'newFile.txt'
* let writer = createWriter('newFile.txt');
* // close the PrintWriter and save the file
* writer.close();
* </code>
* </div>
* <div class='norender notest'>
* <code>
* // 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();
* </code>
* </div>
*/
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 <a href="#/p5.Element">p5.Element</a>,an Array of
* Strings, an Array of JSON, a JSON object, a <a href="#/p5.Table">p5.Table
* </a>, a <a href="#/p5.Image">p5.Image</a>, 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,
* <code>true</code> indicates that the
* output will be optimized for filesize,
* rather than readability.
*
* @example
* <div class="norender"><code>
* // 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');
* </code></div>
*
* <div class="norender"><code>
* // Saves p5.Image as an image
* img = createImage(10, 10);
* save(img, 'myImage.png');
* </code></div>
*
* <div class="norender"><code>
* // Saves p5.Renderer object as an image
* obj = createGraphics(100, 100);
* save(obj, 'myObject.png');
* </code></div>
*
* <div class="norender"><code>
* 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');
* </code></div>
*
* <div class="norender"><code>
* let myJSON = { a: 1, b: true };
*
* // Saves pretty JSON
* save(myJSON, 'my.json');
*
* // Optimizes JSON filesize
* save(myJSON, 'my.json', true);
* </code></div>
*
* <div class="norender"><code>
* // Saves array of strings to text file with line breaks after each item
* let arrayOfStrings = ['a', 'b'];
* save(arrayOfStrings, 'my.txt');
* </code></div>
*
* @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
* <div><code>
* let json = {}; // new JSON Object
*
* json.id = 0;
* json.species = 'Panthera leo';
* json.name = 'Lion';
*
* 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) {
* saveJSON(json, 'lion.json');
* }
* }
*
* // saves the following to a file called "lion.json":
* // {
* // "id": 0,
* // "species": "Panthera leo",
* // "name": "Lion"
* // }
* </code></div>
*
* @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
* <div><code>
* 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
* </code></div>
*
* @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, '"')
.replace(/'/g, ''');
}
/**
* Writes the contents of a <a href="#/p5.Table">Table</a> 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 <a href="#/p5.Table">Table</a> 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
* <div><code>
* 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
* </code></div>
*
* @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) {
//double quotes should be inserted in csv only if contains comma separated single value
if (ext === 'csv' && 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' && 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('<html>');
pWriter.print('<head>');
var str = ' <meta http-equiv="content-type" content';
str += '="text/html;charset=utf-8" />';
pWriter.print(str);
pWriter.print('</head>');
pWriter.print('<body>');
pWriter.print(' <table>');
// make header if it has values
if (header[0] !== '0') {
pWriter.print(' <tr>');
for (var k = 0; k < header.length; k++) {
var e = escapeHelper(header[k]);
pWriter.print(' <td>'.concat(e));
pWriter.print(' </td>');
}
pWriter.print(' </tr>');
}
// make rows
for (var row = 0; row < table.rows.length; row++) {
pWriter.print(' <tr>');
for (var col = 0; col < table.columns.length; col++) {
var entry = table.rows[row].getString(col);
var htmlEntry = escapeHelper(entry);
pWriter.print(' <td>'.concat(htmlEntry));
pWriter.print(' </td>');
}
pWriter.print(' </tr>');
}
pWriter.print(' </table>');
pWriter.print('</body>');
pWriter.print('</html>');
}
// 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 <a href="#/p5/saveStrings">saveStrings</a>, <a href="#/p5/saveJSON">saveJSON</a>, <a href="#/p5/saveTable">saveTable</a> 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 <a href="#/p5/saveStrings">saveStrings</a>, <a href="#/p5/saveJSON">saveJSON</a>, <a href="#/p5/saveTable">saveTable</a> 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': 51,
'../core/friendly_errors/file_errors': 52,
'../core/friendly_errors/validate_params': 54,
'../core/main': 59,
'es6-promise/auto': 23,
'fetch-jsonp': 25,
'file-saver': 26,
'whatwg-fetch': 37
}
],
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 };
} /**
* <a href="#/p5.Table">Table</a> 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
* <a href="http://en.wikipedia.org/wiki/Comma-separated_values">
* comma separated values</a>, 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
* <a href="http://tools.ietf.org/html/rfc4180">here</a>.
* To load files, use the <a href="#/p5/loadTable">loadTable</a> method.
* To save tables to your computer, use the <a href="#/p5/save">save</a> method
* or the <a href="#/p5/saveTable">saveTable</a> method.
*
* Possible options include:
* <ul>
* <li>csv - parse the table as comma-separated values
* <li>tsv - parse the table as tab-separated values
* <li>header - this table has a header (title) row
* </ul>
*/
_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
* <div class="norender">
* <code>
* // 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]);
* }
* }
* </code>
* </div>
*/
this.columns = [];
/**
* An array containing the <a href="#/p5.Table">p5.TableRow</a> objects that make up the
* rows of the table. The same result as calling <a href="#/p5/getRows">getRows()</a>
* @property rows {p5.TableRow[]}
*/
this.rows = [];
};
/**
* Use <a href="#/p5/addRow">addRow()</a> to add a new row of data to a <a href="#/p5.Table">p5.Table</a> 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 <a href="#/p5/set">set()</a>.
*
* If a <a href="#/p5.TableRow">p5.TableRow</a> 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
* <div class="norender">
* <code>
* // 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));
* }
* </code>
* </div>
*
* @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
* <div class="norender">
* <code>
* // 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));
* }
* </code>
* </div>
*
* @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 <a href="#/p5.TableRow">p5.TableRow</a>. 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} <a href="#/p5.TableRow">p5.TableRow</a> object
*
* @example
* <div class="norender">
* <code>
* // 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));
* }
* }
* </code>
* </div>
*
*@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 <a href="#/p5.TableRow">p5.TableRow</a>s.
*
* @method getRows
* @return {p5.TableRow[]} Array of <a href="#/p5.TableRow">p5.TableRow</a>s
*
* @example
* <div class="norender">
* <code>
* // 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));
* }
* </code>
* </div>
*
* @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
* <div class="norender">
* <code>
* // 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'));
* }
* </code>
* </div>
*
* @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
* <div class="norender">
* <code>
* // 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');
* }
* </code>
* </div>
*
*@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
* <div class="norender">
* <code>
* // 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"
* }
* </code>
* </div>
*/
_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
* <div class="norender">
* <code>
* let table;
*
* function setup() {
* table = new p5.Table();
*
* table.addColumn('name');
* table.addColumn('type');
*
* let newRow = table.addRow();
* newRow.setString('name', 'Lion');
* newRow.setString('type', 'Mammal');
*
* newRow = table.addRow();
* newRow.setString('name', 'Snake');
* newRow.setString('type', 'Reptile');
*
* newRow = table.addRow();
* newRow.setString('name', 'Mosquito');
* newRow.setString('type', 'Insect');
*
* newRow = table.addRow();
* newRow.setString('name', 'Lizard');
* newRow.setString('type', 'Reptile');
*
* let rows = table.matchRows('R.*', 'type');
* for (let i = 0; i < rows.length; i++) {
* print(rows[i].getString('name') + ': ' + rows[i].getString('type'));
* }
* }
* // Sketch prints:
* // Snake: Reptile
* // Lizard: Reptile
* </code>
* </div>
*/
_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
* <div class="norender">
* <code>
* // 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"]
* }
* </code>
* </div>
*
*@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
* <div class="norender">
* <code>
* // 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');
* }
* </code>
* </div>
*
*@alt
* no image displayed
*/
_main.default.Table.prototype.clearRows = function() {
delete this.rows;
this.rows = [];
};
/**
* Use <a href="#/p5/addColumn">addColumn()</a> to add a new column to a <a href="#/p5.Table">Table</a> 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
* <div class="norender">
* <code>
* // 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));
* }
* </code>
* </div>
*
*@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
* <div>
* <code>
* // 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);
* }
* </code>
* </div>
*/
_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
* <div>
* <code>
* // 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);
* }
* </code>
* </div>
*/
_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
* <div class="norender"><code>
* function setup() {
* let table = new p5.Table();
*
* table.addColumn('name');
* table.addColumn('type');
*
* let newRow = table.addRow();
* newRow.setString('name', ' $Lion ,');
* newRow.setString('type', ',,,Mammal');
*
* newRow = table.addRow();
* newRow.setString('name', '$Snake ');
* newRow.setString('type', ',,,Reptile');
*
* table.removeTokens(',$ ');
* print(table.getArray());
* }
*
* // prints:
* // 0 "Lion" "Mamal"
* // 1 "Snake" "Reptile"
* </code></div>
*/
_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
* <div class="norender"><code>
* function setup() {
* let table = new p5.Table();
*
* table.addColumn('name');
* table.addColumn('type');
*
* let newRow = table.addRow();
* newRow.setString('name', ' Lion ,');
* newRow.setString('type', ' Mammal ');
*
* newRow = table.addRow();
* newRow.setString('name', ' Snake ');
* newRow.setString('type', ' Reptile ');
*
* table.trim();
* print(table.getArray());
* }
*
* // prints:
* // 0 "Lion" "Mamal"
* // 1 "Snake" "Reptile"
* </code></div>
*/
_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 <a href="#/p5/removeColumn">removeColumn()</a> 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
* <div class="norender">
* <code>
* // 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());
* }
* </code>
* </div>
*
*@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
* <div class="norender">
* <code>
* // 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));
* }
* </code>
* </div>
*
*@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
* <div class="norender">
* <code>
* // 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"]
* }
* </code>
* </div>
*
*@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
* <div class="norender"><code>
* // 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());
* }
* </code></div>
*
* @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
* <div class="norender">
* <code>
* // 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
* }
* </code>
* </div>
*
*@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
* <div class="norender">
* <code>
* // 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
* }
* </code>
* </div>
*
*@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
* <div class="norender">
* <code>
* // Given the CSV file "mammals.csv"
* // in the project's "assets" folder:
* //
* // id,species,name
* // 0,Capra hircus,Goat
* // 1,Panthera pardus,Leopard
* // 2,Equus zebra,Zebra
*
* let table;
*
* function preload() {
* // table is comma separated value "CSV"
* // and has specifiying header for column labels
* table = loadTable('assets/mammals.csv', 'csv', 'header');
* }
*
* function setup() {
* print(table.getString(0, 0)); // 0
* print(table.getString(0, 1)); // Capra hircus
* print(table.getString(0, 2)); // Goat
* print(table.getString(1, 0)); // 1
* print(table.getString(1, 1)); // Panthera pardus
* print(table.getString(1, 2)); // Leopard
* print(table.getString(2, 0)); // 2
* print(table.getString(2, 1)); // Equus zebra
* print(table.getString(2, 2)); // Zebra
* }
* </code>
* </div>
*
*@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
* <div class="norender">
* <code>
* // 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
* }
* </code>
* </div>
*
*@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
* <div class="norender">
* <code>
* // 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]);
* }
* }
* </code>
* </div>
*
*@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': 59 }
],
87: [
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
* <div class="norender"><code>
* // 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());
* }
* </code></div>
*
* @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
* <div class="norender"><code>
* // 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());
* }
* </code></div>
*
* @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
* <div class="norender"><code>
* // 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());
* }
* </code></div>
*
* @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
* <div class="norender"><code>
* // 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);
* }
* </code></div>
*
* @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
* <div class="norender"><code>
* // 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);
* }
* </code></div>
*
* @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
* <div class="norender"><code>
* // 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);
* }
* </code></div>
*
* @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': 59 }
],
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 };
}
/**
* @module IO
* @submodule Input
* @requires core
*/ /**
* XML is a representation of an XML object, able to parse XML code. Use
* <a href="#/p5/loadXML">loadXML()</a> to load external XML files and create XML objects.
*
* @class p5.XML
* @constructor
* @example
* <div class='norender'><code>
* // The following short XML file called "mammals.xml" is parsed
* // in the code below.
* //
* // <?xml version="1.0"?>
* // <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
* </code></div>
*
* @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
* <a href="#/p5.XML">p5.XML</a> object.
*
* @method getParent
* @return {p5.XML} element parent
* @example
* <div class='norender'><code>
* // The following short XML file called "mammals.xml" is parsed
* // in the code below.
* //
* // <?xml version="1.0"?>
* // <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
* </code></div>
*/
_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
* <div class='norender'><code>
* // The following short XML file called "mammals.xml" is parsed
* // in the code below.
* //
* // <?xml version="1.0"?>
* // <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
* </code></div>
*/
_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
* <div class='norender'><code>
* // The following short XML file called "mammals.xml" is parsed
* // in the code below.
* //
* // <?xml version="1.0"?>
* // <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
* </code></div>
*/
_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
* <div class='norender'><code>
* // The following short XML file called "mammals.xml" is parsed
* // in the code below.
* //
* // <?xml version="1.0"?>
* // <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
* </code></div>
*/
_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 <a href="#/p5.XML/getName">getName()</a>
* on each child element individually.
*
* @method listChildren
* @return {String[]} names of the children of the element
* @example<animal
* <div class='norender'><code>
* // The following short XML file called "mammals.xml" is parsed
* // in the code below.
* //
* // <?xml version="1.0"?>
* // <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"]
* </code></div>
*/
_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 <a href="#/p5.XML">p5.XML</a> 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
* <div class='norender'><code>
* // The following short XML file called "mammals.xml" is parsed
* // in the code below.
* //
* // <?xml version="1.0"?>
* // <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"
* </code></div>
*/
_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
* <div class='norender'><code>
* // The following short XML file called "mammals.xml" is parsed
* // in the code below.
* //
* // <?xml version="1.0"?>
* // <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"
* </code></div>
* <div class='norender'><code>
* let xml;
*
* function preload() {
* xml = loadXML('assets/mammals.xml');
* }
*
* function setup() {
* let secondChild = xml.getChild(1);
* print(secondChild.getContent());
* }
*
* // Sketch prints:
* // "Leopard"
* </code></div>
*/
_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 <a href="#/p5.XML">p5.XML</a> object.
* A reference to the newly created child is returned as an <a href="#/p5.XML">p5.XML</a> object.
*
* @method addChild
* @param {p5.XML} node a <a href="#/p5.XML">p5.XML</a> Object which will be the child to be added
* @example
* <div class='norender'><code>
* // The following short XML file called "mammals.xml" is parsed
* // in the code below.
* //
* // <?xml version="1.0"?>
* // <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"
* </code></div>
*/
_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
* <div class='norender'><code>
* // The following short XML file called "mammals.xml" is parsed
* // in the code below.
* //
* // <?xml version="1.0"?>
* // <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"
* </code></div>
* <div class='norender'><code>
* 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"
* </code></div>
*/
_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
* <div class='norender'><code>
* // The following short XML file called "mammals.xml" is parsed
* // in the code below.
* //
* // <?xml version="1.0"?>
* // <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
* </code></div>
*/
_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
* <div class='norender'><code>
* // The following short XML file called "mammals.xml" is parsed
* // in the code below.
* //
* // <?xml version="1.0"?>
* // <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"]
* </code></div>
*/
_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
* <div class='norender'><code>
* // The following short XML file called "mammals.xml" is parsed
* // in the code below.
* //
* // <?xml version="1.0"?>
* // <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
* </code></div>
*/
_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
* <div class='norender'><code>
* // The following short XML file called "mammals.xml" is parsed
* // in the code below.
* //
* // <?xml version="1.0"?>
* // <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
* </code></div>
*/
_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
* <div class='norender'><code>
* // The following short XML file called "mammals.xml" is parsed
* // in the code below.
* //
* // <?xml version="1.0"?>
* // <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"
* </code></div>
*/
_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
* <div class='norender'><code>
* // The following short XML file called "mammals.xml" is parsed
* // in the code below.
* //
* // <?xml version="1.0"?>
* // <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"
* </code></div>
*/
_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
* <div class='norender'><code>
* // The following short XML file called "mammals.xml" is parsed
* // in the code below.
* //
* // <?xml version="1.0"?>
* // <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"
* </code></div>
*/
_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
* <div class='norender'><code>
* // The following short XML file called "mammals.xml" is parsed
* // in the code below.
* //
* // <?xml version="1.0"?>
* // <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"
* </code></div>
*/
_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
* <div class='norender'><code>
* let xml;
*
* function preload() {
* xml = loadXML('assets/mammals.xml');
* }
*
* function setup() {
* print(xml.serialize());
* }
*
* // Sketch prints:
* // <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>
* </code></div>
*/
_main.default.XML.prototype.serialize = function() {
var xmlSerializer = new XMLSerializer();
return xmlSerializer.serializeToString(this.DOM);
};
var _default = _main.default;
exports.default = _default;
},
{ '../core/main': 59 }
],
89: [
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
* <div class = "norender"><code>
* function setup() {
* let x = -3;
* let y = abs(x);
*
* print(x); // -3
* print(y); // 3
* }
* </code></div>
*
* @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
* <div><code>
* 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);
* }
* </code></div>
*
* @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
* <div><code>
* 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
* }
* </code></div>
*
* @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
* <div><code>
* // 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!
* }
* </code></div>
*
* @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
* <div><code>
* 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);
* }
* </code></div>
*
* @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
* <div><code>
* 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);
* }
* </code></div>
*
* @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
* <div><code>
* 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);
* }
* </code></div>
*
* @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
* <div><code>
* 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);
* }
* </code></div>
*
* @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, <a href="#/p5/mag">mag()</a> 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
* <div><code>
* 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"
* }
* </code></div>
*
* @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
* <div><code>
* let value = 25;
* let m = map(value, 0, 100, 0, width);
* ellipse(m, 50, 10, 10);
</code></div>
*
* <div><code>
* 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);
* }
</code></div>
*
* @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. <a href="#/p5/max">max()</a> 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
* <div><code>
* 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);
* }
* </code></div>
*
* @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];
}
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. <a href="#/p5/min">min()</a> 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
* <div><code>
* 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);
* }
* </code></div>
*
* @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];
}
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
* <div><code>
* 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);
* }
* </code></div>
*
* @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 <a href="#/p5/pow">pow()</a> 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
* <div><code>
* 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));
* }
* </code></div>
*
* @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
* <div><code>
* let x = round(3.7);
* text(x, width / 2, height / 2);
* </code></div>
* <div><code>
* let x = round(12.782383, 2);
* text(x, width / 2, height / 2);
* </code></div>
* <div><code>
* 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);
* }
* </code></div>
*
* @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
* <div><code>
* function draw() {
* background(200);
* let eSize = 7;
* let x1 = map(mouseX, 0, width, 0, 10);
* let y1 = 80;
* let x2 = sq(x1);
* let y2 = 20;
*
* // Draw the non-squared.
* line(0, y1, width, y1);
* ellipse(x1, y1, eSize, eSize);
*
* // Draw the squared.
* line(0, y2, width, y2);
* ellipse(x2, y2, eSize, eSize);
*
* // Draw dividing line.
* stroke(100);
* line(0, height / 2, width, height / 2);
*
* // Draw text.
* let spacing = 15;
* noStroke();
* fill(0);
* text('x = ' + x1, 0, y1 + spacing);
* text('sq(x) = ' + x2, 0, y2 + spacing);
* }
* </code></div>
*
* @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
* <div><code>
* function draw() {
* background(200);
* let eSize = 7;
* let x1 = mouseX;
* let y1 = 80;
* let x2 = sqrt(x1);
* let y2 = 20;
*
* // Draw the non-squared.
* line(0, y1, width, y1);
* ellipse(x1, y1, eSize, eSize);
*
* // Draw the squared.
* line(0, y2, width, y2);
* ellipse(x2, y2, eSize, eSize);
*
* // Draw dividing line.
* stroke(100);
* line(0, height / 2, width, height / 2);
*
* // Draw text.
* noStroke();
* fill(0);
* let spacing = 15;
* text('x = ' + x1, 0, y1 + spacing);
* text('sqrt(x) = ' + x2, 0, y2 + spacing);
* }
* </code></div>
*
* @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
* <div>
* <code>
* function setup() {
* createCanvas(windowWidth, windowHeight);
* fill(0);
* text(7345.73472742, 0, 50);
* text(fract(7345.73472742), 0, 100);
* text(1.4215e-15, 150, 50);
* text(fract(1.4215e-15), 150, 100);
* }
* </code>
* </div>
* @alt
* 2 rows of numbers, the first row having 8 numbers and the second having the fractional parts of those numbers.
*/
_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': 59 }
],
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 Math
* @submodule Vector
* @for p5
* @requires core
*/ /**
* Creates a new <a href="#/p5.Vector">p5.Vector</a> (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
* <div><code>
* 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);
* }
* </code></div>
*
* @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': 59 }
],
91: [
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 <b>random()</b> 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.<br /><br /> The main difference to the
* <b>random()</b> 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 <a href="#/p5/noiseSeed">noiseSeed()</a> 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.<br /><br />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. <br /><br />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 <b>noise()</b> 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
* <div>
* <code>
* let xoff = 0.0;
*
* function draw() {
* background(204);
* xoff = xoff + 0.01;
* let n = noise(xoff) * width;
* line(n, 0, n, height);
* }
* </code>
* </div>
* <div>
* <code>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);
* }
* }
* </code>
* </div>
*
* @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 <b>noise()</b>.
*
* By changing these parameters, the signal created by the <b>noise()</b>
* 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
* <div>
* <code>
* let noiseVal;
* let noiseScale = 0.02;
*
* function setup() {
* createCanvas(100, 100);
* }
*
* function draw() {
* background(0);
* for (let y = 0; y < height; y++) {
* for (let x = 0; x < width / 2; x++) {
* noiseDetail(2, 0.2);
* noiseVal = noise((mouseX + x) * noiseScale, (mouseY + y) * noiseScale);
* stroke(noiseVal * 255);
* point(x, y);
* noiseDetail(8, 0.65);
* noiseVal = noise(
* (mouseX + x + width / 2) * noiseScale,
* (mouseY + y) * noiseScale
* );
* stroke(noiseVal * 255);
* point(x + width / 2, y);
* }
* }
* }
* </code>
* </div>
*
* @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 <b>noise()</b>. By default, <b>noise()</b>
* produces different results each time the program is run. Set the
* <b>value</b> 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
* <div>
* <code>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);
* }
* </code>
* </div>
*
* @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': 59 }
],
92: [
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 <a href="#/p5.Vector/mag">mag()</a> and <a href="#/p5.Vector/heading">heading()</a>.
*
* In many of the p5.js examples, you will see <a href="#/p5.Vector">p5.Vector</a> 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 <a href="#/p5.Vector">p5.Vector</a> 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
* <div>
* <code>
* 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);
* </code>
* </div>
*
* @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
* <div class = "norender">
* <code>
* function setup() {
* let v = createVector(20, 30);
* print(String(v)); // prints "p5.Vector Object : [20, 30, 0]"
* }
* </code>
* </div>
*
* <div>
* <code>
* 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();
* }
* </code>
* </div>
*/
_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 <a href="#/p5.Vector">p5.Vector</a>, 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
* <div class="norender">
* <code>
* 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]
* }
* </code>
* </div>
*
* <div>
* <code>
* let v0, v1;
* function setup() {
* createCanvas(100, 100);
*
* v0 = createVector(0, 0);
* v1 = createVector(50, 50);
* }
*
* function draw() {
* background(240);
*
* drawArrow(v0, v1, 'black');
* v1.set(v1.x + random(-1, 1), v1.y + random(-1, 1));
*
* noStroke();
* text('x: ' + round(v1.x) + ' y: ' + round(v1.y), 20, 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();
* }
* </code>
* </div>
*/
/**
* @method set
* @param {p5.Vector|Number[]} value the vector to set
* @chainable
*/
_main.default.Vector.prototype.set = function set(x, y, z) {
if (x instanceof _main.default.Vector) {
this.x = x.x || 0;
this.y = x.y || 0;
this.z = x.z || 0;
return this;
}
if (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;
};
/**
* Gets a copy of the vector, returns a <a href="#/p5.Vector">p5.Vector</a> object.
*
* @method copy
* @return {p5.Vector} the copy of the <a href="#/p5.Vector">p5.Vector</a> object
* @example
* <div class="norender">
* <code>
* let v1 = createVector(1, 2, 3);
* let v2 = v1.copy();
* print(v1.x === v2.x && v1.y === v2.y && v1.z === v2.z);
* // Prints "true"
* </code>
* </div>
*/
_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 <a href="#/p5.Vector">p5.Vector</a>, 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
* <div class="norender">
* <code>
* let v = createVector(1, 2, 3);
* v.add(4, 5, 6);
* // v's components are set to [5, 7, 9]
* </code>
* </div>
*
* <div class="norender">
* <code>
* 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]
* </code>
* </div>
*
* <div class="norender">
* <code>
* // Static method
* let v1 = createVector(1, 2, 3);
* let v2 = createVector(2, 3, 4);
*
* let v3 = p5.Vector.add(v1, v2);
* // v3 has components [3, 5, 7]
* print(v3);
* </code>
* </div>
*
* <div>
* <code>
* // red vector + blue vector = purple vector
* function draw() {
* background(240);
*
* let v0 = createVector(0, 0);
* let v1 = createVector(mouseX, mouseY);
* drawArrow(v0, v1, 'red');
*
* let v2 = createVector(-30, 20);
* drawArrow(v1, v2, 'blue');
*
* let v3 = p5.Vector.add(v1, v2);
* drawArrow(v0, 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();
* }
* </code>
* </div>
*/
/**
* @method add
* @param {p5.Vector|Number[]} value the vector to add
* @chainable
*/
_main.default.Vector.prototype.add = function add(x, y, z) {
if (x instanceof _main.default.Vector) {
this.x += x.x || 0;
this.y += x.y || 0;
this.z += x.z || 0;
return this;
}
if (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;
};
/// HELPERS FOR REMAINDER METHOD
var calculateRemainder2D = function calculateRemainder2D(xComponent, yComponent) {
if (xComponent !== 0) {
this.x = this.x % xComponent;
}
if (yComponent !== 0) {
this.y = this.y % yComponent;
}
return this;
};
var calculateRemainder3D = function calculateRemainder3D(
xComponent,
yComponent,
zComponent
) {
if (xComponent !== 0) {
this.x = this.x % xComponent;
}
if (yComponent !== 0) {
this.y = this.y % yComponent;
}
if (zComponent !== 0) {
this.z = this.z % zComponent;
}
return this;
};
/**
* Gives remainder of a vector when it is divided by another vector.
* See examples for more context.
*
* @method rem
* @param {Number} x the x component of divisor vector
* @param {Number} y the y component of divisor vector
* @param {Number} z the z component of divisor vector
* @chainable
* @example
* <div class='norender'>
* <code>
* let v = createVector(3, 4, 5);
* v.rem(2, 3, 4);
* // v's components are set to [1, 1, 1]
* </code>
* </div>
* <div class="norender">
* <code>
* // Static method
* let v1 = createVector(3, 4, 5);
* let v2 = createVector(2, 3, 4);
*
* let v3 = p5.Vector.rem(v1, v2);
* // v3 has components [1, 1, 1]
* print(v3);
* </code>
* </div>
*/
/**
* @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 <a href="#/p5.Vector">p5.Vector</a>, 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
* <div class="norender">
* <code>
* let v = createVector(4, 5, 6);
* v.sub(1, 1, 1);
* // v's components are set to [3, 4, 5]
* </code>
* </div>
*
* <div class="norender">
* <code>
* 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]
* </code>
* </div>
*
* <div class="norender">
* <code>
* // Static method
* let v1 = createVector(2, 3, 4);
* let v2 = createVector(1, 2, 3);
*
* let v3 = p5.Vector.sub(v1, v2);
* // v3 has components [1, 1, 1]
* print(v3);
* </code>
* </div>
*
* <div>
* <code>
* // 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();
* }
* </code>
* </div>
*/
/**
* @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 <a href="#/p5.Vector">p5.Vector</a> 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
* <div class="norender">
* <code>
* let v = createVector(1, 2, 3);
* v.mult(2);
* // v's components are set to [2, 4, 6]
* </code>
* </div>
*
* <div class="norender">
* <code>
* let v0 = createVector(1, 2, 3);
* let v1 = createVector(2, 3, 4);
* v0.mult(v1); // v0's components are set to [2, 6, 12]
* </code>
* </div>
*
* <div class="norender">
* <code>
* 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]
* </code>
* </div>
*
* <div class="norender">
* <code>
* 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]
* </code>
* </div>
*
* <div class="norender">
* <code>
* // Static method
* let v1 = createVector(1, 2, 3);
* let v2 = p5.Vector.mult(v1, 2);
* // v2 has components [2, 4, 6]
* print(v2);
* </code>
* </div>
*
* <div>
* <code>
* 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();
* }
* </code>
* </div>
*/
/**
* @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 <a href="#/p5.Vector">p5.Vector</a> 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
* <div class="norender">
* <code>
* let v = createVector(6, 4, 2);
* v.div(2); //v's components are set to [3, 2, 1]
* </code>
* </div>
*
* <div class="norender">
* <code>
* 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]
* </code>
* </div>
*
* <div class="norender">
* <code>
* 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]
* </code>
* </div>
*
* <div class="norender">
* <code>
* 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]
* </code>
* </div>
*
* <div class="norender">
* <code>
* // Static method
* let v1 = createVector(6, 4, 2);
* let v2 = p5.Vector.div(v1, 2);
* // v2 has components [3, 2, 1]
* print(v2);
* </code>
* </div>
*
* <div>
* <code>
* 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();
* }
* </code>
* </div>
*/
/**
* @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'
) {
if (x.x === 0 || x.y === 0 || x.z === 0) {
console.warn('p5.Vector.prototype.div:', 'divide by 0');
return this;
}
this.x /= x.x;
this.y /= x.y;
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} magnitude of the vector
* @example
* <div>
* <code>
* function draw() {
* background(240);
*
* let v0 = createVector(0, 0);
* let v1 = createVector(mouseX, mouseY);
* drawArrow(v0, v1, 'black');
*
* noStroke();
* text('vector length: ' + v1.mag().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();
* }
* </code>
* </div>
* <div class="norender">
* <code>
* let v = createVector(20.0, 30.0, 40.0);
* let m = v.mag();
* print(m); // Prints "53.85164807134504"
* </code>
* </div>
*/
_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 <em>(x\*x + y\*y + z\*z)</em>.)
* 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
* <div class="norender">
* <code>
* // Static method
* let v1 = createVector(6, 4, 2);
* print(v1.magSq()); // Prints "56"
* </code>
* </div>
*
* <div>
* <code>
* function draw() {
* background(240);
*
* let v0 = createVector(0, 0);
* let v1 = createVector(mouseX, mouseY);
* drawArrow(v0, v1, 'black');
*
* noStroke();
* text('vector length squared: ' + v1.magSq().toFixed(2), 10, 45, 90, 55);
* }
*
* // 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();
* }
* </code>
* </div>
*/
_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
* <div class="norender">
* <code>
* let v1 = createVector(1, 2, 3);
* let v2 = createVector(2, 3, 4);
*
* print(v1.dot(v2)); // Prints "20"
* </code>
* </div>
*
* <div class="norender">
* <code>
* //Static method
* let v1 = createVector(1, 2, 3);
* let v2 = createVector(3, 2, 1);
* print(p5.Vector.dot(v1, v2)); // Prints "10"
* </code>
* </div>
*/
/**
* @method dot
* @param {p5.Vector} value value component of the vector or a <a href="#/p5.Vector">p5.Vector</a>
* @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 <a href="#/p5.Vector">p5.Vector</a>.
* See the examples for more context.
*
* @method cross
* @param {p5.Vector} v <a href="#/p5.Vector">p5.Vector</a> to be crossed
* @return {p5.Vector} <a href="#/p5.Vector">p5.Vector</a> composed of cross product
* @example
* <div class="norender">
* <code>
* 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);
* </code>
* </div>
*
* <div class="norender">
* <code>
* // Static method
* let v1 = createVector(1, 0, 0);
* let v2 = createVector(0, 1, 0);
*
* let crossProduct = p5.Vector.cross(v1, v2);
* // crossProduct has components [0, 0, 1]
* print(crossProduct);
* </code>
* </div>
*/
_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 <a href="#/p5.Vector">p5.Vector</a>
* @return {Number} the distance
* @example
* <div class="norender">
* <code>
* let v1 = createVector(1, 0, 0);
* let v2 = createVector(0, 1, 0);
*
* let distance = v1.dist(v2); // distance is 1.4142...
* print(distance);
* </code>
* </div>
*
* <div class="norender">
* <code>
* // Static method
* let v1 = createVector(1, 0, 0);
* let v2 = createVector(0, 1, 0);
*
* let distance = p5.Vector.dist(v1, v2);
* // distance is 1.4142...
* print(distance);
* </code>
* </div>
*
* <div>
* <code>
* 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');
*
* noStroke();
* text('distance between vectors: ' + v2.dist(v1).toFixed(2), 5, 50, 95, 50);
* }
*
* // 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();
* }
* </code>
* </div>
*/
_main.default.Vector.prototype.dist = function dist(v) {
return v
.copy()
.sub(this)
.mag();
};
/**
* Normalize the vector to length 1 (make it a unit vector).
*
* @method normalize
* @return {p5.Vector} normalized <a href="#/p5.Vector">p5.Vector</a>
* @example
* <div class="norender">
* <code>
* let v = createVector(10, 20, 2);
* // v has components [10.0, 20.0, 2.0]
* v.normalize();
* // v's components are set to
* // [0.4454354, 0.8908708, 0.089087084]
* </code>
* </div>
* <div>
* <code>
* function draw() {
* background(240);
*
* let v0 = createVector(50, 50);
* let v1 = createVector(mouseX - 50, mouseY - 50);
*
* drawArrow(v0, v1, 'red');
* v1.normalize();
* drawArrow(v0, v1.mult(35), 'blue');
*
* noFill();
* ellipse(50, 50, 35 * 2);
* }
*
* // 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();
* }
* </code>
* </div>
*/
_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 <b>max</b>
* parameter.
*
* @method limit
* @param {Number} max the maximum magnitude for the vector
* @chainable
* @example
* <div class="norender">
* <code>
* 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]
* </code>
* </div>
* <div>
* <code>
* function draw() {
* background(240);
*
* let v0 = createVector(50, 50);
* let v1 = createVector(mouseX - 50, mouseY - 50);
*
* drawArrow(v0, v1, 'red');
* drawArrow(v0, v1.limit(35), 'blue');
*
* noFill();
* ellipse(50, 50, 35 * 2);
* }
*
* // 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();
* }
* </code>
* </div>
*/
_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 <b>len</b>
* parameter.
*
* @method setMag
* @param {number} len the new length for this vector
* @chainable
* @example
* <div class="norender">
* <code>
* 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]
* </code>
* </div>
*
* <div>
* <code>
* 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();
* }
* </code>
* </div>
*/
_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 <a src="#/p5/createVector">createVector()</a>
* will take the current <a = src="#/p5/angleMode">angleMode</a> into consideration, and give the angle
* in radians or degree accordingly.
*
* @method heading
* @return {Number} the angle of rotation
* @example
* <div class = "norender">
* <code>
* function setup() {
* let v1 = createVector(30, 50);
* print(v1.heading()); // 1.0303768265243125
*
* v1 = createVector(40, 50);
* print(v1.heading()); // 0.8960553845713439
*
* v1 = createVector(30, 70);
* print(v1.heading()); // 1.1659045405098132
* }
* </code>
* </div>
*
* <div>
* <code>
* function draw() {
* background(240);
*
* let v0 = createVector(50, 50);
* let v1 = createVector(mouseX - 50, mouseY - 50);
*
* drawArrow(v0, v1, 'black');
*
* let myHeading = v1.heading();
* noStroke();
* text(
* 'vector heading: ' +
* myHeading.toFixed(2) +
* ' radians or ' +
* degrees(myHeading).toFixed(2) +
* ' degrees',
* 10,
* 50,
* 90,
* 50
* );
* }
*
* // 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();
* }
* </code>
* </div>
*/
_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 to a specific angle (only 2D vectors), magnitude remains the
* same
*
* @method setHeading
* @param {number} angle the angle of rotation
* @chainable
* @example
* <div class="norender">
* <code>
* 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
* </code>
* </div>
*/
_main.default.Vector.prototype.setHeading = function setHeading(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
* <div class="norender">
* <code>
* 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]
* </code>
* </div>
*
* <div>
* <code>
* 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();
* }
* </code>
* </div>
*/
_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 <a href="#/p5.Vector">p5.Vector</a>
* @return {Number} the angle between (in radians)
* @example
* <div class="norender">
* <code>
* let v1 = createVector(1, 0, 0);
* let v2 = createVector(0, 1, 0);
*
* let angle = v1.angleBetween(v2);
* // angle is PI/2
* print(angle);
* </code>
* </div>
*
* <div>
* <code>
* function draw() {
* background(240);
* let v0 = createVector(50, 50);
*
* let v1 = createVector(50, 0);
* drawArrow(v0, v1, 'red');
*
* let v2 = createVector(mouseX - 50, mouseY - 50);
* drawArrow(v0, v2, 'blue');
*
* let angleBetween = v1.angleBetween(v2);
* noStroke();
* text(
* 'angle between: ' +
* angleBetween.toFixed(2) +
* ' radians or ' +
* degrees(angleBetween).toFixed(2) +
* ' degrees',
* 10,
* 50,
* 90,
* 50
* );
* }
*
* // 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();
* }
* </code>
* </div>
*/
_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
* <div class="norender">
* <code>
* let v = createVector(1, 1, 0);
*
* v.lerp(3, 3, 0, 0.5); // v now has components [2,2,0]
* </code>
* </div>
*
* <div class="norender">
* <code>
* let v1 = createVector(0, 0, 0);
* let v2 = createVector(100, 100, 0);
*
* let v3 = p5.Vector.lerp(v1, v2, 0.5);
* // v3 has components [50,50,0]
* print(v3);
* </code>
* </div>
*
* <div>
* <code>
* let step = 0.01;
* let amount = 0;
*
* function draw() {
* background(240);
* let v0 = createVector(0, 0);
*
* let v1 = createVector(mouseX, mouseY);
* drawArrow(v0, v1, 'red');
*
* let v2 = createVector(90, 90);
* drawArrow(v0, v2, 'blue');
*
* if (amount > 1 || amount < 0) {
* step *= -1;
* }
* amount += step;
* let v3 = p5.Vector.lerp(v1, v2, amount);
*
* drawArrow(v0, 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();
* }
* </code>
* </div>
*/
/**
* @method lerp
* @param {p5.Vector} v the <a href="#/p5.Vector">p5.Vector</a> 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 <a href="#/p5.Vector">p5.Vector</a> to reflect about, will be normalized by this method
* @chainable
* @example
* <div class="norender">
* <code>
* 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]
* </code>
* </div>
*
* <div>
* <code>
* 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();
* }
* </code>
* </div>
*/
_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 <b>p5.Vector.<a href="#/p5.Vector/copy">copy()</a></b> method to copy into your own
* array.
*
* @method array
* @return {Number[]} an Array with the 3 values
* @example
* <div class = "norender">
* <code>
* function setup() {
* let v = createVector(20, 30);
* print(v.array()); // Prints : Array [20, 30, 0]
* }
* </code>
* </div>
*
* <div class="norender">
* <code>
* 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"
* </code>
* </div>
*/
_main.default.Vector.prototype.array = function array() {
return [this.x || 0, this.y || 0, this.z || 0];
};
/**
* Equality check against a <a href="#/p5.Vector">p5.Vector</a>
*
* @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
* <div class = "norender">
* <code>
* let v1 = createVector(5, 10, 20);
* let v2 = createVector(5, 10, 20);
* let v3 = createVector(13, 10, 19);
*
* print(v1.equals(v2.x, v2.y, v2.z)); // true
* print(v1.equals(v3.x, v3.y, v3.z)); // false
* </code>
* </div>
*
* <div class="norender">
* <code>
* let v1 = createVector(10.0, 20.0, 30.0);
* let v2 = createVector(10.0, 20.0, 30.0);
* let v3 = createVector(0.0, 0.0, 0.0);
* print(v1.equals(v2)); // true
* print(v1.equals(v3)); // false
* </code>
* </div>
*/
/**
* @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 <a href="#/p5/angleMode">angleMode</a>)
* @param {Number} [length] the length of the new vector (defaults to 1)
* @return {p5.Vector} the new <a href="#/p5.Vector">p5.Vector</a> object
* @example
* <div>
* <code>
* 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();
* }
* </code>
* </div>
*/
_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 <a href="#/p5.Vector">p5.Vector</a> object
* @example
* <div modernizr='webgl'>
* <code>
* 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);
* }
* </code>
* </div>
*/
_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 <a href="#/p5.Vector">p5.Vector</a> object
* @example
* <div class="norender">
* <code>
* 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);
* </code>
* </div>
*
* <div>
* <code>
* 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();
* }
* </code>
* </div>
*/
_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 <a href="#/p5.Vector">p5.Vector</a> object
* @example
* <div class="norender">
* <code>
* 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);
* </code>
* </div>
*/
_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 <a href="#/p5.Vector">p5.Vector</a> to add
* @param {p5.Vector} v2 a <a href="#/p5.Vector">p5.Vector</a> to add
* @param {p5.Vector} [target] the vector to receive the result (Optional)
* @return {p5.Vector} the resulting <a href="#/p5.Vector">p5.Vector</a>
*/
_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 <a href="#/p5.Vector">p5.Vector</a>
* @param {p5.Vector} v2 divisor <a href="#/p5.Vector">p5.Vector</a>
*/
/**
* @method rem
* @static
* @param {p5.Vector} v1
* @param {p5.Vector} v2
* @return {p5.Vector} the resulting <a href="#/p5.Vector">p5.Vector</a>
*/
_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 <a href="#/p5.Vector">p5.Vector</a> 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 <a href="#/p5.Vector">p5.Vector</a> to subtract from
* @param {p5.Vector} v2 a <a href="#/p5.Vector">p5.Vector</a> to subtract
* @param {p5.Vector} [target] the vector to receive the result (Optional)
* @return {p5.Vector} the resulting <a href="#/p5.Vector">p5.Vector</a>
*/
_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 <a href="#/p5.Vector">p5.Vector</a>
*/
/**
* @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 <a href="#/p5.Vector">p5.Vector</a>
*/
/**
* @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 <a href="#/p5.Vector">p5.Vector</a>
* @param {p5.Vector} v2 the second <a href="#/p5.Vector">p5.Vector</a>
* @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 <a href="#/p5.Vector">p5.Vector</a>
* @param {p5.Vector} v2 the second <a href="#/p5.Vector">p5.Vector</a>
* @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 <a href="#/p5.Vector">p5.Vector</a>
* @param {p5.Vector} v2 the second <a href="#/p5.Vector">p5.Vector</a>
* @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': 48, '../core/main': 59 }
],
93: [
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 <a href="#/p5/random">random()</a>.
*
* By default, <a href="#/p5/random">random()</a> 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
* <div>
* <code>
* randomSeed(99);
* for (let i = 0; i < 100; i++) {
* let r = random(0, 255);
* stroke(r);
* line(i, 0, i, 100);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* for (let i = 0; i < 100; i++) {
* let r = random(50);
* stroke(r * 5);
* line(50, i, 50 + r, i);
* }
* </code>
* </div>
* <div>
* <code>
* for (let i = 0; i < 100; i++) {
* let r = random(-50, 50);
* line(50, i, 50 + r, i);
* }
* </code>
* </div>
* <div>
* <code>
* // 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
* </code>
* </div>
*
* @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 <a href="#/p5/randomGaussian">randomGaussian()</a> 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.<br>
* If no args, returns a mean of 0 and standard deviation of 1.<br>
* If one arg, that arg is the mean (standard deviation is 1).<br>
* 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
* <div>
* <code>
* for (let y = 0; y < 100; y++) {
* let x = randomGaussian(50, 15);
* line(50, y, x, y);
* }
* </code>
* </div>
* <div>
* <code>
* 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);
* }
* }
* </code>
* </div>
* @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) {
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': 59 }
],
94: [
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 <a href="#/p5/cos">cos()</a>, 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
* <div class= “norender">
* <code>
* let a = PI;
* let c = cos(a);
* let ac = acos(c);
* // Prints: "3.1415927 : -1.0 : 3.1415927"
* print(a + ' : ' + c + ' : ' + ac);
* </code>
* </div>
*
* <div class= “norender">
* <code>
* 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);
* </code>
* </div>
*/ _main.default.prototype.acos = function(ratio) {
return this._fromRadians(Math.acos(ratio));
};
/**
* The inverse of <a href="#/p5/sin">sin()</a>, 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
* <div class= “norender">
* <code>
* let a = PI / 3.0;
* let s = sin(a);
* let as = asin(s);
* // Prints: "1.0471975 : 0.86602540 : 1.0471975"
* print(a + ' : ' + s + ' : ' + as);
* </code>
* </div>
*
* <div class= “norender">
* <code>
* 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);
* </code>
* </div>
*/
_main.default.prototype.asin = function(ratio) {
return this._fromRadians(Math.asin(ratio));
};
/**
* The inverse of <a href="#/p5/tan">tan()</a>, 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
* <div class= “norender">
* <code>
* let a = PI / 3.0;
* let t = tan(a);
* let at = atan(t);
* // Prints: "1.0471975 : 1.7320508 : 1.0471975"
* print(a + ' : ' + t + ' : ' + at);
* </code>
* </div>
*
* <div class= “norender">
* <code>
* 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);
* </code>
* </div>
*/
_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<a href="#/p5/">()</a> 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
* <div>
* <code>
* 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);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/angleMode">angleMode</a>. Values are returned in the range -1 to 1.
*
* @method cos
* @param {Number} angle the angle
* @return {Number} the cosine of the angle
*
* @example
* <div>
* <code>
* 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;
* }
* </code>
* </div>
*
* @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 <a href="#/p5/angleMode">angleMode</a>. Values are returned in the range -1 to 1.
*
* @method sin
* @param {Number} angle the angle
* @return {Number} the sine of the angle
*
* @example
* <div>
* <code>
* 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;
* }
* </code>
* </div>
*
* @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 <a href="#/p5/angleMode">angleMode</a>. 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
* <div>
* <code>
* 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;
* }
* </code>
*
* @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 <a href="#/p5/angleMode">angleMode</a>.
*
* @method degrees
* @param {Number} radians the radians value to convert to degrees
* @return {Number} the converted angle
*
* @example
* <div class= “norender">
* <code>
* let rad = PI / 4;
* let deg = degrees(rad);
* print(rad + ' radians is ' + deg + ' degrees');
* // Prints: 0.7853981633974483 radians is 45 degrees
* </code>
* </div>
*/
_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 <a href="#/p5/angleMode">angleMode</a>.
*
* @method radians
* @param {Number} degrees the degree value to convert to radians
* @return {Number} the converted angle
*
* @example
* <div class= “norender">
* <code>
* let deg = 45.0;
* let rad = radians(deg);
* print(deg + ' degrees is ' + rad + ' radians');
* // Prints: 45 degrees is 0.7853981633974483 radians
* </code>
* </div>
*/
_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
* <div>
* <code>
* 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
* }
* </code>
* </div>
*
* @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': 48, '../core/main': 59 }
],
95: [
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 <a href="#/p5/text">text()</a> 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 <a href="#/p5/text">text()</a>.
* 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
* <div>
* <code>
* textSize(16);
* textAlign(RIGHT);
* text('ABCD', 50, 30);
* textAlign(CENTER);
* text('EFGH', 50, 50);
* textAlign(LEFT);
* text('IJKL', 50, 70);
* </code>
* </div>
*
* <div>
* <code>
* textSize(16);
* strokeWeight(0.5);
*
* line(0, 12, width, 12);
* textAlign(CENTER, TOP);
* text('TOP', 0, 12, width);
*
* line(0, 37, width, 37);
* textAlign(CENTER, CENTER);
* text('CENTER', 0, 37, width);
*
* line(0, 62, width, 62);
* textAlign(CENTER, BASELINE);
* text('BASELINE', 0, 62, width);
*
* line(0, 87, width, 87);
* textAlign(CENTER, BOTTOM);
* text('BOTTOM', 0, 87, width);
* </code>
* </div>
*
* @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 <a href="#/p5/text">text()</a> function.
*
* @method textLeading
* @param {Number} leading the size in pixels for spacing between lines
* @chainable
*
* @example
* <div>
* <code>
* 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);
* </code>
* </div>
*
* @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 <a href="#/p5/text">text()</a> function. Font size is measured in pixels.
*
* @method textSize
* @param {Number} theSize the size of the letters in units of pixels
* @chainable
*
* @example
* <div>
* <code>
* textSize(12);
* text('Font Size 12', 10, 30);
* textSize(14);
* text('Font Size 14', 10, 60);
* textSize(16);
* text('Font Size 16', 10, 90);
* </code>
* </div>
*
* @alt
* 'Font Size 12' displayed small, 'Font Size 14' medium & 'Font Size 16' large
*/
/**
* @method textSize
* @return {Number}
*/
_main.default.prototype.textSize = function(theSize) {
var _this$_renderer3;
_main.default._validateParameters('textSize', arguments);
return (_this$_renderer3 = this._renderer).textSize.apply(
_this$_renderer3,
arguments
);
};
/**
* Sets/gets the style of the text for system fonts to NORMAL, ITALIC, BOLD or BOLDITALIC.
* Note: this may be is overridden by CSS styling. For non-system fonts
* (opentype, truetype, etc.) please load styled fonts instead.
*
* @method textStyle
* @param {Constant} theStyle styling for text, either NORMAL,
* ITALIC, BOLD or BOLDITALIC
* @chainable
* @example
* <div>
* <code>
* strokeWeight(0);
* textSize(12);
* textStyle(NORMAL);
* text('Font Style Normal', 10, 15);
* textStyle(ITALIC);
* text('Font Style Italic', 10, 40);
* textStyle(BOLD);
* text('Font Style Bold', 10, 65);
* textStyle(BOLDITALIC);
* text('Font Style Bold Italic', 10, 90);
* </code>
* </div>
*
* @alt
* Words Font Style Normal displayed normally, Italic in italic, bold in bold and bold italic in bold italics.
*/
/**
* @method textStyle
* @return {String}
*/
_main.default.prototype.textStyle = function(theStyle) {
var _this$_renderer4;
_main.default._validateParameters('textStyle', arguments);
return (_this$_renderer4 = this._renderer).textStyle.apply(
_this$_renderer4,
arguments
);
};
/**
* Calculates 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
* <div>
* <code>
* 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);
* </code>
* </div>
*
* @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
* <div>
* <code>
* 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
* </code>
* </div>
*/
_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
* <div>
* <code>
* 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
* </code>
* </div>
*/
_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': 59 }
],
96: [
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
* <a href="#/p5/loadFont">loadFont()</a> completes
* @param {Function} [onError] function to be executed if
* an error occurs
* @return {p5.Font} <a href="#/p5.Font">p5.Font</a> object
* @example
*
* Calling loadFont() inside <a href="#/p5/preload">preload()</a> guarantees
* that the load operation will have completed before <a href="#/p5/setup">setup()</a>
* and <a href="#/p5/draw">draw()</a> are called.
*
* <div><code>
* let myFont;
* function preload() {
* myFont = loadFont('assets/inconsolata.otf');
* }
*
* function setup() {
* fill('#ED225D');
* textFont(myFont);
* textSize(36);
* text('p5*js', 10, 50);
* }
* </code></div>
*
* Outside of <a href="#/p5/preload">preload()</a>, you may supply a
* callback function to handle the object:
*
* <div><code>
* function setup() {
* loadFont('assets/inconsolata.otf', drawText);
* }
*
* function drawText(font) {
* fill('#ED225D');
* textFont(font, 36);
* text('p5*js', 10, 50);
* }
* </code></div>
*
* You can also use the font filename string (without the file extension) to
* style other HTML elements.
*
* <div><code>
* function preload() {
* loadFont('assets/inconsolata.otf');
* }
*
* function setup() {
* let myDiv = createDiv('hello there');
* myDiv.style('font-family', 'Inconsolata');
* }
* </code></div>
*
* @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
* <a href="#/p5/textFont">textFont()</a> function and a default size will be
* used unless a font is set with <a href="#/p5/textSize">textSize()</a>. Change
* the color of the text with the <a href="#/p5/fill">fill()</a> function. Change
* the outline of the text with the <a href="#/p5/stroke">stroke()</a> and
* <a href="#/p5/strokeWeight">strokeWeight()</a> functions.
*
* The text displays in relation to the <a href="#/p5/textAlign">textAlign()</a>
* 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 <a href="#/p5/rectMode">rectMode()</a>
* 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.
*
* <b>WEBGL</b>: Only opentype/truetype fonts are supported. You must load a font
* using the <a href="#/p5/loadFont">loadFont()</a> method (see the example above).
* <a href="#/p5/stroke">stroke()</a> 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 <a href="#/p5/rectMode">rectMode()</a> for more info
* @param {Number} [y2] by default, the height of the text box,
* see <a href="#/p5/rectMode">rectMode()</a> for more info
* @chainable
* @example
* <div>
* <code>
* textSize(32);
* text('word', 10, 30);
* fill(0, 102, 153);
* text('word', 10, 60);
* fill(0, 102, 153, 51);
* text('word', 10, 90);
* </code>
* </div>
* <div>
* <code>
* let s = 'The quick brown fox jumped over the lazy dog.';
* fill(50);
* text(s, 10, 10, 70, 80); // Text wraps within text box
* </code>
* </div>
*
* <div modernizr='webgl'>
* <code>
* let inconsolata;
* function preload() {
* inconsolata = loadFont('assets/inconsolata.otf');
* }
* function setup() {
* createCanvas(100, 100, WEBGL);
* textFont(inconsolata);
* textSize(width / 3);
* textAlign(CENTER, CENTER);
* }
* function draw() {
* background(0);
* let time = millis();
* rotateX(time / 1000);
* rotateZ(time / 1234);
* text('p5.js', 0, 0);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/text">text()</a> function.
*
* <b>WEBGL</b>: Only fonts loaded via <a href="#/p5/loadFont">loadFont()</a> are supported.
*
* @method textFont
* @return {Object} the current font
*
* @example
* <div>
* <code>
* fill(0);
* textSize(12);
* textFont('Georgia');
* text('Georgia', 12, 30);
* textFont('Helvetica');
* text('Helvetica', 12, 60);
* </code>
* </div>
* <div>
* <code>
* let fontRegular, fontItalic, fontBold;
* function preload() {
* fontRegular = loadFont('assets/Regular.otf');
* fontItalic = loadFont('assets/Italic.ttf');
* fontBold = loadFont('assets/Bold.ttf');
* }
* function setup() {
* background(210);
* fill(0)
.strokeWeight(0)
.textSize(10);
* textFont(fontRegular);
* text('Font Style Normal', 10, 30);
* textFont(fontItalic);
* text('Font Style Italic', 10, 50);
* textFont(fontBold);
* text('Font Style Bold', 10, 70);
* }
* </code>
* </div>
*
* @alt
* word 'Georgia' displayed in font Georgia and 'Helvetica' in font Helvetica
* words Font Style Normal displayed normally, Italic in italic and bold in bold
*/
/**
* @method textFont
* @param {Object|String} font a font loaded via <a href="#/p5/loadFont">loadFont()</a>,
* or a String representing a <a href="https://mzl.la/2dOw8WD">web safe font</a>
* (a font that is generally available across all systems)
* @param {Number} [size] the font size to use
* @chainable
*/
_main.default.prototype.textFont = function(theFont, theSize) {
_main.default._validateParameters('textFont', arguments);
if (arguments.length) {
if (!theFont) {
throw new Error('null font passed to textFont');
}
this._renderer._setProperty('_textFont', theFont);
if (theSize) {
this._renderer._setProperty('_textSize', theSize);
this._renderer._setProperty(
'_textLeading',
theSize * constants._DEFAULT_LEADMULT
);
}
return this._renderer._applyTextProperties();
}
return this._renderer._textFont;
};
var _default = _main.default;
exports.default = _default;
},
{
'../core/constants': 48,
'../core/friendly_errors/fes_core': 51,
'../core/friendly_errors/file_errors': 52,
'../core/friendly_errors/validate_params': 54,
'../core/main': 59,
'opentype.js': 34
}
],
97: [
function(_dereq_, module, exports) {
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.default = void 0;
var _main = _interopRequireDefault(_dereq_('../core/main'));
var constants = _interopRequireWildcard(_dereq_('../core/constants'));
function _getRequireWildcardCache() {
if (typeof WeakMap !== 'function') return null;
var cache = new WeakMap();
_getRequireWildcardCache = function _getRequireWildcardCache() {
return cache;
};
return cache;
}
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
}
if (obj === null || (_typeof(obj) !== 'object' && typeof obj !== 'function')) {
return { default: obj };
}
var cache = _getRequireWildcardCache();
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _typeof(obj) {
if (typeof Symbol === 'function' && 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);
}
/**
* Base class for font handling
* @class p5.Font
* @constructor
* @param {p5} [pInst] pointer to p5 instance
*/
_main.default.Font = function(p) {
this.parent = p;
this.cache = {};
/**
* Underlying opentype font implementation
* @property font
*/
this.font = undefined;
};
/**
* Returns a tight bounding box for the given text string using this
* font
*
* @method textBounds
* @param {String} line a line of text
* @param {Number} x x-position
* @param {Number} y y-position
* @param {Number} [fontSize] font size to use (optional) Default is 12.
* @param {Object} [options] opentype options (optional)
* opentype fonts contains alignment and baseline options.
* Default is 'LEFT' and 'alphabetic'
*
* @return {Object} a rectangle object with properties: x, y, w, h
*
* @example
* <div>
* <code>
* let font;
* let textString = 'Lorem ipsum dolor sit amet.';
* function preload() {
* font = loadFont('./assets/Regular.otf');
* }
* function setup() {
* background(210);
*
* let bbox = font.textBounds(textString, 10, 30, 12);
* fill(255);
* stroke(0);
* rect(bbox.x, bbox.y, bbox.w, bbox.h);
* fill(0);
* noStroke();
*
* textFont(font);
* textSize(12);
* text(textString, 10, 30);
* }
* </code>
* </div>
*
* @alt
*words Lorem ipsum dol go off canvas and contained by white bounding box
*/
_main.default.Font.prototype.textBounds = function(str) {
var x = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var y = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var fontSize = arguments.length > 3 ? arguments[3] : undefined;
var opts = arguments.length > 4 ? arguments[4] : undefined;
// Check cache for existing bounds. Take into consideration the text alignment
// settings. Default alignment should match opentype's origin: left-aligned &
// alphabetic baseline.
var p = (opts && opts.renderer && opts.renderer._pInst) || this.parent;
var ctx = p._renderer.drawingContext;
var alignment = ctx.textAlign || constants.LEFT;
var baseline = ctx.textBaseline || constants.BASELINE;
var cacheResults = false;
var result;
var key;
fontSize = fontSize || p._renderer._textSize;
// NOTE: cache disabled for now pending further discussion of #3436
if (cacheResults) {
key = cacheKey('textBounds', str, x, y, fontSize, alignment, baseline);
result = this.cache[key];
}
if (!result) {
var minX = [];
var minY;
var maxX = [];
var maxY;
var pos;
var xCoords = [];
xCoords[0] = [];
var yCoords = [];
var scale = this._scale(fontSize);
var lineHeight = p._renderer.textLeading();
var lineCount = 0;
this.font.forEachGlyph(str, x, y, fontSize, opts, function(
glyph,
gX,
gY,
gFontSize
) {
var gm = glyph.getMetrics();
if (glyph.index === 0 || glyph.index === 10) {
lineCount += 1;
xCoords[lineCount] = [];
} else {
xCoords[lineCount].push(gX + gm.xMin * scale);
xCoords[lineCount].push(gX + gm.xMax * scale);
yCoords.push(gY + lineCount * lineHeight + -gm.yMin * scale);
yCoords.push(gY + lineCount * lineHeight + -gm.yMax * scale);
}
});
if (xCoords[lineCount].length > 0) {
minX[lineCount] = Math.min.apply(null, xCoords[lineCount]);
maxX[lineCount] = Math.max.apply(null, xCoords[lineCount]);
}
var finalMaxX = 0;
for (var i = 0; i <= lineCount; i++) {
minX[i] = Math.min.apply(null, xCoords[i]);
maxX[i] = Math.max.apply(null, xCoords[i]);
var lineLength = maxX[i] - minX[i];
if (lineLength > finalMaxX) {
finalMaxX = lineLength;
}
}
var finalMinX = Math.min.apply(null, minX);
minY = Math.min.apply(null, yCoords);
maxY = Math.max.apply(null, yCoords);
result = {
x: finalMinX,
y: minY,
h: maxY - minY,
w: finalMaxX,
advance: finalMinX - x
};
// Bounds are now calculated, so shift the x & y to match alignment settings
pos = this._handleAlignment(
p._renderer,
str,
result.x,
result.y,
result.w + result.advance
);
result.x = pos.x;
result.y = pos.y;
if (cacheResults) {
this.cache[key] = result;
}
}
return result;
};
/**
* Computes an array of points following the path for specified text
*
* @method textToPoints
* @param {String} txt a line of text
* @param {Number} x x-position
* @param {Number} y y-position
* @param {Number} fontSize font size to use (optional)
* @param {Object} [options] an (optional) object that can contain:
*
* <br>sampleFactor - the ratio of path-length to number of samples
* (default=.1); higher values yield more points and are therefore
* more precise
*
* <br>simplifyThreshold - if set to a non-zero value, collinear points will be
* be removed from the polygon; the value represents the threshold angle to use
* when determining whether two edges are collinear
*
* @return {Array} an array of points, each with x, y, alpha (the path angle)
* @example
* <div>
* <code>
* let font;
* function preload() {
* font = loadFont('assets/inconsolata.otf');
* }
*
* let points;
* let bounds;
* function setup() {
* createCanvas(100, 100);
* stroke(0);
* fill(255, 104, 204);
*
* points = font.textToPoints('p5', 0, 0, 10, {
* sampleFactor: 5,
* simplifyThreshold: 0
* });
* bounds = font.textBounds(' p5 ', 0, 0, 10);
* }
*
* function draw() {
* background(255);
* beginShape();
* translate(-bounds.x * width / bounds.w, -bounds.y * height / bounds.h);
* for (let i = 0; i < points.length; i++) {
* let p = points[i];
* vertex(
* p.x * width / bounds.w +
* sin(20 * p.y / bounds.h + millis() / 1000) * width / 30,
* p.y * height / bounds.h
* );
* }
* endShape(CLOSE);
* }
* </code>
* </div>
*/
_main.default.Font.prototype.textToPoints = function(
txt,
x,
y,
fontSize,
options
) {
var xoff = 0;
var result = [];
var glyphs = this._getGlyphs(txt);
function isSpace(i) {
return (
(glyphs[i].name && glyphs[i].name === 'space') ||
(txt.length === glyphs.length && txt[i] === ' ') ||
(glyphs[i].index && glyphs[i].index === 3)
);
}
fontSize = fontSize || this.parent._renderer._textSize;
for (var i = 0; i < glyphs.length; i++) {
if (!isSpace(i)) {
// fix to #1817, #2069
var gpath = glyphs[i].getPath(x, y, fontSize),
paths = splitPaths(gpath.commands);
for (var j = 0; j < paths.length; j++) {
var pts = pathToPoints(paths[j], options);
for (var k = 0; k < pts.length; k++) {
pts[k].x += xoff;
result.push(pts[k]);
}
}
}
xoff += glyphs[i].advanceWidth * this._scale(fontSize);
}
return result;
};
// ----------------------------- End API ------------------------------
/**
* Returns the set of opentype glyphs for the supplied string.
*
* Note that there is not a strict one-to-one mapping between characters
* and glyphs, so the list of returned glyphs can be larger or smaller
* than the length of the given string.
*
* @private
* @param {String} str the string to be converted
* @return {Array} the opentype glyphs
*/
_main.default.Font.prototype._getGlyphs = function(str) {
return this.font.stringToGlyphs(str);
};
/**
* Returns an opentype path for the supplied string and position.
*
* @private
* @param {String} line a line of text
* @param {Number} x x-position
* @param {Number} y y-position
* @param {Object} options opentype options (optional)
* @return {Object} the opentype path
*/
_main.default.Font.prototype._getPath = function(line, x, y, options) {
var p = (options && options.renderer && options.renderer._pInst) || this.parent,
renderer = p._renderer,
pos = this._handleAlignment(renderer, line, x, y);
return this.font.getPath(line, pos.x, pos.y, renderer._textSize, options);
};
/*
* Creates an SVG-formatted path-data string
* (See http://www.w3.org/TR/SVG/paths.html#PathData)
* from the given opentype path or string/position
*
* @param {Object} path an opentype path, OR the following:
*
* @param {String} line a line of text
* @param {Number} x x-position
* @param {Number} y y-position
* @param {Object} options opentype options (optional), set options.decimals
* to set the decimal precision of the path-data
*
* @return {Object} this p5.Font object
*/
_main.default.Font.prototype._getPathData = function(line, x, y, options) {
var decimals = 3;
// create path from string/position
if (typeof line === 'string' && arguments.length > 2) {
line = this._getPath(line, x, y, options);
} else if (_typeof(x) === 'object') {
// handle options specified in 2nd arg
options = x;
}
// handle svg arguments
if (options && typeof options.decimals === 'number') {
decimals = options.decimals;
}
return line.toPathData(decimals);
};
/*
* Creates an SVG <path> element, as a string,
* from the given opentype path or string/position
*
* @param {Object} path an opentype path, OR the following:
*
* @param {String} line a line of text
* @param {Number} x x-position
* @param {Number} y y-position
* @param {Object} options opentype options (optional), set options.decimals
* to set the decimal precision of the path-data in the <path> element,
* options.fill to set the fill color for the <path> element,
* options.stroke to set the stroke color for the <path> element,
* options.strokeWidth to set the strokeWidth for the <path> element.
*
* @return {Object} this p5.Font object
*/
_main.default.Font.prototype._getSVG = function(line, x, y, options) {
var decimals = 3;
// create path from string/position
if (typeof line === 'string' && arguments.length > 2) {
line = this._getPath(line, x, y, options);
} else if (_typeof(x) === 'object') {
// handle options specified in 2nd arg
options = x;
}
// handle svg arguments
if (options) {
if (typeof options.decimals === 'number') {
decimals = options.decimals;
}
if (typeof options.strokeWidth === 'number') {
line.strokeWidth = options.strokeWidth;
}
if (typeof options.fill !== 'undefined') {
line.fill = options.fill;
}
if (typeof options.stroke !== 'undefined') {
line.stroke = options.stroke;
}
}
return line.toSVG(decimals);
};
/*
* Renders an opentype path or string/position
* to the current graphics context
*
* @param {Object} path an opentype path, OR the following:
*
* @param {String} line a line of text
* @param {Number} x x-position
* @param {Number} y y-position
* @param {Object} options opentype options (optional)
*
* @return {p5.Font} this p5.Font object
*/
_main.default.Font.prototype._renderPath = function(line, x, y, options) {
var pdata;
var pg = (options && options.renderer) || this.parent._renderer;
var ctx = pg.drawingContext;
if (_typeof(line) === 'object' && line.commands) {
pdata = line.commands;
} else {
//pos = handleAlignment(p, ctx, line, x, y);
pdata = this._getPath(line, x, y, options).commands;
}
ctx.beginPath();
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (
var _iterator = pdata[Symbol.iterator](), _step;
!(_iteratorNormalCompletion = (_step = _iterator.next()).done);
_iteratorNormalCompletion = true
) {
var cmd = _step.value;
if (cmd.type === 'M') {
ctx.moveTo(cmd.x, cmd.y);
} else if (cmd.type === 'L') {
ctx.lineTo(cmd.x, cmd.y);
} else if (cmd.type === 'C') {
ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
} else if (cmd.type === 'Q') {
ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y);
} else if (cmd.type === 'Z') {
ctx.closePath();
}
}
// only draw stroke if manually set by user
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
if (pg._doStroke && pg._strokeSet) {
ctx.stroke();
}
if (pg._doFill) {
// if fill hasn't been set by user, use default-text-fill
if (!pg._fillSet) {
pg._setFill(constants._DEFAULT_TEXT_FILL);
}
ctx.fill();
}
return this;
};
_main.default.Font.prototype._textWidth = function(str, fontSize) {
return this.font.getAdvanceWidth(str, fontSize);
};
_main.default.Font.prototype._textAscent = function(fontSize) {
return this.font.ascender * this._scale(fontSize);
};
_main.default.Font.prototype._textDescent = function(fontSize) {
return -this.font.descender * this._scale(fontSize);
};
_main.default.Font.prototype._scale = function(fontSize) {
return 1 / this.font.unitsPerEm * (fontSize || this.parent._renderer._textSize);
};
_main.default.Font.prototype._handleAlignment = function(
renderer,
line,
x,
y,
textWidth
) {
var fontSize = renderer._textSize;
if (typeof textWidth === 'undefined') {
textWidth = this._textWidth(line, fontSize);
}
switch (renderer._textAlign) {
case constants.CENTER:
x -= textWidth / 2;
break;
case constants.RIGHT:
x -= textWidth;
break;
}
switch (renderer._textBaseline) {
case constants.TOP:
y += this._textAscent(fontSize);
break;
case constants.CENTER:
y += this._textAscent(fontSize) / 2;
break;
case constants.BOTTOM:
y -= this._textDescent(fontSize);
break;
}
return { x: x, y: y };
};
// path-utils
function pathToPoints(cmds, options) {
var opts = parseOpts(options, {
sampleFactor: 0.1,
simplifyThreshold: 0
});
var // total-length
len = pointAtLength(cmds, 0, 1),
t = len / (len * opts.sampleFactor),
pts = [];
for (var i = 0; i < len; i += t) {
pts.push(pointAtLength(cmds, i));
}
if (opts.simplifyThreshold) {
simplify(pts, opts.simplifyThreshold);
}
return pts;
}
function simplify(pts) {
var angle =
arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var num = 0;
for (var i = pts.length - 1; pts.length > 3 && i >= 0; --i) {
if (collinear(at(pts, i - 1), at(pts, i), at(pts, i + 1), angle)) {
// Remove the middle point
pts.splice(i % pts.length, 1);
num++;
}
}
return num;
}
function splitPaths(cmds) {
var paths = [];
var current;
for (var i = 0; i < cmds.length; i++) {
if (cmds[i].type === 'M') {
if (current) {
paths.push(current);
}
current = [];
}
current.push(cmdToArr(cmds[i]));
}
paths.push(current);
return paths;
}
function cmdToArr(cmd) {
var arr = [cmd.type];
if (cmd.type === 'M' || cmd.type === 'L') {
// moveto or lineto
arr.push(cmd.x, cmd.y);
} else if (cmd.type === 'C') {
arr.push(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
} else if (cmd.type === 'Q') {
arr.push(cmd.x1, cmd.y1, cmd.x, cmd.y);
}
// else if (cmd.type === 'Z') { /* no-op */ }
return arr;
}
function parseOpts(options, defaults) {
if (_typeof(options) !== 'object') {
options = defaults;
} else {
for (var key in defaults) {
if (typeof options[key] === 'undefined') {
options[key] = defaults[key];
}
}
}
return options;
}
//////////////////////// Helpers ////////////////////////////
function at(v, i) {
var s = v.length;
return v[i < 0 ? i % s + s : i % s];
}
function collinear(a, b, c, thresholdAngle) {
if (!thresholdAngle) {
return areaTriangle(a, b, c) === 0;
}
if (typeof collinear.tmpPoint1 === 'undefined') {
collinear.tmpPoint1 = [];
collinear.tmpPoint2 = [];
}
var ab = collinear.tmpPoint1,
bc = collinear.tmpPoint2;
ab.x = b.x - a.x;
ab.y = b.y - a.y;
bc.x = c.x - b.x;
bc.y = c.y - b.y;
var dot = ab.x * bc.x + ab.y * bc.y,
magA = Math.sqrt(ab.x * ab.x + ab.y * ab.y),
magB = Math.sqrt(bc.x * bc.x + bc.y * bc.y),
angle = Math.acos(dot / (magA * magB));
return angle < thresholdAngle;
}
function areaTriangle(a, b, c) {
return (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]);
}
// Portions of below code copyright 2008 Dmitry Baranovskiy (via MIT license)
function findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
var t1 = 1 - t;
var t13 = Math.pow(t1, 3);
var t12 = Math.pow(t1, 2);
var t2 = t * t;
var t3 = t2 * t;
var x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x;
var y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y;
var mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x);
var my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y);
var nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x);
var ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y);
var ax = t1 * p1x + t * c1x;
var ay = t1 * p1y + t * c1y;
var cx = t1 * c2x + t * p2x;
var cy = t1 * c2y + t * p2y;
var alpha = 90 - Math.atan2(mx - nx, my - ny) * 180 / Math.PI;
if (mx > nx || my < ny) {
alpha += 180;
}
return {
x: x,
y: y,
m: { x: mx, y: my },
n: { x: nx, y: ny },
start: { x: ax, y: ay },
end: { x: cx, y: cy },
alpha: alpha
};
}
function getPointAtSegmentLength(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) {
return length == null
? bezlen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y)
: findDotsAtSegment(
p1x,
p1y,
c1x,
c1y,
c2x,
c2y,
p2x,
p2y,
getTatLen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length)
);
}
function pointAtLength(path, length, istotal) {
path = path2curve(path);
var x;
var y;
var p;
var l;
var sp = '';
var subpaths = {};
var point;
var len = 0;
for (var i = 0, ii = path.length; i < ii; i++) {
p = path[i];
if (p[0] === 'M') {
x = +p[1];
y = +p[2];
} else {
l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
if (len + l > length) {
if (!istotal) {
point = getPointAtSegmentLength(
x,
y,
p[1],
p[2],
p[3],
p[4],
p[5],
p[6],
length - len
);
return { x: point.x, y: point.y, alpha: point.alpha };
}
}
len += l;
x = +p[5];
y = +p[6];
}
sp += p.shift() + p;
}
subpaths.end = sp;
point = istotal
? len
: findDotsAtSegment(x, y, p[0], p[1], p[2], p[3], p[4], p[5], 1);
if (point.alpha) {
point = { x: point.x, y: point.y, alpha: point.alpha };
}
return point;
}
function pathToAbsolute(pathArray) {
var res = [],
x = 0,
y = 0,
mx = 0,
my = 0,
start = 0;
if (!pathArray) {
// console.warn("Unexpected state: undefined pathArray"); // shouldn't happen
return res;
}
if (pathArray[0][0] === 'M') {
x = +pathArray[0][1];
y = +pathArray[0][2];
mx = x;
my = y;
start++;
res[0] = ['M', x, y];
}
var dots;
var crz =
pathArray.length === 3 &&
pathArray[0][0] === 'M' &&
pathArray[1][0].toUpperCase() === 'R' &&
pathArray[2][0].toUpperCase() === 'Z';
for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) {
res.push((r = []));
pa = pathArray[i];
if (pa[0] !== String.prototype.toUpperCase.call(pa[0])) {
r[0] = String.prototype.toUpperCase.call(pa[0]);
switch (r[0]) {
case 'A':
r[1] = pa[1];
r[2] = pa[2];
r[3] = pa[3];
r[4] = pa[4];
r[5] = pa[5];
r[6] = +(pa[6] + x);
r[7] = +(pa[7] + y);
break;
case 'V':
r[1] = +pa[1] + y;
break;
case 'H':
r[1] = +pa[1] + x;
break;
case 'R':
dots = [x, y].concat(pa.slice(1));
for (var j = 2, jj = dots.length; j < jj; j++) {
dots[j] = +dots[j] + x;
dots[++j] = +dots[j] + y;
}
res.pop();
res = res.concat(catmullRom2bezier(dots, crz));
break;
case 'M':
mx = +pa[1] + x;
my = +pa[2] + y;
break;
default:
for (var _j = 1, _jj = pa.length; _j < _jj; _j++) {
r[_j] = +pa[_j] + (_j % 2 ? x : y);
}
}
} else if (pa[0] === 'R') {
dots = [x, y].concat(pa.slice(1));
res.pop();
res = res.concat(catmullRom2bezier(dots, crz));
r = ['R'].concat(pa.slice(-2));
} else {
for (var k = 0, kk = pa.length; k < kk; k++) {
r[k] = pa[k];
}
}
switch (r[0]) {
case 'Z':
x = mx;
y = my;
break;
case 'H':
x = r[1];
break;
case 'V':
y = r[1];
break;
case 'M':
mx = r[r.length - 2];
my = r[r.length - 1];
break;
default:
x = r[r.length - 2];
y = r[r.length - 1];
}
}
return res;
}
function path2curve(path, path2) {
var p = pathToAbsolute(path),
p2 = path2 && pathToAbsolute(path2);
var attrs = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null };
var attrs2 = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null };
var pcoms1 = []; // path commands of original path p
var pcoms2 = []; // path commands of original path p2
var ii;
var processPath = function processPath(path, d, pcom) {
var nx;
var ny;
var tq = { T: 1, Q: 1 };
if (!path) {
return ['C', d.x, d.y, d.x, d.y, d.x, d.y];
}
if (!(path[0] in tq)) {
d.qx = d.qy = null;
}
switch (path[0]) {
case 'M':
d.X = path[1];
d.Y = path[2];
break;
case 'A':
path = ['C'].concat(a2c.apply(0, [d.x, d.y].concat(path.slice(1))));
break;
case 'S':
if (pcom === 'C' || pcom === 'S') {
nx = d.x * 2 - d.bx;
ny = d.y * 2 - d.by;
} else {
nx = d.x;
ny = d.y;
}
path = ['C', nx, ny].concat(path.slice(1));
break;
case 'T':
if (pcom === 'Q' || pcom === 'T') {
d.qx = d.x * 2 - d.qx;
d.qy = d.y * 2 - d.qy;
} else {
d.qx = d.x;
d.qy = d.y;
}
path = ['C'].concat(q2c(d.x, d.y, d.qx, d.qy, path[1], path[2]));
break;
case 'Q':
d.qx = path[1];
d.qy = path[2];
path = ['C'].concat(q2c(d.x, d.y, path[1], path[2], path[3], path[4]));
break;
case 'L':
path = ['C'].concat(l2c(d.x, d.y, path[1], path[2]));
break;
case 'H':
path = ['C'].concat(l2c(d.x, d.y, path[1], d.y));
break;
case 'V':
path = ['C'].concat(l2c(d.x, d.y, d.x, path[1]));
break;
case 'Z':
path = ['C'].concat(l2c(d.x, d.y, d.X, d.Y));
break;
}
return path;
},
fixArc = function fixArc(pp, i) {
if (pp[i].length > 7) {
pp[i].shift();
var pi = pp[i];
while (pi.length) {
pcoms1[i] = 'A';
if (p2) {
pcoms2[i] = 'A';
}
pp.splice(i++, 0, ['C'].concat(pi.splice(0, 6)));
}
pp.splice(i, 1);
ii = Math.max(p.length, (p2 && p2.length) || 0);
}
},
fixM = function fixM(path1, path2, a1, a2, i) {
if (path1 && path2 && path1[i][0] === 'M' && path2[i][0] !== 'M') {
path2.splice(i, 0, ['M', a2.x, a2.y]);
a1.bx = 0;
a1.by = 0;
a1.x = path1[i][1];
a1.y = path1[i][2];
ii = Math.max(p.length, (p2 && p2.length) || 0);
}
};
var pfirst = ''; // temporary holder for original path command
var pcom = ''; // holder for previous path command of original path
ii = Math.max(p.length, (p2 && p2.length) || 0);
for (var i = 0; i < ii; i++) {
if (p[i]) {
pfirst = p[i][0];
} // save current path command
if (pfirst !== 'C') {
pcoms1[i] = pfirst; // Save current path command
if (i) {
pcom = pcoms1[i - 1];
} // Get previous path command pcom
}
p[i] = processPath(p[i], attrs, pcom);
if (pcoms1[i] !== 'A' && pfirst === 'C') {
pcoms1[i] = 'C';
}
fixArc(p, i); // fixArc adds also the right amount of A:s to pcoms1
if (p2) {
// the same procedures is done to p2
if (p2[i]) {
pfirst = p2[i][0];
}
if (pfirst !== 'C') {
pcoms2[i] = pfirst;
if (i) {
pcom = pcoms2[i - 1];
}
}
p2[i] = processPath(p2[i], attrs2, pcom);
if (pcoms2[i] !== 'A' && pfirst === 'C') {
pcoms2[i] = 'C';
}
fixArc(p2, i);
}
fixM(p, p2, attrs, attrs2, i);
fixM(p2, p, attrs2, attrs, i);
var seg = p[i],
seg2 = p2 && p2[i],
seglen = seg.length,
seg2len = p2 && seg2.length;
attrs.x = seg[seglen - 2];
attrs.y = seg[seglen - 1];
attrs.bx = parseFloat(seg[seglen - 4]) || attrs.x;
attrs.by = parseFloat(seg[seglen - 3]) || attrs.y;
attrs2.bx = p2 && (parseFloat(seg2[seg2len - 4]) || attrs2.x);
attrs2.by = p2 && (parseFloat(seg2[seg2len - 3]) || attrs2.y);
attrs2.x = p2 && seg2[seg2len - 2];
attrs2.y = p2 && seg2[seg2len - 1];
}
return p2 ? [p, p2] : p;
}
function a2c(x1, y1, rx, ry, angle, lac, sweep_flag, x2, y2, recursive) {
// for more information of where this Math came from visit:
// http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
var PI = Math.PI;
var _120 = PI * 120 / 180;
var f1;
var f2;
var cx;
var cy;
var rad = PI / 180 * (+angle || 0);
var res = [];
var xy;
var rotate = function rotate(x, y, rad) {
var X = x * Math.cos(rad) - y * Math.sin(rad),
Y = x * Math.sin(rad) + y * Math.cos(rad);
return { x: X, y: Y };
};
if (!recursive) {
xy = rotate(x1, y1, -rad);
x1 = xy.x;
y1 = xy.y;
xy = rotate(x2, y2, -rad);
x2 = xy.x;
y2 = xy.y;
var x = (x1 - x2) / 2;
var y = (y1 - y2) / 2;
var h = x * x / (rx * rx) + y * y / (ry * ry);
if (h > 1) {
h = Math.sqrt(h);
rx = h * rx;
ry = h * ry;
}
var rx2 = rx * rx,
ry2 = ry * ry;
var k =
(lac === sweep_flag ? -1 : 1) *
Math.sqrt(
Math.abs(
(rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x)
)
);
cx = k * rx * y / ry + (x1 + x2) / 2;
cy = k * -ry * x / rx + (y1 + y2) / 2;
f1 = Math.asin(((y1 - cy) / ry).toFixed(9));
f2 = Math.asin(((y2 - cy) / ry).toFixed(9));
f1 = x1 < cx ? PI - f1 : f1;
f2 = x2 < cx ? PI - f2 : f2;
if (f1 < 0) {
f1 = PI * 2 + f1;
}
if (f2 < 0) {
f2 = PI * 2 + f2;
}
if (sweep_flag && f1 > f2) {
f1 = f1 - PI * 2;
}
if (!sweep_flag && f2 > f1) {
f2 = f2 - PI * 2;
}
} else {
f1 = recursive[0];
f2 = recursive[1];
cx = recursive[2];
cy = recursive[3];
}
var df = f2 - f1;
if (Math.abs(df) > _120) {
var f2old = f2,
x2old = x2,
y2old = y2;
f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
x2 = cx + rx * Math.cos(f2);
y2 = cy + ry * Math.sin(f2);
res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [
f2,
f2old,
cx,
cy
]);
}
df = f2 - f1;
var c1 = Math.cos(f1),
s1 = Math.sin(f1),
c2 = Math.cos(f2),
s2 = Math.sin(f2),
t = Math.tan(df / 4),
hx = 4 / 3 * rx * t,
hy = 4 / 3 * ry * t,
m1 = [x1, y1],
m2 = [x1 + hx * s1, y1 - hy * c1],
m3 = [x2 + hx * s2, y2 - hy * c2],
m4 = [x2, y2];
m2[0] = 2 * m1[0] - m2[0];
m2[1] = 2 * m1[1] - m2[1];
if (recursive) {
return [m2, m3, m4].concat(res);
} else {
res = [m2, m3, m4]
.concat(res)
.join()
.split(',');
var newres = [];
for (var i = 0, ii = res.length; i < ii; i++) {
newres[i] =
i % 2
? rotate(res[i - 1], res[i], rad).y
: rotate(res[i], res[i + 1], rad).x;
}
return newres;
}
}
// http://schepers.cc/getting-to-the-point
function catmullRom2bezier(crp, z) {
var d = [];
for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) {
var p = [
{
x: +crp[i - 2],
y: +crp[i - 1]
},
{
x: +crp[i],
y: +crp[i + 1]
},
{
x: +crp[i + 2],
y: +crp[i + 3]
},
{
x: +crp[i + 4],
y: +crp[i + 5]
}
];
if (z) {
if (!i) {
p[0] = {
x: +crp[iLen - 2],
y: +crp[iLen - 1]
};
} else if (iLen - 4 === i) {
p[3] = {
x: +crp[0],
y: +crp[1]
};
} else if (iLen - 2 === i) {
p[2] = {
x: +crp[0],
y: +crp[1]
};
p[3] = {
x: +crp[2],
y: +crp[3]
};
}
} else {
if (iLen - 4 === i) {
p[3] = p[2];
} else if (!i) {
p[0] = {
x: +crp[i],
y: +crp[i + 1]
};
}
}
d.push([
'C',
(-p[0].x + 6 * p[1].x + p[2].x) / 6,
(-p[0].y + 6 * p[1].y + p[2].y) / 6,
(p[1].x + 6 * p[2].x - p[3].x) / 6,
(p[1].y + 6 * p[2].y - p[3].y) / 6,
p[2].x,
p[2].y
]);
}
return d;
}
function l2c(x1, y1, x2, y2) {
return [x1, y1, x2, y2, x2, y2];
}
function q2c(x1, y1, ax, ay, x2, y2) {
var _13 = 1 / 3,
_23 = 2 / 3;
return [
_13 * x1 + _23 * ax,
_13 * y1 + _23 * ay,
_13 * x2 + _23 * ax,
_13 * y2 + _23 * ay,
x2,
y2
];
}
function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) {
if (z == null) {
z = 1;
}
z = z > 1 ? 1 : z < 0 ? 0 : z;
var z2 = z / 2;
var n = 12;
var Tvalues = [
-0.1252,
0.1252,
-0.3678,
0.3678,
-0.5873,
0.5873,
-0.7699,
0.7699,
-0.9041,
0.9041,
-0.9816,
0.9816
];
var sum = 0;
var Cvalues = [
0.2491,
0.2491,
0.2335,
0.2335,
0.2032,
0.2032,
0.1601,
0.1601,
0.1069,
0.1069,
0.0472,
0.0472
];
for (var i = 0; i < n; i++) {
var ct = z2 * Tvalues[i] + z2,
xbase = base3(ct, x1, x2, x3, x4),
ybase = base3(ct, y1, y2, y3, y4),
comb = xbase * xbase + ybase * ybase;
sum += Cvalues[i] * Math.sqrt(comb);
}
return z2 * sum;
}
function getTatLen(x1, y1, x2, y2, x3, y3, x4, y4, ll) {
if (ll < 0 || bezlen(x1, y1, x2, y2, x3, y3, x4, y4) < ll) {
return;
}
var t = 1;
var step = t / 2;
var t2 = t - step;
var l;
var e = 0.01;
l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2);
while (Math.abs(l - ll) > e) {
step /= 2;
t2 += (l < ll ? 1 : -1) * step;
l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2);
}
return t2;
}
function base3(t, p1, p2, p3, p4) {
var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4,
t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3;
return t * t2 - 3 * p1 + 3 * p2;
}
function cacheKey() {
var hash = '';
for (var i = arguments.length - 1; i >= 0; --i) {
hash += '\uFF1F'.concat(
i < 0 || arguments.length <= i ? undefined : arguments[i]
);
}
return hash;
}
var _default = _main.default;
exports.default = _default;
},
{ '../core/constants': 48, '../core/main': 59 }
],
98: [
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 Array Functions
* @for p5
* @requires core
*/ /**
* Adds a value to the end of an array. Extends the length of
* the array by one. Maps to Array.push().
*
* @method append
* @deprecated Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push">array.push(value)</a> instead.
* @param {Array} array Array to append
* @param {any} value to be added to the Array
* @return {Array} the array that was appended to
* @example
* <div class='norender'><code>
* function setup() {
* let myArray = ['Mango', 'Apple', 'Papaya'];
* print(myArray); // ['Mango', 'Apple', 'Papaya']
*
* append(myArray, 'Peach');
* print(myArray); // ['Mango', 'Apple', 'Papaya', 'Peach']
* }
* </code></div>
*/ _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 <a href="#/p5/concat">concat()</a>.
*
* 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 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin">arr1.copyWithin(arr2)</a> 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
* <div class='norender'><code>
* let src = ['A', 'B', 'C'];
* let dst = [1, 2, 3];
* let srcPosition = 1;
* let dstPosition = 0;
* let length = 2;
*
* print(src); // ['A', 'B', 'C']
* print(dst); // [ 1 , 2 , 3 ]
*
* arrayCopy(src, srcPosition, dst, dstPosition, length);
* print(dst); // ['B', 'C', 3]
* </code></div>
*/
/**
* @method arrayCopy
* @deprecated Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin">arr1.copyWithin(arr2)</a> instead.
* @param {Array} src
* @param {Array} dst
* @param {Integer} [length]
*/
_main.default.prototype.arrayCopy = function(
src,
srcPosition,
dst,
dstPosition,
length
) {
// the index to begin splicing from dst array
var start;
var end;
if (typeof length !== 'undefined') {
end = Math.min(length, src.length);
start = dstPosition;
src = src.slice(srcPosition, end + srcPosition);
} else {
if (typeof dst !== 'undefined') {
// src, dst, length
// rename so we don't get confused
end = dst;
end = Math.min(end, src.length);
} else {
// src, dst
end = src.length;
}
start = 0;
// rename so we don't get confused
dst = srcPosition;
src = src.slice(0, end);
}
// Since we are not returning the array and JavaScript is pass by reference
// we must modify the actual values of the array
// instead of reassigning arrays
Array.prototype.splice.apply(dst, [start, end].concat(src));
};
/**
* Concatenates two arrays, maps to Array.concat(). Does not modify the
* input arrays.
*
* @method concat
* @deprecated Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat">arr1.concat(arr2)</a> instead.
* @param {Array} a first Array to concatenate
* @param {Array} b second Array to concatenate
* @return {Array} concatenated array
*
* @example
* <div class = 'norender'><code>
* function setup() {
* let arr1 = ['A', 'B', 'C'];
* let arr2 = [1, 2, 3];
*
* print(arr1); // ['A','B','C']
* print(arr2); // [1,2,3]
*
* let arr3 = concat(arr1, arr2);
*
* print(arr1); // ['A','B','C']
* print(arr2); // [1, 2, 3]
* print(arr3); // ['A','B','C', 1, 2, 3]
* }
* </code></div>
*/
_main.default.prototype.concat = function(list0, list1) {
return list0.concat(list1);
};
/**
* Reverses the order of an array, maps to Array.reverse()
*
* @method reverse
* @deprecated Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse">array.reverse()</a> instead.
* @param {Array} list Array to reverse
* @return {Array} the reversed list
* @example
* <div class='norender'><code>
* function setup() {
* let myArray = ['A', 'B', 'C'];
* print(myArray); // ['A','B','C']
*
* reverse(myArray);
* print(myArray); // ['C','B','A']
* }
* </code></div>
*/
_main.default.prototype.reverse = function(list) {
return list.reverse();
};
/**
* Decreases an array by one element and returns the shortened array,
* maps to Array.pop().
*
* @method shorten
* @deprecated Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop">array.pop()</a> instead.
* @param {Array} list Array to shorten
* @return {Array} shortened Array
* @example
* <div class = 'norender'><code>
* function setup() {
* let myArray = ['A', 'B', 'C'];
* print(myArray); // ['A', 'B', 'C']
* let newArray = shorten(myArray);
* print(myArray); // ['A','B','C']
* print(newArray); // ['A','B']
* }
* </code></div>
*/
_main.default.prototype.shorten = function(list) {
list.pop();
return list;
};
/**
* Randomizes the order of the elements of an array. Implements
* <a href='http://Bost.Ocks.org/mike/shuffle/' target=_blank>
* Fisher-Yates Shuffle Algorithm</a>.
*
* @method shuffle
* @param {Array} array Array to shuffle
* @param {Boolean} [bool] modify passed array
* @return {Array} shuffled Array
* @example
* <div><code>
* 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);
* }
* </code></div>
*/
_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 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort">array.sort()</a> instead.
* @param {Array} list Array to sort
* @param {Integer} [count] number of elements to sort, starting from 0
* @return {Array} the sorted list
*
* @example
* <div class = 'norender'><code>
* 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']
* }
* </code></div>
* <div class = 'norender'><code>
* 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]
* }
* </code></div>
*/
_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 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice">array.splice()</a> 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
* <div class = 'norender'><code>
* function setup() {
* let myArray = [0, 1, 2, 3, 4];
* let insArray = ['A', 'B', 'C'];
* print(myArray); // [0, 1, 2, 3, 4]
* print(insArray); // ['A','B','C']
*
* splice(myArray, insArray, 3);
* print(myArray); // [0,1,2,'A','B','C',3,4]
* }
* </code></div>
*/
_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 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice">array.slice()</a> 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
* <div class = 'norender'><code>
* function setup() {
* let myArray = [1, 2, 3, 4, 5];
* print(myArray); // [1, 2, 3, 4, 5]
*
* let sub1 = subset(myArray, 0, 3);
* let sub2 = subset(myArray, 2, 2);
* print(sub1); // [1,2,3]
* print(sub2); // [3,4]
* }
* </code></div>
*/
_main.default.prototype.subset = function(list, start, count) {
if (typeof count !== 'undefined') {
return list.slice(start, start + count);
} else {
return list.slice(start, list.length);
}
};
var _default = _main.default;
exports.default = _default;
},
{ '../core/main': 59 }
],
99: [
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 Conversion
* @for p5
* @requires core
*/ /**
* Converts a string to its floating point representation. The contents of a
* string must resemble a number, or NaN (not a number) will be returned.
* For example, float("1234.56") evaluates to 1234.56, but float("giraffe")
* will return NaN.
*
* When an array of values is passed in, then an array of floats of the same
* length is returned.
*
* @method float
* @param {String} str float string to parse
* @return {Number} floating point representation of string
* @example
* <div><code>
* let str = '20';
* let diameter = float(str);
* ellipse(width / 2, height / 2, diameter, diameter);
* </code></div>
* <div class='norender'><code>
* print(float('10.31')); // 10.31
* print(float('Infinity')); // Infinity
* print(float('-Infinity')); // -Infinity
* </code></div>
*
* @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
* <div class='norender'><code>
* print(int('10')); // 10
* print(int(10.31)); // 10
* print(int(-10)); // -10
* print(int(true)); // 1
* print(int(false)); // 0
* print(int([false, true, '10.3', 9.8])); // [0, 1, 10, 9]
* print(int(Infinity)); // Infinity
* print(int('-Infinity')); // -Infinity
* </code></div>
*/
/**
* @method int
* @param {Array} ns values to parse
* @return {Number[]} integer representation of values
*/
_main.default.prototype.int = function(n) {
var radix =
arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10;
if (n === Infinity || n === 'Infinity') {
return Infinity;
} else if (n === -Infinity || n === '-Infinity') {
return -Infinity;
} else if (typeof n === 'string') {
return parseInt(n, radix);
} else if (typeof n === 'number') {
return n | 0;
} else if (typeof n === 'boolean') {
return n ? 1 : 0;
} else if (n instanceof Array) {
return n.map(function(n) {
return _main.default.prototype.int(n, radix);
});
}
};
/**
* Converts a boolean, string or number to its string representation.
* When an array of values is passed in, then an array of strings of the same
* length is returned.
*
* @method str
* @param {String|Boolean|Number|Array} n value to parse
* @return {String} string representation of value
* @example
* <div class='norender'><code>
* print(str('10')); // "10"
* print(str(10.31)); // "10.31"
* print(str(-10)); // "-10"
* print(str(true)); // "true"
* print(str(false)); // "false"
* print(str([true, '10.3', 9.8])); // [ "true", "10.3", "9.8" ]
* </code></div>
*/
_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
* <div class='norender'><code>
* print(boolean(0)); // false
* print(boolean(1)); // true
* print(boolean('true')); // true
* print(boolean('abcd')); // false
* print(boolean([0, 12, 'true'])); // [false, true, true]
* </code></div>
*/
_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
* <div class='norender'><code>
* print(byte(127)); // 127
* print(byte(128)); // -128
* print(byte(23.4)); // 23
* print(byte('23.4')); // 23
* print(byte('hello')); // NaN
* print(byte(true)); // 1
* print(byte([0, 255, '100'])); // [0, -1, 100]
* </code></div>
*/
/**
* @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
* <div class='norender'><code>
* print(char(65)); // "A"
* print(char('65')); // "A"
* print(char([65, 66, 67])); // [ "A", "B", "C" ]
* print(join(char([65, 66, 67]), '')); // "ABC"
* </code></div>
*/
/**
* @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
* <div class='norender'><code>
* print(unchar('A')); // 65
* print(unchar(['A', 'B', 'C'])); // [ 65, 66, 67 ]
* print(unchar(split('ABC', ''))); // [ 65, 66, 67 ]
* </code></div>
*/
/**
* @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
* <div class='norender'><code>
* print(hex(255)); // "000000FF"
* print(hex(255, 6)); // "0000FF"
* print(hex([0, 127, 255], 6)); // [ "000000", "00007F", "0000FF" ]
* print(Infinity); // "FFFFFFFF"
* print(-Infinity); // "00000000"
* </code></div>
*/
/**
* @method hex
* @param {Number[]} ns array of values to parse
* @param {Number} [digits]
* @return {String[]} hexadecimal string representation of values
*/
_main.default.prototype.hex = function(n, digits) {
digits = digits === undefined || digits === null ? (digits = 8) : digits;
if (n instanceof Array) {
return n.map(function(n) {
return _main.default.prototype.hex(n, digits);
});
} else if (n === Infinity || n === -Infinity) {
var c = n === Infinity ? 'F' : '0';
return c.repeat(digits);
} else if (typeof n === 'number') {
if (n < 0) {
n = 0xffffffff + n + 1;
}
var hex = Number(n)
.toString(16)
.toUpperCase();
while (hex.length < digits) {
hex = '0'.concat(hex);
}
if (hex.length >= digits) {
hex = hex.substring(hex.length - digits, hex.length);
}
return hex;
}
};
/**
* Converts a string representation of a hexadecimal number to its equivalent
* integer value. When an array of strings in hexadecimal notation is passed
* in, an array of integers of the same length is returned.
*
* @method unhex
* @param {String} n value to parse
* @return {Number} integer representation of hexadecimal value
*
* @example
* <div class='norender'><code>
* print(unhex('A')); // 10
* print(unhex('FF')); // 255
* print(unhex(['FF', 'AA', '00'])); // [ 255, 170, 0 ]
* </code></div>
*/
/**
* @method unhex
* @param {Array} ns values to parse
* @return {Number[]} integer representations of hexadecimal value
*/
_main.default.prototype.unhex = function(n) {
if (n instanceof Array) {
return n.map(_main.default.prototype.unhex);
} else {
return parseInt('0x'.concat(n), 16);
}
};
var _default = _main.default;
exports.default = _default;
},
{ '../core/main': 59 }
],
100: [
function(_dereq_, module, exports) {
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.default = void 0;
var _main = _interopRequireDefault(_dereq_('../core/main'));
_dereq_('../core/friendly_errors/validate_params');
_dereq_('../core/friendly_errors/file_errors');
_dereq_('../core/friendly_errors/fes_core');
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
} /** //return p5; //LM is this a mistake?
* @module Data
* @submodule String Functions
* @for p5
* @requires core
*/
/**
* Combines an array of Strings into one String, each separated by the
* character(s) used for the separator parameter. To join arrays of ints or
* floats, it's necessary to first convert them to Strings using <a href="#/p5/nf">nf()</a> or
* nfs().
*
* @method join
* @param {Array} list array of Strings to be joined
* @param {String} separator String to be placed between each item
* @return {String} joined String
* @example
* <div>
* <code>
* let array = ['Hello', 'world!'];
* let separator = ' ';
* let message = join(array, separator);
* text(message, 5, 50);
* </code>
* </div>
*
* @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
* <div>
* <code>
* let string = 'Hello p5js*!';
* let regexp = 'p5js\\*';
* let m = match(string, regexp);
* text(m, 5, 50);
* </code>
* </div>
*
* @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
* <div class="norender">
* <code>
* let string = 'Hello p5js*! Hello world!';
* let regexp = 'Hello';
* matchAll(string, regexp);
* </code>
* </div>
*/
_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
* <div>
* <code>
* 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);
*
* text(nf(num1, 4, 2), 10, 30);
* text(nf(num2, 4, 2), 10, 80);
* // Draw dividing line
* stroke(120);
* line(0, 50, width, 50);
* }
* </code>
* </div>
*
* @alt
* "0321.00" middle top, -1321.00" middle bottom canvas
*/
/**
* @method nf
* @param {Array} nums the Numbers to format
* @param {Integer|String} [left]
* @param {Integer|String} [right]
* @return {String[]} formatted Strings
*/
_main.default.prototype.nf = function(nums, left, right) {
_main.default._validateParameters('nf', arguments);
if (nums instanceof Array) {
return nums.map(function(x) {
return doNf(x, left, right);
});
} else {
var typeOfFirst = Object.prototype.toString.call(nums);
if (typeOfFirst === '[object Arguments]') {
if (nums.length === 3) {
return this.nf(nums[0], nums[1], nums[2]);
} else if (nums.length === 2) {
return this.nf(nums[0], nums[1]);
} else {
return this.nf(nums[0]);
}
} else {
return doNf(nums, left, right);
}
}
};
function doNf(num, left, right) {
var neg = num < 0;
var n = neg ? num.toString().substring(1) : num.toString();
var decimalInd = n.indexOf('.');
var intPart = decimalInd !== -1 ? n.substring(0, decimalInd) : n;
var decPart = decimalInd !== -1 ? n.substring(decimalInd + 1) : '';
var str = neg ? '-' : '';
if (typeof right !== 'undefined') {
var decimal = '';
if (decimalInd !== -1 || right - decPart.length > 0) {
decimal = '.';
}
if (decPart.length > right) {
decPart = decPart.substring(0, right);
}
for (var i = 0; i < left - intPart.length; i++) {
str += '0';
}
str += intPart;
str += decimal;
str += decPart;
for (var j = 0; j < right - decPart.length; j++) {
str += '0';
}
return str;
} else {
for (var k = 0; k < Math.max(left - intPart.length, 0); k++) {
str += '0';
}
str += n;
return str;
}
}
/**
* Utility function for formatting numbers into strings and placing
* appropriate commas to mark units of 1000. There are two versions: one
* for formatting ints, and one for formatting an array of ints. The value
* for the right parameter should always be a positive integer.
*
* @method nfc
* @param {Number|String} num the Number to format
* @param {Integer|String} [right] number of digits to the right of the
* decimal point
* @return {String} formatted String
*
* @example
* <div>
* <code>
* function setup() {
* background(200);
* let num = 11253106.115;
* let numArr = [1, 1, 2];
*
* noStroke();
* fill(0);
* textSize(12);
*
* // Draw formatted numbers
* text(nfc(num, 4), 10, 30);
* text(nfc(numArr, 2), 10, 80);
*
* // Draw dividing line
* stroke(120);
* line(0, 50, width, 50);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/nf">nf()</a> 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
* <div>
* <code>
* function setup() {
* background(200);
* let num1 = 11253106.115;
* let num2 = -11253106.115;
*
* noStroke();
* fill(0);
* textSize(12);
*
* // Draw formatted numbers
* text(nfp(num1, 4, 2), 10, 30);
* text(nfp(num2, 4, 2), 10, 80);
*
* // Draw dividing line
* stroke(120);
* line(0, 50, width, 50);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/nf">nf()</a> 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
* <div>
* <code>
* 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);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/split">split()</a> 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 <a href="#/p5/splitTokens">splitTokens()</a> 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
* <div>
* <code>
* let names = 'Pat,Xio,Alex';
* let splitString = split(names, ',');
* text(splitString[0], 5, 30);
* text(splitString[1], 5, 50);
* text(splitString[2], 5, 70);
* </code>
* </div>
*
* @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 <a href="#/p5/splitTokens">splitTokens()</a> 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
* <div class = "norender">
* <code>
* function setup() {
* let myStr = 'Mango, Banana, Lime';
* let myStrArr = splitTokens(myStr, ',');
*
* print(myStrArr); // prints : ["Mango"," Banana"," Lime"]
* }
* </code>
* </div>
*/
_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
* <div>
* <code>
* let string = trim(' No new lines\n ');
* text(string + ' here', 2, 50);
* </code>
* </div>
*
* @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': 51,
'../core/friendly_errors/file_errors': 52,
'../core/friendly_errors/validate_params': 54,
'../core/main': 59
}
],
101: [
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 <a href="#/p5/day">day()</a> function
* returns the current day as a value from 1 - 31.
*
* @method day
* @return {Integer} the current day
* @example
* <div>
* <code>
* let d = day();
* text('Current day: \n' + d, 5, 50);
* </code>
* </div>
*
* @alt
* Current day is displayed
*/ _main.default.prototype.day = function() {
return new Date().getDate();
};
/**
* p5.js communicates with the clock on your computer. The <a href="#/p5/hour">hour()</a> function
* returns the current hour as a value from 0 - 23.
*
* @method hour
* @return {Integer} the current hour
* @example
* <div>
* <code>
* let h = hour();
* text('Current hour:\n' + h, 5, 50);
* </code>
* </div>
*
* @alt
* Current hour is displayed
*/
_main.default.prototype.hour = function() {
return new Date().getHours();
};
/**
* p5.js communicates with the clock on your computer. The <a href="#/p5/minute">minute()</a> function
* returns the current minute as a value from 0 - 59.
*
* @method minute
* @return {Integer} the current minute
* @example
* <div>
* <code>
* let m = minute();
* text('Current minute: \n' + m, 5, 50);
* </code>
* </div>
*
* @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
* <div>
* <code>
* let millisecond = millis();
* text('Milliseconds \nrunning: \n' + millisecond, 5, 40);
* </code>
* </div>
*
* @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 <a href="#/p5/month">month()</a> function
* returns the current month as a value from 1 - 12.
*
* @method month
* @return {Integer} the current month
* @example
* <div>
* <code>
* let m = month();
* text('Current month: \n' + m, 5, 50);
* </code>
* </div>
*
* @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 <a href="#/p5/second">second()</a> function
* returns the current second as a value from 0 - 59.
*
* @method second
* @return {Integer} the current second
* @example
* <div>
* <code>
* let s = second();
* text('Current second: \n' + s, 5, 50);
* </code>
* </div>
*
* @alt
* Current second is displayed
*/
_main.default.prototype.second = function() {
return new Date().getSeconds();
};
/**
* p5.js communicates with the clock on your computer. The <a href="#/p5/year">year()</a> function
* returns the current year as an integer (2014, 2015, 2016, etc).
*
* @method year
* @return {Integer} the current year
* @example
* <div>
* <code>
* let y = year();
* text('Current year: \n' + y, 5, 50);
* </code>
* </div>
*
* @alt
* Current year is displayed
*/
_main.default.prototype.year = function() {
return new Date().getFullYear();
};
var _default = _main.default;
exports.default = _default;
},
{ '../core/main': 59 }
],
102: [
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
* <div>
* <code>
* // draw a plane
* // with width 50 and height 50
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(200);
* plane(50, 50);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* // draw a spinning box
* // with width, height and depth of 50
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(200);
* rotateX(frameCount * 0.01);
* rotateY(frameCount * 0.01);
* box(50);
* }
* </code>
* </div>
*/
_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
* <div>
* <code>
* // draw a sphere with radius 40
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(205, 102, 94);
* sphere(40);
* }
* </code>
* </div>
*
* @example
* <div>
* <code>
* 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');
* }
*
* function draw() {
* background(205, 105, 94);
* rotateY(millis() / 1000);
* sphere(40, detailX.value(), 16);
* }
* </code>
* </div>
*
* @example
* <div>
* <code>
* 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');
* }
*
* function draw() {
* background(205, 105, 94);
* rotateY(millis() / 1000);
* sphere(40, 16, detailY.value());
* }
* </code>
* </div>
*/
_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
* <div>
* <code>
* // draw a spinning cylinder
* // with radius 20 and height 50
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(205, 105, 94);
* rotateX(frameCount * 0.01);
* rotateZ(frameCount * 0.01);
* cylinder(20, 50);
* }
* </code>
* </div>
*
* @example
* <div>
* <code>
* // 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');
* }
*
* function draw() {
* background(205, 105, 94);
* rotateY(millis() / 1000);
* cylinder(20, 75, detailX.value(), 1);
* }
* </code>
* </div>
*
* @example
* <div>
* <code>
* // 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');
* }
*
* function draw() {
* background(205, 105, 94);
* rotateY(millis() / 1000);
* cylinder(20, 75, 16, detailY.value());
* }
* </code>
* </div>
*/
_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
* <div>
* <code>
* // draw a spinning cone
* // with radius 40 and height 70
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(200);
* rotateX(frameCount * 0.01);
* rotateZ(frameCount * 0.01);
* cone(40, 70);
* }
* </code>
* </div>
*
* @example
* <div>
* <code>
* // 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');
* }
*
* function draw() {
* background(205, 102, 94);
* rotateY(millis() / 1000);
* cone(30, 65, detailX.value(), 16);
* }
* </code>
* </div>
*
* @example
* <div>
* <code>
* // 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');
* }
*
* function draw() {
* background(205, 102, 94);
* rotateY(millis() / 1000);
* cone(30, 65, 16, detailY.value());
* }
* </code>
* </div>
*/
_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
* <div>
* <code>
* // draw an ellipsoid
* // with radius 30, 40 and 40.
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(205, 105, 94);
* ellipsoid(30, 40, 40);
* }
* </code>
* </div>
*
* @example
* <div>
* <code>
* // 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');
* }
*
* function draw() {
* background(205, 105, 94);
* rotateY(millis() / 1000);
* ellipsoid(30, 40, 40, detailX.value(), 8);
* }
* </code>
* </div>
*
* @example
* <div>
* <code>
* // 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');
* }
*
* function draw() {
* background(205, 105, 9);
* rotateY(millis() / 1000);
* ellipsoid(30, 40, 40, 12, detailY.value());
* }
* </code>
* </div>
*/
_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
* <div>
* <code>
* // draw a spinning torus
* // with ring radius 30 and tube radius 15
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(205, 102, 94);
* rotateX(frameCount * 0.01);
* rotateY(frameCount * 0.01);
* torus(30, 15);
* }
* </code>
* </div>
*
* @example
* <div>
* <code>
* // 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');
* }
*
* function draw() {
* background(205, 102, 94);
* rotateY(millis() / 1000);
* torus(30, 15, detailX.value(), 12);
* }
* </code>
* </div>
*
* @example
* <div>
* <code>
* // 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');
* }
*
* function draw() {
* background(205, 102, 94);
* rotateY(millis() / 1000);
* torus(30, 15, 16, detailY.value());
* }
* </code>
* </div>
*/
_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
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(50);
* stroke(255);
* strokeWeight(4);
* point(25, 0);
* strokeWeight(3);
* point(-25, 0);
* strokeWeight(2);
* point(0, 25);
* strokeWeight(1);
* point(0, -25);
* }
* </code>
* </div>
*/
_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(0, 1, 0));
vertices.push(new _main.default.Vector(1, 0, 0));
this.strokeIndices = [[0, 1], [1, 2], [2, 0]];
this.vertices = vertices;
this.faces = [[0, 1, 2]];
this.uvs = [0, 0, 0, 1, 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 {
// prettier-ignore
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._renderer._doStroke) {
console.log('Cannot stroke ${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 perPixelLighting = this._pInst._glAttributes.perPixelLighting;
var x = args[0];
var y = args[1];
var width = args[2];
var height = args[3];
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;
}
return this;
};
// prettier-ignore
_main.default.RendererGL.prototype.quad = function (x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) {
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);
if (!this.geometryInHash(gId)) {
var _quad = function _quad() {
this.vertices.push(new _main.default.Vector(x1, y1, z1));
this.vertices.push(new _main.default.Vector(x2, y2, z2));
this.vertices.push(new _main.default.Vector(x3, y3, z3));
this.vertices.push(new _main.default.Vector(x4, y4, z4));
this.uvs.push(0, 0, 1, 0, 1, 1, 0, 1);
this.strokeIndices = [[0, 1], [1, 2], [2, 3], [3, 0]];
};
var quadGeom = new _main.default.Geometry(2, 2, _quad);
quadGeom.
computeNormals().
_makeTriangleEdges().
_edgesToVertices();
quadGeom.faces = [[0, 1, 2], [2, 3, 0]];
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
* <div>
* <code>
* //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);
* }
* </code>
* </div>
*/
_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;
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;
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]
];
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);
}
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]
];
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);
}
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;
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;
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]
];
for (i = 0; i < LUTLength; i++) {
_x =
w_x[0] * this._lookUpTableQuadratic[i][0] +
w_x[1] * this._lookUpTableQuadratic[i][1] +
w_x[2] * this._lookUpTableQuadratic[i][2];
_y =
w_y[0] * this._lookUpTableQuadratic[i][0] +
w_y[1] * this._lookUpTableQuadratic[i][1] +
w_y[2] * this._lookUpTableQuadratic[i][2];
this.vertex(_x, _y);
}
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]
];
for (i = 0; i < LUTLength; i++) {
_x =
w_x[0] * this._lookUpTableQuadratic[i][0] +
w_x[1] * this._lookUpTableQuadratic[i][1] +
w_x[2] * this._lookUpTableQuadratic[i][2];
_y =
w_y[0] * this._lookUpTableQuadratic[i][0] +
w_y[1] * this._lookUpTableQuadratic[i][1] +
w_y[2] * this._lookUpTableQuadratic[i][2];
_z =
w_z[0] * this._lookUpTableQuadratic[i][0] +
w_z[1] * this._lookUpTableQuadratic[i][1] +
w_z[2] * this._lookUpTableQuadratic[i][2];
this.vertex(_x, _y, _z);
}
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.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': 48, '../core/main': 59, './p5.Geometry': 108 }
],
103: [
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 };
} /** // implementation based on three.js 'orbitControls':
* @module Lights, Camera
* @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
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* normalMaterial();
* }
* function draw() {
* background(200);
* orbitControl();
* rotateY(0.5);
* box(30, 50);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* camera(0, -30, 100, 0, 0, 0, 0, 1, 0);
* normalMaterial();
* debugMode();
* }
*
* function draw() {
* background(200);
* orbitControl();
* box(15, 30);
* // Press the spacebar to turn debugMode off!
* if (keyIsDown(32)) {
* noDebugMode();
* }
* }
* </code>
* </div>
* @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
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* camera(0, -30, 100, 0, 0, 0, 0, 1, 0);
* normalMaterial();
* debugMode(GRID);
* }
*
* function draw() {
* background(200);
* orbitControl();
* box(15, 30);
* }
* </code>
* </div>
* @alt
* a 3D box is centered on a grid in a 3D sketch.
*
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* camera(0, -30, 100, 0, 0, 0, 0, 1, 0);
* normalMaterial();
* debugMode(AXES);
* }
*
* function draw() {
* background(200);
* orbitControl();
* box(15, 30);
* }
* </code>
* </div>
* @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
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* camera(0, -30, 100, 0, 0, 0, 0, 1, 0);
* normalMaterial();
* debugMode(GRID, 100, 10, 0, 0, 0);
* }
*
* function draw() {
* background(200);
* orbitControl();
* box(15, 30);
* }
* </code>
* </div>
* @alt
* a 3D box is centered on a grid in a 3D sketch
*
* @example
* <div>
* <code>
* 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);
* }
*
* 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);
* }
* </code>
* </div>
* @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
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* camera(0, -30, 100, 0, 0, 0, 0, 1, 0);
* normalMaterial();
* debugMode();
* }
*
* function draw() {
* background(200);
* orbitControl();
* box(15, 30);
* // Press the spacebar to turn debugMode off!
* if (keyIsDown(32)) {
* noDebugMode();
* }
* }
* </code>
* </div>
* @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': 48, '../core/main': 59 }
],
104: [
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 };
} /**
* @method ambientLight
* @param {String} value a color string
* @chainable
*/ /**
* @module Lights, Camera
* @submodule Lights
* @for p5
* @requires core
*/ /**
* Creates an ambient light with a color. Ambient light is light that comes from everywhere on the canvas.
* It has no particular source.
* @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] the alpha value
* @chainable
*
* @example
* <div>
* <code>
* createCanvas(100, 100, WEBGL);
* ambientLight(0);
* ambientMaterial(250);
* sphere(40);
* </code>
* </div>
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
* function draw() {
* background(51);
* ambientLight(100); // white light
* ambientMaterial(255, 102, 94); // magenta material
* box(30);
* }
* </code>
* </div>
* @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
* <a href="https://processing.org/reference/lightSpecular_.html">lightSpecular</a>.
*
* @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
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* noStroke();
* }
*
* function draw() {
* background(0);
* shininess(20);
* ambientLight(50);
* specularColor(255, 0, 0);
* pointLight(255, 0, 0, 0, -50, 50);
* specularColor(0, 255, 0);
* pointLight(0, 255, 0, 0, 50, 50);
* specularMaterial(255);
* sphere(40);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
* 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);
* }
* </code>
* </div>
*
* @alt
* light source on canvas changeable with mouse position
*/
/**
* @method directionalLight
* @param {Number[]|String|p5.Color} color color Array, CSS color string,
* or <a href="#/p5.Color">p5.Color</a> value
* @param {Number} x x axis direction
* @param {Number} y y axis direction
* @param {Number} z z axis direction
* @chainable
*/
/**
* @method directionalLight
* @param {Number[]|String|p5.Color} color
* @param {p5.Vector} position
* @chainable
*/
/**
* @method directionalLight
* @param {Number} v1
* @param {Number} v2
* @param {Number} v3
* @param {Number} x
* @param {Number} y
* @param {Number} z
* @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 a color and a light position
*
* A maximum of 5 pointLight can be active at one time
* @method pointLight
* @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
* @chainable
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
* 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);
* }
* </code>
* </div>
*
* @alt
* spot light on canvas changes position with mouse
*/
/**
* @method pointLight
* @param {Number} v1
* @param {Number} v2
* @param {Number} v3
* @param {p5.Vector} position the position of the light
* @chainable
*/
/**
* @method pointLight
* @param {Number[]|String|p5.Color} color color Array, CSS color string,
* or <a href="#/p5.Color">p5.Color</a> value
* @param {Number} x
* @param {Number} y
* @param {Number} z
* @chainable
*/
/**
* @method pointLight
* @param {Number[]|String|p5.Color} 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;
};
/**
* Sets the default ambient and directional light. The defaults are <a href="#/p5/ambientLight">ambientLight(128, 128, 128)</a> and <a href="#/p5/directionalLight">directionalLight(128, 128, 128, 0, 0, -1)</a>. Lights need to be included in the <a href="#/p5/draw">draw()</a> to remain persistent in a looping program. Placing them in the <a href="#/p5/setup">setup()</a> of a looping program will cause them to only have an effect the first time through the loop.
* @method lights
* @chainable
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
* function draw() {
* background(0);
* lights();
* rotateX(millis() / 1000);
* rotateY(millis() / 1000);
* rotateZ(millis() / 1000);
* box();
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* noStroke();
* }
* function draw() {
* background(0);
* let locX = mouseX - width / 2;
* let locY = mouseY - height / 2;
* translate(-25, 0, 0);
* lightFalloff(1, 0, 0);
* pointLight(250, 250, 250, locX, locY, 50);
* sphere(20);
* translate(50, 0, 0);
* lightFalloff(0.9, 0.01, 0);
* pointLight(250, 250, 250, locX, locY, 50);
* sphere(20);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
* 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);
* }
* </code>
* </div>
*
* @alt
* Spot light on a sphere which changes position with mouse
*/
/**
* @method spotLight
* @param {Number[]|String|p5.Color} color color Array, CSS color string,
* or <a href="#/p5.Color">p5.Color</a> value
* @param {p5.Vector} position the position of the light
* @param {p5.Vector} direction the direction of the light
* @param {Number} [angle]
* @param {Number} [conc]
*/
/**
* @method spotLight
* @param {Number} v1
* @param {Number} v2
* @param {Number} v3
* @param {p5.Vector} position
* @param {p5.Vector} direction
* @param {Number} [angle]
* @param {Number} [conc]
*/
/**
* @method spotLight
* @param {Number[]|String|p5.Color} color
* @param {Number} x
* @param {Number} y
* @param {Number} z
* @param {p5.Vector} direction
* @param {Number} [angle]
* @param {Number} [conc]
*/
/**
* @method spotLight
* @param {Number[]|String|p5.Color} color
* @param {p5.Vector} position
* @param {Number} rx
* @param {Number} ry
* @param {Number} rz
* @param {Number} [angle]
* @param {Number} [conc]
*/
/**
* @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} [conc]
*/
/**
* @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} [conc]
*/
/**
* @method spotLight
* @param {Number[]|String|p5.Color} color
* @param {Number} x
* @param {Number} y
* @param {Number} z
* @param {Number} rx
* @param {Number} ry
* @param {Number} rz
* @param {Number} [angle]
* @param {Number} [conc]
*/
_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;
};
/**
* This function will remove all the lights from the sketch for the
* subsequent materials rendered. It affects all the subsequent methods.
* Calls to lighting methods made after noLights() will re-enable lights
* in the sketch.
* @method noLights
* @chainable
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
* function draw() {
* background(0);
* noStroke();
*
* ambientLight(150, 0, 0);
* translate(-25, 0, 0);
* ambientMaterial(250);
* sphere(20);
*
* noLights();
* ambientLight(0, 150, 0);
* translate(50, 0, 0);
* ambientMaterial(250);
* sphere(20);
* }
* </code>
* </div>
*
* @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': 59 }
],
105: [
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.
*
* <a href="#/p5/loadModel">loadModel()</a> should be placed inside of <a href="#/p5/preload">preload()</a>.
* 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
* <a href="#/p5/loadModel">loadModel()</a> 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 <a href="#/p5/scale">scale()</a> 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
* (<code>.stl</code>, <code>.obj</code>).
* @return {p5.Geometry} the <a href="#/p5.Geometry">p5.Geometry</a> object
*
* @example
* <div>
* <code>
* //draw a spinning octahedron
* let octahedron;
*
* function preload() {
* octahedron = loadModel('assets/octahedron.obj');
* }
*
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(200);
* rotateX(frameCount * 0.01);
* rotateY(frameCount * 0.01);
* model(octahedron);
* }
* </code>
* </div>
*
* @alt
* Vertically rotating 3-d octahedron.
*
* @example
* <div>
* <code>
* //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);
* }
* </code>
* </div>
*
* @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 <a href="#/p5.Geometry">p5.Geometry</a> 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
* <div>
* <code>
* //draw a spinning octahedron
* let octahedron;
*
* function preload() {
* octahedron = loadModel('assets/octahedron.obj');
* }
*
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(200);
* rotateX(frameCount * 0.01);
* rotateY(frameCount * 0.01);
* model(octahedron);
* }
* </code>
* </div>
*
* @alt
* Vertically rotating 3-d octahedron.
*/
_main.default.prototype.model = function(model) {
this._assert3d('model');
_main.default._validateParameters('model', arguments);
if (model.vertices.length > 0) {
if (!this._renderer.geometryInHash(model.gid)) {
model._makeTriangleEdges()._edgesToVertices();
this._renderer.createBuffers(model.gid, model);
}
this._renderer.drawBuffers(model.gid);
}
};
var _default = _main.default;
exports.default = _default;
},
{ '../core/main': 59, './p5.Geometry': 108 }
],
106: [
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.Texture');
function _getRequireWildcardCache() {
if (typeof WeakMap !== 'function') return null;
var cache = new WeakMap();
_getRequireWildcardCache = function _getRequireWildcardCache() {
return cache;
};
return cache;
}
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
}
if (obj === null || (_typeof(obj) !== 'object' && typeof obj !== 'function')) {
return { default: obj };
}
var cache = _getRequireWildcardCache();
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* @module Lights, Camera
* @submodule Material
* @for p5
* @requires core
*/ /**
* Loads a custom shader from the provided vertex and fragment
* shader paths. The shader files are loaded asynchronously in the
* background, so this method should be used in <a href="#/p5/preload">preload()</a>.
*
* For now, there are three main types of shaders. p5 will automatically
* supply appropriate vertices, normals, colors, and lighting attributes
* if the parameters defined in the shader match the names.
*
* @method loadShader
* @param {String} vertFilename path to file containing vertex shader
* source code
* @param {String} fragFilename path to file containing fragment shader
* source code
* @param {function} [callback] callback to be executed after loadShader
* completes. On success, the Shader object is passed as the first argument.
* @param {function} [errorCallback] callback to be executed when an error
* occurs inside loadShader. On error, the error is passed as the first
* argument.
* @return {p5.Shader} a shader object created from the provided
* vertex and fragment shader files.
*
* @example
* <div modernizr='webgl'>
* <code>
* let mandel;
* function preload() {
* // load the shader definitions from files
* mandel = loadShader('assets/shader.vert', 'assets/shader.frag');
* }
* function setup() {
* createCanvas(100, 100, WEBGL);
* // use the shader
* shader(mandel);
* noStroke();
* mandel.setUniform('p', [-0.74364388703, 0.13182590421]);
* }
*
* function draw() {
* mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000))));
* quad(-1, -1, 1, -1, 1, 1, -1, 1);
* }
* </code>
* </div>
*
* @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
* <div modernizr='webgl'>
* <code>
* // 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);
* }
* </code>
* </div>
*
* @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 <a href="#/p5/shader">shader()</a> 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
* <a href="#/p5/loadShader">loadShader()</a>.
*
* @method shader
* @chainable
* @param {p5.Shader} [s] the desired <a href="#/p5.Shader">p5.Shader</a> to use for rendering
* shapes.
*
* @example
* <div modernizr='webgl'>
* <code>
* // 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;
* }
* </code>
* </div>
*
* @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 <a href="#/p5/shader">shader()</a>.
*
* @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
* <a href="https://p5js.org/examples/3d-materials.html">example</a>.
* @method normalMaterial
* @chainable
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(200);
* normalMaterial();
* sphere(40);
* }
* </code>
* </div>
* @alt
* Red, green and blue gradient.
*/
_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;
};
/**
* Texture for geometry. You can view other possible materials in this
* <a href="https://p5js.org/examples/3d-materials.html">example</a>.
* @method texture
* @param {p5.Image|p5.MediaElement|p5.Graphics} tex 2-dimensional graphics
* to render as texture
* @chainable
* @example
* <div>
* <code>
* let img;
* function preload() {
* img = loadImage('assets/laDefense.jpg');
* }
*
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(0);
* rotateZ(frameCount * 0.01);
* rotateX(frameCount * 0.01);
* rotateY(frameCount * 0.01);
* //pass image as texture
* texture(img);
* box(200, 200, 200);
* }
* </code>
* </div>
*
* <div>
* <code>
* let pg;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
* pg = createGraphics(200, 200);
* pg.textSize(75);
* }
*
* function draw() {
* background(0);
* pg.background(255);
* pg.text('hello!', 0, 100);
* //pass image as texture
* texture(pg);
* rotateX(0.5);
* noStroke();
* plane(50);
* }
* </code>
* </div>
*
* <div>
* <code>
* let vid;
* function preload() {
* vid = createVideo('assets/fingers.mov');
* vid.hide();
* }
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(0);
* //pass video frame as texture
* texture(vid);
* rect(-40, -40, 80, 80);
* }
*
* function mousePressed() {
* vid.loop();
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* let img;
*
* function preload() {
* img = loadImage('assets/laDefense.jpg');
* }
*
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* texture(img);
* textureMode(NORMAL);
* beginShape();
* vertex(-50, -50, 0, 0);
* vertex(50, -50, 1, 0);
* vertex(50, 50, 1, 1);
* vertex(-50, 50, 0, 1);
* endShape();
* }
* </code>
* </div>
*
* @alt
* the underside of a white umbrella and gridded ceiling above
*
* <div>
* <code>
* let img;
*
* function preload() {
* img = loadImage('assets/laDefense.jpg');
* }
*
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* texture(img);
* textureMode(NORMAL);
* beginShape();
* vertex(-50, -50, 0, 0);
* vertex(50, -50, img.width, 0);
* vertex(50, 50, img.width, img.height);
* vertex(-50, 50, 0, img.height);
* endShape();
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* let img;
* function preload() {
* img = loadImage('assets/rockies128.jpg');
* }
*
* function setup() {
* createCanvas(100, 100, WEBGL);
* textureWrap(MIRROR);
* }
*
* 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();
* }
* </code>
* </div>
*
* @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 <a href="https://p5js.org/examples/3d-materials.html">example containing all possible materials</a>.
* @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
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
* function draw() {
* background(0);
* noStroke();
* ambientLight(200);
* ambientMaterial(70, 130, 230);
* sphere(40);
* }
* </code>
* </div>
* <div>
* <code>
* // 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);
* }
* </code>
* </div>
* <div>
* <code>
* // 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);
* }
* </code>
* </div>
* @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
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
* function draw() {
* background(0);
* noStroke();
* ambientLight(0);
* emissiveMaterial(130, 230, 0);
* sphere(40);
* }
* </code>
* </div>
*
* @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 <a href="https://p5js.org/examples/3d-materials.html">example containing all possible materials</a>.
*
* @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
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
* function draw() {
* background(0);
* ambientLight(50);
* pointLight(250, 250, 250, 100, 100, 30);
* specularMaterial(250);
* sphere(40);
* }
* </code>
* </div>
* @alt
* diffused radiating light source from top right of canvas
*/
/**
* @method specularMaterial
* @param {Number[]|String|p5.Color} color color Array, or CSS color 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.curFillColor = color._array;
this._renderer._useSpecularMaterial = true;
this._renderer._useEmissiveMaterial = false;
this._renderer._useNormalMaterial = false;
this._renderer._enableLighting = true;
this._renderer._tex = null;
return this;
};
/**
* Sets the amount of gloss in the surface of shapes.
* Used in combination with specularMaterial() in setting
* the material properties of shapes. The default and minimum value is 1.
* @method shininess
* @param {Number} shine Degree of Shininess.
* Defaults to 1.
* @chainable
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
* function draw() {
* background(0);
* noStroke();
* let locX = mouseX - width / 2;
* let locY = mouseY - height / 2;
* ambientLight(60, 60, 60);
* pointLight(255, 255, 255, locX, locY, 50);
* specularMaterial(250);
* translate(-25, 0, 0);
* shininess(1);
* sphere(20);
* translate(50, 0, 0);
* shininess(20);
* sphere(20);
* }
* </code>
* </div>
* @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': 48, '../core/main': 59, './p5.Texture': 115 }
],
107: [
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 <a href = "https://www.openprocessing.org/sketch/740258">example</a>
* 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
* <div>
* <code>
* 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);
* }
* </code>
* </div>
*
* @example
* <div>
* <code>
* //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);
* }
* </code>
* </div>
* @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 <a href="#/p5/angleMode">angleMode</a> units
* @param {Number} [aspect] camera frustum aspect ratio
* @param {Number} [near] frustum near plane length
* @param {Number} [far] frustum far plane length
* @chainable
* @example
* <div>
* <code>
* //drag the mouse to look around!
* function setup() {
* createCanvas(100, 100, WEBGL);
* perspective(PI / 3.0, width / height, 0.1, 500);
* }
* function draw() {
* background(200);
* orbitControl();
* normalMaterial();
*
* rotateX(-0.3);
* rotateY(-0.2);
* translate(0, 0, -50);
*
* push();
* translate(-15, 0, sin(frameCount / 30) * 95);
* box(30);
* pop();
* push();
* translate(15, 0, sin(frameCount / 30 + PI) * 95);
* box(30);
* pop();
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* //drag the mouse to look around!
* //there's no vanishing point
* function setup() {
* createCanvas(100, 100, WEBGL);
* ortho(-width / 2, width / 2, height / 2, -height / 2, 0, 500);
* }
* function draw() {
* background(200);
* orbitControl();
* normalMaterial();
*
* rotateX(0.2);
* rotateY(-0.2);
* push();
* translate(-15, 0, sin(frameCount / 30) * 65);
* box(30);
* pop();
* push();
* translate(15, 0, sin(frameCount / 30 + PI) * 65);
* box(30);
* pop();
* }
* </code>
* </div>
*
* @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
* <a href="https://p5js.org/reference/#/p5/perspective">perspective()</a>.
*
* @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
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* setAttributes('antialias', true);
* frustum(-0.1, 0.1, -0.1, 0.1, 0.1, 200);
* }
* function draw() {
* background(200);
* orbitControl();
* strokeWeight(10);
* stroke(0, 0, 255);
* noFill();
*
* rotateY(-0.2);
* rotateX(-0.3);
* push();
* translate(-15, 0, sin(frameCount / 30) * 25);
* box(30);
* pop();
* push();
* translate(15, 0, sin(frameCount / 30 + PI) * 25);
* box(30);
* pop();
* }
* </code>
* </div>
*
* @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 <a href="#/p5.Camera">p5.Camera</a> 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
* <div><code>
* // 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);
* }
* </code></div>
*
* @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
* <a href="https://github.com/processing/p5.js/wiki/Getting-started-with-WebGL-in-p5">
* WebGL mode</a>. It contains camera position, orientation, and projection
* information necessary for rendering a 3D scene.
*
* New p5.Camera objects can be made through the
* <a href="#/p5/createCamera">createCamera()</a> 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 <a href="#/p5/setCamera">setCamera()</a> 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 <a href="#/p5.Camera/move">move()</a> method,
* for instance, moves the camera along its own axes, whereas the
* <a href="#/p5.Camera/setPosition">setPosition()</a>
* method sets the camera's position in world-space.
*
* @class p5.Camera
* @param {rendererGL} rendererGL instance of WebGL renderer
* @example
* <div>
* <code>
* let cam;
* let delta = 0.01;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
* normalMaterial();
* cam = createCamera();
* // set initial pan angle
* cam.pan(-0.8);
* }
*
* 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);
* }
* </code>
* </div>
*
* @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 Projection Methods
////////////////////////////////////////////////////////////////////////////////
/**
* Sets a perspective projection for a p5.Camera object and sets parameters
* for that projection according to <a href="#/p5/perspective">perspective()</a>
* syntax.
* @method perspective
* @for p5.Camera
*/
_main.default.Camera.prototype.perspective = function(fovy, aspect, near, far) {
this.cameraType = arguments.length > 0 ? 'custom' : 'default';
if (typeof fovy === 'undefined') {
fovy = this.defaultCameraFOV;
// this avoids issue where setting angleMode(DEGREES) before calling
// perspective leads to a smaller than expected FOV (because
// _computeCameraDefaultSettings computes in radians)
this.cameraFOV = fovy;
} else {
this.cameraFOV = this._renderer._pInst._toRadians(fovy);
}
if (typeof aspect === 'undefined') {
aspect = this.defaultAspectRatio;
}
if (typeof near === 'undefined') {
near = this.defaultCameraNear;
}
if (typeof far === 'undefined') {
far = this.defaultCameraFar;
}
if (near <= 0.0001) {
near = 0.01;
console.log(
'Avoid perspective near plane values close to or below 0. ' +
'Setting value to 0.01.'
);
}
if (far < near) {
console.log(
'Perspective far plane value is less than near plane value. ' +
'Nothing will be shown.'
);
}
this.aspectRatio = aspect;
this.cameraNear = near;
this.cameraFar = far;
this.projMatrix = _main.default.Matrix.identity();
var f = 1.0 / Math.tan(this.cameraFOV / 2);
var nf = 1.0 / (this.cameraNear - this.cameraFar);
// prettier-ignore
this.projMatrix.set(f / aspect, 0, 0, 0,
0, -f, 0, 0,
0, 0, (far + near) * nf, -1,
0, 0, 2 * far * near * nf, 0);
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]
);
}
};
/**
* Sets an orthographic projection for a p5.Camera object and sets parameters
* for that projection according to <a href="#/p5/ortho">ortho()</a> syntax.
* @method ortho
* @for p5.Camera
*/
_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.0 / w;
var y = +2.0 / h;
var z = -2.0 / d;
var tx = -(right + left) / w;
var ty = -(top + bottom) / h;
var tz = -(far + near) / d;
this.projMatrix = _main.default.Matrix.identity();
// prettier-ignore
this.projMatrix.set(x, 0, 0, 0,
0, -y, 0, 0,
0, 0, z, 0,
tx, ty, tz, 1);
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';
};
/**
* @method frustum
* @for p5.Camera
*/
_main.default.Camera.prototype.frustum = 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.0 * near) / w;
var y = +(2.0 * near) / h;
var z = -(2.0 * far * near) / d;
var tx = (right + left) / w;
var ty = (top + bottom) / h;
var tz = -(far + near) / d;
this.projMatrix = _main.default.Matrix.identity();
// prettier-ignore
this.projMatrix.set(x, 0, 0, 0,
0, y, 0, 0,
tx, ty, tz, -1,
0, 0, z, 0);
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';
};
////////////////////////////////////////////////////////////////////////////////
// Camera Orientation Methods
////////////////////////////////////////////////////////////////////////////////
/**
* Rotate camera view about arbitrary axis defined by x,y,z
* based on http://learnwebgl.brown37.net/07_cameras/camera_rotating_motion.html
* @method _rotateView
* @private
*/
_main.default.Camera.prototype._rotateView = function(a, x, y, z) {
var centerX = this.centerX;
var centerY = this.centerY;
var centerZ = this.centerZ;
// move center by eye position such that rotation happens around eye position
centerX -= this.eyeX;
centerY -= this.eyeY;
centerZ -= this.eyeZ;
var rotation = _main.default.Matrix.identity(this._renderer._pInst);
rotation.rotate(this._renderer._pInst._toRadians(a), x, y, z);
// prettier-ignore
var rotatedCenter = [
centerX * rotation.mat4[0] + centerY * rotation.mat4[4] + centerZ * rotation.mat4[8],
centerX * rotation.mat4[1] + centerY * rotation.mat4[5] + centerZ * rotation.mat4[9],
centerX * rotation.mat4[2] + centerY * rotation.mat4[6] + centerZ * rotation.mat4[10]];
// add eye position back into center
rotatedCenter[0] += this.eyeX;
rotatedCenter[1] += this.eyeY;
rotatedCenter[2] += this.eyeZ;
this.camera(
this.eyeX,
this.eyeY,
this.eyeZ,
rotatedCenter[0],
rotatedCenter[1],
rotatedCenter[2],
this.upX,
this.upY,
this.upZ
);
};
/**
* Panning rotates the camera view to the left and right.
* @method pan
* @param {Number} angle amount to rotate camera in current
* <a href="#/p5/angleMode">angleMode</a> units.
* Greater than 0 values rotate counterclockwise (to the left).
* @example
* <div>
* <code>
* let cam;
* let delta = 0.01;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
* normalMaterial();
* cam = createCamera();
* // set initial pan angle
* cam.pan(-0.8);
* }
*
* 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);
* }
* </code>
* </div>
*
* @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
* <a href="#/p5/angleMode">angleMode</a> units.
* Greater than 0 values rotate counterclockwise (to the left).
* @example
* <div>
* <code>
* let cam;
* let delta = 0.01;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
* normalMaterial();
* cam = createCamera();
* // set initial tilt
* cam.tilt(-0.8);
* }
*
* function draw() {
* background(200);
*
* // pan camera according to angle 'delta'
* cam.tilt(delta);
*
* // every 160 frames, switch direction
* if (frameCount % 160 === 0) {
* delta *= -1;
* }
*
* rotateY(frameCount * 0.01);
* translate(0, -100, 0);
* box(20);
* translate(0, 35, 0);
* box(20);
* translate(0, 35, 0);
* box(20);
* translate(0, 35, 0);
* box(20);
* translate(0, 35, 0);
* box(20);
* translate(0, 35, 0);
* box(20);
* translate(0, 35, 0);
* box(20);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* let cam;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
* normalMaterial();
* cam = createCamera();
* }
*
* function draw() {
* background(200);
*
* // look at a new random point every 60 frames
* if (frameCount % 60 === 0) {
* cam.lookAt(random(-100, 100), random(-50, 50), 0);
* }
*
* 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);
* }
* </code>
* </div>
*
* @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
* <a href="#/p5/camera">camera()</a> 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;
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.
// 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
* <div>
* <code>
* // 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);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* // press '1' '2' or '3' keys to set camera position
*
* let cam;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
* normalMaterial();
* cam = createCamera();
* }
*
* function draw() {
* background(200);
*
* // '1' key
* if (keyIsDown(49)) {
* cam.setPosition(30, 0, 80);
* }
* // '2' key
* if (keyIsDown(50)) {
* cam.setPosition(0, 0, 80);
* }
* // '3' key
* if (keyIsDown(51)) {
* cam.setPosition(-30, 0, 80);
* }
*
* box(20);
* }
* </code>
* </div>
*
* @alt
* camera position changes as the user presses keys, altering view of a 3D box
*/
_main.default.Camera.prototype.setPosition = function(x, y, z) {
var diffX = x - this.eyeX;
var diffY = y - this.eyeY;
var diffZ = z - this.eyeZ;
this.camera(
x,
y,
z,
this.centerX + diffX,
this.centerY + diffY,
this.centerZ + diffZ,
0,
1,
0
);
};
////////////////////////////////////////////////////////////////////////////////
// Camera Helper Methods
////////////////////////////////////////////////////////////////////////////////
// @TODO: combine this function with _setDefaultCamera to compute these values
// as-needed
_main.default.Camera.prototype._computeCameraDefaultSettings = function() {
this.defaultCameraFOV = 60 / 180 * Math.PI;
this.defaultAspectRatio = this._renderer.width / this._renderer.height;
this.defaultEyeX = 0;
this.defaultEyeY = 0;
this.defaultEyeZ =
this._renderer.height / 2.0 / Math.tan(this.defaultCameraFOV / 2.0);
this.defaultCenterX = 0;
this.defaultCenterY = 0;
this.defaultCenterZ = 0;
this.defaultCameraNear = this.defaultEyeZ * 0.1;
this.defaultCameraFar = this.defaultEyeZ * 10;
};
//detect if user didn't set the camera
//then call this function below
_main.default.Camera.prototype._setDefaultCamera = function() {
this.cameraFOV = this.defaultCameraFOV;
this.aspectRatio = this.defaultAspectRatio;
this.eyeX = this.defaultEyeX;
this.eyeY = this.defaultEyeY;
this.eyeZ = this.defaultEyeZ;
this.centerX = this.defaultCenterX;
this.centerY = this.defaultCenterY;
this.centerZ = this.defaultCenterZ;
this.upX = 0;
this.upY = 1;
this.upZ = 0;
this.cameraNear = this.defaultCameraNear;
this.cameraFar = this.defaultCameraFar;
this.perspective();
this.camera();
this.cameraType = 'default';
};
_main.default.Camera.prototype._resize = function() {
// If we're using the default camera, update the aspect ratio
if (this.cameraType === 'default') {
this._computeCameraDefaultSettings();
this._setDefaultCamera();
} else {
this.perspective(
this.cameraFOV,
this._renderer.width / this._renderer.height
);
}
};
/**
* Returns a copy of a camera.
* @method copy
* @private
*/
_main.default.Camera.prototype.copy = function() {
var _cam = new _main.default.Camera(this._renderer);
_cam.cameraFOV = this.cameraFOV;
_cam.aspectRatio = this.aspectRatio;
_cam.eyeX = this.eyeX;
_cam.eyeY = this.eyeY;
_cam.eyeZ = this.eyeZ;
_cam.centerX = this.centerX;
_cam.centerY = this.centerY;
_cam.centerZ = this.centerZ;
_cam.cameraNear = this.cameraNear;
_cam.cameraFar = this.cameraFar;
_cam.cameraType = this.cameraType;
_cam.cameraMatrix = this.cameraMatrix.copy();
_cam.projMatrix = this.projMatrix.copy();
return _cam;
};
/**
* Returns a camera's local axes: left-right, up-down, and forward-backward,
* as defined by vectors in world-space.
* @method _getLocalAxes
* @private
*/
_main.default.Camera.prototype._getLocalAxes = function() {
// calculate camera local Z vector
var z0 = this.eyeX - this.centerX;
var z1 = this.eyeY - this.centerY;
var z2 = this.eyeZ - this.centerZ;
// normalize camera local Z vector
var eyeDist = Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
if (eyeDist !== 0) {
z0 /= eyeDist;
z1 /= eyeDist;
z2 /= eyeDist;
}
// calculate camera Y vector
var y0 = this.upX;
var y1 = this.upY;
var y2 = this.upZ;
// compute camera local X vector as up vector (local Y) cross local Z
var x0 = y1 * z2 - y2 * z1;
var x1 = -y0 * z2 + y2 * z0;
var x2 = y0 * z1 - y1 * z0;
// recompute y = z cross x
y0 = z1 * x2 - z2 * x1;
y1 = -z0 * x2 + z2 * x0;
y2 = z0 * x1 - z1 * x0;
// cross product gives area of parallelogram, which is < 1.0 for
// non-perpendicular unit-length vectors; so normalize x, y here:
var xmag = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);
if (xmag !== 0) {
x0 /= xmag;
x1 /= xmag;
x2 /= xmag;
}
var ymag = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2);
if (ymag !== 0) {
y0 /= ymag;
y1 /= ymag;
y2 /= ymag;
}
return {
x: [x0, x1, x2],
y: [y0, y1, y2],
z: [z0, z1, z2]
};
};
/**
* Orbits the camera about center point. For use with orbitControl().
* @method _orbit
* @private
* @param {Number} dTheta change in spherical coordinate theta
* @param {Number} dPhi change in spherical coordinate phi
* @param {Number} dRadius change in radius
*/
_main.default.Camera.prototype._orbit = function(dTheta, dPhi, dRadius) {
var diffX = this.eyeX - this.centerX;
var diffY = this.eyeY - this.centerY;
var diffZ = this.eyeZ - this.centerZ;
// get spherical coorinates for current camera position about origin
var camRadius = Math.sqrt(diffX * diffX + diffY * diffY + diffZ * diffZ);
// from https://github.com/mrdoob/three.js/blob/dev/src/math/Spherical.js#L72-L73
var camTheta = Math.atan2(diffX, diffZ); // equatorial angle
var camPhi = Math.acos(Math.max(-1, Math.min(1, diffY / camRadius))); // polar angle
// add change
camTheta += dTheta;
camPhi += dPhi;
camRadius += dRadius;
// prevent zooming through the center:
if (camRadius < 0) {
camRadius = 0.1;
}
// prevent rotation over the zenith / under bottom
if (camPhi > Math.PI) {
camPhi = Math.PI;
} else if (camPhi <= 0) {
camPhi = 0.001;
}
// from https://github.com/mrdoob/three.js/blob/dev/src/math/Vector3.js#L628-L632
var _x = Math.sin(camPhi) * camRadius * Math.sin(camTheta);
var _y = Math.cos(camPhi) * camRadius;
var _z = Math.sin(camPhi) * camRadius * Math.cos(camTheta);
this.camera(
_x + this.centerX,
_y + this.centerY,
_z + this.centerZ,
this.centerX,
this.centerY,
this.centerZ,
0,
1,
0
);
};
/**
* Returns true if camera is currently attached to renderer.
* @method _isActive
* @private
*/
_main.default.Camera.prototype._isActive = function() {
return this === this._renderer._curCamera;
};
/**
* Sets rendererGL's current camera to a p5.Camera object. Allows switching
* between multiple cameras.
* @method setCamera
* @param {p5.Camera} cam p5.Camera object
* @for p5
* @example
* <div>
* <code>
* let cam1, cam2;
* let currentCamera;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
* normalMaterial();
*
* cam1 = createCamera();
* cam2 = createCamera();
* cam2.setPosition(30, 0, 50);
* cam2.lookAt(0, 0, 0);
* cam2.ortho();
*
* // set variable for previously active camera:
* currentCamera = 1;
* }
*
* function draw() {
* background(200);
*
* // camera 1:
* cam1.lookAt(0, 0, 0);
* cam1.setPosition(sin(frameCount / 60) * 200, 0, 100);
*
* // every 100 frames, switch between the two cameras
* if (frameCount % 100 === 0) {
* if (currentCamera === 1) {
* setCamera(cam1);
* currentCamera = 0;
* } else {
* setCamera(cam2);
* currentCamera = 1;
* }
* }
*
* drawBoxes();
* }
*
* function drawBoxes() {
* 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);
* }
* </code>
* </div>
*
* @alt
* Canvas switches between two camera views, each showing a series of spinning
* 3D boxes.
*/
_main.default.prototype.setCamera = function(cam) {
this._renderer._curCamera = cam;
// set the projection matrix (which is not normally updated each frame)
this._renderer.uPMatrix.set(
cam.projMatrix.mat4[0],
cam.projMatrix.mat4[1],
cam.projMatrix.mat4[2],
cam.projMatrix.mat4[3],
cam.projMatrix.mat4[4],
cam.projMatrix.mat4[5],
cam.projMatrix.mat4[6],
cam.projMatrix.mat4[7],
cam.projMatrix.mat4[8],
cam.projMatrix.mat4[9],
cam.projMatrix.mat4[10],
cam.projMatrix.mat4[11],
cam.projMatrix.mat4[12],
cam.projMatrix.mat4[13],
cam.projMatrix.mat4[14],
cam.projMatrix.mat4[15]
);
};
var _default = _main.default.Camera;
exports.default = _default;
},
{ '../core/main': 59 }
],
108: [
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 };
} /** //some of the functions are adjusted from Three.js(http://threejs.org)
* @module Lights, Camera
* @submodule Material
* @for p5
* @requires core
* @requires p5.Geometry
*/
/**
* p5 Geometry class
* @class p5.Geometry
* @constructor
* @param {Integer} [detailX] number of vertices on horizontal surface
* @param {Integer} [detailY] number of vertices on horizontal surface
* @param {function} [callback] function to call upon object instantiation.
*/ _main.default.Geometry = function(detailX, detailY, callback) {
//an array containing every vertex
//@type [p5.Vector]
this.vertices = []; //an array containing every vertex for stroke drawing
this.lineVertices = []; //an array 1 normal per lineVertex with
//final position representing which direction to
//displace for strokeWeight
//[[0,0,-1,1], [0,1,0,-1] ...];
this.lineNormals = [];
//an array containing 1 normal per vertex
//@type [p5.Vector]
//[p5.Vector, p5.Vector, p5.Vector,p5.Vector, p5.Vector, p5.Vector,...]
this.vertexNormals = [];
//an array containing each three vertex indices that form a face
//[[0, 1, 2], [2, 1, 3], ...]
this.faces = [];
//a 2D array containing uvs for every vertex
//[[0.0,0.0],[1.0,0.0], ...]
this.uvs = [];
// a 2D array containing edge connectivity pattern for create line vertices
//based on faces for most objects;
this.edges = [];
this.vertexColors = [];
this.detailX = detailX !== undefined ? detailX : 1;
this.detailY = detailY !== undefined ? detailY : 1;
this.dirtyFlags = {};
if (callback instanceof Function) {
callback.call(this);
}
return this; // TODO: is this a constructor?
};
_main.default.Geometry.prototype.reset = function() {
this.lineVertices.length = 0;
this.lineNormals.length = 0;
this.vertices.length = 0;
this.edges.length = 0;
this.vertexColors.length = 0;
this.vertexNormals.length = 0;
this.uvs.length = 0;
this.dirtyFlags = {};
};
/**
* computes faces for geometry objects based on the vertices.
* @method computeFaces
* @chainable
*/
_main.default.Geometry.prototype.computeFaces = function() {
this.faces.length = 0;
var sliceCount = this.detailX + 1;
var a, b, c, d;
for (var i = 0; i < this.detailY; i++) {
for (var j = 0; j < this.detailX; j++) {
a = i * sliceCount + j; // + offset;
b = i * sliceCount + j + 1; // + offset;
c = (i + 1) * sliceCount + j + 1; // + offset;
d = (i + 1) * sliceCount + j; // + offset;
this.faces.push([a, b, d]);
this.faces.push([d, b, c]);
}
}
return this;
};
_main.default.Geometry.prototype._getFaceNormal = function(faceId) {
//This assumes that vA->vB->vC is a counter-clockwise ordering
var face = this.faces[faceId];
var vA = this.vertices[face[0]];
var vB = this.vertices[face[1]];
var vC = this.vertices[face[2]];
var ab = _main.default.Vector.sub(vB, vA);
var ac = _main.default.Vector.sub(vC, vA);
var n = _main.default.Vector.cross(ab, ac);
var ln = _main.default.Vector.mag(n);
var sinAlpha =
ln / (_main.default.Vector.mag(ab) * _main.default.Vector.mag(ac));
if (sinAlpha === 0 || isNaN(sinAlpha)) {
console.warn(
'p5.Geometry.prototype._getFaceNormal:',
'face has colinear sides or a repeated vertex'
);
return n;
}
if (sinAlpha > 1) sinAlpha = 1; // handle float rounding error
return n.mult(Math.asin(sinAlpha) / ln);
};
/**
* computes smooth normals per vertex as an average of each
* face.
* @method computeNormals
* @chainable
*/
_main.default.Geometry.prototype.computeNormals = function() {
var vertexNormals = this.vertexNormals;
var vertices = this.vertices;
var faces = this.faces;
var iv;
// initialize the vertexNormals array with empty vectors
vertexNormals.length = 0;
for (iv = 0; iv < vertices.length; ++iv) {
vertexNormals.push(new _main.default.Vector());
}
// loop through all the faces adding its normal to the normal
// of each of its vertices
for (var f = 0; f < faces.length; ++f) {
var face = faces[f];
var faceNormal = this._getFaceNormal(f);
// all three vertices get the normal added
for (var fv = 0; fv < 3; ++fv) {
var vertexIndex = face[fv];
vertexNormals[vertexIndex].add(faceNormal);
}
}
// normalize the normals
for (iv = 0; iv < vertices.length; ++iv) {
vertexNormals[iv].normalize();
}
return this;
};
/**
* Averages the vertex normals. Used in curved
* surfaces
* @method averageNormals
* @chainable
*/
_main.default.Geometry.prototype.averageNormals = function() {
for (var i = 0; i <= this.detailY; i++) {
var offset = this.detailX + 1;
var temp = _main.default.Vector.add(
this.vertexNormals[i * offset],
this.vertexNormals[i * offset + this.detailX]
);
temp = _main.default.Vector.div(temp, 2);
this.vertexNormals[i * offset] = temp;
this.vertexNormals[i * offset + this.detailX] = temp;
}
return this;
};
/**
* Averages pole normals. Used in spherical primitives
* @method averagePoleNormals
* @chainable
*/
_main.default.Geometry.prototype.averagePoleNormals = function() {
//average the north pole
var sum = new _main.default.Vector(0, 0, 0);
for (var i = 0; i < this.detailX; i++) {
sum.add(this.vertexNormals[i]);
}
sum = _main.default.Vector.div(sum, this.detailX);
for (var _i = 0; _i < this.detailX; _i++) {
this.vertexNormals[_i] = sum;
}
//average the south pole
sum = new _main.default.Vector(0, 0, 0);
for (
var _i2 = this.vertices.length - 1;
_i2 > this.vertices.length - 1 - this.detailX;
_i2--
) {
sum.add(this.vertexNormals[_i2]);
}
sum = _main.default.Vector.div(sum, this.detailX);
for (
var _i3 = this.vertices.length - 1;
_i3 > this.vertices.length - 1 - this.detailX;
_i3--
) {
this.vertexNormals[_i3] = sum;
}
return this;
};
/**
* Create a 2D array for establishing stroke connections
* @private
* @chainable
*/
_main.default.Geometry.prototype._makeTriangleEdges = function() {
this.edges.length = 0;
if (Array.isArray(this.strokeIndices)) {
for (var i = 0, max = this.strokeIndices.length; i < max; i++) {
this.edges.push(this.strokeIndices[i]);
}
} else {
for (var j = 0; j < this.faces.length; j++) {
this.edges.push([this.faces[j][0], this.faces[j][1]]);
this.edges.push([this.faces[j][1], this.faces[j][2]]);
this.edges.push([this.faces[j][2], this.faces[j][0]]);
}
}
return this;
};
/**
* Create 4 vertices for each stroke line, two at the beginning position
* and two at the end position. These vertices are displaced relative to
* that line's normal on the GPU
* @private
* @chainable
*/
_main.default.Geometry.prototype._edgesToVertices = function() {
this.lineVertices.length = 0;
this.lineNormals.length = 0;
for (var i = 0; i < this.edges.length; i++) {
var begin = this.vertices[this.edges[i][0]];
var end = this.vertices[this.edges[i][1]];
var dir = end
.copy()
.sub(begin)
.normalize();
var a = begin.array();
var b = begin.array();
var c = end.array();
var d = end.array();
var dirAdd = dir.array();
var dirSub = dir.array();
// below is used to displace the pair of vertices at beginning and end
// in opposite directions
dirAdd.push(1);
dirSub.push(-1);
this.lineNormals.push(dirAdd, dirSub, dirAdd, dirAdd, dirSub, dirSub);
this.lineVertices.push(a, b, c, c, b, d);
}
return this;
};
/**
* Modifies all vertices to be centered within the range -100 to 100.
* @method normalize
* @chainable
*/
_main.default.Geometry.prototype.normalize = function() {
if (this.vertices.length > 0) {
// Find the corners of our bounding box
var maxPosition = this.vertices[0].copy();
var minPosition = this.vertices[0].copy();
for (var i = 0; i < this.vertices.length; i++) {
maxPosition.x = Math.max(maxPosition.x, this.vertices[i].x);
minPosition.x = Math.min(minPosition.x, this.vertices[i].x);
maxPosition.y = Math.max(maxPosition.y, this.vertices[i].y);
minPosition.y = Math.min(minPosition.y, this.vertices[i].y);
maxPosition.z = Math.max(maxPosition.z, this.vertices[i].z);
minPosition.z = Math.min(minPosition.z, this.vertices[i].z);
}
var center = _main.default.Vector.lerp(maxPosition, minPosition, 0.5);
var dist = _main.default.Vector.sub(maxPosition, minPosition);
var longestDist = Math.max(Math.max(dist.x, dist.y), dist.z);
var scale = 200 / longestDist;
for (var _i4 = 0; _i4 < this.vertices.length; _i4++) {
this.vertices[_i4].sub(center);
this.vertices[_i4].mult(scale);
}
}
return this;
};
var _default = _main.default.Geometry;
exports.default = _default;
},
{ '../core/main': 59 }
],
109: [
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 };
}
/**
* @requires constants
* @todo see methods below needing further implementation.
* future consideration: implement SIMD optimizations
* when browser compatibility becomes available
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/
* Reference/Global_Objects/SIMD
*/ var GLMAT_ARRAY_TYPE = Array;
var isMatrixArray = function isMatrixArray(x) {
return x instanceof Array;
};
if (typeof Float32Array !== 'undefined') {
GLMAT_ARRAY_TYPE = Float32Array;
isMatrixArray = function isMatrixArray(x) {
return x instanceof Array || x instanceof Float32Array;
};
}
/**
* A class to describe a 4x4 matrix
* for model and view matrix manipulation in the p5js webgl renderer.
* @class p5.Matrix
* @private
* @constructor
* @param {Array} [mat4] array literal of our 4x4 matrix
*/
_main.default.Matrix = function() {
var args = new Array(arguments.length);
for (var i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
// This is default behavior when object
// instantiated using createMatrix()
// @todo implement createMatrix() in core/math.js
if (args.length && args[args.length - 1] instanceof _main.default) {
this.p5 = args[args.length - 1];
}
if (args[0] === 'mat3') {
this.mat3 = Array.isArray(args[1])
? args[1]
: new GLMAT_ARRAY_TYPE([1, 0, 0, 0, 1, 0, 0, 0, 1]);
} else {
this.mat4 = Array.isArray(args[0])
? args[0]
: new GLMAT_ARRAY_TYPE([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
}
return this;
};
/**
* Sets the x, y, and z component of the vector using two or three separate
* variables, the data from a p5.Matrix, or the values from a float array.
*
* @method set
* @param {p5.Matrix|Float32Array|Number[]} [inMatrix] the input p5.Matrix or
* an Array of length 16
* @chainable
*/
/**
* @method set
* @param {Number[]} elements 16 numbers passed by value to avoid
* array copying.
* @chainable
*/
_main.default.Matrix.prototype.set = function(inMatrix) {
if (inMatrix instanceof _main.default.Matrix) {
this.mat4 = inMatrix.mat4;
return this;
} else if (isMatrixArray(inMatrix)) {
this.mat4 = inMatrix;
return this;
} else if (arguments.length === 16) {
this.mat4[0] = arguments[0];
this.mat4[1] = arguments[1];
this.mat4[2] = arguments[2];
this.mat4[3] = arguments[3];
this.mat4[4] = arguments[4];
this.mat4[5] = arguments[5];
this.mat4[6] = arguments[6];
this.mat4[7] = arguments[7];
this.mat4[8] = arguments[8];
this.mat4[9] = arguments[9];
this.mat4[10] = arguments[10];
this.mat4[11] = arguments[11];
this.mat4[12] = arguments[12];
this.mat4[13] = arguments[13];
this.mat4[14] = arguments[14];
this.mat4[15] = arguments[15];
}
return this;
};
/**
* Gets a copy of the vector, returns a p5.Matrix object.
*
* @method get
* @return {p5.Matrix} the copy of the p5.Matrix object
*/
_main.default.Matrix.prototype.get = function() {
return new _main.default.Matrix(this.mat4, this.p5);
};
/**
* return a copy of a matrix
* @method copy
* @return {p5.Matrix} the result matrix
*/
_main.default.Matrix.prototype.copy = function() {
var copied = new _main.default.Matrix(this.p5);
copied.mat4[0] = this.mat4[0];
copied.mat4[1] = this.mat4[1];
copied.mat4[2] = this.mat4[2];
copied.mat4[3] = this.mat4[3];
copied.mat4[4] = this.mat4[4];
copied.mat4[5] = this.mat4[5];
copied.mat4[6] = this.mat4[6];
copied.mat4[7] = this.mat4[7];
copied.mat4[8] = this.mat4[8];
copied.mat4[9] = this.mat4[9];
copied.mat4[10] = this.mat4[10];
copied.mat4[11] = this.mat4[11];
copied.mat4[12] = this.mat4[12];
copied.mat4[13] = this.mat4[13];
copied.mat4[14] = this.mat4[14];
copied.mat4[15] = this.mat4[15];
return copied;
};
/**
* return an identity matrix
* @method identity
* @return {p5.Matrix} the result matrix
*/
_main.default.Matrix.identity = function(pInst) {
return new _main.default.Matrix(pInst);
};
/**
* transpose according to a given matrix
* @method transpose
* @param {p5.Matrix|Float32Array|Number[]} a the matrix to be
* based on to transpose
* @chainable
*/
_main.default.Matrix.prototype.transpose = function(a) {
var a01, a02, a03, a12, a13, a23;
if (a instanceof _main.default.Matrix) {
a01 = a.mat4[1];
a02 = a.mat4[2];
a03 = a.mat4[3];
a12 = a.mat4[6];
a13 = a.mat4[7];
a23 = a.mat4[11];
this.mat4[0] = a.mat4[0];
this.mat4[1] = a.mat4[4];
this.mat4[2] = a.mat4[8];
this.mat4[3] = a.mat4[12];
this.mat4[4] = a01;
this.mat4[5] = a.mat4[5];
this.mat4[6] = a.mat4[9];
this.mat4[7] = a.mat4[13];
this.mat4[8] = a02;
this.mat4[9] = a12;
this.mat4[10] = a.mat4[10];
this.mat4[11] = a.mat4[14];
this.mat4[12] = a03;
this.mat4[13] = a13;
this.mat4[14] = a23;
this.mat4[15] = a.mat4[15];
} else if (isMatrixArray(a)) {
a01 = a[1];
a02 = a[2];
a03 = a[3];
a12 = a[6];
a13 = a[7];
a23 = a[11];
this.mat4[0] = a[0];
this.mat4[1] = a[4];
this.mat4[2] = a[8];
this.mat4[3] = a[12];
this.mat4[4] = a01;
this.mat4[5] = a[5];
this.mat4[6] = a[9];
this.mat4[7] = a[13];
this.mat4[8] = a02;
this.mat4[9] = a12;
this.mat4[10] = a[10];
this.mat4[11] = a[14];
this.mat4[12] = a03;
this.mat4[13] = a13;
this.mat4[14] = a23;
this.mat4[15] = a[15];
}
return this;
};
/**
* invert matrix according to a give matrix
* @method invert
* @param {p5.Matrix|Float32Array|Number[]} a the matrix to be
* based on to invert
* @chainable
*/
_main.default.Matrix.prototype.invert = function(a) {
var a00, a01, a02, a03, a10, a11, a12, a13;
var a20, a21, a22, a23, a30, a31, a32, a33;
if (a instanceof _main.default.Matrix) {
a00 = a.mat4[0];
a01 = a.mat4[1];
a02 = a.mat4[2];
a03 = a.mat4[3];
a10 = a.mat4[4];
a11 = a.mat4[5];
a12 = a.mat4[6];
a13 = a.mat4[7];
a20 = a.mat4[8];
a21 = a.mat4[9];
a22 = a.mat4[10];
a23 = a.mat4[11];
a30 = a.mat4[12];
a31 = a.mat4[13];
a32 = a.mat4[14];
a33 = a.mat4[15];
} else if (isMatrixArray(a)) {
a00 = a[0];
a01 = a[1];
a02 = a[2];
a03 = a[3];
a10 = a[4];
a11 = a[5];
a12 = a[6];
a13 = a[7];
a20 = a[8];
a21 = a[9];
a22 = a[10];
a23 = a[11];
a30 = a[12];
a31 = a[13];
a32 = a[14];
a33 = a[15];
}
var b00 = a00 * a11 - a01 * a10;
var b01 = a00 * a12 - a02 * a10;
var b02 = a00 * a13 - a03 * a10;
var b03 = a01 * a12 - a02 * a11;
var b04 = a01 * a13 - a03 * a11;
var b05 = a02 * a13 - a03 * a12;
var b06 = a20 * a31 - a21 * a30;
var b07 = a20 * a32 - a22 * a30;
var b08 = a20 * a33 - a23 * a30;
var b09 = a21 * a32 - a22 * a31;
var b10 = a21 * a33 - a23 * a31;
var b11 = a22 * a33 - a23 * a32;
// Calculate the determinant
var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
if (!det) {
return null;
}
det = 1.0 / det;
this.mat4[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
this.mat4[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
this.mat4[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
this.mat4[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
this.mat4[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
this.mat4[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
this.mat4[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
this.mat4[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
this.mat4[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
this.mat4[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
this.mat4[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
this.mat4[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
this.mat4[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
this.mat4[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
this.mat4[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
this.mat4[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
return this;
};
/**
* Inverts a 3x3 matrix
* @method invert3x3
* @chainable
*/
_main.default.Matrix.prototype.invert3x3 = function() {
var a00 = this.mat3[0];
var a01 = this.mat3[1];
var a02 = this.mat3[2];
var a10 = this.mat3[3];
var a11 = this.mat3[4];
var a12 = this.mat3[5];
var a20 = this.mat3[6];
var a21 = this.mat3[7];
var a22 = this.mat3[8];
var b01 = a22 * a11 - a12 * a21;
var b11 = -a22 * a10 + a12 * a20;
var b21 = a21 * a10 - a11 * a20;
// Calculate the determinant
var det = a00 * b01 + a01 * b11 + a02 * b21;
if (!det) {
return null;
}
det = 1.0 / det;
this.mat3[0] = b01 * det;
this.mat3[1] = (-a22 * a01 + a02 * a21) * det;
this.mat3[2] = (a12 * a01 - a02 * a11) * det;
this.mat3[3] = b11 * det;
this.mat3[4] = (a22 * a00 - a02 * a20) * det;
this.mat3[5] = (-a12 * a00 + a02 * a10) * det;
this.mat3[6] = b21 * det;
this.mat3[7] = (-a21 * a00 + a01 * a20) * det;
this.mat3[8] = (a11 * a00 - a01 * a10) * det;
return this;
};
/**
* transposes a 3x3 p5.Matrix by a mat3
* @method transpose3x3
* @param {Number[]} mat3 1-dimensional array
* @chainable
*/
_main.default.Matrix.prototype.transpose3x3 = function(mat3) {
var a01 = mat3[1],
a02 = mat3[2],
a12 = mat3[5];
this.mat3[1] = mat3[3];
this.mat3[2] = mat3[6];
this.mat3[3] = a01;
this.mat3[5] = mat3[7];
this.mat3[6] = a02;
this.mat3[7] = a12;
return this;
};
/**
* converts a 4x4 matrix to its 3x3 inverse transform
* commonly used in MVMatrix to NMatrix conversions.
* @method invertTranspose
* @param {p5.Matrix} mat4 the matrix to be based on to invert
* @chainable
* @todo finish implementation
*/
_main.default.Matrix.prototype.inverseTranspose = function(matrix) {
if (this.mat3 === undefined) {
console.error('sorry, this function only works with mat3');
} else {
//convert mat4 -> mat3
this.mat3[0] = matrix.mat4[0];
this.mat3[1] = matrix.mat4[1];
this.mat3[2] = matrix.mat4[2];
this.mat3[3] = matrix.mat4[4];
this.mat3[4] = matrix.mat4[5];
this.mat3[5] = matrix.mat4[6];
this.mat3[6] = matrix.mat4[8];
this.mat3[7] = matrix.mat4[9];
this.mat3[8] = matrix.mat4[10];
}
var inverse = this.invert3x3();
// check inverse succeeded
if (inverse) {
inverse.transpose3x3(this.mat3);
} else {
// in case of singularity, just zero the matrix
for (var i = 0; i < 9; i++) {
this.mat3[i] = 0;
}
}
return this;
};
/**
* inspired by Toji's mat4 determinant
* @method determinant
* @return {Number} Determinant of our 4x4 matrix
*/
_main.default.Matrix.prototype.determinant = function() {
var d00 = this.mat4[0] * this.mat4[5] - this.mat4[1] * this.mat4[4],
d01 = this.mat4[0] * this.mat4[6] - this.mat4[2] * this.mat4[4],
d02 = this.mat4[0] * this.mat4[7] - this.mat4[3] * this.mat4[4],
d03 = this.mat4[1] * this.mat4[6] - this.mat4[2] * this.mat4[5],
d04 = this.mat4[1] * this.mat4[7] - this.mat4[3] * this.mat4[5],
d05 = this.mat4[2] * this.mat4[7] - this.mat4[3] * this.mat4[6],
d06 = this.mat4[8] * this.mat4[13] - this.mat4[9] * this.mat4[12],
d07 = this.mat4[8] * this.mat4[14] - this.mat4[10] * this.mat4[12],
d08 = this.mat4[8] * this.mat4[15] - this.mat4[11] * this.mat4[12],
d09 = this.mat4[9] * this.mat4[14] - this.mat4[10] * this.mat4[13],
d10 = this.mat4[9] * this.mat4[15] - this.mat4[11] * this.mat4[13],
d11 = this.mat4[10] * this.mat4[15] - this.mat4[11] * this.mat4[14];
// Calculate the determinant
return d00 * d11 - d01 * d10 + d02 * d09 + d03 * d08 - d04 * d07 + d05 * d06;
};
/**
* multiply two mat4s
* @method mult
* @param {p5.Matrix|Float32Array|Number[]} multMatrix The matrix
* we want to multiply by
* @chainable
*/
_main.default.Matrix.prototype.mult = function(multMatrix) {
var _src;
if (multMatrix === this || multMatrix === this.mat4) {
_src = this.copy().mat4; // only need to allocate in this rare case
} else if (multMatrix instanceof _main.default.Matrix) {
_src = multMatrix.mat4;
} else if (isMatrixArray(multMatrix)) {
_src = multMatrix;
} else if (arguments.length === 16) {
_src = arguments;
} else {
return; // nothing to do.
}
// each row is used for the multiplier
var b0 = this.mat4[0],
b1 = this.mat4[1],
b2 = this.mat4[2],
b3 = this.mat4[3];
this.mat4[0] = b0 * _src[0] + b1 * _src[4] + b2 * _src[8] + b3 * _src[12];
this.mat4[1] = b0 * _src[1] + b1 * _src[5] + b2 * _src[9] + b3 * _src[13];
this.mat4[2] = b0 * _src[2] + b1 * _src[6] + b2 * _src[10] + b3 * _src[14];
this.mat4[3] = b0 * _src[3] + b1 * _src[7] + b2 * _src[11] + b3 * _src[15];
b0 = this.mat4[4];
b1 = this.mat4[5];
b2 = this.mat4[6];
b3 = this.mat4[7];
this.mat4[4] = b0 * _src[0] + b1 * _src[4] + b2 * _src[8] + b3 * _src[12];
this.mat4[5] = b0 * _src[1] + b1 * _src[5] + b2 * _src[9] + b3 * _src[13];
this.mat4[6] = b0 * _src[2] + b1 * _src[6] + b2 * _src[10] + b3 * _src[14];
this.mat4[7] = b0 * _src[3] + b1 * _src[7] + b2 * _src[11] + b3 * _src[15];
b0 = this.mat4[8];
b1 = this.mat4[9];
b2 = this.mat4[10];
b3 = this.mat4[11];
this.mat4[8] = b0 * _src[0] + b1 * _src[4] + b2 * _src[8] + b3 * _src[12];
this.mat4[9] = b0 * _src[1] + b1 * _src[5] + b2 * _src[9] + b3 * _src[13];
this.mat4[10] = b0 * _src[2] + b1 * _src[6] + b2 * _src[10] + b3 * _src[14];
this.mat4[11] = b0 * _src[3] + b1 * _src[7] + b2 * _src[11] + b3 * _src[15];
b0 = this.mat4[12];
b1 = this.mat4[13];
b2 = this.mat4[14];
b3 = this.mat4[15];
this.mat4[12] = b0 * _src[0] + b1 * _src[4] + b2 * _src[8] + b3 * _src[12];
this.mat4[13] = b0 * _src[1] + b1 * _src[5] + b2 * _src[9] + b3 * _src[13];
this.mat4[14] = b0 * _src[2] + b1 * _src[6] + b2 * _src[10] + b3 * _src[14];
this.mat4[15] = b0 * _src[3] + b1 * _src[7] + b2 * _src[11] + b3 * _src[15];
return this;
};
_main.default.Matrix.prototype.apply = function(multMatrix) {
var _src;
if (multMatrix === this || multMatrix === this.mat4) {
_src = this.copy().mat4; // only need to allocate in this rare case
} else if (multMatrix instanceof _main.default.Matrix) {
_src = multMatrix.mat4;
} else if (isMatrixArray(multMatrix)) {
_src = multMatrix;
} else if (arguments.length === 16) {
_src = arguments;
} else {
return; // nothing to do.
}
var mat4 = this.mat4;
// each row is used for the multiplier
var m0 = mat4[0];
var m4 = mat4[4];
var m8 = mat4[8];
var m12 = mat4[12];
mat4[0] = _src[0] * m0 + _src[1] * m4 + _src[2] * m8 + _src[3] * m12;
mat4[4] = _src[4] * m0 + _src[5] * m4 + _src[6] * m8 + _src[7] * m12;
mat4[8] = _src[8] * m0 + _src[9] * m4 + _src[10] * m8 + _src[11] * m12;
mat4[12] = _src[12] * m0 + _src[13] * m4 + _src[14] * m8 + _src[15] * m12;
var m1 = mat4[1];
var m5 = mat4[5];
var m9 = mat4[9];
var m13 = mat4[13];
mat4[1] = _src[0] * m1 + _src[1] * m5 + _src[2] * m9 + _src[3] * m13;
mat4[5] = _src[4] * m1 + _src[5] * m5 + _src[6] * m9 + _src[7] * m13;
mat4[9] = _src[8] * m1 + _src[9] * m5 + _src[10] * m9 + _src[11] * m13;
mat4[13] = _src[12] * m1 + _src[13] * m5 + _src[14] * m9 + _src[15] * m13;
var m2 = mat4[2];
var m6 = mat4[6];
var m10 = mat4[10];
var m14 = mat4[14];
mat4[2] = _src[0] * m2 + _src[1] * m6 + _src[2] * m10 + _src[3] * m14;
mat4[6] = _src[4] * m2 + _src[5] * m6 + _src[6] * m10 + _src[7] * m14;
mat4[10] = _src[8] * m2 + _src[9] * m6 + _src[10] * m10 + _src[11] * m14;
mat4[14] = _src[12] * m2 + _src[13] * m6 + _src[14] * m10 + _src[15] * m14;
var m3 = mat4[3];
var m7 = mat4[7];
var m11 = mat4[11];
var m15 = mat4[15];
mat4[3] = _src[0] * m3 + _src[1] * m7 + _src[2] * m11 + _src[3] * m15;
mat4[7] = _src[4] * m3 + _src[5] * m7 + _src[6] * m11 + _src[7] * m15;
mat4[11] = _src[8] * m3 + _src[9] * m7 + _src[10] * m11 + _src[11] * m15;
mat4[15] = _src[12] * m3 + _src[13] * m7 + _src[14] * m11 + _src[15] * m15;
return this;
};
/**
* scales a p5.Matrix by scalars or a vector
* @method scale
* @param {p5.Vector|Float32Array|Number[]} s vector to scale by
* @chainable
*/
_main.default.Matrix.prototype.scale = function(x, y, z) {
if (x instanceof _main.default.Vector) {
// x is a vector, extract the components from it.
y = x.y;
z = x.z;
x = x.x; // must be last
} else if (x instanceof Array) {
// x is an array, extract the components from it.
y = x[1];
z = x[2];
x = x[0]; // must be last
}
this.mat4[0] *= x;
this.mat4[1] *= x;
this.mat4[2] *= x;
this.mat4[3] *= x;
this.mat4[4] *= y;
this.mat4[5] *= y;
this.mat4[6] *= y;
this.mat4[7] *= y;
this.mat4[8] *= z;
this.mat4[9] *= z;
this.mat4[10] *= z;
this.mat4[11] *= z;
return this;
};
/**
* rotate our Matrix around an axis by the given angle.
* @method rotate
* @param {Number} a The angle of rotation in radians
* @param {p5.Vector|Number[]} axis the axis(es) to rotate around
* @chainable
* inspired by Toji's gl-matrix lib, mat4 rotation
*/
_main.default.Matrix.prototype.rotate = function(a, x, y, z) {
if (x instanceof _main.default.Vector) {
// x is a vector, extract the components from it.
y = x.y;
z = x.z;
x = x.x; //must be last
} else if (x instanceof Array) {
// x is an array, extract the components from it.
y = x[1];
z = x[2];
x = x[0]; //must be last
}
var len = Math.sqrt(x * x + y * y + z * z);
x *= 1 / len;
y *= 1 / len;
z *= 1 / len;
var a00 = this.mat4[0];
var a01 = this.mat4[1];
var a02 = this.mat4[2];
var a03 = this.mat4[3];
var a10 = this.mat4[4];
var a11 = this.mat4[5];
var a12 = this.mat4[6];
var a13 = this.mat4[7];
var a20 = this.mat4[8];
var a21 = this.mat4[9];
var a22 = this.mat4[10];
var a23 = this.mat4[11];
//sin,cos, and tan of respective angle
var sA = Math.sin(a);
var cA = Math.cos(a);
var tA = 1 - cA;
// Construct the elements of the rotation matrix
var b00 = x * x * tA + cA;
var b01 = y * x * tA + z * sA;
var b02 = z * x * tA - y * sA;
var b10 = x * y * tA - z * sA;
var b11 = y * y * tA + cA;
var b12 = z * y * tA + x * sA;
var b20 = x * z * tA + y * sA;
var b21 = y * z * tA - x * sA;
var b22 = z * z * tA + cA;
// rotation-specific matrix multiplication
this.mat4[0] = a00 * b00 + a10 * b01 + a20 * b02;
this.mat4[1] = a01 * b00 + a11 * b01 + a21 * b02;
this.mat4[2] = a02 * b00 + a12 * b01 + a22 * b02;
this.mat4[3] = a03 * b00 + a13 * b01 + a23 * b02;
this.mat4[4] = a00 * b10 + a10 * b11 + a20 * b12;
this.mat4[5] = a01 * b10 + a11 * b11 + a21 * b12;
this.mat4[6] = a02 * b10 + a12 * b11 + a22 * b12;
this.mat4[7] = a03 * b10 + a13 * b11 + a23 * b12;
this.mat4[8] = a00 * b20 + a10 * b21 + a20 * b22;
this.mat4[9] = a01 * b20 + a11 * b21 + a21 * b22;
this.mat4[10] = a02 * b20 + a12 * b21 + a22 * b22;
this.mat4[11] = a03 * b20 + a13 * b21 + a23 * b22;
return this;
};
/**
* @todo finish implementing this method!
* translates
* @method translate
* @param {Number[]} v vector to translate by
* @chainable
*/
_main.default.Matrix.prototype.translate = function(v) {
var x = v[0],
y = v[1],
z = v[2] || 0;
this.mat4[12] += this.mat4[0] * x + this.mat4[4] * y + this.mat4[8] * z;
this.mat4[13] += this.mat4[1] * x + this.mat4[5] * y + this.mat4[9] * z;
this.mat4[14] += this.mat4[2] * x + this.mat4[6] * y + this.mat4[10] * z;
this.mat4[15] += this.mat4[3] * x + this.mat4[7] * y + this.mat4[11] * z;
};
_main.default.Matrix.prototype.rotateX = function(a) {
this.rotate(a, 1, 0, 0);
};
_main.default.Matrix.prototype.rotateY = function(a) {
this.rotate(a, 0, 1, 0);
};
_main.default.Matrix.prototype.rotateZ = function(a) {
this.rotate(a, 0, 0, 1);
};
/**
* sets the perspective matrix
* @method perspective
* @param {Number} fovy [description]
* @param {Number} aspect [description]
* @param {Number} near near clipping plane
* @param {Number} far far clipping plane
* @chainable
*/
_main.default.Matrix.prototype.perspective = function(fovy, aspect, near, far) {
var f = 1.0 / Math.tan(fovy / 2),
nf = 1 / (near - far);
this.mat4[0] = f / aspect;
this.mat4[1] = 0;
this.mat4[2] = 0;
this.mat4[3] = 0;
this.mat4[4] = 0;
this.mat4[5] = f;
this.mat4[6] = 0;
this.mat4[7] = 0;
this.mat4[8] = 0;
this.mat4[9] = 0;
this.mat4[10] = (far + near) * nf;
this.mat4[11] = -1;
this.mat4[12] = 0;
this.mat4[13] = 0;
this.mat4[14] = 2 * far * near * nf;
this.mat4[15] = 0;
return this;
};
/**
* sets the ortho matrix
* @method ortho
* @param {Number} left [description]
* @param {Number} right [description]
* @param {Number} bottom [description]
* @param {Number} top [description]
* @param {Number} near near clipping plane
* @param {Number} far far clipping plane
* @chainable
*/
_main.default.Matrix.prototype.ortho = function(
left,
right,
bottom,
top,
near,
far
) {
var lr = 1 / (left - right),
bt = 1 / (bottom - top),
nf = 1 / (near - far);
this.mat4[0] = -2 * lr;
this.mat4[1] = 0;
this.mat4[2] = 0;
this.mat4[3] = 0;
this.mat4[4] = 0;
this.mat4[5] = -2 * bt;
this.mat4[6] = 0;
this.mat4[7] = 0;
this.mat4[8] = 0;
this.mat4[9] = 0;
this.mat4[10] = 2 * nf;
this.mat4[11] = 0;
this.mat4[12] = (left + right) * lr;
this.mat4[13] = (top + bottom) * bt;
this.mat4[14] = (far + near) * nf;
this.mat4[15] = 1;
return this;
};
/**
* PRIVATE
*/
// matrix methods adapted from:
// https://developer.mozilla.org/en-US/docs/Web/WebGL/
// gluPerspective
//
// function _makePerspective(fovy, aspect, znear, zfar){
// const ymax = znear * Math.tan(fovy * Math.PI / 360.0);
// const ymin = -ymax;
// const xmin = ymin * aspect;
// const xmax = ymax * aspect;
// return _makeFrustum(xmin, xmax, ymin, ymax, znear, zfar);
// }
////
//// glFrustum
////
//function _makeFrustum(left, right, bottom, top, znear, zfar){
// const X = 2*znear/(right-left);
// const Y = 2*znear/(top-bottom);
// const A = (right+left)/(right-left);
// const B = (top+bottom)/(top-bottom);
// const C = -(zfar+znear)/(zfar-znear);
// const D = -2*zfar*znear/(zfar-znear);
// const frustrumMatrix =[
// X, 0, A, 0,
// 0, Y, B, 0,
// 0, 0, C, D,
// 0, 0, -1, 0
//];
//return frustrumMatrix;
// }
// function _setMVPMatrices(){
////an identity matrix
////@TODO use the p5.Matrix class to abstract away our MV matrices and
///other math
//const _mvMatrix =
//[
// 1.0,0.0,0.0,0.0,
// 0.0,1.0,0.0,0.0,
// 0.0,0.0,1.0,0.0,
// 0.0,0.0,0.0,1.0
//];
var _default = _main.default.Matrix;
exports.default = _default;
},
{ '../core/main': 59 }
],
110: [
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 };
}
_main.default.RenderBuffer = function(size, src, dst, attr, renderer, map) {
this.size = size; // the number of FLOATs in each vertex
this.src = src; // the name of the model's source array
this.dst = dst; // the name of the geometry's buffer
this.attr = attr; // the name of the vertex attribute
this._renderer = renderer;
this.map = map; // optional, a transformation function to apply to src
};
/**
* Enables and binds the buffers used by shader when the appropriate data exists in geometry.
* Must always be done prior to drawing geometry in WebGL.
* @param {p5.Geometry} geometry Geometry that is going to be drawn
* @param {p5.Shader} shader Active shader
* @private
*/
_main.default.RenderBuffer.prototype._prepareBuffer = function(geometry, shader) {
var attributes = shader.attributes;
var gl = this._renderer.GL;
var model;
if (geometry.model) {
model = geometry.model;
} else {
model = geometry;
}
// loop through each of the buffer definitions
var attr = attributes[this.attr];
if (!attr) {
return;
}
// check if the model has the appropriate source array
var buffer = geometry[this.dst];
var src = model[this.src];
if (src.length > 0) {
// check if we need to create the GL buffer
var createBuffer = !buffer;
if (createBuffer) {
// create and remember the buffer
geometry[this.dst] = buffer = gl.createBuffer();
}
// bind the buffer
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
// check if we need to fill the buffer with data
if (createBuffer || model.dirtyFlags[this.src] !== false) {
var map = this.map;
// get the values from the model, possibly transformed
var values = map ? map(src) : src;
// fill the buffer with the values
this._renderer._bindBuffer(buffer, gl.ARRAY_BUFFER, values);
// mark the model's source array as clean
model.dirtyFlags[this.src] = false;
}
// enable the attribute
shader.enableAttrib(attr, this.size);
}
};
var _default = _main.default.RenderBuffer;
exports.default = _default;
},
{ '../core/main': 59 }
],
111: [
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.RenderBuffer');
function _getRequireWildcardCache() {
if (typeof WeakMap !== 'function') return null;
var cache = new WeakMap();
_getRequireWildcardCache = function _getRequireWildcardCache() {
return cache;
};
return cache;
}
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
}
if (obj === null || (_typeof(obj) !== 'object' && typeof obj !== 'function')) {
return { default: obj };
}
var cache = _getRequireWildcardCache();
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Welcome to RendererGL Immediate Mode.
* Immediate mode is used for drawing custom shapes
* from a set of vertices. Immediate Mode is activated
* when you call <a href="#/p5/beginShape">beginShape()</a> & de-activated when you call <a href="#/p5/endShape">endShape()</a>.
* Immediate mode is a style of programming borrowed
* from OpenGL's (now-deprecated) immediate mode.
* It differs from p5.js' default, Retained Mode, which caches
* geometries and buffers on the CPU to reduce the number of webgl
* draw calls. Retained mode is more efficient & performative,
* however, Immediate Mode is useful for sketching quick
* geometric ideas.
*/ /**
* Begin shape drawing. This is a helpful way of generating
* custom shapes quickly. However in WEBGL mode, application
* performance will likely drop as a result of too many calls to
* <a href="#/p5/beginShape">beginShape()</a> / <a href="#/p5/endShape">endShape()</a>. As a high performance alternative,
* please use p5.js geometry primitives.
* @private
* @method beginShape
* @param {Number} mode webgl primitives mode. beginShape supports the
* following modes:
* POINTS,LINES,LINE_STRIP,LINE_LOOP,TRIANGLES,
* TRIANGLE_STRIP, TRIANGLE_FAN and TESS(WEBGL only)
* @chainable
*/ _main.default.RendererGL.prototype.beginShape = function(mode) {
this.immediateMode.shapeMode =
mode !== undefined ? mode : constants.TRIANGLE_FAN;
this.immediateMode.geometry.reset();
return this;
};
/**
* adds a vertex to be drawn in a custom Shape.
* @private
* @method vertex
* @param {Number} x x-coordinate of vertex
* @param {Number} y y-coordinate of vertex
* @param {Number} z z-coordinate of vertex
* @chainable
* @TODO implement handling of <a href="#/p5.Vector">p5.Vector</a> args
*/ _main.default.RendererGL.prototype.vertex = function(x, y) {
var z, u, v;
// default to (x, y) mode: all other arugments assumed to be 0.
z = u = v = 0;
if (arguments.length === 3) {
// (x, y, z) mode: (u, v) assumed to be 0.
z = arguments[2];
} else if (arguments.length === 4) {
// (x, y, u, v) mode: z assumed to be 0.
u = arguments[2];
v = arguments[3];
} else if (arguments.length === 5) {
// (x, y, z, u, v) mode
z = arguments[2];
u = arguments[3];
v = arguments[4];
}
var vert = new _main.default.Vector(x, y, z);
this.immediateMode.geometry.vertices.push(vert);
var vertexColor = this.curFillColor || [0.5, 0.5, 0.5, 1.0];
this.immediateMode.geometry.vertexColors.push(
vertexColor[0],
vertexColor[1],
vertexColor[2],
vertexColor[3]
);
if (this.textureMode === constants.IMAGE) {
if (this._tex !== null) {
if (this._tex.width > 0 && this._tex.height > 0) {
u /= this._tex.width;
v /= this._tex.height;
}
} else if (this._tex === null && arguments.length >= 4) {
// Only throw this warning if custom uv's have been provided
console.warn(
'You must first call texture() before using' +
' vertex() with image based u and v coordinates'
);
}
}
this.immediateMode.geometry.uvs.push(u, v);
this.immediateMode._bezierVertex[0] = x;
this.immediateMode._bezierVertex[1] = y;
this.immediateMode._bezierVertex[2] = z;
this.immediateMode._quadraticVertex[0] = x;
this.immediateMode._quadraticVertex[1] = y;
this.immediateMode._quadraticVertex[2] = z;
return this;
};
/**
* End shape drawing and render vertices to screen.
* @chainable
*/
_main.default.RendererGL.prototype.endShape = function(
mode,
isCurve,
isBezier,
isQuadratic,
isContour,
shapeKind
) {
if (this.immediateMode.shapeMode === constants.POINTS) {
this._drawPoints(
this.immediateMode.geometry.vertices,
this.immediateMode.buffers.point
);
return this;
}
this._processVertices.apply(this, arguments);
if (this._doFill) {
if (this.immediateMode.geometry.vertices.length > 1) {
this._drawImmediateFill();
}
}
if (this._doStroke) {
if (this.immediateMode.geometry.lineVertices.length > 1) {
this._drawImmediateStroke();
}
}
this.isBezier = false;
this.isQuadratic = false;
this.isCurve = false;
this.immediateMode._bezierVertex.length = 0;
this.immediateMode._quadraticVertex.length = 0;
this.immediateMode._curveVertex.length = 0;
return this;
};
/**
* Called from endShape(). This function calculates the stroke vertices for custom shapes and
* tesselates shapes when applicable.
* @private
* @param {Number} mode webgl primitives mode. beginShape supports the
* following modes:
* POINTS,LINES,LINE_STRIP,LINE_LOOP,TRIANGLES,
* TRIANGLE_STRIP, TRIANGLE_FAN and TESS(WEBGL only)
*/
_main.default.RendererGL.prototype._processVertices = function(mode) {
if (this.immediateMode.geometry.vertices.length === 0) return;
var calculateStroke = this._doStroke && this.drawMode !== constants.TEXTURE;
var shouldClose = mode === constants.CLOSE;
if (calculateStroke) {
this.immediateMode.geometry.edges = this._calculateEdges(
this.immediateMode.shapeMode,
this.immediateMode.geometry.vertices,
shouldClose
);
this.immediateMode.geometry._edgesToVertices();
}
// For hollow shapes, user must set mode to TESS
var convexShape = this.immediateMode.shapeMode === constants.TESS;
// We tesselate when drawing curves or convex shapes
var shouldTess =
(this.isBezier || this.isQuadratic || this.isCurve || convexShape) &&
this.immediateMode.shapeMode !== constants.LINES;
if (shouldTess) {
this._tesselateShape();
}
};
/**
* Called from _processVertices(). This function calculates the stroke vertices for custom shapes and
* tesselates shapes when applicable.
* @private
* @returns {Array[Number]} indices for custom shape vertices indicating edges.
*/
_main.default.RendererGL.prototype._calculateEdges = function(
shapeMode,
verts,
shouldClose
) {
var res = [];
var i = 0;
switch (shapeMode) {
case constants.TRIANGLE_STRIP:
for (i = 0; i < verts.length - 2; i++) {
res.push([i, i + 1]);
res.push([i, i + 2]);
}
res.push([i, i + 1]);
break;
case constants.TRIANGLES:
for (i = 0; i < verts.length - 2; i = i + 3) {
res.push([i, i + 1]);
res.push([i + 1, i + 2]);
res.push([i + 2, i]);
}
break;
case constants.LINES:
for (i = 0; i < verts.length - 1; i = i + 2) {
res.push([i, i + 1]);
}
break;
default:
for (i = 0; i < verts.length - 1; i++) {
res.push([i, i + 1]);
}
break;
}
if (shouldClose) {
res.push([verts.length - 1, 0]);
}
return res;
};
/**
* Called from _processVertices() when applicable. This function tesselates immediateMode.geometry.
* @private
*/
_main.default.RendererGL.prototype._tesselateShape = function() {
this.immediateMode.shapeMode = constants.TRIANGLES;
var contours = [
new Float32Array(this._vToNArray(this.immediateMode.geometry.vertices))
];
var polyTriangles = this._triangulate(contours);
this.immediateMode.geometry.vertices = [];
for (
var j = 0, polyTriLength = polyTriangles.length;
j < polyTriLength;
j = j + 3
) {
this.vertex(polyTriangles[j], polyTriangles[j + 1], polyTriangles[j + 2]);
}
};
/**
* Called from endShape(). Responsible for calculating normals, setting shader uniforms,
* enabling all appropriate buffers, applying color blend, and drawing the fill geometry.
* @private
*/
_main.default.RendererGL.prototype._drawImmediateFill = function() {
var gl = this.GL;
var shader = this._getImmediateFillShader();
this._calculateNormals(this.immediateMode.geometry);
this._setFillUniforms(shader);
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (
var _iterator = this.immediateMode.buffers.fill[Symbol.iterator](), _step;
!(_iteratorNormalCompletion = (_step = _iterator.next()).done);
_iteratorNormalCompletion = true
) {
var buff = _step.value;
buff._prepareBuffer(this.immediateMode.geometry, shader);
}
// LINE_STRIP and LINES are not used for rendering, instead
// they only indicate a way to modify vertices during the _processVertices() step
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
if (
this.immediateMode.shapeMode === constants.LINE_STRIP ||
this.immediateMode.shapeMode === constants.LINES
) {
this.immediateMode.shapeMode = constants.TRIANGLE_FAN;
}
this._applyColorBlend(this.curFillColor);
gl.drawArrays(
this.immediateMode.shapeMode,
0,
this.immediateMode.geometry.vertices.length
);
shader.unbindShader();
};
/**
* Called from endShape(). Responsible for calculating normals, setting shader uniforms,
* enabling all appropriate buffers, applying color blend, and drawing the stroke geometry.
* @private
*/
_main.default.RendererGL.prototype._drawImmediateStroke = function() {
var gl = this.GL;
var shader = this._getImmediateStrokeShader();
this._setStrokeUniforms(shader);
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (
var _iterator2 = this.immediateMode.buffers.stroke[Symbol.iterator](),
_step2;
!(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done);
_iteratorNormalCompletion2 = true
) {
var buff = _step2.value;
buff._prepareBuffer(this.immediateMode.geometry, shader);
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
this._applyColorBlend(this.curStrokeColor);
gl.drawArrays(gl.TRIANGLES, 0, this.immediateMode.geometry.lineVertices.length);
shader.unbindShader();
};
/**
* Called from _drawImmediateFill(). Currently adds default normals which
* only work for flat shapes.
* @parem
* @private
*/
_main.default.RendererGL.prototype._calculateNormals = function(geometry) {
geometry.vertices.forEach(function() {
geometry.vertexNormals.push(new _main.default.Vector(0, 0, 1));
});
};
var _default = _main.default.RendererGL;
exports.default = _default;
},
{ '../core/constants': 48, '../core/main': 59, './p5.RenderBuffer': 110 }
],
112: [
function(_dereq_, module, exports) {
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.default = void 0;
var _main = _interopRequireDefault(_dereq_('../core/main'));
_dereq_('./p5.RendererGL');
_dereq_('./p5.RenderBuffer');
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
} //Retained Mode. The default mode for rendering 3D primitives
//in WEBGL.
var hashCount = 0;
/**
* _initBufferDefaults
* @private
* @description initializes buffer defaults. runs each time a new geometry is
* registered
* @param {String} gId key of the geometry object
* @returns {Object} a new buffer object
*/
_main.default.RendererGL.prototype._initBufferDefaults = function(gId) {
this._freeBuffers(gId);
//@TODO remove this limit on hashes in retainedMode.geometry
hashCount++;
if (hashCount > 1000) {
var key = Object.keys(this.retainedMode.geometry)[0];
delete this.retainedMode.geometry[key];
hashCount--;
}
//create a new entry in our retainedMode.geometry
return (this.retainedMode.geometry[gId] = {});
};
_main.default.RendererGL.prototype._freeBuffers = function(gId) {
var buffers = this.retainedMode.geometry[gId];
if (!buffers) {
return;
}
delete this.retainedMode.geometry[gId];
hashCount--;
var gl = this.GL;
if (buffers.indexBuffer) {
gl.deleteBuffer(buffers.indexBuffer);
}
function freeBuffers(defs) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (
var _iterator = defs[Symbol.iterator](), _step;
!(_iteratorNormalCompletion = (_step = _iterator.next()).done);
_iteratorNormalCompletion = true
) {
var def = _step.value;
if (buffers[def.dst]) {
gl.deleteBuffer(buffers[def.dst]);
buffers[def.dst] = null;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
// free all the buffers
freeBuffers(this.retainedMode.buffers.stroke);
freeBuffers(this.retainedMode.buffers.fill);
};
/**
* creates a buffers object that holds the WebGL render buffers
* for a geometry.
* @private
* @param {String} gId key of the geometry object
* @param {p5.Geometry} model contains geometry data
*/
_main.default.RendererGL.prototype.createBuffers = function(gId, model) {
var gl = this.GL;
//initialize the gl buffers for our geom groups
var buffers = this._initBufferDefaults(gId);
buffers.model = model;
var indexBuffer = buffers.indexBuffer;
if (model.faces.length) {
// allocate space for faces
if (!indexBuffer) indexBuffer = buffers.indexBuffer = gl.createBuffer();
var vals = _main.default.RendererGL.prototype._flatten(model.faces);
this._bindBuffer(indexBuffer, gl.ELEMENT_ARRAY_BUFFER, vals, Uint16Array);
// the vertex count is based on the number of faces
buffers.vertexCount = model.faces.length * 3;
} else {
// the index buffer is unused, remove it
if (indexBuffer) {
gl.deleteBuffer(indexBuffer);
buffers.indexBuffer = null;
}
// the vertex count comes directly from the model
buffers.vertexCount = model.vertices ? model.vertices.length : 0;
}
buffers.lineVertexCount = model.lineVertices ? model.lineVertices.length : 0;
return buffers;
};
/**
* Draws buffers given a geometry key ID
* @private
* @param {String} gId ID in our geom hash
* @chainable
*/
_main.default.RendererGL.prototype.drawBuffers = function(gId) {
var gl = this.GL;
var geometry = this.retainedMode.geometry[gId];
if (this._doStroke && geometry.lineVertexCount > 0) {
var strokeShader = this._getRetainedStrokeShader();
this._setStrokeUniforms(strokeShader);
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (
var _iterator2 = this.retainedMode.buffers.stroke[Symbol.iterator](),
_step2;
!(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done);
_iteratorNormalCompletion2 = true
) {
var buff = _step2.value;
buff._prepareBuffer(geometry, strokeShader);
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
this._applyColorBlend(this.curStrokeColor);
this._drawArrays(gl.TRIANGLES, gId);
strokeShader.unbindShader();
}
if (this._doFill) {
var fillShader = this._getRetainedFillShader();
this._setFillUniforms(fillShader);
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (
var _iterator3 = this.retainedMode.buffers.fill[Symbol.iterator](),
_step3;
!(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done);
_iteratorNormalCompletion3 = true
) {
var _buff = _step3.value;
_buff._prepareBuffer(geometry, fillShader);
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
if (geometry.indexBuffer) {
//vertex index buffer
this._bindBuffer(geometry.indexBuffer, gl.ELEMENT_ARRAY_BUFFER);
}
this._applyColorBlend(this.curFillColor);
this._drawElements(gl.TRIANGLES, gId);
fillShader.unbindShader();
}
return this;
};
/**
* Calls drawBuffers() with a scaled model/view matrix.
*
* This is used by various 3d primitive methods (in primitives.js, eg. plane,
* box, torus, etc...) to allow caching of un-scaled geometries. Those
* geometries are generally created with unit-length dimensions, cached as
* such, and then scaled appropriately in this method prior to rendering.
*
* @private
* @method drawBuffersScaled
* @param {String} gId ID in our geom hash
* @param {Number} scaleX the amount to scale in the X direction
* @param {Number} scaleY the amount to scale in the Y direction
* @param {Number} scaleZ the amount to scale in the Z direction
*/
_main.default.RendererGL.prototype.drawBuffersScaled = function(
gId,
scaleX,
scaleY,
scaleZ
) {
var uMVMatrix = this.uMVMatrix.copy();
try {
this.uMVMatrix.scale(scaleX, scaleY, scaleZ);
this.drawBuffers(gId);
} finally {
this.uMVMatrix = uMVMatrix;
}
};
_main.default.RendererGL.prototype._drawArrays = function(drawMode, gId) {
this.GL.drawArrays(
drawMode,
0,
this.retainedMode.geometry[gId].lineVertexCount
);
return this;
};
_main.default.RendererGL.prototype._drawElements = function(drawMode, gId) {
var buffers = this.retainedMode.geometry[gId];
var gl = this.GL;
// render the fill
if (buffers.indexBuffer) {
// we're drawing faces
gl.drawElements(gl.TRIANGLES, buffers.vertexCount, gl.UNSIGNED_SHORT, 0);
} else {
// drawing vertices
gl.drawArrays(drawMode || gl.TRIANGLES, 0, buffers.vertexCount);
}
};
_main.default.RendererGL.prototype._drawPoints = function(
vertices,
vertexBuffer
) {
var gl = this.GL;
var pointShader = this._getImmediatePointShader();
this._setPointUniforms(pointShader);
this._bindBuffer(
vertexBuffer,
gl.ARRAY_BUFFER,
this._vToNArray(vertices),
Float32Array,
gl.STATIC_DRAW
);
pointShader.enableAttrib(pointShader.attributes.aPosition, 3);
gl.drawArrays(gl.Points, 0, vertices.length);
pointShader.unbindShader();
};
var _default = _main.default.RendererGL;
exports.default = _default;
},
{ '../core/main': 59, './p5.RenderBuffer': 110, './p5.RendererGL': 113 }
],
113: [
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 _libtess = _interopRequireDefault(_dereq_('libtess'));
_dereq_('./p5.Shader');
_dereq_('./p5.Camera');
_dereq_('../core/p5.Renderer');
_dereq_('./p5.Matrix');
var _path = _dereq_('path');
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;
}
}
var lightingShader =
'precision highp float;\nprecision highp int;\n\nuniform mat4 uViewMatrix;\n\nuniform bool uUseLighting;\n\nuniform int uAmbientLightCount;\nuniform vec3 uAmbientColor[5];\n\nuniform int uDirectionalLightCount;\nuniform vec3 uLightingDirection[5];\nuniform vec3 uDirectionalDiffuseColors[5];\nuniform vec3 uDirectionalSpecularColors[5];\n\nuniform int uPointLightCount;\nuniform vec3 uPointLightLocation[5];\nuniform vec3 uPointLightDiffuseColors[5];\t\nuniform vec3 uPointLightSpecularColors[5];\n\nuniform int uSpotLightCount;\nuniform float uSpotLightAngle[5];\nuniform float uSpotLightConc[5];\nuniform vec3 uSpotLightDiffuseColors[5];\nuniform vec3 uSpotLightSpecularColors[5];\nuniform vec3 uSpotLightLocation[5];\nuniform vec3 uSpotLightDirection[5];\n\nuniform bool uSpecular;\nuniform float uShininess;\n\nuniform float uConstantAttenuation;\nuniform float uLinearAttenuation;\nuniform float uQuadraticAttenuation;\n\nconst float specularFactor = 2.0;\nconst float diffuseFactor = 0.73;\n\nstruct LightResult {\n float specular;\n float diffuse;\n};\n\nfloat _phongSpecular(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float shininess) {\n\n vec3 R = reflect(lightDirection, surfaceNormal);\n return pow(max(0.0, dot(R, viewDirection)), shininess);\n}\n\nfloat _lambertDiffuse(vec3 lightDirection, vec3 surfaceNormal) {\n return max(0.0, dot(-lightDirection, surfaceNormal));\n}\n\nLightResult _light(vec3 viewDirection, vec3 normal, vec3 lightVector) {\n\n vec3 lightDir = normalize(lightVector);\n\n //compute our diffuse & specular terms\n LightResult lr;\n if (uSpecular)\n lr.specular = _phongSpecular(lightDir, viewDirection, normal, uShininess);\n lr.diffuse = _lambertDiffuse(lightDir, normal);\n return lr;\n}\n\nvoid totalLight(\n vec3 modelPosition,\n vec3 normal,\n out vec3 totalDiffuse,\n out vec3 totalSpecular\n) {\n\n totalSpecular = vec3(0.0);\n\n if (!uUseLighting) {\n totalDiffuse = vec3(1.0);\n return;\n }\n\n totalDiffuse = vec3(0.0);\n\n vec3 viewDirection = normalize(-modelPosition);\n\n for (int j = 0; j < 5; j++) {\n if (j < uDirectionalLightCount) {\n vec3 lightVector = (uViewMatrix * vec4(uLightingDirection[j], 0.0)).xyz;\n vec3 lightColor = uDirectionalDiffuseColors[j];\n vec3 specularColor = uDirectionalSpecularColors[j];\n LightResult result = _light(viewDirection, normal, lightVector);\n totalDiffuse += result.diffuse * lightColor;\n totalSpecular += result.specular * lightColor * specularColor;\n }\n\n if (j < uPointLightCount) {\n vec3 lightPosition = (uViewMatrix * vec4(uPointLightLocation[j], 1.0)).xyz;\n vec3 lightVector = modelPosition - lightPosition;\n \n //calculate attenuation\n float lightDistance = length(lightVector);\n float lightFalloff = 1.0 / (uConstantAttenuation + lightDistance * uLinearAttenuation + (lightDistance * lightDistance) * uQuadraticAttenuation);\n vec3 lightColor = lightFalloff * uPointLightDiffuseColors[j];\n vec3 specularColor = lightFalloff * uPointLightSpecularColors[j];\n\n LightResult result = _light(viewDirection, normal, lightVector);\n totalDiffuse += result.diffuse * lightColor;\n totalSpecular += result.specular * lightColor * specularColor;\n }\n\n if(j < uSpotLightCount) {\n vec3 lightPosition = (uViewMatrix * vec4(uSpotLightLocation[j], 1.0)).xyz;\n vec3 lightVector = modelPosition - lightPosition;\n \n float lightDistance = length(lightVector);\n float lightFalloff = 1.0 / (uConstantAttenuation + lightDistance * uLinearAttenuation + (lightDistance * lightDistance) * uQuadraticAttenuation);\n\n vec3 lightDirection = (uViewMatrix * vec4(uSpotLightDirection[j], 0.0)).xyz;\n float spotDot = dot(normalize(lightVector), normalize(lightDirection));\n float spotFalloff;\n if(spotDot < uSpotLightAngle[j]) {\n spotFalloff = 0.0;\n }\n else {\n spotFalloff = pow(spotDot, uSpotLightConc[j]);\n }\n lightFalloff *= spotFalloff;\n\n vec3 lightColor = uSpotLightDiffuseColors[j];\n vec3 specularColor = uSpotLightSpecularColors[j];\n \n LightResult result = _light(viewDirection, normal, lightVector);\n \n totalDiffuse += result.diffuse * lightColor * lightFalloff;\n totalSpecular += result.specular * lightColor * specularColor * lightFalloff;\n }\n }\n\n totalDiffuse *= diffuseFactor;\n totalSpecular *= specularFactor;\n}\n';
var defaultShaders = {
immediateVert:
'attribute vec3 aPosition;\nattribute vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform float uResolution;\nuniform float uPointSize;\n\nvarying vec4 vColor;\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vColor = aVertexColor;\n gl_PointSize = uPointSize;\n}\n',
vertexColorVert:
'attribute vec3 aPosition;\nattribute vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nvarying vec4 vColor;\n\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vColor = aVertexColor;\n}\n',
vertexColorFrag:
'precision mediump float;\nvarying vec4 vColor;\nvoid main(void) {\n gl_FragColor = vColor;\n}',
normalVert:
'attribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\n\nvarying vec3 vVertexNormal;\nvarying highp vec2 vVertTexCoord;\n\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vVertexNormal = normalize(vec3( uNormalMatrix * aNormal ));\n vVertTexCoord = aTexCoord;\n}\n',
normalFrag:
'precision mediump float;\nvarying vec3 vVertexNormal;\nvoid main(void) {\n gl_FragColor = vec4(vVertexNormal, 1.0);\n}',
basicFrag:
'precision mediump float;\nuniform vec4 uMaterialColor;\nvoid main(void) {\n gl_FragColor = uMaterialColor;\n}',
lightVert:
lightingShader +
'// include lighting.glgl\n\nattribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\n\nvarying highp vec2 vVertTexCoord;\nvarying vec3 vDiffuseColor;\nvarying vec3 vSpecularColor;\n\nvoid main(void) {\n\n vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * viewModelPosition;\n\n vec3 vertexNormal = normalize(uNormalMatrix * aNormal);\n vVertTexCoord = aTexCoord;\n\n totalLight(viewModelPosition.xyz, vertexNormal, vDiffuseColor, vSpecularColor);\n\n for (int i = 0; i < 8; i++) {\n if (i < uAmbientLightCount) {\n vDiffuseColor += uAmbientColor[i];\n }\n }\n}\n',
lightTextureFrag:
'precision highp float;\n\nuniform vec4 uMaterialColor;\nuniform vec4 uTint;\nuniform sampler2D uSampler;\nuniform bool isTexture;\nuniform bool uEmissive;\n\nvarying highp vec2 vVertTexCoord;\nvarying vec3 vDiffuseColor;\nvarying vec3 vSpecularColor;\n\nvoid main(void) {\n if(uEmissive && !isTexture) {\n gl_FragColor = uMaterialColor;\n }\n else {\n gl_FragColor = isTexture ? texture2D(uSampler, vVertTexCoord) * (uTint / vec4(255, 255, 255, 255)) : uMaterialColor;\n gl_FragColor.rgb = gl_FragColor.rgb * vDiffuseColor + vSpecularColor;\n }\n}',
phongVert:
'precision highp float;\nprecision highp int;\n\nattribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nuniform vec3 uAmbientColor[5];\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\nuniform int uAmbientLightCount;\n\nvarying vec3 vNormal;\nvarying vec2 vTexCoord;\nvarying vec3 vViewPosition;\nvarying vec3 vAmbientColor;\n\nvoid main(void) {\n\n vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n\n // Pass varyings to fragment shader\n vViewPosition = viewModelPosition.xyz;\n gl_Position = uProjectionMatrix * viewModelPosition; \n\n vNormal = uNormalMatrix * aNormal;\n vTexCoord = aTexCoord;\n\n // TODO: this should be a uniform\n vAmbientColor = vec3(0.0);\n for (int i = 0; i < 5; i++) {\n if (i < uAmbientLightCount) {\n vAmbientColor += uAmbientColor[i];\n }\n }\n}\n',
phongFrag:
lightingShader +
'// include lighting.glsl\nprecision highp float;\nprecision highp int;\n\nuniform vec4 uMaterialColor;\nuniform vec4 uTint;\nuniform sampler2D uSampler;\nuniform bool isTexture;\nuniform bool uEmissive;\n\nvarying vec3 vNormal;\nvarying vec2 vTexCoord;\nvarying vec3 vViewPosition;\nvarying vec3 vAmbientColor;\n\nvoid main(void) {\n\n vec3 diffuse;\n vec3 specular;\n totalLight(vViewPosition, normalize(vNormal), diffuse, specular);\n\n if(uEmissive && !isTexture) {\n gl_FragColor = uMaterialColor;\n }\n else {\n gl_FragColor = isTexture ? texture2D(uSampler, vTexCoord) * (uTint / vec4(255, 255, 255, 255)) : uMaterialColor;\n gl_FragColor.rgb = gl_FragColor.rgb * (diffuse + vAmbientColor) + specular;\n }\n}',
fontVert:
"precision mediump float;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nuniform vec4 uGlyphRect;\nuniform float uGlyphOffset;\n\nvarying vec2 vTexCoord;\nvarying float w;\n\nvoid main() {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n\n // scale by the size of the glyph's rectangle\n positionVec4.xy *= uGlyphRect.zw - uGlyphRect.xy;\n\n // move to the corner of the glyph\n positionVec4.xy += uGlyphRect.xy;\n\n // move to the letter's line offset\n positionVec4.x += uGlyphOffset;\n \n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vTexCoord = aTexCoord;\n w = gl_Position.w;\n}\n",
fontFrag:
"#extension GL_OES_standard_derivatives : enable\nprecision mediump float;\n\n#if 0\n // simulate integer math using floats\n\t#define int float\n\t#define ivec2 vec2\n\t#define INT(x) float(x)\n\n\tint ifloor(float v) { return floor(v); }\n\tivec2 ifloor(vec2 v) { return floor(v); }\n\n#else\n // use native integer math\n\tprecision highp int;\n\t#define INT(x) x\n\n\tint ifloor(float v) { return int(v); }\n\tint ifloor(int v) { return v; }\n\tivec2 ifloor(vec2 v) { return ivec2(v); }\n\n#endif\n\nuniform sampler2D uSamplerStrokes;\nuniform sampler2D uSamplerRowStrokes;\nuniform sampler2D uSamplerRows;\nuniform sampler2D uSamplerColStrokes;\nuniform sampler2D uSamplerCols;\n\nuniform ivec2 uStrokeImageSize;\nuniform ivec2 uCellsImageSize;\nuniform ivec2 uGridImageSize;\n\nuniform ivec2 uGridOffset;\nuniform ivec2 uGridSize;\nuniform vec4 uMaterialColor;\n\nvarying vec2 vTexCoord;\n\n// some helper functions\nint round(float v) { return ifloor(v + 0.5); }\nivec2 round(vec2 v) { return ifloor(v + 0.5); }\nfloat saturate(float v) { return clamp(v, 0.0, 1.0); }\nvec2 saturate(vec2 v) { return clamp(v, 0.0, 1.0); }\n\nint mul(float v1, int v2) {\n return ifloor(v1 * float(v2));\n}\n\nivec2 mul(vec2 v1, ivec2 v2) {\n return ifloor(v1 * vec2(v2) + 0.5);\n}\n\n// unpack a 16-bit integer from a float vec2\nint getInt16(vec2 v) {\n ivec2 iv = round(v * 255.0);\n return iv.x * INT(128) + iv.y;\n}\n\nvec2 pixelScale;\nvec2 coverage = vec2(0.0);\nvec2 weight = vec2(0.5);\nconst float minDistance = 1.0/8192.0;\nconst float hardness = 1.05; // amount of antialias\n\n// the maximum number of curves in a glyph\nconst int N = INT(250);\n\n// retrieves an indexed pixel from a sampler\nvec4 getTexel(sampler2D sampler, int pos, ivec2 size) {\n int width = size.x;\n int y = ifloor(pos / width);\n int x = pos - y * width; // pos % width\n\n return texture2D(sampler, (vec2(x, y) + 0.5) / vec2(size));\n}\n\nvoid calulateCrossings(vec2 p0, vec2 p1, vec2 p2, out vec2 C1, out vec2 C2) {\n\n // get the coefficients of the quadratic in t\n vec2 a = p0 - p1 * 2.0 + p2;\n vec2 b = p0 - p1;\n vec2 c = p0 - vTexCoord;\n\n // found out which values of 't' it crosses the axes\n vec2 surd = sqrt(max(vec2(0.0), b * b - a * c));\n vec2 t1 = ((b - surd) / a).yx;\n vec2 t2 = ((b + surd) / a).yx;\n\n // approximate straight lines to avoid rounding errors\n if (abs(a.y) < 0.001)\n t1.x = t2.x = c.y / (2.0 * b.y);\n\n if (abs(a.x) < 0.001)\n t1.y = t2.y = c.x / (2.0 * b.x);\n\n // plug into quadratic formula to find the corrdinates of the crossings\n C1 = ((a * t1 - b * 2.0) * t1 + c) * pixelScale;\n C2 = ((a * t2 - b * 2.0) * t2 + c) * pixelScale;\n}\n\nvoid coverageX(vec2 p0, vec2 p1, vec2 p2) {\n\n vec2 C1, C2;\n calulateCrossings(p0, p1, p2, C1, C2);\n\n // determine on which side of the x-axis the points lie\n bool y0 = p0.y > vTexCoord.y;\n bool y1 = p1.y > vTexCoord.y;\n bool y2 = p2.y > vTexCoord.y;\n\n // could web be under the curve (after t1)?\n if (y1 ? !y2 : y0) {\n // add the coverage for t1\n coverage.x += saturate(C1.x + 0.5);\n // calculate the anti-aliasing for t1\n weight.x = min(weight.x, abs(C1.x));\n }\n\n // are we outside the curve (after t2)?\n if (y1 ? !y0 : y2) {\n // subtract the coverage for t2\n coverage.x -= saturate(C2.x + 0.5);\n // calculate the anti-aliasing for t2\n weight.x = min(weight.x, abs(C2.x));\n }\n}\n\n// this is essentially the same as coverageX, but with the axes swapped\nvoid coverageY(vec2 p0, vec2 p1, vec2 p2) {\n\n vec2 C1, C2;\n calulateCrossings(p0, p1, p2, C1, C2);\n\n bool x0 = p0.x > vTexCoord.x;\n bool x1 = p1.x > vTexCoord.x;\n bool x2 = p2.x > vTexCoord.x;\n\n if (x1 ? !x2 : x0) {\n coverage.y -= saturate(C1.y + 0.5);\n weight.y = min(weight.y, abs(C1.y));\n }\n\n if (x1 ? !x0 : x2) {\n coverage.y += saturate(C2.y + 0.5);\n weight.y = min(weight.y, abs(C2.y));\n }\n}\n\nvoid main() {\n\n // calculate the pixel scale based on screen-coordinates\n pixelScale = hardness / fwidth(vTexCoord);\n\n // which grid cell is this pixel in?\n ivec2 gridCoord = ifloor(vTexCoord * vec2(uGridSize));\n\n // intersect curves in this row\n {\n // the index into the row info bitmap\n int rowIndex = gridCoord.y + uGridOffset.y;\n // fetch the info texel\n vec4 rowInfo = getTexel(uSamplerRows, rowIndex, uGridImageSize);\n // unpack the rowInfo\n int rowStrokeIndex = getInt16(rowInfo.xy);\n int rowStrokeCount = getInt16(rowInfo.zw);\n\n for (int iRowStroke = INT(0); iRowStroke < N; iRowStroke++) {\n if (iRowStroke >= rowStrokeCount)\n break;\n\n // each stroke is made up of 3 points: the start and control point\n // and the start of the next curve.\n // fetch the indices of this pair of strokes:\n vec4 strokeIndices = getTexel(uSamplerRowStrokes, rowStrokeIndex++, uCellsImageSize);\n\n // unpack the stroke index\n int strokePos = getInt16(strokeIndices.xy);\n\n // fetch the two strokes\n vec4 stroke0 = getTexel(uSamplerStrokes, strokePos + INT(0), uStrokeImageSize);\n vec4 stroke1 = getTexel(uSamplerStrokes, strokePos + INT(1), uStrokeImageSize);\n\n // calculate the coverage\n coverageX(stroke0.xy, stroke0.zw, stroke1.xy);\n }\n }\n\n // intersect curves in this column\n {\n int colIndex = gridCoord.x + uGridOffset.x;\n vec4 colInfo = getTexel(uSamplerCols, colIndex, uGridImageSize);\n int colStrokeIndex = getInt16(colInfo.xy);\n int colStrokeCount = getInt16(colInfo.zw);\n \n for (int iColStroke = INT(0); iColStroke < N; iColStroke++) {\n if (iColStroke >= colStrokeCount)\n break;\n\n vec4 strokeIndices = getTexel(uSamplerColStrokes, colStrokeIndex++, uCellsImageSize);\n\n int strokePos = getInt16(strokeIndices.xy);\n vec4 stroke0 = getTexel(uSamplerStrokes, strokePos + INT(0), uStrokeImageSize);\n vec4 stroke1 = getTexel(uSamplerStrokes, strokePos + INT(1), uStrokeImageSize);\n coverageY(stroke0.xy, stroke0.zw, stroke1.xy);\n }\n }\n\n weight = saturate(1.0 - weight * 2.0);\n float distance = max(weight.x + weight.y, minDistance); // manhattan approx.\n float antialias = abs(dot(coverage, weight) / distance);\n float cover = min(abs(coverage.x), abs(coverage.y));\n gl_FragColor = uMaterialColor;\n gl_FragColor.a *= saturate(max(antialias, cover));\n}",
lineVert:
"/*\n Part of the Processing project - http://processing.org\n Copyright (c) 2012-15 The Processing Foundation\n Copyright (c) 2004-12 Ben Fry and Casey Reas\n Copyright (c) 2001-04 Massachusetts Institute of Technology\n This library is free software; you can redistribute it and/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation, version 2.1.\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n You should have received a copy of the GNU Lesser General\n Public License along with this library; if not, write to the\n Free Software Foundation, Inc., 59 Temple Place, Suite 330,\n Boston, MA 02111-1307 USA\n*/\n\n#define PROCESSING_LINE_SHADER\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform float uStrokeWeight;\n\nuniform vec4 uViewport;\nuniform int uPerspective;\n\nattribute vec4 aPosition;\nattribute vec4 aDirection;\n \nvoid main() {\n // using a scale <1 moves the lines towards the camera\n // in order to prevent popping effects due to half of\n // the line disappearing behind the geometry faces.\n vec3 scale = vec3(0.9995);\n\n vec4 posp = uModelViewMatrix * aPosition;\n vec4 posq = uModelViewMatrix * (aPosition + vec4(aDirection.xyz, 0));\n\n // Moving vertices slightly toward the camera\n // to avoid depth-fighting with the fill triangles.\n // Discussed here:\n // http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=252848 \n posp.xyz = posp.xyz * scale;\n posq.xyz = posq.xyz * scale;\n\n vec4 p = uProjectionMatrix * posp;\n vec4 q = uProjectionMatrix * posq;\n\n // formula to convert from clip space (range -1..1) to screen space (range 0..[width or height])\n // screen_p = (p.xy/p.w + <1,1>) * 0.5 * uViewport.zw\n\n // prevent division by W by transforming the tangent formula (div by 0 causes\n // the line to disappear, see https://github.com/processing/processing/issues/5183)\n // t = screen_q - screen_p\n //\n // tangent is normalized and we don't care which aDirection it points to (+-)\n // t = +- normalize( screen_q - screen_p )\n // t = +- normalize( (q.xy/q.w+<1,1>)*0.5*uViewport.zw - (p.xy/p.w+<1,1>)*0.5*uViewport.zw )\n //\n // extract common factor, <1,1> - <1,1> cancels out\n // t = +- normalize( (q.xy/q.w - p.xy/p.w) * 0.5 * uViewport.zw )\n //\n // convert to common divisor\n // t = +- normalize( ((q.xy*p.w - p.xy*q.w) / (p.w*q.w)) * 0.5 * uViewport.zw )\n //\n // remove the common scalar divisor/factor, not needed due to normalize and +-\n // (keep uViewport - can't remove because it has different components for x and y\n // and corrects for aspect ratio, see https://github.com/processing/processing/issues/5181)\n // t = +- normalize( (q.xy*p.w - p.xy*q.w) * uViewport.zw )\n\n vec2 tangent = normalize((q.xy*p.w - p.xy*q.w) * uViewport.zw);\n\n // flip tangent to normal (it's already normalized)\n vec2 normal = vec2(-tangent.y, tangent.x);\n\n float thickness = aDirection.w * uStrokeWeight;\n vec2 offset = normal * thickness / 2.0;\n\n vec2 curPerspScale;\n\n if(uPerspective == 1) {\n // Perspective ---\n // convert from world to clip by multiplying with projection scaling factor\n // to get the right thickness (see https://github.com/processing/processing/issues/5182)\n // invert Y, projections in Processing invert Y\n curPerspScale = (uProjectionMatrix * vec4(1, -1, 0, 0)).xy;\n } else {\n // No Perspective ---\n // multiply by W (to cancel out division by W later in the pipeline) and\n // convert from screen to clip (derived from clip to screen above)\n curPerspScale = p.w / (0.5 * uViewport.zw);\n }\n\n gl_Position.xy = p.xy + offset.xy * curPerspScale;\n gl_Position.zw = p.zw;\n}\n",
lineFrag:
'precision mediump float;\nprecision mediump int;\n\nuniform vec4 uMaterialColor;\n\nvoid main() {\n gl_FragColor = uMaterialColor;\n}',
pointVert:
'attribute vec3 aPosition;\nuniform float uPointSize;\nvarying float vStrokeWeight;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nvoid main() {\n\tvec4 positionVec4 = vec4(aPosition, 1.0);\n\tgl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n\tgl_PointSize = uPointSize;\n\tvStrokeWeight = uPointSize;\n}',
pointFrag:
'precision mediump float;\nprecision mediump int;\nuniform vec4 uMaterialColor;\nvarying float vStrokeWeight;\n\nvoid main(){\n\tfloat mask = 0.0;\n\n\t// make a circular mask using the gl_PointCoord (goes from 0 - 1 on a point)\n // might be able to get a nicer edge on big strokeweights with smoothstep but slightly less performant\n\n\tmask = step(0.98, length(gl_PointCoord * 2.0 - 1.0));\n\n\t// if strokeWeight is 1 or less lets just draw a square\n\t// this prevents weird artifacting from carving circles when our points are really small\n\t// if strokeWeight is larger than 1, we just use it as is\n\n\tmask = mix(0.0, mask, clamp(floor(vStrokeWeight - 0.5),0.0,1.0));\n\n\t// throw away the borders of the mask\n // otherwise we get weird alpha blending issues\n\n\tif(mask > 0.98){\n discard;\n \t}\n\n \tgl_FragColor = vec4(uMaterialColor.rgb * (1.0 - mask), uMaterialColor.a) ;\n}'
};
/**
* 3D graphics class
* @private
* @class p5.RendererGL
* @constructor
* @extends p5.Renderer
* @todo extend class to include public method for offscreen
* rendering (FBO).
*/
_main.default.RendererGL = function(elt, pInst, isMainCanvas, attr) {
_main.default.Renderer.call(this, elt, pInst, isMainCanvas);
this._setAttributeDefaults(pInst);
this._initContext();
this.isP3D = true; //lets us know we're in 3d mode
// This redundant property is useful in reminding you that you are
// interacting with WebGLRenderingContext, still worth considering future removal
this.GL = this.drawingContext;
this._pInst._setProperty('drawingContext', this.drawingContext);
// erasing
this._isErasing = false;
// lights
this._enableLighting = false;
this.ambientLightColors = [];
this.specularColors = [1, 1, 1];
this.directionalLightDirections = [];
this.directionalLightDiffuseColors = [];
this.directionalLightSpecularColors = [];
this.pointLightPositions = [];
this.pointLightDiffuseColors = [];
this.pointLightSpecularColors = [];
this.spotLightPositions = [];
this.spotLightDirections = [];
this.spotLightDiffuseColors = [];
this.spotLightSpecularColors = [];
this.spotLightAngle = [];
this.spotLightConc = [];
this.drawMode = constants.FILL;
this.curFillColor = this._cachedFillStyle = [1, 1, 1, 1];
this.curStrokeColor = this._cachedStrokeStyle = [0, 0, 0, 1];
this.curBlendMode = constants.BLEND;
this._cachedBlendMode = undefined;
this.blendExt = this.GL.getExtension('EXT_blend_minmax');
this._isBlending = false;
this._useSpecularMaterial = false;
this._useEmissiveMaterial = false;
this._useNormalMaterial = false;
this._useShininess = 1;
this._tint = [255, 255, 255, 255];
// lightFalloff variables
this.constantAttenuation = 1;
this.linearAttenuation = 0;
this.quadraticAttenuation = 0;
/**
* model view, projection, & normal
* matrices
*/
this.uMVMatrix = new _main.default.Matrix();
this.uPMatrix = new _main.default.Matrix();
this.uNMatrix = new _main.default.Matrix('mat3');
// Camera
this._curCamera = new _main.default.Camera(this);
this._curCamera._computeCameraDefaultSettings();
this._curCamera._setDefaultCamera();
this._defaultLightShader = undefined;
this._defaultImmediateModeShader = undefined;
this._defaultNormalShader = undefined;
this._defaultColorShader = undefined;
this._defaultPointShader = undefined;
this.userFillShader = undefined;
this.userStrokeShader = undefined;
this.userPointShader = undefined;
// Default drawing is done in Retained Mode
// Geometry and Material hashes stored here
this.retainedMode = {
geometry: {},
buffers: {
// prettier-ignore
stroke: [
new _main.default.RenderBuffer(3, 'lineVertices', 'lineVertexBuffer', 'aPosition', this, this._flatten),
new _main.default.RenderBuffer(4, 'lineNormals', 'lineNormalBuffer', 'aDirection', this, this._flatten)],
// prettier-ignore
fill: [
new _main.default.RenderBuffer(3, 'vertices', 'vertexBuffer', 'aPosition', this, this._vToNArray),
new _main.default.RenderBuffer(3, 'vertexNormals', 'normalBuffer', 'aNormal', this, this._vToNArray),
new _main.default.RenderBuffer(4, 'vertexColors', 'colorBuffer', 'aMaterialColor', this),
new _main.default.RenderBuffer(3, 'vertexAmbients', 'ambientBuffer', 'aAmbientColor', this),
//new BufferDef(3, 'vertexSpeculars', 'specularBuffer', 'aSpecularColor'),
new _main.default.RenderBuffer(2, 'uvs', 'uvBuffer', 'aTexCoord', this, this._flatten)],
// prettier-ignore
text: [
new _main.default.RenderBuffer(3, 'vertices', 'vertexBuffer', 'aPosition', this, this._vToNArray),
new _main.default.RenderBuffer(2, 'uvs', 'uvBuffer', 'aTexCoord', this, this._flatten)]
}
};
// Immediate Mode
// Geometry and Material hashes stored here
this.immediateMode = {
geometry: new _main.default.Geometry(),
shapeMode: constants.TRIANGLE_FAN,
_bezierVertex: [],
_quadraticVertex: [],
_curveVertex: [],
buffers: {
// prettier-ignore
fill: [
new _main.default.RenderBuffer(3, 'vertices', 'vertexBuffer', 'aPosition', this, this._vToNArray),
new _main.default.RenderBuffer(3, 'vertexNormals', 'normalBuffer', 'aNormal', this, this._vToNArray),
new _main.default.RenderBuffer(4, 'vertexColors', 'colorBuffer', 'aVertexColor', this),
new _main.default.RenderBuffer(3, 'vertexAmbients', 'ambientBuffer', 'aAmbientColor', this),
new _main.default.RenderBuffer(2, 'uvs', 'uvBuffer', 'aTexCoord', this, this._flatten)],
// prettier-ignore
stroke: [
new _main.default.RenderBuffer(3, 'lineVertices', 'lineVertexBuffer', 'aPosition', this, this._flatten),
new _main.default.RenderBuffer(4, 'lineNormals', 'lineNormalBuffer', 'aDirection', this, this._flatten)],
point: this.GL.createBuffer()
}
};
this.pointSize = 5.0; //default point size
this.curStrokeWeight = 1;
// array of textures created in this gl context via this.getTexture(src)
this.textures = [];
this.textureMode = constants.IMAGE;
// default wrap settings
this.textureWrapX = constants.CLAMP;
this.textureWrapY = constants.CLAMP;
this._tex = null;
this._curveTightness = 6;
// lookUpTable for coefficients needed to be calculated for bezierVertex, same are used for curveVertex
this._lookUpTableBezier = [];
// lookUpTable for coefficients needed to be calculated for quadraticVertex
this._lookUpTableQuadratic = [];
// current curveDetail in the Bezier lookUpTable
this._lutBezierDetail = 0;
// current curveDetail in the Quadratic lookUpTable
this._lutQuadraticDetail = 0;
this._tessy = this._initTessy();
this.fontInfos = {};
this._curShader = undefined;
return this;
};
_main.default.RendererGL.prototype = Object.create(
_main.default.Renderer.prototype
);
//////////////////////////////////////////////
// Setting
//////////////////////////////////////////////
_main.default.RendererGL.prototype._setAttributeDefaults = function(pInst) {
// See issue #3850, safer to enable AA in Safari
var applyAA = navigator.userAgent.toLowerCase().includes('safari');
var defaults = {
alpha: true,
depth: true,
stencil: true,
antialias: applyAA,
premultipliedAlpha: false,
preserveDrawingBuffer: true,
perPixelLighting: true
};
if (pInst._glAttributes === null) {
pInst._glAttributes = defaults;
} else {
pInst._glAttributes = Object.assign(defaults, pInst._glAttributes);
}
return;
};
_main.default.RendererGL.prototype._initContext = function() {
try {
this.drawingContext =
this.canvas.getContext('webgl', this._pInst._glAttributes) ||
this.canvas.getContext('experimental-webgl', this._pInst._glAttributes);
if (this.drawingContext === null) {
throw new Error('Error creating webgl context');
} else {
var gl = this.drawingContext;
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
this._viewport = this.drawingContext.getParameter(
this.drawingContext.VIEWPORT
);
}
} catch (er) {
throw er;
}
};
//This is helper function to reset the context anytime the attributes
//are changed with setAttributes()
_main.default.RendererGL.prototype._resetContext = function(options, callback) {
var w = this.width;
var h = this.height;
var defaultId = this.canvas.id;
var isPGraphics = this._pInst instanceof _main.default.Graphics;
if (isPGraphics) {
var pg = this._pInst;
pg.canvas.parentNode.removeChild(pg.canvas);
pg.canvas = document.createElement('canvas');
var node = pg._pInst._userNode || document.body;
node.appendChild(pg.canvas);
_main.default.Element.call(pg, pg.canvas, pg._pInst);
pg.width = w;
pg.height = h;
} else {
var c = this.canvas;
if (c) {
c.parentNode.removeChild(c);
}
c = document.createElement('canvas');
c.id = defaultId;
if (this._pInst._userNode) {
this._pInst._userNode.appendChild(c);
} else {
document.body.appendChild(c);
}
this._pInst.canvas = c;
}
var renderer = new _main.default.RendererGL(
this._pInst.canvas,
this._pInst,
!isPGraphics
);
this._pInst._setProperty('_renderer', renderer);
renderer.resize(w, h);
renderer._applyDefaults();
if (!isPGraphics) {
this._pInst._elements.push(renderer);
}
if (typeof callback === 'function') {
//setTimeout with 0 forces the task to the back of the queue, this ensures that
//we finish switching out the renderer
setTimeout(function() {
callback.apply(window._renderer, options);
}, 0);
}
};
/**
* @module Rendering
* @submodule Rendering
* @for p5
*/
/**
* Set attributes for the WebGL Drawing context.
* This is a way of adjusting how the WebGL
* renderer works to fine-tune the display and performance.
*
* Note that this will reinitialize the drawing context
* if called after the WebGL canvas is made.
*
* If an object is passed as the parameter, all attributes
* not declared in the object will be set to defaults.
*
* The available attributes are:
* <br>
* alpha - indicates if the canvas contains an alpha buffer
* default is true
*
* depth - indicates whether the drawing buffer has a depth buffer
* of at least 16 bits - default is true
*
* stencil - indicates whether the drawing buffer has a stencil buffer
* of at least 8 bits
*
* antialias - indicates whether or not to perform anti-aliasing
* default is false (true in Safari)
*
* premultipliedAlpha - indicates that the page compositor will assume
* the drawing buffer contains colors with pre-multiplied alpha
* default is false
*
* preserveDrawingBuffer - if true the buffers will not be cleared and
* and will preserve their values until cleared or overwritten by author
* (note that p5 clears automatically on draw loop)
* default is true
*
* perPixelLighting - if true, per-pixel lighting will be used in the
* lighting shader otherwise per-vertex lighting is used.
* default is true.
*
* @method setAttributes
* @for p5
* @param {String} key Name of attribute
* @param {Boolean} value New value of named attribute
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(255);
* push();
* rotateZ(frameCount * 0.02);
* rotateX(frameCount * 0.02);
* rotateY(frameCount * 0.02);
* fill(0, 0, 0);
* box(50);
* pop();
* }
* </code>
* </div>
* <br>
* Now with the antialias attribute set to true.
* <br>
* <div>
* <code>
* function setup() {
* setAttributes('antialias', true);
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(255);
* push();
* rotateZ(frameCount * 0.02);
* rotateX(frameCount * 0.02);
* rotateY(frameCount * 0.02);
* fill(0, 0, 0);
* box(50);
* pop();
* }
* </code>
* </div>
*
* <div>
* <code>
* // press the mouse button to disable perPixelLighting
* function setup() {
* createCanvas(100, 100, WEBGL);
* noStroke();
* fill(255);
* }
*
* let lights = [
* { c: '#f00', t: 1.12, p: 1.91, r: 0.2 },
* { c: '#0f0', t: 1.21, p: 1.31, r: 0.2 },
* { c: '#00f', t: 1.37, p: 1.57, r: 0.2 },
* { c: '#ff0', t: 1.12, p: 1.91, r: 0.7 },
* { c: '#0ff', t: 1.21, p: 1.31, r: 0.7 },
* { c: '#f0f', t: 1.37, p: 1.57, r: 0.7 }
* ];
*
* function draw() {
* let t = millis() / 1000 + 1000;
* background(0);
* directionalLight(color('#222'), 1, 1, 1);
*
* for (let i = 0; i < lights.length; i++) {
* let light = lights[i];
* pointLight(
* color(light.c),
* p5.Vector.fromAngles(t * light.t, t * light.p, width * light.r)
* );
* }
*
* specularMaterial(255);
* sphere(width * 0.1);
*
* rotateX(t * 0.77);
* rotateY(t * 0.83);
* rotateZ(t * 0.91);
* torus(width * 0.3, width * 0.07, 24, 10);
* }
*
* function mousePressed() {
* setAttributes('perPixelLighting', false);
* noStroke();
* fill(255);
* }
* function mouseReleased() {
* setAttributes('perPixelLighting', true);
* noStroke();
* fill(255);
* }
* </code>
* </div>
*
* @alt a rotating cube with smoother edges
*/
/**
* @method setAttributes
* @for p5
* @param {Object} obj object with key-value pairs
*/
_main.default.prototype.setAttributes = function(key, value) {
if (typeof this._glAttributes === 'undefined') {
console.log(
'You are trying to use setAttributes on a p5.Graphics object ' +
'that does not use a WEBGL renderer.'
);
return;
}
var unchanged = true;
if (typeof value !== 'undefined') {
//first time modifying the attributes
if (this._glAttributes === null) {
this._glAttributes = {};
}
if (this._glAttributes[key] !== value) {
//changing value of previously altered attribute
this._glAttributes[key] = value;
unchanged = false;
}
//setting all attributes with some change
} else if (key instanceof Object) {
if (this._glAttributes !== key) {
this._glAttributes = key;
unchanged = false;
}
}
//@todo_FES
if (!this._renderer.isP3D || unchanged) {
return;
}
if (!this._setupDone) {
for (var x in this._renderer.retainedMode.geometry) {
if (this._renderer.retainedMode.geometry.hasOwnProperty(x)) {
console.error(
'Sorry, Could not set the attributes, you need to call setAttributes() ' +
'before calling the other drawing methods in setup()'
);
return;
}
}
}
this.push();
this._renderer._resetContext();
this.pop();
if (this._renderer._curCamera) {
this._renderer._curCamera._renderer = this._renderer;
}
};
/**
* @class p5.RendererGL
*/
_main.default.RendererGL.prototype._update = function() {
// reset model view and apply initial camera transform
// (containing only look at info; no projection).
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]
);
// reset light data for new frame.
this.ambientLightColors.length = 0;
this.specularColors = [1, 1, 1];
this.directionalLightDirections.length = 0;
this.directionalLightDiffuseColors.length = 0;
this.directionalLightSpecularColors.length = 0;
this.pointLightPositions.length = 0;
this.pointLightDiffuseColors.length = 0;
this.pointLightSpecularColors.length = 0;
this.spotLightPositions.length = 0;
this.spotLightDirections.length = 0;
this.spotLightDiffuseColors.length = 0;
this.spotLightSpecularColors.length = 0;
this.spotLightAngle.length = 0;
this.spotLightConc.length = 0;
this._enableLighting = false;
//reset tint value for new frame
this._tint = [255, 255, 255, 255];
//Clear depth every frame
this.GL.clear(this.GL.DEPTH_BUFFER_BIT);
};
/**
* [background description]
*/
_main.default.RendererGL.prototype.background = function() {
var _this$_pInst;
var _col = (_this$_pInst = this._pInst).color.apply(_this$_pInst, arguments);
var _r = _col.levels[0] / 255;
var _g = _col.levels[1] / 255;
var _b = _col.levels[2] / 255;
var _a = _col.levels[3] / 255;
this.GL.clearColor(_r, _g, _b, _a);
this.GL.clear(this.GL.COLOR_BUFFER_BIT);
};
//////////////////////////////////////////////
// COLOR
//////////////////////////////////////////////
/**
* Basic fill material for geometry with a given color
* @method fill
* @class p5.RendererGL
* @param {Number|Number[]|String|p5.Color} v1 gray value,
* red or hue value (depending on the current color mode),
* or color Array, or CSS color string
* @param {Number} [v2] green or saturation value
* @param {Number} [v3] blue or brightness value
* @param {Number} [a] opacity
* @chainable
* @example
* <div>
* <code>
* function setup() {
* createCanvas(200, 200, WEBGL);
* }
*
* function draw() {
* background(0);
* noStroke();
* fill(100, 100, 240);
* rotateX(frameCount * 0.01);
* rotateY(frameCount * 0.01);
* box(75, 75, 75);
* }
* </code>
* </div>
*
* @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
* <div>
* <code>
* function setup() {
* createCanvas(200, 200, WEBGL);
* }
*
* function draw() {
* background(0);
* stroke(240, 150, 150);
* fill(100, 100, 240);
* rotateX(frameCount * 0.01);
* rotateY(frameCount * 0.01);
* box(75, 75, 75);
* }
* </code>
* </div>
*
* @alt
* black canvas with purple cube with pink outline spinning
*/
_main.default.RendererGL.prototype.stroke = function(r, g, b, a) {
//@todo allow transparency in stroking currently doesn't have
//any impact and causes problems with specularMaterial
arguments[3] = 255;
var color = _main.default.prototype.color.apply(this._pInst, arguments);
this.curStrokeColor = color._array;
};
_main.default.RendererGL.prototype.strokeCap = function(cap) {
// @TODO : to be implemented
console.error('Sorry, strokeCap() is not yet implemented in WEBGL mode');
};
_main.default.RendererGL.prototype.strokeJoin = function(join) {
// @TODO : to be implemented
// https://processing.org/reference/strokeJoin_.html
console.error('Sorry, strokeJoin() is not yet implemented in WEBGL mode');
};
_main.default.RendererGL.prototype.filter = function(filterType) {
// filter can be achieved using custom shaders.
// https://github.com/aferriss/p5jsShaderExamples
// https://itp-xstory.github.io/p5js-shaders/#/
console.error('filter() does not work in WEBGL mode');
};
_main.default.RendererGL.prototype.blendMode = function(mode) {
if (
mode === constants.DARKEST ||
mode === constants.LIGHTEST ||
mode === constants.ADD ||
mode === constants.BLEND ||
mode === constants.SUBTRACT ||
mode === constants.SCREEN ||
mode === constants.EXCLUSION ||
mode === constants.REPLACE ||
mode === constants.MULTIPLY ||
mode === constants.REMOVE
)
this.curBlendMode = mode;
else if (
mode === constants.BURN ||
mode === constants.OVERLAY ||
mode === constants.HARD_LIGHT ||
mode === constants.SOFT_LIGHT ||
mode === constants.DODGE
) {
console.warn(
'BURN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, and DODGE only work for blendMode in 2D mode.'
);
}
};
_main.default.RendererGL.prototype.erase = function(opacityFill, opacityStroke) {
if (!this._isErasing) {
this._applyBlendMode(constants.REMOVE);
this._isErasing = true;
this._cachedFillStyle = this.curFillColor.slice();
this.curFillColor = [1, 1, 1, opacityFill / 255];
this._cachedStrokeStyle = this.curStrokeColor.slice();
this.curStrokeColor = [1, 1, 1, opacityStroke / 255];
}
};
_main.default.RendererGL.prototype.noErase = function() {
if (this._isErasing) {
this._isErasing = false;
this.curFillColor = this._cachedFillStyle.slice();
this.curStrokeColor = this._cachedStrokeStyle.slice();
this.blendMode(this._cachedBlendMode);
}
};
/**
* Change weight of stroke
* @method strokeWeight
* @param {Number} stroke weight to be used for drawing
* @example
* <div>
* <code>
* function setup() {
* createCanvas(200, 400, WEBGL);
* setAttributes('antialias', true);
* }
*
* function draw() {
* background(0);
* noStroke();
* translate(0, -100, 0);
* stroke(240, 150, 150);
* fill(100, 100, 240);
* push();
* strokeWeight(8);
* rotateX(frameCount * 0.01);
* rotateY(frameCount * 0.01);
* sphere(75);
* pop();
* push();
* translate(0, 200, 0);
* strokeWeight(1);
* rotateX(frameCount * 0.01);
* rotateY(frameCount * 0.01);
* sphere(75);
* pop();
* }
* </code>
* </div>
*
* @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);
// prettier-ignore
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;
// prettier-ignore
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, _g, _b, _a);
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 {
// prettier-ignore
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._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;
return style;
};
_main.default.RendererGL.prototype.resetMatrix = function() {
this.uMVMatrix = _main.default.Matrix.identity(this._pInst);
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('uMaterialColor', this.curStrokeColor);
strokeShader.setUniform('uStrokeWeight', this.curStrokeWeight);
};
_main.default.RendererGL.prototype._setFillUniforms = function(fillShader) {
fillShader.bindShader();
// TODO: optimize
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('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._initTessy = function initTesselator() {
// function called for each vertex of tesselator output
function vertexCallback(data, polyVertArray) {
polyVertArray[polyVertArray.length] = data[0];
polyVertArray[polyVertArray.length] = data[1];
polyVertArray[polyVertArray.length] = data[2];
}
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) {
return [coords[0], coords[1], coords[2]];
}
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
// since only doing 2d tesselation here, provide z=1 normal to skip
// iterating over verts only to get the same answer.
// comment out to test normal-generation code
this._tessy.gluTessNormal(0, 0, 1);
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 += 3) {
var coords = [contour[j], contour[j + 1], contour[j + 2]];
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': 48,
'../core/main': 59,
'../core/p5.Renderer': 62,
'./p5.Camera': 107,
'./p5.Matrix': 109,
'./p5.Shader': 114,
libtess: 32,
path: 35
}
],
114: [
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 };
}
/**
* This module defines the p5.Shader class
* @module Lights, Camera
* @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 =
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_VEC3 ||
uniform.type === gl.INT_VEC4;
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() {
// TODO: migrate stuff from material.js here
// - OR - have material.js define this function
};
_main.default.Shader.prototype._setMatrixUniforms = function() {
this.setUniform('uProjectionMatrix', this._renderer.uPMatrix.mat4);
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('uModelViewMatrix', this._renderer.uMVMatrix.mat4);
this.setUniform('uViewMatrix', this._renderer._curCamera.cameraMatrix.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;
};
/**
* Wrapper around gl.uniform functions.
* As we store uniform info in the shader we can use that
* to do type checking on the supplied data and call
* the appropriate function.
* @method setUniform
* @chainable
* @param {String} uniformName the name of the uniform in the
* shader program
* @param {Object|Number|Boolean|Number[]} data the data to be associated
* with that uniform; type varies (could be a single numerical value, array,
* matrix, or texture / sampler reference)
*
* @example
* <div modernizr='webgl'>
* <code>
* // 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();
* }
*
* 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;
* }
* </code>
* </div>
*
* @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 {
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 = this._renderer.getTexture(data);
gl.uniform1i(uniform.location, uniform.samplerIndex);
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.samplerIndex > 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;
if (!attr.enabled) {
gl.enableVertexAttribArray(loc);
attr.enabled = 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': 59 }
],
115: [
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 };
}
/**
* This module defines the p5.Texture class
* @module Lights, Camera
* @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.
*/ _main.default.Texture = function(renderer, obj) {
this._renderer = renderer;
var gl = this._renderer.GL;
this.src = obj;
this.glTex = undefined;
this.glTarget = gl.TEXTURE_2D;
this.glFormat = gl.RGBA;
this.mipmaps = false;
this.glMinFilter = gl.LINEAR;
this.glMagFilter = gl.LINEAR;
this.glWrapS = gl.CLAMP_TO_EDGE;
this.glWrapT = gl.CLAMP_TO_EDGE;
// 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);
this.isSrcP5Image = obj instanceof _main.default.Image;
this.isSrcP5Graphics = obj instanceof _main.default.Graphics;
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.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 1x1 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,
gl.UNSIGNED_BYTE,
tmpdata
);
} else {
// data is ready: just push the texture!
gl.texImage2D(
this.glTarget,
0,
this.glFormat,
this.glFormat,
gl.UNSIGNED_BYTE,
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,
gl.UNSIGNED_BYTE,
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 widthPowerOfTwo = isPowerOfTwo(this.width);
var heightPowerOfTwo = isPowerOfTwo(this.height);
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': 48, '../core/main': 59 }
],
116: [
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);
}
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 };
}
// 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), 0);
var ixMax = Math.min(Math.ceil(mmX.max * charGridWidth), 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), 0);
var iyMax = Math.min(Math.ceil(mmY.max * charGridHeight), 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.0 / 3.0);
// 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 & 0x7f,
_strokeCount >> 7,
_strokeCount & 0x7f
);
// 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 & 0x7f, 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': 48,
'../core/main': 59,
'./p5.RendererGL.Retained': 112,
'./p5.Shader': 114
}
],
117: [
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. Check out {{link}} for more information about why.",
checkUserDefinedFns:
"It seems that you may have accidentally written {{name}} instead of {{actualName}}.\n\nPlease 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. (More info at {{link}})',
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:
'{{func}}() was expecting {{formatType}} for the {{position}} parameter, received an empty variable instead. {{location}}\n\nIf not intentional, this is often a problem with scope: {{link}}',
type_TOO_FEW_ARGUMENTS:
'{{func}}() was expecting at least {{minParams}} arguments, but received only {{argCount}}. {{location}}',
type_TOO_MANY_ARGUMENTS:
'{{func}}() was expecting no more than {{maxParams}} arguments, but received {{argCount}}. {{location}}',
type_WRONG_TYPE:
'{{func}}() was expecting {{formatType}} for the {{position}} parameter, received {{argType}} instead. {{location}}'
},
globalErrors: {
reference: {
notDefined:
'There\'s an error due to "{{symbol}}" not being defined in the current scope {{location}}.\n\nIf you have defined it in your code, you should check its scope, spelling, and letter-casing (JavaScript is case-sensitive). For more:\n{{url1}}\n{{url2}}'
},
stackSubseq:
'▶️ Called from line {{line}} in "{{func}}" in {{file}} ({{location}})\n\n',
stackTop:
'▶️ Error at line {{line}} in "{{func}}" in {{file}} ({{location}})\n\n',
syntax: {
invalidToken:
"There's a syntax error due to a symbol that JavaScript doesn't recognize or didn't expect at it's place.\nFor more: {{url}}",
unexpectedToken:
"There's a syntax error due to a symbol that wasn't expected at it's place.\nUsually this is due to a typo. Check the line number in the error below for anything missing/extra.\nFor more: {{url}}"
},
type: {
notfunc:
'There\'s an error as "{{symbol}}" could not be called as a function {{location}}.\nCheck the spelling, letter-casing (Javacript is case-sensitive) and its type.\nFor more: {{url}}',
notfuncObj:
'There\'s an error as "{{symbol}}" could not be called as a function {{location}}.\nVerify whether "{{obj}}" has "{{symbol}}" in it and check the spelling, letter-casing (Javacript is case-sensitive) and its type.\nFor more: {{url}}'
}
},
libraryError:
'An error with message "{{error}}" occured inside the p5js library when {{func}} was called {{location}}\n\nIf not stated otherwise, it might be an issue with the arguments passed to {{func}}.',
location: '(on line {{line}} in {{file}} [{{location}}])',
misspelling:
'It seems that you may have accidentally written "{{name}}" instead of "{{actualName}}" {{location}}.\n\nPlease correct it to {{actualName}} if you wish to use the {{type}} from p5.js',
misspelling_plural:
'It seems that you may have accidentally written "{{name}}" {{location}}.\n\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\nFor more details, see: {{link}}",
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}}',
welcome:
'Welcome! This is your friendly debugger. To turn me off, switch to using p5.min.js.',
wrongPreload:
'An error with message "{{error}}" occured inside the p5js library when "{{func}}" was called {{location}}.\n\nIf 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.'
}
};
},
{}
],
118: [
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'];
exports.languages = languages;
},
{ './en/translation': 117 }
]
},
{},
[43]
)(43);
});