From f8a78c05fc5cbe473d04edee6dc1b8d81c0280b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benedikt=20Gro=C3=9F?= Date: Tue, 5 Dec 2023 09:36:54 +0100 Subject: [PATCH] Updated dependency p5.js --- libraries/p5.js | 79530 ++++++++++++++++++++++++---------------- libraries/p5.sound.js | 2 +- 2 files changed, 46954 insertions(+), 32578 deletions(-) diff --git a/libraries/p5.js b/libraries/p5.js index 5c879d0..6c470be 100644 --- a/libraries/p5.js +++ b/libraries/p5.js @@ -1,4 +1,4 @@ -/*! p5.js v1.6.0 February 22, 2023 */ +/*! p5.js v1.9.0 November 28, 2023 */ (function (f) { if (typeof exports === 'object' && typeof module !== 'undefined') { module.exports = f() @@ -58,12 +58,12 @@ 'params': [ { 'name': 'text', - 'description': '

description of the canvas

\n', + 'description': '

description of the canvas.

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

either LABEL or FALLBACK

\n', + 'description': '

either LABEL or FALLBACK.

\n', 'type': 'Constant', 'optional': true } @@ -76,17 +76,17 @@ 'params': [ { 'name': 'name', - 'description': '

name of the element

\n', + 'description': '

name of the element.

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

description of the element

\n', + 'description': '

description of the element.

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

either LABEL or FALLBACK

\n', + 'description': '

either LABEL or FALLBACK.

\n', 'type': 'Constant', 'optional': true } @@ -99,7 +99,7 @@ 'params': [ { 'name': 'display', - 'description': '

either FALLBACK or LABEL

\n', + 'description': '

either FALLBACK or LABEL.

\n', 'type': 'Constant', 'optional': true } @@ -112,7 +112,7 @@ 'params': [ { 'name': 'display', - 'description': '

either FALLBACK or LABEL

\n', + 'description': '

either FALLBACK or LABEL.

\n', 'type': 'Constant', 'optional': true } @@ -125,7 +125,7 @@ 'params': [ { 'name': 'color', - 'description': '

p5.Color object, color components,\n or CSS color

\n', + 'description': '

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

\n', 'type': 'p5.Color|Number[]|String' } ], @@ -137,7 +137,7 @@ 'params': [ { 'name': 'color', - 'description': '

p5.Color object, color components,\n or CSS color

\n', + 'description': '

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

\n', 'type': 'p5.Color|Number[]|String' } ], @@ -149,7 +149,7 @@ 'params': [ { 'name': 'color', - 'description': '

p5.Color object, color components,\n or CSS color

\n', + 'description': '

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

\n', 'type': 'p5.Color|Number[]|String' } ], @@ -170,7 +170,7 @@ }, { 'name': 'alpha', - 'description': '

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

\n', + 'description': '

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

\n', 'type': 'Number', 'optional': true } @@ -180,17 +180,17 @@ 'params': [ { 'name': 'v1', - 'description': '

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

\n', + 'description': '

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

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

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

\n', + 'description': '

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

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

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

\n', + 'description': '

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

\n', 'type': 'Number' }, { @@ -205,7 +205,7 @@ 'params': [ { 'name': 'value', - 'description': '

a color string

\n', + 'description': '

a color string.

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

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

\n', + 'description': '

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

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

p5.Color object, color components,\n or CSS color

\n', + 'description': '

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

\n', 'type': 'p5.Color|Number[]|String' } ], @@ -247,7 +247,7 @@ 'params': [ { 'name': 'color', - 'description': '

p5.Color object, color components,\n or CSS color

\n', + 'description': '

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

\n', 'type': 'p5.Color|Number[]|String' } ], @@ -259,17 +259,17 @@ 'params': [ { 'name': 'c1', - 'description': '

interpolate from this color

\n', + 'description': '

interpolate from this color.

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

interpolate to this color

\n', + 'description': '

interpolate to this color.

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

number between 0 and 1

\n', + 'description': '

number between 0 and 1.

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

p5.Color object, color components,\n or CSS color

\n', + 'description': '

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

\n', 'type': 'p5.Color|Number[]|String' } ], @@ -293,7 +293,7 @@ 'params': [ { 'name': 'color', - 'description': '

p5.Color object, color components,\n or CSS color

\n', + 'description': '

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

\n', 'type': 'p5.Color|Number[]|String' } ], @@ -305,13 +305,49 @@ 'params': [ { 'name': 'color', - 'description': '

p5.Color object, color components,\n or CSS color

\n', + 'description': '

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

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

An object containing clip settings.

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

A function that draws the mask shape.

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

An object containing clip settings.

\n', + 'type': 'Object', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Color' + }, 'background': { 'name': 'background', 'class': 'p5', @@ -331,12 +367,12 @@ 'params': [ { 'name': 'colorstring', - 'description': '

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

\n', + 'description': '

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

\n', 'type': 'String' }, { 'name': 'a', - 'description': '

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

\n', + 'description': '

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

\n', 'type': 'Number', 'optional': true } @@ -347,7 +383,7 @@ 'params': [ { 'name': 'gray', - 'description': '

specifies a value between white and black

\n', + 'description': '

specifies a value between white and black.

\n', 'type': 'Number' }, { @@ -363,17 +399,17 @@ 'params': [ { 'name': 'v1', - 'description': '

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

\n', + 'description': '

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

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

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

\n', + 'description': '

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

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

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

\n', + 'description': '

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

\n', 'type': 'Number' }, { @@ -389,7 +425,7 @@ 'params': [ { 'name': 'values', - 'description': '

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

\n', + 'description': '

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

\n', 'type': 'Number[]' } ], @@ -399,7 +435,7 @@ 'params': [ { 'name': 'image', - 'description': '

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

\n', + 'description': '

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

\n', 'type': 'p5.Image' }, { @@ -418,22 +454,22 @@ 'params': [ { 'name': 'r', - 'description': '

normalized red val.

\n', + 'description': '

normalized red value.

\n', 'type': 'Number' }, { 'name': 'g', - 'description': '

normalized green val.

\n', + 'description': '

normalized green value.

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

normalized blue val.

\n', + 'description': '

normalized blue value.

\n', 'type': 'Number' }, { 'name': 'a', - 'description': '

normalized alpha val.

\n', + 'description': '

normalized alpha value.

\n', 'type': 'Number' } ], @@ -449,12 +485,12 @@ 'params': [ { 'name': 'mode', - 'description': '

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

\n', + 'description': '

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

\n', 'type': 'Constant' }, { 'name': 'max', - 'description': '

range for all values

\n', + 'description': '

range for all values.

\n', 'type': 'Number', 'optional': true } @@ -470,22 +506,22 @@ }, { 'name': 'max1', - 'description': '

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

\n', + 'description': '

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

\n', 'type': 'Number' }, { 'name': 'max2', - 'description': '

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

\n', + 'description': '

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

\n', 'type': 'Number' }, { 'name': 'max3', - 'description': '

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

\n', + 'description': '

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

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

range for the alpha

\n', + 'description': '

range for the alpha.

\n', 'type': 'Number', 'optional': true } @@ -503,17 +539,17 @@ 'params': [ { 'name': 'v1', - 'description': '

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

\n', + 'description': '

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

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

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

\n', + 'description': '

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

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

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

\n', + 'description': '

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

\n', 'type': 'Number' }, { @@ -529,7 +565,7 @@ 'params': [ { 'name': 'value', - 'description': '

a color string

\n', + 'description': '

a color string.

\n', 'type': 'String' } ], @@ -539,7 +575,7 @@ 'params': [ { 'name': 'gray', - 'description': '

a gray value

\n', + 'description': '

a grayscale value.

\n', 'type': 'Number' }, { @@ -555,7 +591,7 @@ 'params': [ { 'name': 'values', - 'description': '

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

\n', + 'description': '

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

\n', 'type': 'Number[]' } ], @@ -565,7 +601,7 @@ 'params': [ { 'name': 'color', - 'description': '

the fill color

\n', + 'description': '

the fill color.

\n', 'type': 'p5.Color' } ], @@ -592,17 +628,17 @@ 'params': [ { 'name': 'v1', - 'description': '

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

\n', + 'description': '

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

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

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

\n', + 'description': '

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

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

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

\n', + 'description': '

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

\n', 'type': 'Number' }, { @@ -618,7 +654,7 @@ 'params': [ { 'name': 'value', - 'description': '

a color string

\n', + 'description': '

a color string.

\n', 'type': 'String' } ], @@ -628,7 +664,7 @@ 'params': [ { 'name': 'gray', - 'description': '

a gray value

\n', + 'description': '

a grayscale value.

\n', 'type': 'Number' }, { @@ -644,7 +680,7 @@ 'params': [ { 'name': 'values', - 'description': '

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

\n', + 'description': '

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

\n', 'type': 'Number[]' } ], @@ -654,7 +690,7 @@ 'params': [ { 'name': 'color', - 'description': '

the stroke color

\n', + 'description': '

the stroke color.

\n', 'type': 'p5.Color' } ], @@ -667,13 +703,13 @@ 'params': [ { 'name': 'strengthFill', - 'description': '

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.

\n', + 'description': '

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

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

A number (0-255) for the strength of erasing for a shape\'s stroke.\n This will default to 255 when no argument is given, which\n is full strength.

\n', + 'description': '

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

\n', 'type': 'Number', 'optional': true } @@ -691,37 +727,37 @@ 'params': [ { 'name': 'x', - 'description': '

x-coordinate of the arc\'s ellipse

\n', + 'description': '

x-coordinate of the arc\'s ellipse.

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

y-coordinate of the arc\'s ellipse

\n', + 'description': '

y-coordinate of the arc\'s ellipse.

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

width of the arc\'s ellipse by default

\n', + 'description': '

width of the arc\'s ellipse by default.

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

height of the arc\'s ellipse by default

\n', + 'description': '

height of the arc\'s ellipse by default.

\n', 'type': 'Number' }, { 'name': 'start', - 'description': '

angle to start the arc, specified in radians

\n', + 'description': '

angle to start the arc, specified in radians.

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

angle to stop the arc, specified in radians

\n', + 'description': '

angle to stop the arc, specified in radians.

\n', 'type': 'Number' }, { 'name': 'mode', - 'description': '

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

\n', + 'description': '

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

\n', 'type': 'Constant', 'optional': true }, @@ -790,7 +826,7 @@ }, { 'name': 'detail', - 'description': '

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

\n', + 'description': '

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

\n', 'type': 'Integer', 'optional': true } @@ -829,22 +865,22 @@ 'params': [ { 'name': 'x1', - 'description': '

the x-coordinate of the first point

\n', + 'description': '

the x-coordinate of the first point.

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

the y-coordinate of the first point

\n', + 'description': '

the y-coordinate of the first point.

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

the x-coordinate of the second point

\n', + 'description': '

the x-coordinate of the second point.

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

the y-coordinate of the second point

\n', + 'description': '

the y-coordinate of the second point.

\n', 'type': 'Number' } ], @@ -864,7 +900,7 @@ }, { 'name': 'z1', - 'description': '

the z-coordinate of the first point

\n', + 'description': '

the z-coordinate of the first point.

\n', 'type': 'Number' }, { @@ -879,7 +915,7 @@ }, { 'name': 'z2', - 'description': '

the z-coordinate of the second point

\n', + 'description': '

the z-coordinate of the second point.

\n', 'type': 'Number' } ], @@ -896,17 +932,17 @@ 'params': [ { 'name': 'x', - 'description': '

the x-coordinate

\n', + 'description': '

the x-coordinate.

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

the y-coordinate

\n', + 'description': '

the y-coordinate.

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

the z-coordinate (for WebGL mode)

\n', + 'description': '

the z-coordinate (for WebGL mode).

\n', 'type': 'Number', 'optional': true } @@ -916,8 +952,8 @@ { 'params': [ { - 'name': 'coordinate_vector', - 'description': '

the coordinate vector

\n', + 'name': 'coordinateVector', + 'description': '

the coordinate vector.

\n', 'type': 'p5.Vector' } ], @@ -934,53 +970,53 @@ 'params': [ { 'name': 'x1', - 'description': '

the x-coordinate of the first point

\n', + 'description': '

the x-coordinate of the first point.

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

the y-coordinate of the first point

\n', + 'description': '

the y-coordinate of the first point.

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

the x-coordinate of the second point

\n', + 'description': '

the x-coordinate of the second point.

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

the y-coordinate of the second point

\n', + 'description': '

the y-coordinate of the second point.

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

the x-coordinate of the third point

\n', + 'description': '

the x-coordinate of the third point.

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

the y-coordinate of the third point

\n', + 'description': '

the y-coordinate of the third point.

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

the x-coordinate of the fourth point

\n', + 'description': '

the x-coordinate of the fourth point.

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

the y-coordinate of the fourth point

\n', + 'description': '

the y-coordinate of the fourth point.

\n', 'type': 'Number' }, { 'name': 'detailX', - 'description': '

number of segments in the x-direction

\n', + 'description': '

number of segments in the x-direction.

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

number of segments in the y-direction

\n', + 'description': '

number of segments in the y-direction.

\n', 'type': 'Integer', 'optional': true } @@ -1001,7 +1037,7 @@ }, { 'name': 'z1', - 'description': '

the z-coordinate of the first point

\n', + 'description': '

the z-coordinate of the first point.

\n', 'type': 'Number' }, { @@ -1016,7 +1052,7 @@ }, { 'name': 'z2', - 'description': '

the z-coordinate of the second point

\n', + 'description': '

the z-coordinate of the second point.

\n', 'type': 'Number' }, { @@ -1031,7 +1067,7 @@ }, { 'name': 'z3', - 'description': '

the z-coordinate of the third point

\n', + 'description': '

the z-coordinate of the third point.

\n', 'type': 'Number' }, { @@ -1046,7 +1082,7 @@ }, { 'name': 'z4', - 'description': '

the z-coordinate of the fourth point

\n', + 'description': '

the z-coordinate of the fourth point.

\n', 'type': 'Number' }, { @@ -1145,13 +1181,13 @@ }, { 'name': 'detailX', - 'description': '

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

\n', + 'description': '

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

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

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

\n', + 'description': '

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

\n', 'type': 'Integer', 'optional': true } @@ -1211,32 +1247,32 @@ 'params': [ { 'name': 'x1', - 'description': '

x-coordinate of the first point

\n', + 'description': '

x-coordinate of the first point.

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

y-coordinate of the first point

\n', + 'description': '

y-coordinate of the first point.

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

x-coordinate of the second point

\n', + 'description': '

x-coordinate of the second point.

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

y-coordinate of the second point

\n', + 'description': '

y-coordinate of the second point.

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

x-coordinate of the third point

\n', + 'description': '

x-coordinate of the third point.

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

y-coordinate of the third point

\n', + 'description': '

y-coordinate of the third point.

\n', 'type': 'Number' } ], @@ -1306,7 +1342,7 @@ 'params': [ { 'name': 'weight', - 'description': '

the weight of the stroke (in pixels)

\n', + 'description': '

the weight of the stroke (in pixels).

\n', 'type': 'Number' } ], @@ -1877,6 +1913,12 @@ 'description': '

use CLOSE to close the shape

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

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

\n', + 'type': 'Integer', + 'optional': true } ], 'class': 'p5', @@ -2077,6 +2119,11 @@ 'class': 'p5', 'module': 'Constants' }, + 'WEBGL2': { + 'name': 'WEBGL2', + 'class': 'p5', + 'module': 'Constants' + }, 'ARROW': { 'name': 'ARROW', 'class': 'p5', @@ -2587,6 +2634,16 @@ 'class': 'p5', 'module': 'Constants' }, + 'FLAT': { + 'name': 'FLAT', + 'class': 'p5', + 'module': 'Constants' + }, + 'SMOOTH': { + 'name': 'SMOOTH', + 'class': 'p5', + 'module': 'Constants' + }, 'LANDSCAPE': { 'name': 'LANDSCAPE', 'class': 'p5', @@ -2627,12 +2684,37 @@ 'class': 'p5', 'module': 'Constants' }, + 'UNSIGNED_BYTE': { + 'name': 'UNSIGNED_BYTE', + 'class': 'p5', + 'module': 'Constants' + }, + 'UNSIGNED_INT': { + 'name': 'UNSIGNED_INT', + 'class': 'p5', + 'module': 'Constants' + }, + 'FLOAT': { + 'name': 'FLOAT', + 'class': 'p5', + 'module': 'Constants' + }, + 'HALF_FLOAT': { + 'name': 'HALF_FLOAT', + 'class': 'p5', + 'module': 'Constants' + }, + 'RGBA': { + 'name': 'RGBA', + 'class': 'p5', + 'module': 'Constants' + }, 'print': { 'name': 'print', 'params': [ { 'name': 'contents', - 'description': '

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

\n', + 'description': '

content to print to the console.

\n', 'type': 'Any' } ], @@ -2659,18 +2741,18 @@ 'params': [ { 'name': 'type', - 'description': '

Built-In: either ARROW, CROSS, HAND, MOVE, TEXT and WAIT\n Native CSS properties: \'grab\', \'progress\', \'cell\' etc.\n External: path for cursor\'s images\n (Allowed File extensions: .cur, .gif, .jpg, .jpeg, .png)\n For more information on Native CSS cursors and url visit:\n https://developer.mozilla.org/en-US/docs/Web/CSS/cursor

\n', + 'description': '

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

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

the horizontal active spot of the cursor (must be less than 32)

\n', + 'description': '

horizontal active spot of the cursor.

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

the vertical active spot of the cursor (must be less than 32)

\n', + 'description': '

vertical active spot of the cursor.

\n', 'type': 'Number', 'optional': true } @@ -2687,7 +2769,7 @@ 'params': [ { 'name': 'fps', - 'description': '

number of frames to be displayed every second

\n', + 'description': '

number of frames to draw per second.

\n', 'type': 'Number' } ], @@ -2709,6 +2791,11 @@ 'class': 'p5', 'module': 'Environment' }, + 'webglVersion': { + 'name': 'webglVersion', + 'class': 'p5', + 'module': 'Environment' + }, 'displayWidth': { 'name': 'displayWidth', 'class': 'p5', @@ -2734,8 +2821,8 @@ 'params': [ { 'name': 'event', - 'description': '

optional Event callback argument.

\n', - 'type': 'Object', + 'description': '

optional resize Event.

\n', + 'type': 'UIEvent', 'optional': true } ], @@ -2757,7 +2844,7 @@ 'params': [ { 'name': 'val', - 'description': '

whether the sketch should be in fullscreen mode\nor not

\n', + 'description': '

whether the sketch should be in fullscreen mode.

\n', 'type': 'Boolean', 'optional': true } @@ -2774,8 +2861,9 @@ 'params': [ { 'name': 'val', - 'description': '

whether or how much the sketch should scale

\n', - 'type': 'Number' + 'description': '

desired pixel density.

\n', + 'type': 'Number', + 'optional': true } ], 'chainable': 1 @@ -2925,26 +3013,56 @@ }, 'createCanvas': { 'name': 'createCanvas', - 'params': [ - { - 'name': 'w', - 'description': '

width of the canvas

\n', - 'type': 'Number' - }, + 'class': 'p5', + 'module': 'Rendering', + 'overloads': [ { - 'name': 'h', - 'description': '

height of the canvas

\n', - 'type': 'Number' + 'params': [ + { + 'name': 'w', + 'description': '

width of the canvas

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

height of the canvas

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

either P2D or WEBGL

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

existing html canvas element

\n', + 'type': 'HTMLCanvasElement', + 'optional': true + } + ] }, { - 'name': 'renderer', - 'description': '

either P2D or WEBGL

\n', - 'type': 'Constant', - 'optional': true + 'params': [ + { + 'name': 'w', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'h', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'canvas', + 'description': '', + 'type': 'HTMLCanvasElement', + 'optional': true + } + ] } - ], - 'class': 'p5', - 'module': 'Rendering' + ] }, 'resizeCanvas': { 'name': 'resizeCanvas', @@ -2976,21 +3094,64 @@ }, 'createGraphics': { 'name': 'createGraphics', - 'params': [ + 'class': 'p5', + 'module': 'Rendering', + 'overloads': [ { - 'name': 'w', - 'description': '

width of the offscreen graphics buffer

\n', - 'type': 'Number' + 'params': [ + { + 'name': 'w', + 'description': '

width of the offscreen graphics buffer

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

height of the offscreen graphics buffer

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

either P2D or WEBGL\n undefined defaults to p2d

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

existing html canvas element

\n', + 'type': 'HTMLCanvasElement', + 'optional': true + } + ] }, { - 'name': 'h', - 'description': '

height of the offscreen graphics buffer

\n', - 'type': 'Number' - }, + 'params': [ + { + 'name': 'w', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'h', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'canvas', + 'description': '', + 'type': 'HTMLCanvasElement', + 'optional': true + } + ] + } + ] + }, + 'createFramebuffer': { + 'name': 'createFramebuffer', + 'params': [ { - 'name': 'renderer', - 'description': '

either P2D or WEBGL\n undefined defaults to p2d

\n', - 'type': 'Constant', + 'name': 'options', + 'description': '

An optional object with configuration

\n', + 'type': 'Object', 'optional': true } ], @@ -3078,7 +3239,7 @@ 'params': [ { 'name': 'arr', - 'description': '

an array of numbers - should be 6 or 16 length (23 or 44 matrix values)

\n', + 'description': '

an array of numbers - should be 6 or 16 length (2×3 or 4×4 matrix values)

\n', 'type': 'Array' } ], @@ -3088,32 +3249,32 @@ 'params': [ { 'name': 'a', - 'description': '

numbers which define the 2×3 or 4x4 matrix to be multiplied

\n', + 'description': '

numbers which define the 2×3 or 4×4 matrix to be multiplied

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

numbers which define the 2×3 or 4x4 matrix to be multiplied

\n', + 'description': '

numbers which define the 2×3 or 4×4 matrix to be multiplied

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

numbers which define the 2×3 or 4x4 matrix to be multiplied

\n', + 'description': '

numbers which define the 2×3 or 4×4 matrix to be multiplied

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

numbers which define the 2×3 or 4x4 matrix to be multiplied

\n', + 'description': '

numbers which define the 2×3 or 4×4 matrix to be multiplied

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

numbers which define the 2×3 or 4x4 matrix to be multiplied

\n', + 'description': '

numbers which define the 2×3 or 4×4 matrix to be multiplied

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

numbers which define the 2×3 or 4x4 matrix to be multiplied

\n', + 'description': '

numbers which define the 2×3 or 4×4 matrix to be multiplied

\n', 'type': 'Number' } ], @@ -3153,52 +3314,52 @@ }, { 'name': 'g', - 'description': '

numbers which define the 4x4 matrix to be multiplied

\n', + 'description': '

numbers which define the 4×4 matrix to be multiplied

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

numbers which define the 4x4 matrix to be multiplied

\n', + 'description': '

numbers which define the 4×4 matrix to be multiplied

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

numbers which define the 4x4 matrix to be multiplied

\n', + 'description': '

numbers which define the 4×4 matrix to be multiplied

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

numbers which define the 4x4 matrix to be multiplied

\n', + 'description': '

numbers which define the 4×4 matrix to be multiplied

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

numbers which define the 4x4 matrix to be multiplied

\n', + 'description': '

numbers which define the 4×4 matrix to be multiplied

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

numbers which define the 4x4 matrix to be multiplied

\n', + 'description': '

numbers which define the 4×4 matrix to be multiplied

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

numbers which define the 4x4 matrix to be multiplied

\n', + 'description': '

numbers which define the 4×4 matrix to be multiplied

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

numbers which define the 4x4 matrix to be multiplied

\n', + 'description': '

numbers which define the 4×4 matrix to be multiplied

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

numbers which define the 4x4 matrix to be multiplied

\n', + 'description': '

numbers which define the 4×4 matrix to be multiplied

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

numbers which define the 4x4 matrix to be multiplied

\n', + 'description': '

numbers which define the 4×4 matrix to be multiplied

\n', 'type': 'Number' } ], @@ -3477,12 +3638,12 @@ 'params': [ { 'name': 'selectors', - 'description': '

CSS selector string of element to search for

\n', + 'description': '

CSS selector string of element to search for.

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

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

\n', + 'description': '

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

\n', 'type': 'String|p5.Element|HTMLElement', 'optional': true } @@ -3495,12 +3656,12 @@ 'params': [ { 'name': 'selectors', - 'description': '

CSS selector string of elements to search for

\n', + 'description': '

CSS selector string of element to search for.

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

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

\n', + 'description': '

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

\n', 'type': 'String|p5.Element|HTMLElement', 'optional': true } @@ -3518,7 +3679,7 @@ 'params': [ { 'name': 'fxn', - 'description': '

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

\n', + 'description': '

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

\n', 'type': 'Function|Boolean' } ], @@ -3530,7 +3691,7 @@ 'params': [ { 'name': 'fxn', - 'description': '

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

\n', + 'description': '

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

\n', 'type': 'Function|Boolean' } ], @@ -3542,7 +3703,7 @@ 'params': [ { 'name': 'html', - 'description': '

inner HTML for element created

\n', + 'description': '

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

\n', 'type': 'String', 'optional': true } @@ -3555,7 +3716,7 @@ 'params': [ { 'name': 'html', - 'description': '

inner HTML for element created

\n', + 'description': '

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

\n', 'type': 'String', 'optional': true } @@ -3568,7 +3729,7 @@ 'params': [ { 'name': 'html', - 'description': '

inner HTML for element created

\n', + 'description': '

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

\n', 'type': 'String', 'optional': true } @@ -3585,12 +3746,12 @@ 'params': [ { 'name': 'src', - 'description': '

src path or url for image

\n', + 'description': '

relative path or URL for the image.

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

alternate text to be used if image does not load. You can use also an empty string ("") if that an image is not intended to be viewed.

\n', + 'description': '

alternate text for the image.

\n', 'type': 'String' } ] @@ -3609,12 +3770,13 @@ }, { 'name': 'crossOrigin', - 'description': '

crossOrigin property of the img element; use either \'anonymous\' or \'use-credentials\' to retrieve the image with cross-origin access (for later use with canvas. if an empty string("") is passed, CORS is not used

\n', - 'type': 'String' + 'description': '

crossOrigin property to use when fetching the image.

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

callback to be called once image data is loaded with the p5.Element as argument

\n', + 'description': '

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

\n', 'type': 'Function', 'optional': true } @@ -3627,17 +3789,17 @@ 'params': [ { 'name': 'href', - 'description': '

url of page to link to

\n', + 'description': '

URL of linked page.

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

inner html of link element to display

\n', + 'description': '

inner HTML of link element to display.

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

target where new link should open,\n could be _blank, _self, _parent, _top.

\n', + 'description': '

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

\n', 'type': 'String', 'optional': true } @@ -3650,23 +3812,23 @@ 'params': [ { 'name': 'min', - 'description': '

minimum value of the slider

\n', + 'description': '

minimum value of the slider.

\n', 'type': 'Number' }, { 'name': 'max', - 'description': '

maximum value of the slider

\n', + 'description': '

maximum value of the slider.

\n', 'type': 'Number' }, { 'name': 'value', - 'description': '

default value of the slider

\n', + 'description': '

default value of the slider.

\n', 'type': 'Number', 'optional': true }, { 'name': 'step', - 'description': '

step size for each tick of the slider (if step is set to 0, the slider will move continuously from the minimum to the maximum value)

\n', + 'description': '

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

\n', 'type': 'Number', 'optional': true } @@ -3679,12 +3841,12 @@ 'params': [ { 'name': 'label', - 'description': '

label displayed on the button

\n', + 'description': '

label displayed on the button.

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

value of the button

\n', + 'description': '

value of the button.

\n', 'type': 'String', 'optional': true } @@ -3697,13 +3859,13 @@ 'params': [ { 'name': 'label', - 'description': '

label displayed after checkbox

\n', + 'description': '

label displayed after the checkbox.

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

value of the checkbox; checked is true, unchecked is false

\n', + 'description': '

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

\n', 'type': 'Boolean', 'optional': true } @@ -3720,7 +3882,7 @@ 'params': [ { 'name': 'multiple', - 'description': '

true if dropdown should support multiple selections

\n', + 'description': '

support multiple selections.

\n', 'type': 'Boolean', 'optional': true } @@ -3730,7 +3892,7 @@ 'params': [ { 'name': 'existing', - 'description': '

DOM select element

\n', + 'description': '

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

\n', 'type': 'Object' } ] @@ -3746,13 +3908,8 @@ 'params': [ { 'name': 'containerElement', - 'description': '

A container HTML Element, either a div\nor span, inside which all existing radio inputs will be considered as options.

\n', - 'type': 'Object' - }, - { - 'name': 'name', - 'description': '

A name parameter for each Input Element.

\n', - 'type': 'String', + 'description': '

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

\n', + 'type': 'Object', 'optional': true } ] @@ -3761,8 +3918,9 @@ 'params': [ { 'name': 'name', - 'description': '', - 'type': 'String' + 'description': '

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

\n', + 'type': 'String', + 'optional': true } ] }, @@ -3777,7 +3935,7 @@ 'params': [ { 'name': 'value', - 'description': '

default color of element

\n', + 'description': '

default color as a CSS color string.

\n', 'type': 'String|p5.Color', 'optional': true } @@ -3794,12 +3952,13 @@ 'params': [ { 'name': 'value', - 'description': '

default value of the input box

\n', - 'type': 'String' + 'description': '

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

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

type of text, ie text, password etc. Defaults to text.\n Needs a value to be specified first.

\n', + 'description': '

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

\n', 'type': 'String', 'optional': true } @@ -3822,12 +3981,12 @@ 'params': [ { 'name': 'callback', - 'description': '

callback function for when a file is loaded

\n', + 'description': '

function to call once the file loads.

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

optional, to allow multiple files to be selected

\n', + 'description': '

allow multiple files to be selected.

\n', 'type': 'Boolean', 'optional': true } @@ -3840,12 +3999,12 @@ 'params': [ { 'name': 'src', - 'description': '

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

\n', + 'description': '

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

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

callback function to be called upon\n \'canplaythrough\' event fire, that is, when the\n browser can play the media, and estimates that\n enough data has been loaded to play the media\n up to its end without having to stop for\n further buffering of content

\n', + 'description': '

function to call once the video is ready to play.

\n', 'type': 'Function', 'optional': true } @@ -3858,13 +4017,13 @@ 'params': [ { 'name': 'src', - 'description': '

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

\n', + 'description': '

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

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

callback function to be called upon\n \'canplaythrough\' event fire, that is, when the\n browser can play the media, and estimates that\n enough data has been loaded to play the media\n up to its end without having to stop for\n further buffering of content

\n', + 'description': '

function to call once the audio is ready to play.

\n', 'type': 'Function', 'optional': true } @@ -3877,12 +4036,13 @@ 'params': [ { 'name': 'type', - 'description': '

type of capture, either VIDEO or\n AUDIO if none specified, default both,\n or a Constraints object

\n', - 'type': 'String|Constant|Object' + 'description': '

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

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

function to be called once\n stream has loaded

\n', + 'description': '

function to call once the stream\n has loaded.

\n', 'type': 'Function', 'optional': true } @@ -3895,12 +4055,12 @@ 'params': [ { 'name': 'tag', - 'description': '

tag for the new element

\n', + 'description': '

tag for the new element.

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

html content to be inserted into the element

\n', + 'description': '

HTML content to insert into the element.

\n', 'type': 'String', 'optional': true } @@ -4038,7 +4198,7 @@ { 'name': 'event', 'description': '

optional KeyboardEvent callback argument.

\n', - 'type': 'Object', + 'type': 'KeyboardEvent', 'optional': true } ], @@ -4051,7 +4211,7 @@ { 'name': 'event', 'description': '

optional KeyboardEvent callback argument.

\n', - 'type': 'Object', + 'type': 'KeyboardEvent', 'optional': true } ], @@ -4064,7 +4224,7 @@ { 'name': 'event', 'description': '

optional KeyboardEvent callback argument.

\n', - 'type': 'Object', + 'type': 'KeyboardEvent', 'optional': true } ], @@ -4149,7 +4309,7 @@ { 'name': 'event', 'description': '

optional MouseEvent callback argument.

\n', - 'type': 'Object', + 'type': 'MouseEvent', 'optional': true } ], @@ -4162,7 +4322,7 @@ { 'name': 'event', 'description': '

optional MouseEvent callback argument.

\n', - 'type': 'Object', + 'type': 'MouseEvent', 'optional': true } ], @@ -4175,7 +4335,7 @@ { 'name': 'event', 'description': '

optional MouseEvent callback argument.

\n', - 'type': 'Object', + 'type': 'MouseEvent', 'optional': true } ], @@ -4188,7 +4348,7 @@ { 'name': 'event', 'description': '

optional MouseEvent callback argument.

\n', - 'type': 'Object', + 'type': 'MouseEvent', 'optional': true } ], @@ -4201,7 +4361,7 @@ { 'name': 'event', 'description': '

optional MouseEvent callback argument.

\n', - 'type': 'Object', + 'type': 'MouseEvent', 'optional': true } ], @@ -4214,7 +4374,7 @@ { 'name': 'event', 'description': '

optional MouseEvent callback argument.

\n', - 'type': 'Object', + 'type': 'MouseEvent', 'optional': true } ], @@ -4227,7 +4387,7 @@ { 'name': 'event', 'description': '

optional WheelEvent callback argument.

\n', - 'type': 'Object', + 'type': 'WheelEvent', 'optional': true } ], @@ -4255,7 +4415,7 @@ { 'name': 'event', 'description': '

optional TouchEvent callback argument.

\n', - 'type': 'Object', + 'type': 'TouchEvent', 'optional': true } ], @@ -4268,7 +4428,7 @@ { 'name': 'event', 'description': '

optional TouchEvent callback argument.

\n', - 'type': 'Object', + 'type': 'TouchEvent', 'optional': true } ], @@ -4281,7 +4441,7 @@ { 'name': 'event', 'description': '

optional TouchEvent callback argument.

\n', - 'type': 'Object', + 'type': 'TouchEvent', 'optional': true } ], @@ -4293,12 +4453,12 @@ 'params': [ { 'name': 'width', - 'description': '

width in pixels

\n', + 'description': '

width in pixels.

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

height in pixels

\n', + 'description': '

height in pixels.

\n', 'type': 'Integer' } ], @@ -4314,18 +4474,18 @@ 'params': [ { 'name': 'selectedCanvas', - 'description': '

a variable\n representing a specific html5 canvas (optional)

\n', - 'type': 'p5.Element|HTMLCanvasElement' + 'description': '

reference to a\n specific HTML5 canvas element.

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

file name. Defaults to \'untitled\'.

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

\'jpg\' or \'png\'

\n', + 'description': '

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

\n', 'type': 'String', 'optional': true } @@ -4354,27 +4514,27 @@ 'params': [ { 'name': 'filename', - 'description': '', + 'description': '

prefix of file name.

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

\'jpg\' or \'png\'

\n', + 'description': '

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

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

Duration in seconds to save the frames for. This parameter will be constrained to be less or equal to 15.

\n', + 'description': '

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

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

Framerate to save the frames in. This parameter will be constrained to be less or equal to 22.

\n', + 'description': '

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

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

A callback function that will be executed\n to handle the image data. This function\n should accept an array as argument. The\n array will contain the specified number of\n frames of objects. Each object has three\n properties: imageData - an\n image/octet-stream, filename and extension.

\n', + 'description': '

callback function that will be executed\n to handle the image data. This function\n should accept an array as argument. The\n array will contain the specified number of\n frames of objects. Each object has three\n properties: imageData, filename, and extension.

\n', 'type': 'Function(Array)', 'optional': true } @@ -4387,18 +4547,18 @@ 'params': [ { 'name': 'path', - 'description': '

Path of the image to be loaded

\n', + 'description': '

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

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

Function to be called once\n the image is loaded. Will be passed the\n p5.Image.

\n', + 'description': '

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

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

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

\n', + 'description': '

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

\n', 'type': 'Function(Event)', 'optional': true } @@ -4411,18 +4571,19 @@ 'params': [ { 'name': 'filename', - 'description': '

File name of your gif

\n', + 'description': '

file name of gif.

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

Duration in seconds that you wish to capture from your sketch

\n', + 'description': '

duration in seconds to capture from the sketch.

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

An optional object that can contain two more arguments: delay, specifying\nhow much time we should wait before recording, and units, a string that can be either \'seconds\' or\n\'frames\'. By default it\'s \'seconds\'.

\n', - 'type': 'Object' + 'description': '

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

\n', + 'type': 'Object', + 'optional': true } ], 'class': 'p5', @@ -4437,28 +4598,28 @@ 'params': [ { 'name': 'img', - 'description': '

the image to display

\n', - 'type': 'p5.Image|p5.Element|p5.Texture' + 'description': '

image to display.

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

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

\n', + 'description': '

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

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

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

\n', + 'description': '

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

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

the width to draw the image

\n', + 'description': '

width to draw the image.

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

the height to draw the image

\n', + 'description': '

height to draw the image.

\n', 'type': 'Number', 'optional': true } @@ -4469,7 +4630,7 @@ { 'name': 'img', 'description': '', - 'type': 'p5.Image|p5.Element|p5.Texture' + 'type': 'p5.Image|p5.Element|p5.Texture|p5.Framebuffer|p5.FramebufferTexture' }, { 'name': 'dx', @@ -4544,17 +4705,17 @@ 'params': [ { 'name': 'v1', - 'description': '

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

\n', + 'description': '

red or hue value.

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

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

\n', + 'description': '

green or saturation value.

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

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

\n', + 'description': '

blue or brightness.

\n', 'type': 'Number' }, { @@ -4569,7 +4730,7 @@ 'params': [ { 'name': 'value', - 'description': '

a color string

\n', + 'description': '

CSS color string.

\n', 'type': 'String' } ] @@ -4578,7 +4739,7 @@ 'params': [ { 'name': 'gray', - 'description': '

a gray value

\n', + 'description': '

grayscale value.

\n', 'type': 'Number' }, { @@ -4593,7 +4754,7 @@ 'params': [ { 'name': 'values', - 'description': '

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

\n', + 'description': '

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

\n', 'type': 'Number[]' } ] @@ -4619,7 +4780,7 @@ 'params': [ { 'name': 'mode', - 'description': '

either CORNER, CORNERS, or CENTER

\n', + 'description': '

either CORNER, CORNERS, or CENTER.

\n', 'type': 'Constant' } ], @@ -4640,47 +4801,47 @@ 'params': [ { 'name': 'srcImage', - 'description': '

source image

\n', + 'description': '

source image.

\n', 'type': 'p5.Image' }, { 'name': 'sx', - 'description': '

X coordinate of the source\'s upper left corner

\n', + 'description': '

x-coordinate of the source\'s upper-left corner.

\n', 'type': 'Integer' }, { 'name': 'sy', - 'description': '

Y coordinate of the source\'s upper left corner

\n', + 'description': '

y-coordinate of the source\'s upper-left corner.

\n', 'type': 'Integer' }, { 'name': 'sw', - 'description': '

source image width

\n', + 'description': '

source image width.

\n', 'type': 'Integer' }, { 'name': 'sh', - 'description': '

source image height

\n', + 'description': '

source image height.

\n', 'type': 'Integer' }, { 'name': 'dx', - 'description': '

X coordinate of the destination\'s upper left corner

\n', + 'description': '

x-coordinate of the destination\'s upper-left corner.

\n', 'type': 'Integer' }, { 'name': 'dy', - 'description': '

Y coordinate of the destination\'s upper left corner

\n', + 'description': '

y-coordinate of the destination\'s upper-left corner.

\n', 'type': 'Integer' }, { 'name': 'dw', - 'description': '

destination image width

\n', + 'description': '

destination image width.

\n', 'type': 'Integer' }, { 'name': 'dh', - 'description': '

destination image height

\n', + 'description': '

destination image height.

\n', 'type': 'Integer' }, { @@ -4750,47 +4911,47 @@ 'params': [ { 'name': 'srcImage', - 'description': '

source image

\n', + 'description': '

source image.

\n', 'type': 'p5.Image|p5.Element' }, { 'name': 'sx', - 'description': '

X coordinate of the source\'s upper left corner

\n', + 'description': '

x-coordinate of the source\'s upper-left corner.

\n', 'type': 'Integer' }, { 'name': 'sy', - 'description': '

Y coordinate of the source\'s upper left corner

\n', + 'description': '

y-coordinate of the source\'s upper-left corner.

\n', 'type': 'Integer' }, { 'name': 'sw', - 'description': '

source image width

\n', + 'description': '

source image width.

\n', 'type': 'Integer' }, { 'name': 'sh', - 'description': '

source image height

\n', + 'description': '

source image height.

\n', 'type': 'Integer' }, { 'name': 'dx', - 'description': '

X coordinate of the destination\'s upper left corner

\n', + 'description': '

x-coordinate of the destination\'s upper-left corner.

\n', 'type': 'Integer' }, { 'name': 'dy', - 'description': '

Y coordinate of the destination\'s upper left corner

\n', + 'description': '

y-coordinate of the destination\'s upper-left corner.

\n', 'type': 'Integer' }, { 'name': 'dw', - 'description': '

destination image width

\n', + 'description': '

destination image width.

\n', 'type': 'Integer' }, { 'name': 'dh', - 'description': '

destination image height

\n', + 'description': '

destination image height.

\n', 'type': 'Integer' } ] @@ -4843,21 +5004,55 @@ }, 'filter': { 'name': 'filter', - 'params': [ + 'class': 'p5', + 'module': 'Image', + 'overloads': [ { - 'name': 'filterType', - 'description': '

either THRESHOLD, GRAY, OPAQUE, INVERT,\n POSTERIZE, BLUR, ERODE, DILATE or BLUR.\n See Filters.js for docs on\n each available filter

\n', - 'type': 'Constant' + 'params': [ + { + 'name': 'filterType', + 'description': '

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

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

parameter unique to each filter.

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

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

\n', + 'type': 'Boolean', + 'optional': true + } + ] }, { - 'name': 'filterParam', - 'description': '

an optional parameter unique\n to each filter, see above

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

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

\n', + 'type': 'p5.Shader' + } + ] } - ], - 'class': 'p5', - 'module': 'Image' + ] }, 'get': { 'name': 'get', @@ -4868,22 +5063,22 @@ 'params': [ { 'name': 'x', - 'description': '

x-coordinate of the pixel

\n', + 'description': '

x-coordinate of the pixel.

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

y-coordinate of the pixel

\n', + 'description': '

y-coordinate of the pixel.

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

width

\n', + 'description': '

width of the subsection to be returned.

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

height

\n', + 'description': '

height of the subsection to be returned.

\n', 'type': 'Number' } ] @@ -4918,17 +5113,17 @@ 'params': [ { 'name': 'x', - 'description': '

x-coordinate of the pixel

\n', + 'description': '

x-coordinate of the pixel.

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

y-coordinate of the pixel

\n', + 'description': '

y-coordinate of the pixel.

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

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

\n', + 'description': '

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

\n', 'type': 'Number|Number[]|Object' } ], @@ -4940,25 +5135,25 @@ 'params': [ { 'name': 'x', - 'description': '

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

\n', + 'description': '

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

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

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

\n', + 'description': '

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

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

width of region to update

\n', + 'description': '

width of region to update.

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

height of region to update

\n', + 'description': '

height of region to update.

\n', 'type': 'Number', 'optional': true } @@ -5527,7 +5722,7 @@ 'params': [ { 'name': 'n', - 'description': '

number to compute

\n', + 'description': '

number to compute.

\n', 'type': 'Number' } ], @@ -5539,7 +5734,7 @@ 'params': [ { 'name': 'n', - 'description': '

number to round up

\n', + 'description': '

number to round up.

\n', 'type': 'Number' } ], @@ -5551,17 +5746,17 @@ 'params': [ { 'name': 'n', - 'description': '

number to constrain

\n', + 'description': '

number to constrain.

\n', 'type': 'Number' }, { 'name': 'low', - 'description': '

minimum limit

\n', + 'description': '

minimum limit.

\n', 'type': 'Number' }, { 'name': 'high', - 'description': '

maximum limit

\n', + 'description': '

maximum limit.

\n', 'type': 'Number' } ], @@ -5577,22 +5772,22 @@ 'params': [ { 'name': 'x1', - 'description': '

x-coordinate of the first point

\n', + 'description': '

x-coordinate of the first point.

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

y-coordinate of the first point

\n', + 'description': '

y-coordinate of the first point.

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

x-coordinate of the second point

\n', + 'description': '

x-coordinate of the second point.

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

y-coordinate of the second point

\n', + 'description': '

y-coordinate of the second point.

\n', 'type': 'Number' } ] @@ -5611,7 +5806,7 @@ }, { 'name': 'z1', - 'description': '

z-coordinate of the first point

\n', + 'description': '

z-coordinate of the first point.

\n', 'type': 'Number' }, { @@ -5626,7 +5821,7 @@ }, { 'name': 'z2', - 'description': '

z-coordinate of the second point

\n', + 'description': '

z-coordinate of the second point.

\n', 'type': 'Number' } ] @@ -5638,7 +5833,7 @@ 'params': [ { 'name': 'n', - 'description': '

exponent to raise

\n', + 'description': '

exponent to raise.

\n', 'type': 'Number' } ], @@ -5650,7 +5845,7 @@ 'params': [ { 'name': 'n', - 'description': '

number to round down

\n', + 'description': '

number to round down.

\n', 'type': 'Number' } ], @@ -5662,17 +5857,17 @@ 'params': [ { 'name': 'start', - 'description': '

first value

\n', + 'description': '

first value.

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

second value

\n', + 'description': '

second value.

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

number

\n', + 'description': '

number.

\n', 'type': 'Number' } ], @@ -5684,7 +5879,7 @@ 'params': [ { 'name': 'n', - 'description': '

number greater than 0

\n', + 'description': '

number greater than 0.

\n', 'type': 'Number' } ], @@ -5695,13 +5890,13 @@ 'name': 'mag', 'params': [ { - 'name': 'a', - 'description': '

first value

\n', + 'name': 'x', + 'description': '

first component.

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

second value

\n', + 'name': 'y', + 'description': '

second component.

\n', 'type': 'Number' } ], @@ -5713,32 +5908,32 @@ 'params': [ { 'name': 'value', - 'description': '

the incoming value to be converted

\n', + 'description': '

the incoming value to be converted.

\n', 'type': 'Number' }, { 'name': 'start1', - 'description': '

lower bound of the value\'s current range

\n', + 'description': '

lower bound of the value\'s current range.

\n', 'type': 'Number' }, { 'name': 'stop1', - 'description': '

upper bound of the value\'s current range

\n', + 'description': '

upper bound of the value\'s current range.

\n', 'type': 'Number' }, { 'name': 'start2', - 'description': '

lower bound of the value\'s target range

\n', + 'description': '

lower bound of the value\'s target range.

\n', 'type': 'Number' }, { 'name': 'stop2', - 'description': '

upper bound of the value\'s target range

\n', + 'description': '

upper bound of the value\'s target range.

\n', 'type': 'Number' }, { 'name': 'withinBounds', - 'description': '

constrain the value to the newly mapped range

\n', + 'description': '

constrain the value to the newly mapped range.

\n', 'type': 'Boolean', 'optional': true } @@ -5755,12 +5950,12 @@ 'params': [ { 'name': 'n0', - 'description': '

Number to compare

\n', + 'description': '

first number to compare.

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

Number to compare

\n', + 'description': '

second number to compare.

\n', 'type': 'Number' } ] @@ -5769,7 +5964,7 @@ 'params': [ { 'name': 'nums', - 'description': '

Numbers to compare

\n', + 'description': '

numbers to compare.

\n', 'type': 'Number[]' } ] @@ -5785,12 +5980,12 @@ 'params': [ { 'name': 'n0', - 'description': '

Number to compare

\n', + 'description': '

first number to compare.

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

Number to compare

\n', + 'description': '

second number to compare.

\n', 'type': 'Number' } ] @@ -5799,7 +5994,7 @@ 'params': [ { 'name': 'nums', - 'description': '

Numbers to compare

\n', + 'description': '

numbers to compare.

\n', 'type': 'Number[]' } ] @@ -5811,17 +6006,17 @@ 'params': [ { 'name': 'value', - 'description': '

incoming value to be normalized

\n', + 'description': '

incoming value to be normalized.

\n', 'type': 'Number' }, { 'name': 'start', - 'description': '

lower bound of the value\'s current range

\n', + 'description': '

lower bound of the value\'s current range.

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

upper bound of the value\'s current range

\n', + 'description': '

upper bound of the value\'s current range.

\n', 'type': 'Number' } ], @@ -5833,12 +6028,12 @@ 'params': [ { 'name': 'n', - 'description': '

base of the exponential expression

\n', + 'description': '

base of the exponential expression.

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

power by which to raise the base

\n', + 'description': '

power by which to raise the base.

\n', 'type': 'Number' } ], @@ -5850,12 +6045,12 @@ 'params': [ { 'name': 'n', - 'description': '

number to round

\n', + 'description': '

number to round.

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

number of decimal places to round to, default is 0

\n', + 'description': '

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

\n', 'type': 'Number', 'optional': true } @@ -5868,7 +6063,7 @@ 'params': [ { 'name': 'n', - 'description': '

number to square

\n', + 'description': '

number to square.

\n', 'type': 'Number' } ], @@ -5880,7 +6075,7 @@ 'params': [ { 'name': 'n', - 'description': '

non-negative number to square root

\n', + 'description': '

non-negative number to square root.

\n', 'type': 'Number' } ], @@ -5891,8 +6086,8 @@ 'name': 'fract', 'params': [ { - 'name': 'num', - 'description': '

Number whose fractional part needs to be found out

\n', + 'name': 'n', + 'description': '

number whose fractional part will be found.

\n', 'type': 'Number' } ], @@ -5904,19 +6099,19 @@ 'params': [ { 'name': 'x', - 'description': '

x component of the vector

\n', + 'description': '

x component of the vector.

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

y component of the vector

\n', + 'description': '

y component of the vector.

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

z component of the vector

\n', + 'description': '

z component of the vector.

\n', 'type': 'Number', 'optional': true } @@ -5929,18 +6124,18 @@ 'params': [ { 'name': 'x', - 'description': '

x-coordinate in noise space

\n', + 'description': '

x-coordinate in noise space.

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

y-coordinate in noise space

\n', + 'description': '

y-coordinate in noise space.

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

z-coordinate in noise space

\n', + 'description': '

z-coordinate in noise space.

\n', 'type': 'Number', 'optional': true } @@ -5953,12 +6148,12 @@ 'params': [ { 'name': 'lod', - 'description': '

number of octaves to be used by the noise

\n', + 'description': '

number of octaves to be used by the noise.

\n', 'type': 'Number' }, { 'name': 'falloff', - 'description': '

falloff factor for each octave

\n', + 'description': '

falloff factor for each octave.

\n', 'type': 'Number' } ], @@ -5970,7 +6165,7 @@ 'params': [ { 'name': 'seed', - 'description': '

the seed value

\n', + 'description': '

seed value.

\n', 'type': 'Number' } ], @@ -5982,7 +6177,7 @@ 'params': [ { 'name': 'seed', - 'description': '

the seed value

\n', + 'description': '

seed value.

\n', 'type': 'Number' } ], @@ -5998,13 +6193,13 @@ 'params': [ { 'name': 'min', - 'description': '

the lower bound (inclusive)

\n', + 'description': '

lower bound (inclusive).

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

the upper bound (exclusive)

\n', + 'description': '

upper bound (exclusive).

\n', 'type': 'Number', 'optional': true } @@ -6014,7 +6209,7 @@ 'params': [ { 'name': 'choices', - 'description': '

the array to choose from

\n', + 'description': '

array to choose from.

\n', 'type': 'Array' } ] @@ -6026,13 +6221,13 @@ 'params': [ { 'name': 'mean', - 'description': '

the mean

\n', + 'description': '

mean.

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

the standard deviation

\n', + 'description': '

standard deviation.

\n', 'type': 'Number', 'optional': true } @@ -6045,7 +6240,7 @@ 'params': [ { 'name': 'value', - 'description': '

the value whose arc cosine is to be returned

\n', + 'description': '

value whose arc cosine is to be returned.

\n', 'type': 'Number' } ], @@ -6057,7 +6252,7 @@ 'params': [ { 'name': 'value', - 'description': '

the value whose arc sine is to be returned

\n', + 'description': '

value whose arc sine is to be returned.

\n', 'type': 'Number' } ], @@ -6069,7 +6264,7 @@ 'params': [ { 'name': 'value', - 'description': '

the value whose arc tangent is to be returned

\n', + 'description': '

value whose arc tangent is to be returned.

\n', 'type': 'Number' } ], @@ -6081,12 +6276,12 @@ 'params': [ { 'name': 'y', - 'description': '

y-coordinate of the point

\n', + 'description': '

y-coordinate of the point.

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

x-coordinate of the point

\n', + 'description': '

x-coordinate of the point.

\n', 'type': 'Number' } ], @@ -6098,7 +6293,7 @@ 'params': [ { 'name': 'angle', - 'description': '

the angle

\n', + 'description': '

the angle.

\n', 'type': 'Number' } ], @@ -6110,7 +6305,7 @@ 'params': [ { 'name': 'angle', - 'description': '

the angle

\n', + 'description': '

the angle.

\n', 'type': 'Number' } ], @@ -6122,7 +6317,7 @@ 'params': [ { 'name': 'angle', - 'description': '

the angle

\n', + 'description': '

the angle.

\n', 'type': 'Number' } ], @@ -6134,7 +6329,7 @@ 'params': [ { 'name': 'radians', - 'description': '

the radians value to convert to degrees

\n', + 'description': '

radians value to convert to degrees.

\n', 'type': 'Number' } ], @@ -6146,7 +6341,7 @@ 'params': [ { 'name': 'degrees', - 'description': '

the degree value to convert to radians

\n', + 'description': '

degree value to convert to radians.

\n', 'type': 'Number' } ], @@ -6162,7 +6357,7 @@ 'params': [ { 'name': 'mode', - 'description': '

either RADIANS or DEGREES

\n', + 'description': '

either RADIANS or DEGREES.

\n', 'type': 'Constant' } ] @@ -6182,12 +6377,12 @@ 'params': [ { 'name': 'horizAlign', - 'description': '

horizontal alignment, either LEFT,\n CENTER, or RIGHT

\n', + 'description': '

horizontal alignment, either LEFT,\n CENTER, or RIGHT.

\n', 'type': 'Constant' }, { 'name': 'vertAlign', - 'description': '

vertical alignment, either TOP,\n BOTTOM, CENTER, or BASELINE

\n', + 'description': '

vertical alignment, either TOP,\n BOTTOM, CENTER, or BASELINE.

\n', 'type': 'Constant', 'optional': true } @@ -6209,7 +6404,7 @@ 'params': [ { 'name': 'leading', - 'description': '

the size in pixels for spacing between lines

\n', + 'description': '

spacing between lines of text in units of pixels.

\n', 'type': 'Number' } ], @@ -6229,8 +6424,8 @@ { 'params': [ { - 'name': 'theSize', - 'description': '

the size of the letters in units of pixels

\n', + 'name': 'size', + 'description': '

size of the letters in units of pixels

\n', 'type': 'Number' } ], @@ -6250,7 +6445,7 @@ { 'params': [ { - 'name': 'theStyle', + 'name': 'style', 'description': '

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

\n', 'type': 'Constant' } @@ -6267,8 +6462,8 @@ 'name': 'textWidth', 'params': [ { - 'name': 'theText', - 'description': '

the String of characters to measure

\n', + 'name': 'str', + 'description': '

string of text to measure.

\n', 'type': 'String' } ], @@ -6289,8 +6484,8 @@ 'name': 'textWrap', 'params': [ { - 'name': 'wrapStyle', - 'description': '

text wrapping style, either WORD or CHAR

\n', + 'name': 'style', + 'description': '

text wrapping style, either WORD or CHAR.

\n', 'type': 'Constant' } ], @@ -6302,18 +6497,18 @@ 'params': [ { 'name': 'path', - 'description': '

name of the file or url to load

\n', + 'description': '

path of the font to be loaded.

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

function to be executed after\n loadFont() completes

\n', + 'name': 'successCallback', + 'description': '

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

\n', 'type': 'Function', 'optional': true }, { - 'name': 'onError', - 'description': '

function to be executed if\n an error occurs

\n', + 'name': 'failureCallback', + 'description': '

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

\n', 'type': 'Function', 'optional': true } @@ -6326,28 +6521,28 @@ 'params': [ { 'name': 'str', - 'description': '

the alphanumeric\n symbols to be displayed

\n', + 'description': '

text to be displayed.

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

x-coordinate of text

\n', + 'description': '

x-coordinate of the text box.

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

y-coordinate of text

\n', + 'description': '

y-coordinate of the text box.

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

by default, the width of the text box,\n see rectMode() for more info

\n', + 'name': 'maxWidth', + 'description': '

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

\n', 'type': 'Number', 'optional': true }, { - 'name': 'y2', - 'description': '

by default, the height of the text box,\n see rectMode() for more info

\n', + 'name': 'maxHeight', + 'description': '

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

\n', 'type': 'Number', 'optional': true } @@ -6368,12 +6563,12 @@ 'params': [ { 'name': 'font', - 'description': '

a font loaded via loadFont(),\nor a String representing a web safe font\n(a font that is generally available across all systems)

\n', + 'description': '

font as a p5.Font object or a string.

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

the font size to use

\n', + 'description': '

font size in pixels.

\n', 'type': 'Number', 'optional': true } @@ -7105,6 +7300,40 @@ 'class': 'p5', 'module': 'IO' }, + 'beginGeometry': { + 'name': 'beginGeometry', + 'class': 'p5', + 'module': 'Shape' + }, + 'endGeometry': { + 'name': 'endGeometry', + 'class': 'p5', + 'module': 'Shape' + }, + 'buildGeometry': { + 'name': 'buildGeometry', + 'params': [ + { + 'name': 'callback', + 'description': '

A function that draws shapes.

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

The geometry whose resources should be freed

\n', + 'type': 'p5.Geometry' + } + ], + 'class': 'p5', + 'module': 'Shape' + }, 'plane': { 'name': 'plane', 'params': [ @@ -7366,6 +7595,12 @@ 'description': '

sensitivity to scroll movement along Z axis

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

An optional object that can contain additional settings,\ndisableTouchActions - Boolean, default value is true.\nSetting this to true makes mobile interactions smoother by preventing\naccidental interactions with the page while orbiting. But if you\'re already\ndoing it via css or want the default touch actions, consider setting it to false.\nfreeRotation - Boolean, default value is false.\nBy default, horizontal movement of the mouse or touch pointer rotates the camera\naround the y-axis, and vertical movement rotates the camera around the x-axis.\nBut if setting this option to true, the camera always rotates in the direction\nthe pointer is moving. For zoom and move, the behavior is the same regardless of\ntrue/false.

\n', + 'type': 'Object', + 'optional': true } ], 'class': 'p5', @@ -7886,6 +8121,18 @@ } ] }, + 'imageLight': { + 'name': 'imageLight', + 'params': [ + { + 'name': 'img', + 'description': '

image for the background

\n', + 'type': 'p5.image' + } + ], + 'class': 'p5', + 'module': '3D' + }, 'lights': { 'name': 'lights', 'class': 'p5', @@ -8418,6 +8665,18 @@ 'class': 'p5', 'module': '3D' }, + 'createFilterShader': { + 'name': 'createFilterShader', + 'params': [ + { + 'name': 'fragSrc', + 'description': '

source code for the fragment shader

\n', + 'type': 'String' + } + ], + 'class': 'p5', + 'module': '3D' + }, 'shader': { 'name': 'shader', 'params': [ @@ -8441,7 +8700,7 @@ { 'name': 'tex', 'description': '

image to use as texture

\n', - 'type': 'p5.Image|p5.MediaElement|p5.Graphics|p5.Texture' + 'type': 'p5.Image|p5.MediaElement|p5.Graphics|p5.Texture|p5.Framebuffer|p5.FramebufferTexture' } ], 'class': 'p5', @@ -8848,6 +9107,33 @@ 'class': 'p5', 'module': '3D' }, + 'vertexNormal': { + 'name': 'vertexNormal', + 'params': [ + { + 'name': 'x', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'v', + 'description': '', + 'type': 'Vector' + } + ], + 'class': 'p5', + 'module': 'Shape' + }, 'setAttributes': { 'name': 'setAttributes', 'class': 'p5', @@ -9074,7 +9360,7 @@ 'params': [ { 'name': 'format', - 'description': '

How the color string will be formatted.\nLeaving this empty formats the string as rgba(r, g, b, a).\n\'#rgb\' \'#rgba\' \'#rrggbb\' and \'#rrggbbaa\' format as hexadecimal color codes.\n\'rgb\' \'hsb\' and \'hsl\' return the color formatted in the specified color mode.\n\'rgba\' \'hsba\' and \'hsla\' are the same as above but with alpha channels.\n\'rgb%\' \'hsb%\' \'hsl%\' \'rgba%\' \'hsba%\' and \'hsla%\' format as percentages.

\n', + 'description': '

how the color string will be formatted.\nLeaving this empty formats the string as rgba(r, g, b, a).\n\'#rgb\' \'#rgba\' \'#rrggbb\' and \'#rrggbbaa\' format as hexadecimal color codes.\n\'rgb\' \'hsb\' and \'hsl\' return the color formatted in the specified color mode.\n\'rgba\' \'hsba\' and \'hsla\' are the same as above but with alpha channels.\n\'rgb%\' \'hsb%\' \'hsl%\' \'rgba%\' \'hsba%\' and \'hsla%\' format as percentages.

\n', 'type': 'String', 'optional': true } @@ -9087,7 +9373,7 @@ 'params': [ { 'name': 'red', - 'description': '

the new red value

\n', + 'description': '

the new red value.

\n', 'type': 'Number' } ], @@ -9099,7 +9385,7 @@ 'params': [ { 'name': 'green', - 'description': '

the new green value

\n', + 'description': '

the new green value.

\n', 'type': 'Number' } ], @@ -9111,7 +9397,7 @@ 'params': [ { 'name': 'blue', - 'description': '

the new blue value

\n', + 'description': '

the new blue value.

\n', 'type': 'Number' } ], @@ -9123,7 +9409,7 @@ 'params': [ { 'name': 'alpha', - 'description': '

the new alpha value

\n', + 'description': '

the new alpha value.

\n', 'type': 'Number' } ], @@ -9137,6 +9423,16 @@ 'class': 'p5.Element', 'module': 'DOM' }, + 'width': { + 'name': 'width', + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'height': { + 'name': 'height', + 'class': 'p5.Element', + 'module': 'DOM' + }, 'parent': { 'name': 'parent', 'class': 'p5.Element', @@ -9146,7 +9442,7 @@ 'params': [ { 'name': 'parent', - 'description': '

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

\n', + 'description': '

ID, p5.Element,\n or HTMLElement of desired parent element.

\n', 'type': 'String|p5.Element|Object' } ], @@ -9167,7 +9463,7 @@ 'params': [ { 'name': 'id', - 'description': '

ID of the element

\n', + 'description': '

ID of the element.

\n', 'type': 'String' } ], @@ -9188,7 +9484,7 @@ 'params': [ { 'name': 'class', - 'description': '

class to add

\n', + 'description': '

class to add.

\n', 'type': 'String' } ], @@ -9205,7 +9501,7 @@ 'params': [ { 'name': 'fxn', - 'description': '

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

\n', + 'description': '

function to call when the mouse is\n pressed over the element.\n false disables the function.

\n', 'type': 'Function|Boolean' } ], @@ -9217,7 +9513,7 @@ 'params': [ { 'name': 'fxn', - 'description': '

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

\n', + 'description': '

function to call when the mouse is\n double clicked over the element.\n false disables the function.

\n', 'type': 'Function|Boolean' } ], @@ -9229,7 +9525,7 @@ 'params': [ { 'name': 'fxn', - 'description': '

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

\n', + 'description': '

function to call when the mouse wheel is\n scrolled over the element.\n false disables the function.

\n', 'type': 'Function|Boolean' } ], @@ -9241,7 +9537,7 @@ 'params': [ { 'name': 'fxn', - 'description': '

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

\n', + 'description': '

function to call when the mouse is\n pressed over the element.\n false disables the function.

\n', 'type': 'Function|Boolean' } ], @@ -9253,7 +9549,7 @@ 'params': [ { 'name': 'fxn', - 'description': '

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

\n', + 'description': '

function to call when the mouse is\n pressed and released over the element.\n false disables the function.

\n', 'type': 'Function|Boolean' } ], @@ -9265,7 +9561,7 @@ 'params': [ { 'name': 'fxn', - 'description': '

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

\n', + 'description': '

function to call when the mouse\n moves over the element.\n false disables the function.

\n', 'type': 'Function|Boolean' } ], @@ -9277,7 +9573,7 @@ 'params': [ { 'name': 'fxn', - 'description': '

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

\n', + 'description': '

function to call when the mouse\n moves onto the element.\n false disables the function.

\n', 'type': 'Function|Boolean' } ], @@ -9289,7 +9585,7 @@ 'params': [ { 'name': 'fxn', - 'description': '

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

\n', + 'description': '

function to call when the mouse\n moves off the element.\n false disables the function.

\n', 'type': 'Function|Boolean' } ], @@ -9301,7 +9597,7 @@ 'params': [ { 'name': 'fxn', - 'description': '

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

\n', + 'description': '

function to call when the touch\n starts.\n false disables the function.

\n', 'type': 'Function|Boolean' } ], @@ -9313,7 +9609,7 @@ 'params': [ { 'name': 'fxn', - 'description': '

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

\n', + 'description': '

function to call when the touch\n moves over the element.\n false disables the function.

\n', 'type': 'Function|Boolean' } ], @@ -9325,7 +9621,7 @@ 'params': [ { 'name': 'fxn', - 'description': '

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

\n', + 'description': '

function to call when the touch\n ends.\n false disables the function.

\n', 'type': 'Function|Boolean' } ], @@ -9337,7 +9633,7 @@ 'params': [ { 'name': 'fxn', - 'description': '

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

\n', + 'description': '

function to call when the file is\n dragged over the element.\n false disables the function.

\n', 'type': 'Function|Boolean' } ], @@ -9349,7 +9645,7 @@ 'params': [ { 'name': 'fxn', - 'description': '

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

\n', + 'description': '

function to call when the file is\n dragged off the element.\n false disables the function.

\n', 'type': 'Function|Boolean' } ], @@ -9510,7 +9806,7 @@ 'params': [ { 'name': 'property', - 'description': '

property to be set

\n', + 'description': '

style property to set.

\n', 'type': 'String' } ] @@ -9524,7 +9820,7 @@ }, { 'name': 'value', - 'description': '

value to assign to property

\n', + 'description': '

value to assign to the property.

\n', 'type': 'String|p5.Color' } ], @@ -9545,12 +9841,12 @@ 'params': [ { 'name': 'attr', - 'description': '

attribute to set

\n', + 'description': '

attribute to set.

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

value to assign to attribute

\n', + 'description': '

value to assign to the attribute.

\n', 'type': 'String' } ], @@ -9563,7 +9859,7 @@ 'params': [ { 'name': 'attr', - 'description': '

attribute to remove

\n', + 'description': '

attribute to remove.

\n', 'type': 'String' } ], @@ -9614,12 +9910,12 @@ 'params': [ { 'name': 'w', - 'description': '

width of the element, either AUTO, or a number

\n', + 'description': '

width of the element, either AUTO, or a number.

\n', 'type': 'Number|Constant' }, { 'name': 'h', - 'description': '

height of the element, either AUTO, or a number

\n', + 'description': '

height of the element, either AUTO, or a number.

\n', 'type': 'Number|Constant', 'optional': true } @@ -9638,18 +9934,31 @@ 'params': [ { 'name': 'callback', - 'description': '

callback to receive loaded file, called for each file dropped.

\n', + 'description': '

called when a file loads. Called once for each file dropped.

\n', 'type': 'Function' }, { 'name': 'fxn', - 'description': '

callback triggered once when files are dropped with the drop event.

\n', + 'description': '

called once when any files are dropped.

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

pass another p5.Element

\n', + 'type': 'p5.Element', + 'optional': true + } + ], + 'class': 'p5.Element', + 'module': 'DOM' } }, 'p5.Graphics': { @@ -9662,6 +9971,11 @@ 'name': 'remove', 'class': 'p5.Graphics', 'module': 'Rendering' + }, + 'createFramebuffer': { + 'name': 'createFramebuffer', + 'class': 'p5.Graphics', + 'module': 'Rendering' } }, 'JSON': { @@ -9928,8 +10242,9 @@ 'params': [ { 'name': 'shouldAutoplay', - 'description': '

whether the element should autoplay

\n', - 'type': 'Boolean' + 'description': '

whether the element should autoplay.

\n', + 'type': 'Boolean', + 'optional': true } ], 'class': 'p5.MediaElement', @@ -9948,7 +10263,7 @@ 'params': [ { 'name': 'val', - 'description': '

volume between 0.0 and 1.0

\n', + 'description': '

volume between 0.0 and 1.0.

\n', 'type': 'Number' } ], @@ -9969,7 +10284,7 @@ 'params': [ { 'name': 'speed', - 'description': '

speed multiplier for element playback

\n', + 'description': '

speed multiplier for playback.

\n', 'type': 'Number' } ], @@ -9990,7 +10305,7 @@ 'params': [ { 'name': 'time', - 'description': '

time to jump to (in seconds)

\n', + 'description': '

time to jump to (in seconds).

\n', 'type': 'Number' } ], @@ -10008,7 +10323,7 @@ 'params': [ { 'name': 'callback', - 'description': '

function to call when the\n soundfile has ended. The\n media element will be passed\n in as the argument to the\n callback.

\n', + 'description': '

function to call when playback ends.\n The p5.MediaElement is passed as\n the argument.

\n', 'type': 'Function' } ], @@ -10047,17 +10362,17 @@ 'params': [ { 'name': 'time', - 'description': '

Time in seconds, relative to this media\n element\'s playback. For example, to trigger\n an event every time playback reaches two\n seconds, pass in the number 2. This will be\n passed as the first parameter to\n the callback function.

\n', + 'description': '

cue time to run the callback function.

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

Name of a function that will be\n called at the given time. The callback will\n receive time and (optionally) param as its\n two parameters.

\n', + 'description': '

function to call at the cue time.

\n', 'type': 'Function' }, { 'name': 'value', - 'description': '

An object to be passed as the\n second parameter to the\n callback function.

\n', + 'description': '

object to pass as the argument to\n callback.

\n', 'type': 'Object', 'optional': true } @@ -10070,7 +10385,7 @@ 'params': [ { 'name': 'id', - 'description': '

ID of the cue, as returned by addCue

\n', + 'description': '

ID of the cue, created by media.addCue().

\n', 'type': 'Number' } ], @@ -10079,13 +10394,6 @@ }, 'clearCues': { 'name': 'clearCues', - 'params': [ - { - 'name': 'id', - 'description': '

ID of the cue, as returned by addCue

\n', - 'type': 'Number' - } - ], 'class': 'p5.MediaElement', 'module': 'DOM' } @@ -10138,6 +10446,19 @@ 'class': 'p5.Image', 'module': 'Image' }, + 'pixelDensity': { + 'name': 'pixelDensity', + 'params': [ + { + 'name': 'density', + 'description': '

A scaling factor for the number of pixels per\nside

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Image', + 'module': 'Image' + }, 'loadPixels': { 'name': 'loadPixels', 'class': 'p5.Image', @@ -10152,22 +10473,22 @@ 'params': [ { 'name': 'x', - 'description': '

x-offset of the target update area for the\n underlying canvas

\n', + 'description': '

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

\n', 'type': 'Integer' }, { 'name': 'y', - 'description': '

y-offset of the target update area for the\n underlying canvas

\n', + 'description': '

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

\n', 'type': 'Integer' }, { 'name': 'w', - 'description': '

width of the target update area for the\n underlying canvas

\n', + 'description': '

width of the subsection to update.

\n', 'type': 'Integer' }, { 'name': 'h', - 'description': '

height of the target update area for the\n underlying canvas

\n', + 'description': '

height of the subsection to update.

\n', 'type': 'Integer' } ] @@ -10187,22 +10508,22 @@ 'params': [ { 'name': 'x', - 'description': '

x-coordinate of the pixel

\n', + 'description': '

x-coordinate of the pixel.

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

y-coordinate of the pixel

\n', + 'description': '

y-coordinate of the pixel.

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

width

\n', + 'description': '

width of the subsection to be returned.

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

height

\n', + 'description': '

height of the subsection to be returned.

\n', 'type': 'Number' } ] @@ -10232,17 +10553,17 @@ 'params': [ { 'name': 'x', - 'description': '

x-coordinate of the pixel

\n', + 'description': '

x-coordinate of the pixel.

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

y-coordinate of the pixel

\n', + 'description': '

y-coordinate of the pixel.

\n', 'type': 'Number' }, { 'name': 'a', - 'description': '

grayscale value | pixel array |\n a p5.Color | image to copy

\n', + 'description': '

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

\n', 'type': 'Number|Number[]|Object' } ], @@ -10254,12 +10575,12 @@ 'params': [ { 'name': 'width', - 'description': '

the resized image width

\n', + 'description': '

resized image width.

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

the resized image height

\n', + 'description': '

resized image height.

\n', 'type': 'Number' } ], @@ -10275,47 +10596,47 @@ 'params': [ { 'name': 'srcImage', - 'description': '

source image

\n', + 'description': '

source image.

\n', 'type': 'p5.Image|p5.Element' }, { 'name': 'sx', - 'description': '

X coordinate of the source\'s upper left corner

\n', + 'description': '

x-coordinate of the source\'s upper-left corner.

\n', 'type': 'Integer' }, { 'name': 'sy', - 'description': '

Y coordinate of the source\'s upper left corner

\n', + 'description': '

y-coordinate of the source\'s upper-left corner.

\n', 'type': 'Integer' }, { 'name': 'sw', - 'description': '

source image width

\n', + 'description': '

source image width.

\n', 'type': 'Integer' }, { 'name': 'sh', - 'description': '

source image height

\n', + 'description': '

source image height.

\n', 'type': 'Integer' }, { 'name': 'dx', - 'description': '

X coordinate of the destination\'s upper left corner

\n', + 'description': '

x-coordinate of the destination\'s upper-left corner.

\n', 'type': 'Integer' }, { 'name': 'dy', - 'description': '

Y coordinate of the destination\'s upper left corner

\n', + 'description': '

y-coordinate of the destination\'s upper-left corner.

\n', 'type': 'Integer' }, { 'name': 'dw', - 'description': '

destination image width

\n', + 'description': '

destination image width.

\n', 'type': 'Integer' }, { 'name': 'dh', - 'description': '

destination image height

\n', + 'description': '

destination image height.

\n', 'type': 'Integer' } ] @@ -10371,7 +10692,7 @@ 'params': [ { 'name': 'srcImage', - 'description': '

source image

\n', + 'description': '

source image.

\n', 'type': 'p5.Image' } ], @@ -10383,12 +10704,12 @@ 'params': [ { 'name': 'filterType', - 'description': '

either THRESHOLD, GRAY, OPAQUE, INVERT,\n POSTERIZE, ERODE, DILATE or BLUR.\n See Filters.js for docs on\n each available filter

\n', + 'description': '

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

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

an optional parameter unique\n to each filter, see above

\n', + 'description': '

parameter unique to each filter.

\n', 'type': 'Number', 'optional': true } @@ -10410,42 +10731,42 @@ }, { 'name': 'sx', - 'description': '

X coordinate of the source\'s upper left corner

\n', + 'description': '

x-coordinate of the source\'s upper-left corner.

\n', 'type': 'Integer' }, { 'name': 'sy', - 'description': '

Y coordinate of the source\'s upper left corner

\n', + 'description': '

y-coordinate of the source\'s upper-left corner.

\n', 'type': 'Integer' }, { 'name': 'sw', - 'description': '

source image width

\n', + 'description': '

source image width.

\n', 'type': 'Integer' }, { 'name': 'sh', - 'description': '

source image height

\n', + 'description': '

source image height.

\n', 'type': 'Integer' }, { 'name': 'dx', - 'description': '

X coordinate of the destination\'s upper left corner

\n', + 'description': '

x-coordinate of the destination\'s upper-left corner.

\n', 'type': 'Integer' }, { 'name': 'dy', - 'description': '

Y coordinate of the destination\'s upper left corner

\n', + 'description': '

y-coordinate of the destination\'s upper-left corner.

\n', 'type': 'Integer' }, { 'name': 'dw', - 'description': '

destination image width

\n', + 'description': '

destination image width.

\n', 'type': 'Integer' }, { 'name': 'dh', - 'description': '

destination image height

\n', + 'description': '

destination image height.

\n', 'type': 'Integer' }, { @@ -10511,13 +10832,14 @@ 'params': [ { 'name': 'filename', - 'description': '

give your file a name

\n', + 'description': '

filename. Defaults to \'untitled\'.

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

\'png\' or \'jpg\'

\n', - 'type': 'String' + 'description': '

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

\n', + 'type': 'String', + 'optional': true } ], 'class': 'p5.Image', @@ -10538,7 +10860,7 @@ 'params': [ { 'name': 'index', - 'description': '

the index for the frame that should be displayed

\n', + 'description': '

index of the frame to display.

\n', 'type': 'Number' } ], @@ -10565,12 +10887,12 @@ 'params': [ { 'name': 'd', - 'description': '

the amount in milliseconds to delay between switching frames

\n', + 'description': '

delay in milliseconds between switching frames.

\n', 'type': 'Number' }, { 'name': 'index', - 'description': '

the index of the frame that should have the new delay value {optional}

\n', + 'description': '

index of the frame that will have its delay modified.

\n', 'type': 'Number', 'optional': true } @@ -11263,19 +11585,19 @@ 'params': [ { 'name': 'x', - 'description': '

The x component of the vector

\n', + 'description': '

x component of the vector.

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

The y component of the vector

\n', + 'description': '

y component of the vector.

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

The z component of the vector

\n', + 'description': '

z component of the vector.

\n', 'type': 'Number', 'optional': true } @@ -11286,7 +11608,7 @@ 'params': [ { 'name': 'value', - 'description': '

The vector to set

\n', + 'description': '

vector to set.

\n', 'type': 'p5.Vector|Number[]' } ], @@ -11324,18 +11646,18 @@ 'params': [ { 'name': 'x', - 'description': '

The x component of the vector to be added

\n', + 'description': '

x component of the vector to be added.

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

The y component of the vector to be added

\n', + 'description': '

y component of the vector to be added.

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

The z component of the vector to be added

\n', + 'description': '

z component of the vector to be added.

\n', 'type': 'Number', 'optional': true } @@ -11366,7 +11688,7 @@ }, { 'name': 'target', - 'description': '

The vector to receive the result

\n', + 'description': '

vector to receive the result.

\n', 'type': 'p5.Vector', 'optional': true } @@ -11384,17 +11706,17 @@ 'params': [ { 'name': 'x', - 'description': '

The x component of divisor vector

\n', + 'description': '

x component of divisor vector.

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

The y component of divisor vector

\n', + 'description': '

y component of divisor vector.

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

The z component of divisor vector

\n', + 'description': '

z component of divisor vector.

\n', 'type': 'Number' } ], @@ -11404,7 +11726,7 @@ 'params': [ { 'name': 'value', - 'description': '

The divisor vector

\n', + 'description': '

divisor vector.

\n', 'type': 'p5.Vector | Number[]' } ], @@ -11451,18 +11773,18 @@ 'params': [ { 'name': 'x', - 'description': '

The x component of the vector to subtract

\n', + 'description': '

x component of the vector to subtract.

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

The y component of the vector to subtract

\n', + 'description': '

y component of the vector to subtract.

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

The z component of the vector to subtract

\n', + 'description': '

z component of the vector to subtract.

\n', 'type': 'Number', 'optional': true } @@ -11493,7 +11815,7 @@ }, { 'name': 'target', - 'description': '

The vector to receive the result

\n', + 'description': '

vector to receive the result.

\n', 'type': 'p5.Vector', 'optional': true } @@ -11521,17 +11843,17 @@ 'params': [ { 'name': 'x', - 'description': '

The number to multiply with the x component of the vector

\n', + 'description': '

number to multiply with the x component of the vector.

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

The number to multiply with the y component of the vector

\n', + 'description': '

number to multiply with the y component of the vector.

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

The number to multiply with the z component of the vector

\n', + 'description': '

number to multiply with the z component of the vector.

\n', 'type': 'Number', 'optional': true } @@ -11542,7 +11864,7 @@ 'params': [ { 'name': 'arr', - 'description': '

The array to multiply with the components of the vector

\n', + 'description': '

array to multiply with the components of the vector.

\n', 'type': 'Number[]' } ], @@ -11552,7 +11874,7 @@ 'params': [ { 'name': 'v', - 'description': '

The vector to multiply with the components of the original vector

\n', + 'description': '

vector to multiply with the components of the original vector.

\n', 'type': 'p5.Vector' } ], @@ -11593,7 +11915,7 @@ }, { 'name': 'target', - 'description': '

the vector to receive the result

\n', + 'description': '

vector to receive the result.

\n', 'type': 'p5.Vector', 'optional': true } @@ -11663,17 +11985,17 @@ 'params': [ { 'name': 'x', - 'description': '

The number to divide with the x component of the vector

\n', + 'description': '

number to divide with the x component of the vector.

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

The number to divide with the y component of the vector

\n', + 'description': '

number to divide with the y component of the vector.

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

The number to divide with the z component of the vector

\n', + 'description': '

number to divide with the z component of the vector.

\n', 'type': 'Number', 'optional': true } @@ -11684,7 +12006,7 @@ 'params': [ { 'name': 'arr', - 'description': '

The array to divide the components of the vector by

\n', + 'description': '

array to divide the components of the vector by.

\n', 'type': 'Number[]' } ], @@ -11694,7 +12016,7 @@ 'params': [ { 'name': 'v', - 'description': '

The vector to divide the components of the original vector by

\n', + 'description': '

vector to divide the components of the original vector by.

\n', 'type': 'p5.Vector' } ], @@ -11837,18 +12159,18 @@ 'params': [ { 'name': 'x', - 'description': '

The x component of the vector

\n', + 'description': '

x component of the vector.

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

The y component of the vector

\n', + 'description': '

y component of the vector.

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

The z component of the vector

\n', + 'description': '

z component of the vector.

\n', 'type': 'Number', 'optional': true } @@ -11857,8 +12179,8 @@ { 'params': [ { - 'name': 'value', - 'description': '

value component of the vector or a p5.Vector

\n', + 'name': 'v', + 'description': '

p5.Vector to be dotted.

\n', 'type': 'p5.Vector' } ] @@ -11867,12 +12189,12 @@ 'params': [ { 'name': 'v1', - 'description': '

The first p5.Vector

\n', + 'description': '

first p5.Vector.

\n', 'type': 'p5.Vector' }, { 'name': 'v2', - 'description': '

The second p5.Vector

\n', + 'description': '

second p5.Vector.

\n', 'type': 'p5.Vector' } ], @@ -11889,7 +12211,7 @@ 'params': [ { 'name': 'v', - 'description': '

p5.Vector to be crossed

\n', + 'description': '

p5.Vector to be crossed.

\n', 'type': 'p5.Vector' } ] @@ -11898,12 +12220,12 @@ 'params': [ { 'name': 'v1', - 'description': '

The first p5.Vector

\n', + 'description': '

first p5.Vector.

\n', 'type': 'p5.Vector' }, { 'name': 'v2', - 'description': '

The second p5.Vector

\n', + 'description': '

second p5.Vector.

\n', 'type': 'p5.Vector' } ], @@ -11920,7 +12242,7 @@ 'params': [ { 'name': 'v', - 'description': '

The x, y, and z coordinates of a p5.Vector

\n', + 'description': '

x, y, and z coordinates of a p5.Vector.

\n', 'type': 'p5.Vector' } ] @@ -11978,7 +12300,7 @@ 'params': [ { 'name': 'max', - 'description': '

The maximum magnitude for the vector

\n', + 'description': '

maximum magnitude for the vector.

\n', 'type': 'Number' } ], @@ -12016,7 +12338,7 @@ 'params': [ { 'name': 'len', - 'description': '

The new length for this vector

\n', + 'description': '

new length for this vector.

\n', 'type': 'Number' } ], @@ -12071,7 +12393,7 @@ 'params': [ { 'name': 'angle', - 'description': '

The angle of rotation

\n', + 'description': '

angle of rotation.

\n', 'type': 'Number' } ], @@ -12087,7 +12409,7 @@ 'params': [ { 'name': 'angle', - 'description': '

The angle of rotation

\n', + 'description': '

angle of rotation.

\n', 'type': 'Number' } ], @@ -12125,7 +12447,7 @@ 'params': [ { 'name': 'value', - 'description': '

The x, y, and z components of a p5.Vector

\n', + 'description': '

x, y, and z components of a p5.Vector.

\n', 'type': 'p5.Vector' } ] @@ -12134,12 +12456,12 @@ 'params': [ { 'name': 'v1', - 'description': '

the first vector

\n', + 'description': '

the first vector.

\n', 'type': 'p5.Vector' }, { 'name': 'v2', - 'description': '

the second vector

\n', + 'description': '

the second vector.

\n', 'type': 'p5.Vector' } ], @@ -12156,22 +12478,22 @@ 'params': [ { 'name': 'x', - 'description': '

The x component

\n', + 'description': '

x component.

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

The y component

\n', + 'description': '

y component.

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

The z component

\n', + 'description': '

z component.

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

The amount of interpolation; some value between 0.0\n (old vector) and 1.0 (new vector). 0.9 is very near\n the new vector. 0.5 is halfway in between.

\n', + 'description': '

amount of interpolation between 0.0 (old vector)\n and 1.0 (new vector). 0.5 is halfway between.

\n', 'type': 'Number' } ], @@ -12181,7 +12503,7 @@ 'params': [ { 'name': 'v', - 'description': '

The p5.Vector to lerp to

\n', + 'description': '

p5.Vector to lerp toward.

\n', 'type': 'p5.Vector' }, { @@ -12220,6 +12542,53 @@ } ] }, + 'slerp': { + 'name': 'slerp', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'v', + 'description': '

p5.Vector to slerp toward.

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

amount of interpolation between 0.0 (old vector)\n and 1.0 (new vector). 0.5 is halfway between.

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

old vector.

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

new vector.

\n', + 'type': 'p5.Vector' + }, + { + 'name': 'amt', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'target', + 'description': '

vector to receive the result.

\n', + 'type': 'p5.Vector', + 'optional': true + } + ], + 'static': 1 + } + ] + }, 'reflect': { 'name': 'reflect', 'class': 'p5.Vector', @@ -12229,7 +12598,7 @@ 'params': [ { 'name': 'surfaceNormal', - 'description': '

the p5.Vector\n to reflect about.

\n', + 'description': '

p5.Vector\n to reflect about.

\n', 'type': 'p5.Vector' } ], @@ -12239,7 +12608,7 @@ 'params': [ { 'name': 'incidentVector', - 'description': '

vector to be reflected

\n', + 'description': '

vector to be reflected.

\n', 'type': 'p5.Vector' }, { @@ -12249,7 +12618,7 @@ }, { 'name': 'target', - 'description': '

the vector to receive the result (Optional)

\n', + 'description': '

vector to receive the result.

\n', 'type': 'p5.Vector', 'optional': true } @@ -12288,19 +12657,19 @@ 'params': [ { 'name': 'x', - 'description': '

The x component of the vector

\n', + 'description': '

x component of the vector.

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

The y component of the vector

\n', + 'description': '

y component of the vector.

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

The z component of the vector

\n', + 'description': '

z component of the vector.

\n', 'type': 'Number', 'optional': true } @@ -12310,7 +12679,7 @@ 'params': [ { 'name': 'value', - 'description': '

The vector to compare

\n', + 'description': '

vector to compare.

\n', 'type': 'p5.Vector|Array' } ] @@ -12337,12 +12706,12 @@ 'params': [ { 'name': 'angle', - 'description': '

The desired angle, in radians (unaffected by angleMode)

\n', + 'description': '

desired angle, in radians. Unaffected by angleMode().

\n', 'type': 'Number' }, { 'name': 'length', - 'description': '

The length of the new vector (defaults to 1)

\n', + 'description': '

length of the new vector (defaults to 1).

\n', 'type': 'Number', 'optional': true } @@ -12355,17 +12724,17 @@ 'params': [ { 'name': 'theta', - 'description': '

The polar angle, in radians (zero is up)

\n', + 'description': '

polar angle in radians (zero is up).

\n', 'type': 'Number' }, { 'name': 'phi', - 'description': '

The azimuthal angle, in radians\n (zero is out of the screen)

\n', + 'description': '

azimuthal angle in radians\n (zero is out of the screen).

\n', 'type': 'Number' }, { 'name': 'length', - 'description': '

The length of the new vector (defaults to 1)

\n', + 'description': '

length of the new vector (defaults to 1).

\n', 'type': 'Number', 'optional': true } @@ -12394,31 +12763,25 @@ 'name': 'textBounds', 'params': [ { - 'name': 'line', - 'description': '

a line of text

\n', + 'name': 'str', + 'description': '

string of text.

\n', 'type': 'String' }, { 'name': 'x', - 'description': '

x-position

\n', + 'description': '

x-coordinate of the text.

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

y-position

\n', + 'description': '

y-coordinate of the text.

\n', 'type': 'Number' }, { 'name': 'fontSize', - 'description': '

font size to use (optional) Default is 12.

\n', + 'description': '

font size. Defaults to the current\n textSize().

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

opentype options (optional)\n opentype fonts contains alignment and baseline options.\n Default is \'LEFT\' and \'alphabetic\'

\n', - 'type': 'Object', - 'optional': true } ], 'class': 'p5.Font', @@ -12428,28 +12791,29 @@ 'name': 'textToPoints', 'params': [ { - 'name': 'txt', - 'description': '

a line of text

\n', + 'name': 'str', + 'description': '

string of text.

\n', 'type': 'String' }, { 'name': 'x', - 'description': '

x-position

\n', + 'description': '

x-coordinate of the text.

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

y-position

\n', + 'description': '

y-coordinate of the text.

\n', 'type': 'Number' }, { 'name': 'fontSize', - 'description': '

font size to use (optional)

\n', - 'type': 'Number' + 'description': '

font size. Defaults to the current\n textSize().

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

an (optional) object that can contain:

\n


sampleFactor - the ratio of path-length to number of samples\n(default=.1); higher values yield more points and are therefore\nmore precise

\n


simplifyThreshold - if set to a non-zero value, collinear points will be\nbe removed from the polygon; the value represents the threshold angle to use\nwhen determining whether two edges are collinear

\n', + 'description': '

object with sampleFactor and simplifyThreshold\n properties.

\n', 'type': 'Object', 'optional': true } @@ -12613,9 +12977,189 @@ ], 'class': 'p5.Camera', 'module': '3D' + }, + 'set': { + 'name': 'set', + 'params': [ + { + 'name': 'cam', + 'description': '

source camera

\n', + 'type': 'p5.Camera' + } + ], + 'class': 'p5.Camera', + 'module': '3D' + }, + 'slerp': { + 'name': 'slerp', + 'params': [ + { + 'name': 'cam0', + 'description': '

first p5.Camera

\n', + 'type': 'p5.Camera' + }, + { + 'name': 'cam1', + 'description': '

second p5.Camera

\n', + 'type': 'p5.Camera' + }, + { + 'name': 'amt', + 'description': '

amount to use for interpolation during slerp

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Camera', + 'module': '3D' + } + }, + 'p5.Framebuffer': { + 'pixels': { + 'name': 'pixels', + 'class': 'p5.Framebuffer', + 'module': 'Rendering' + }, + 'resize': { + 'name': 'resize', + 'params': [ + { + 'name': 'width', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'height', + 'description': '', + 'type': 'Number' + } + ], + 'class': 'p5.Framebuffer', + 'module': 'Rendering' + }, + 'pixelDensity': { + 'name': 'pixelDensity', + 'params': [ + { + 'name': 'density', + 'description': '

A scaling factor for the number of pixels per\nside of the framebuffer

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

Whether or not the framebuffer should resize\nalong with the canvas it\'s attached to

\n', + 'type': 'Boolean', + 'optional': true + } + ], + 'class': 'p5.Framebuffer', + 'module': 'Rendering' + }, + 'createCamera': { + 'name': 'createCamera', + 'class': 'p5.Framebuffer', + 'module': 'Rendering' + }, + 'remove': { + 'name': 'remove', + 'class': 'p5.Framebuffer', + 'module': 'Rendering' + }, + 'begin': { + 'name': 'begin', + 'class': 'p5.Framebuffer', + 'module': 'Rendering' + }, + 'end': { + 'name': 'end', + 'class': 'p5.Framebuffer', + 'module': 'Rendering' + }, + 'draw': { + 'name': 'draw', + 'params': [ + { + 'name': 'callback', + 'description': '

A function to run that draws to the canvas. The\nfunction will immediately be run, but it will draw to the framebuffer\ninstead of the canvas.

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

x-coordinate of the pixel

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

y-coordinate of the pixel

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

width of the section to be returned

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

height of the section to be returned

\n', + 'type': 'Number' + } + ] + }, + { + 'params': [ + ] + }, + { + 'params': [ + { + 'name': 'x', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '', + 'type': 'Number' + } + ] + } + ] + }, + 'color': { + 'name': 'color', + 'class': 'p5.Framebuffer', + 'module': 'Rendering' + }, + 'depth': { + 'name': 'depth', + 'class': 'p5.Framebuffer', + 'module': 'Rendering' } }, 'p5.Geometry': { + 'clearColors': { + 'name': 'clearColors', + 'class': 'p5.Geometry', + 'module': 'Shape' + }, 'computeFaces': { 'name': 'computeFaces', 'class': 'p5.Geometry', @@ -12623,6 +13167,20 @@ }, 'computeNormals': { 'name': 'computeNormals', + 'params': [ + { + 'name': 'shadingType', + 'description': '

shading type (FLAT for flat shading or SMOOTH for smooth shading) for buildGeometry() outputs. Defaults to FLAT.

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

An optional object with configuration.

\n', + 'type': 'Object', + 'optional': true + } + ], 'class': 'p5.Geometry', 'module': 'Shape' }, @@ -12643,6 +13201,18 @@ } }, 'p5.Shader': { + 'copyToContext': { + 'name': 'copyToContext', + 'params': [ + { + 'name': 'context', + 'description': '

The graphic or instance to copy this shader to.\nPass window if you need to copy to the main canvas.

\n', + 'type': 'p5|p5.Graphics' + } + ], + 'class': 'p5.Shader', + 'module': '3D' + }, 'setUniform': { 'name': 'setUniform', 'params': [ @@ -15907,7 +16477,7 @@ 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. + } // Support decoding URL-safe base64 strings, as Node.js does. // See: https://en.wikipedia.org/wiki/Base64#URL_applications revLookup['-'.charCodeAt(0)] = 62; @@ -15916,7 +16486,7 @@ 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 + } // Trim off extra bytes after placeholder bytes are found // See: https://github.com/beatgammit/base64-js/issues/42 var validLen = b64.indexOf('='); @@ -15924,7 +16494,7 @@ var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4; return [validLen, placeHoldersLen]; - } // base64 is 4/3 + up to two characters of the original data + } // base64 is 4/3 + up to two characters of the original data function byteLength(b64) { var lens = getLens(b64); @@ -15941,7 +16511,8 @@ 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 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) { @@ -15984,7 +16555,7 @@ // 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 + } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1]; @@ -16075,7 +16646,7 @@ function createBuffer(length) { if (length > K_MAX_LENGTH) { throw new RangeError('The value "' + length + '" is invalid for option "size"'); - } // Return an augmented `Uint8Array` instance + } // Return an augmented `Uint8Array` instance var buf = new Uint8Array(length); Object.setPrototypeOf(buf, Buffer.prototype); @@ -16099,7 +16670,7 @@ return allocUnsafe(arg); } return from(arg, encodingOrOffset, length); - } // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + } // 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, { @@ -16147,7 +16718,8 @@ Buffer.from = function (value, encodingOrOffset, length) { return from(value, encodingOrOffset, length); - }; // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: + }; + // 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); @@ -16234,7 +16806,7 @@ buf = new Uint8Array(array, byteOffset); } else { buf = new Uint8Array(array, byteOffset, length); - } // Return an augmented `Uint8Array` instance + } // Return an augmented `Uint8Array` instance Object.setPrototypeOf(buf, Buffer.prototype); return buf; @@ -16356,7 +16928,8 @@ } 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 + if (!mustMatch && len === 0) return 0; + // Use a for loop to avoid recursion var loweredCase = false; for (; ; ) { switch (encoding) { @@ -16387,7 +16960,8 @@ } 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 + 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. @@ -16395,7 +16969,7 @@ // 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 + } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { @@ -16406,7 +16980,7 @@ } if (end <= 0) { return ''; - } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0; start >>>= 0; @@ -16439,7 +17013,7 @@ loweredCase = true; } } - } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) + } // 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 @@ -16559,7 +17133,8 @@ if (x < y) return - 1; if (y < x) return 1; return 0; - }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + }; + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: @@ -16570,7 +17145,8 @@ // - 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 (buffer.length === 0) return - 1; + // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset; byteOffset = 0; @@ -16583,7 +17159,7 @@ 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 + } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset; if (byteOffset >= buffer.length) { @@ -16592,11 +17168,11 @@ } else if (byteOffset < 0) { if (dir) byteOffset = 0; else return - 1; - } // Normalize val + } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding); - } // Finally, search either indexOf (if dir is true) or lastIndexOf + } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails @@ -16720,11 +17296,13 @@ if (offset === undefined) { encoding = 'utf8'; length = this.length; - offset = 0; // Buffer#write(string, encoding) + 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]) + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset >>> 0; if (isFinite(length)) { @@ -16850,7 +17428,7 @@ i += bytesPerSequence; } return decodeCodePointsArray(res); - } // Based on http://stackoverflow.com/a/22747272/680742, the browser with + } // 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 @@ -16859,7 +17437,7 @@ 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". + } // Decode in chunks to avoid "call stack size exceeded". var res = ''; var i = 0; @@ -16919,7 +17497,8 @@ end = len; } if (end < start) end = start; - var newBuf = this.subarray(start, end); // Return an augmented `Uint8Array` instance + var newBuf = this.subarray(start, end); + // Return an augmented `Uint8Array` instance Object.setPrototypeOf(newBuf, Buffer.prototype); return newBuf; }; @@ -17252,21 +17831,25 @@ }; Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert); - }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + }; + // 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 > 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 (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 < 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; @@ -17284,7 +17867,8 @@ Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart); } return len; - }; // Usage: + }; + // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) @@ -17316,7 +17900,7 @@ val = val & 255; } else if (typeof val === 'boolean') { val = Number(val); - } // Invalid ranges are not set to a default, so can range check early. + } // 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'); @@ -17343,14 +17927,18 @@ } } return this; - }; // HELPER FUNCTIONS + }; + // 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 + 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 + '='; } @@ -17364,7 +17952,8 @@ var bytes = [ ]; for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); // is surrogate component + codePoint = string.charCodeAt(i); + // is surrogate component if (codePoint > 55295 && codePoint < 57344) { // last char was a lead if (!leadSurrogate) { @@ -17377,24 +17966,25 @@ // unpaired lead if ((units -= 3) > - 1) bytes.push(239, 191, 189); continue; - } // valid lead + } // valid lead leadSurrogate = codePoint; continue; - } // 2 leads in a row + } // 2 leads in a row if (codePoint < 56320) { if ((units -= 3) > - 1) bytes.push(239, 191, 189); leadSurrogate = codePoint; continue; - } // valid surrogate pair + } // valid surrogate pair codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > - 1) bytes.push(239, 191, 189); } - leadSurrogate = null; // encode utf8 + leadSurrogate = null; + // encode utf8 if (codePoint < 128) { if ((units -= 1) < 0) break; bytes.push(codePoint); @@ -17447,7 +18037,7 @@ dst[i + offset] = src[i]; } return i; - } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass + } // 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 @@ -17457,7 +18047,7 @@ function numberIsNaN(obj) { // For IE11 support return obj !== obj; // eslint-disable-line no-self-compare - } // Create lookup table for `toString('hex')` + } // Create lookup table for `toString('hex')` // See: https://github.com/feross/buffer/issues/219 var hexSliceLookupTable = function () { @@ -17476,7 +18066,7 @@ { 'base64-js': 20, 'buffer': 22, - 'ieee754': 260 + 'ieee754': 268 } ], 23: [ @@ -17511,14 +18101,15 @@ var create = _dereq_('../internals/object-create'); var definePropertyModule = _dereq_('../internals/object-define-property'); var UNSCOPABLES = wellKnownSymbol('unscopables'); - var ArrayPrototype = Array.prototype; // Array.prototype[@@unscopables] + var ArrayPrototype = Array.prototype; + // Array.prototype[@@unscopables] // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables if (ArrayPrototype[UNSCOPABLES] == undefined) { definePropertyModule.f(ArrayPrototype, UNSCOPABLES, { configurable: true, value: create(null) }); - } // add a key to Array.prototype[@@unscopables] + } // add a key to Array.prototype[@@unscopables] module.exports = function (key) { ArrayPrototype[UNSCOPABLES][key] = true; @@ -17527,13 +18118,14 @@ { '../internals/object-create': 108, '../internals/object-define-property': 110, - '../internals/well-known-symbol': 164 + '../internals/well-known-symbol': 166 } ], 26: [ function (_dereq_, module, exports) { 'use strict'; - var charAt = _dereq_('../internals/string-multibyte').charAt; // `AdvanceStringIndex` abstract operation + var charAt = _dereq_('../internals/string-multibyte').charAt; + // `AdvanceStringIndex` abstract operation // https://tc39.github.io/ecma262/#sec-advancestringindex module.exports = function (S, index, unicode) { return index + (unicode ? charAt(S, index).length : 1); @@ -17601,7 +18193,8 @@ var ObjectPrototype = Object.prototype; var isPrototypeOf = ObjectPrototype.isPrototypeOf; var TO_STRING_TAG = wellKnownSymbol('toStringTag'); - var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG'); // Fixing native typed arrays in Opera Presto crashes the browser, see #595 + var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG'); + // Fixing native typed arrays in Opera Presto crashes the browser, see #595 var NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(global.opera) !== 'Opera'; var TYPED_ARRAY_TAG_REQIRED = false; var NAME; @@ -17665,8 +18258,7 @@ // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable try { return redefine(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && Int8Array[KEY] || property); - } catch (error) { - /* empty */ + } catch (error) { /* empty */ } } else return; } @@ -17679,7 +18271,7 @@ }; for (NAME in TypedArrayConstructorsList) { if (!global[NAME]) NATIVE_ARRAY_BUFFER_VIEWS = false; - } // WebKit bug - typed arrays constructors prototype is Object.prototype + } // WebKit bug - typed arrays constructors prototype is Object.prototype if (!NATIVE_ARRAY_BUFFER_VIEWS || typeof TypedArray != 'function' || TypedArray === Function.prototype) { // eslint-disable-next-line no-shadow @@ -17695,7 +18287,7 @@ if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) { if (global[NAME]) setPrototypeOf(global[NAME].prototype, TypedArrayPrototype); } - } // WebKit bug - one more object in Uint8ClampedArray prototype chain + } // WebKit bug - one more object in Uint8ClampedArray prototype chain if (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) { setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype); @@ -17736,8 +18328,8 @@ '../internals/object-get-prototype-of': 115, '../internals/object-set-prototype-of': 119, '../internals/redefine': 126, - '../internals/uid': 161, - '../internals/well-known-symbol': 164 + '../internals/uid': 163, + '../internals/well-known-symbol': 166 } ], 31: [ @@ -17865,30 +18457,24 @@ getUint8: function getUint8(byteOffset) { return get(this, 1, byteOffset) [0]; }, - getInt16: function getInt16(byteOffset /* , littleEndian */ - ) { + getInt16: function getInt16(byteOffset /* , littleEndian */ ) { var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined); return (bytes[1] << 8 | bytes[0]) << 16 >> 16; }, - getUint16: function getUint16(byteOffset /* , littleEndian */ - ) { + getUint16: function getUint16(byteOffset /* , littleEndian */ ) { var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined); return bytes[1] << 8 | bytes[0]; }, - getInt32: function getInt32(byteOffset /* , littleEndian */ - ) { + getInt32: function getInt32(byteOffset /* , littleEndian */ ) { return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined)); }, - getUint32: function getUint32(byteOffset /* , littleEndian */ - ) { + getUint32: function getUint32(byteOffset /* , littleEndian */ ) { return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined)) >>> 0; }, - getFloat32: function getFloat32(byteOffset /* , littleEndian */ - ) { + getFloat32: function getFloat32(byteOffset /* , littleEndian */ ) { return unpackIEEE754(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 23); }, - getFloat64: function getFloat64(byteOffset /* , littleEndian */ - ) { + getFloat64: function getFloat64(byteOffset /* , littleEndian */ ) { return unpackIEEE754(get(this, 8, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 52); }, setInt8: function setInt8(byteOffset, value) { @@ -17897,28 +18483,22 @@ setUint8: function setUint8(byteOffset, value) { set(this, 1, byteOffset, packInt8, value); }, - setInt16: function setInt16(byteOffset, value /* , littleEndian */ - ) { + setInt16: function setInt16(byteOffset, value /* , littleEndian */ ) { set(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined); }, - setUint16: function setUint16(byteOffset, value /* , littleEndian */ - ) { + setUint16: function setUint16(byteOffset, value /* , littleEndian */ ) { set(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined); }, - setInt32: function setInt32(byteOffset, value /* , littleEndian */ - ) { + setInt32: function setInt32(byteOffset, value /* , littleEndian */ ) { set(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined); }, - setUint32: function setUint32(byteOffset, value /* , littleEndian */ - ) { + setUint32: function setUint32(byteOffset, value /* , littleEndian */ ) { set(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined); }, - setFloat32: function setFloat32(byteOffset, value /* , littleEndian */ - ) { + setFloat32: function setFloat32(byteOffset, value /* , littleEndian */ ) { set(this, 4, byteOffset, packFloat32, value, arguments.length > 2 ? arguments[2] : undefined); }, - setFloat64: function setFloat64(byteOffset, value /* , littleEndian */ - ) { + setFloat64: function setFloat64(byteOffset, value /* , littleEndian */ ) { set(this, 8, byteOffset, packFloat64, value, arguments.length > 2 ? arguments[2] : undefined); } }); @@ -17944,11 +18524,11 @@ } } ArrayBufferPrototype.constructor = $ArrayBuffer; - } // WebKit bug - the same parent prototype for typed arrays and data view + } // WebKit bug - the same parent prototype for typed arrays and data view if (setPrototypeOf && getPrototypeOf($DataViewPrototype) !== ObjectPrototype) { setPrototypeOf($DataViewPrototype, ObjectPrototype); - } // iOS Safari 7.x bug + } // iOS Safari 7.x bug var testView = new $DataView(new $ArrayBuffer(2)); var nativeSetInt8 = $DataViewPrototype.setInt8; @@ -17988,9 +18568,9 @@ '../internals/object-set-prototype-of': 119, '../internals/redefine-all': 125, '../internals/set-to-string-tag': 135, - '../internals/to-index': 149, - '../internals/to-integer': 151, - '../internals/to-length': 152 + '../internals/to-index': 151, + '../internals/to-integer': 153, + '../internals/to-length': 154 } ], 32: [ @@ -17999,12 +18579,11 @@ var toObject = _dereq_('../internals/to-object'); var toAbsoluteIndex = _dereq_('../internals/to-absolute-index'); var toLength = _dereq_('../internals/to-length'); - var min = Math.min; // `Array.prototype.copyWithin` method implementation + var min = Math.min; + // `Array.prototype.copyWithin` method implementation // https://tc39.github.io/ecma262/#sec-array.prototype.copywithin module.exports = [ - ].copyWithin || function copyWithin(target /* = 0 */ - , start /* = 0, end = @length */ - ) { + ].copyWithin || function copyWithin(target /* = 0 */ , start /* = 0, end = @length */ ) { var O = toObject(this); var len = toLength(O.length); var to = toAbsoluteIndex(target, len); @@ -18027,9 +18606,9 @@ }; }, { - '../internals/to-absolute-index': 148, - '../internals/to-length': 152, - '../internals/to-object': 153 + '../internals/to-absolute-index': 150, + '../internals/to-length': 154, + '../internals/to-object': 155 } ], 33: [ @@ -18037,10 +18616,10 @@ 'use strict'; var toObject = _dereq_('../internals/to-object'); var toAbsoluteIndex = _dereq_('../internals/to-absolute-index'); - var toLength = _dereq_('../internals/to-length'); // `Array.prototype.fill` method implementation + var toLength = _dereq_('../internals/to-length'); + // `Array.prototype.fill` method implementation // https://tc39.github.io/ecma262/#sec-array.prototype.fill - module.exports = function fill(value /* , start = 0, end = @length */ - ) { + module.exports = function fill(value /* , start = 0, end = @length */ ) { var O = toObject(this); var length = toLength(O.length); var argumentsLength = arguments.length; @@ -18052,9 +18631,9 @@ }; }, { - '../internals/to-absolute-index': 148, - '../internals/to-length': 152, - '../internals/to-object': 153 + '../internals/to-absolute-index': 150, + '../internals/to-length': 154, + '../internals/to-object': 155 } ], 34: [ @@ -18064,10 +18643,10 @@ var arrayMethodIsStrict = _dereq_('../internals/array-method-is-strict'); var arrayMethodUsesToLength = _dereq_('../internals/array-method-uses-to-length'); var STRICT_METHOD = arrayMethodIsStrict('forEach'); - var USES_TO_LENGTH = arrayMethodUsesToLength('forEach'); // `Array.prototype.forEach` method implementation + var USES_TO_LENGTH = arrayMethodUsesToLength('forEach'); + // `Array.prototype.forEach` method implementation // https://tc39.github.io/ecma262/#sec-array.prototype.foreach - module.exports = !STRICT_METHOD || !USES_TO_LENGTH ? function forEach(callbackfn /* , thisArg */ - ) { + module.exports = !STRICT_METHOD || !USES_TO_LENGTH ? function forEach(callbackfn /* , thisArg */ ) { return $forEach(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } : [ @@ -18088,10 +18667,10 @@ var isArrayIteratorMethod = _dereq_('../internals/is-array-iterator-method'); var toLength = _dereq_('../internals/to-length'); var createProperty = _dereq_('../internals/create-property'); - var getIteratorMethod = _dereq_('../internals/get-iterator-method'); // `Array.from` method implementation + var getIteratorMethod = _dereq_('../internals/get-iterator-method'); + // `Array.from` method implementation // https://tc39.github.io/ecma262/#sec-array.from - module.exports = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */ - ) { + module.exports = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */ ) { var O = toObject(arrayLike); var C = typeof this == 'function' ? this : Array; var argumentsLength = arguments.length; @@ -18105,7 +18684,8 @@ iterator, next, value; - if (mapping) mapfn = bind(mapfn, argumentsLength > 2 ? arguments[2] : undefined, 2); // if the target is not iterable or it's an array with the default iterator - use a simple case + if (mapping) mapfn = bind(mapfn, argumentsLength > 2 ? arguments[2] : undefined, 2); + // if the target is not iterable or it's an array with the default iterator - use a simple case if (iteratorMethod != undefined && !(C == Array && isArrayIteratorMethod(iteratorMethod))) { iterator = iteratorMethod.call(O); next = iterator.next; @@ -18135,25 +18715,29 @@ '../internals/function-bind-context': 72, '../internals/get-iterator-method': 75, '../internals/is-array-iterator-method': 89, - '../internals/to-length': 152, - '../internals/to-object': 153 + '../internals/to-length': 154, + '../internals/to-object': 155 } ], 36: [ function (_dereq_, module, exports) { var toIndexedObject = _dereq_('../internals/to-indexed-object'); var toLength = _dereq_('../internals/to-length'); - var toAbsoluteIndex = _dereq_('../internals/to-absolute-index'); // `Array.prototype.{ indexOf, includes }` methods implementation + var toAbsoluteIndex = _dereq_('../internals/to-absolute-index'); + // `Array.prototype.{ indexOf, includes }` methods implementation var createMethod = function (IS_INCLUDES) { return function ($this, el, fromIndex) { var O = toIndexedObject($this); var length = toLength(O.length); var index = toAbsoluteIndex(fromIndex, length); - var value; // Array#includes uses SameValueZero equality algorithm + var value; + // Array#includes uses SameValueZero equality algorithm // eslint-disable-next-line no-self-compare if (IS_INCLUDES && el != el) while (length > index) { - value = O[index++]; // eslint-disable-next-line no-self-compare - if (value != value) return true; // Array#indexOf ignores holes, Array#includes - not + value = O[index++]; + // eslint-disable-next-line no-self-compare + if (value != value) return true; + // Array#indexOf ignores holes, Array#includes - not } else for (; length > index; index++) { if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0; } @@ -18170,9 +18754,9 @@ }; }, { - '../internals/to-absolute-index': 148, - '../internals/to-indexed-object': 150, - '../internals/to-length': 152 + '../internals/to-absolute-index': 150, + '../internals/to-indexed-object': 152, + '../internals/to-length': 154 } ], 37: [ @@ -18183,7 +18767,8 @@ var toLength = _dereq_('../internals/to-length'); var arraySpeciesCreate = _dereq_('../internals/array-species-create'); var push = [ - ].push; // `Array.prototype.{ forEach, map, filter, some, every, find, findIndex }` methods implementation + ].push; + // `Array.prototype.{ forEach, map, filter, some, every, find, findIndex }` methods implementation var createMethod = function (TYPE) { var IS_MAP = TYPE == 1; var IS_FILTER = TYPE == 2; @@ -18253,8 +18838,8 @@ '../internals/array-species-create': 43, '../internals/function-bind-context': 72, '../internals/indexed-object': 84, - '../internals/to-length': 152, - '../internals/to-object': 153 + '../internals/to-length': 154, + '../internals/to-object': 155 } ], 38: [ @@ -18271,15 +18856,16 @@ var NEGATIVE_ZERO = !!nativeLastIndexOf && 1 / [ 1 ].lastIndexOf(1, - 0) < 0; - var STRICT_METHOD = arrayMethodIsStrict('lastIndexOf'); // For preventing possible almost infinite loop in non-standard implementations, test the forward version of the method + var STRICT_METHOD = arrayMethodIsStrict('lastIndexOf'); + // For preventing possible almost infinite loop in non-standard implementations, test the forward version of the method var USES_TO_LENGTH = arrayMethodUsesToLength('indexOf', { ACCESSORS: true, 1: 0 }); - var FORCED = NEGATIVE_ZERO || !STRICT_METHOD || !USES_TO_LENGTH; // `Array.prototype.lastIndexOf` method implementation + var FORCED = NEGATIVE_ZERO || !STRICT_METHOD || !USES_TO_LENGTH; + // `Array.prototype.lastIndexOf` method implementation // https://tc39.github.io/ecma262/#sec-array.prototype.lastindexof - module.exports = FORCED ? function lastIndexOf(searchElement /* , fromIndex = @[*-1] */ - ) { + module.exports = FORCED ? function lastIndexOf(searchElement /* , fromIndex = @[*-1] */ ) { // convert -0 to +0 if (NEGATIVE_ZERO) return nativeLastIndexOf.apply(this, arguments) || 0; var O = toIndexedObject(this); @@ -18295,9 +18881,9 @@ { '../internals/array-method-is-strict': 40, '../internals/array-method-uses-to-length': 41, - '../internals/to-indexed-object': 150, - '../internals/to-integer': 151, - '../internals/to-length': 152 + '../internals/to-indexed-object': 152, + '../internals/to-integer': 153, + '../internals/to-length': 154 } ], 39: [ @@ -18327,7 +18913,7 @@ { '../internals/engine-v8-version': 66, '../internals/fails': 69, - '../internals/well-known-symbol': 164 + '../internals/well-known-symbol': 166 } ], 40: [ @@ -18394,7 +18980,8 @@ var aFunction = _dereq_('../internals/a-function'); var toObject = _dereq_('../internals/to-object'); var IndexedObject = _dereq_('../internals/indexed-object'); - var toLength = _dereq_('../internals/to-length'); // `Array.prototype.{ reduce, reduceRight }` methods implementation + var toLength = _dereq_('../internals/to-length'); + // `Array.prototype.{ reduce, reduceRight }` methods implementation var createMethod = function (IS_RIGHT) { return function (that, callbackfn, argumentsLength, memo) { aFunction(callbackfn); @@ -18432,8 +19019,8 @@ { '../internals/a-function': 23, '../internals/indexed-object': 84, - '../internals/to-length': 152, - '../internals/to-object': 153 + '../internals/to-length': 154, + '../internals/to-object': 155 } ], 43: [ @@ -18441,12 +19028,14 @@ var isObject = _dereq_('../internals/is-object'); var isArray = _dereq_('../internals/is-array'); var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); - var SPECIES = wellKnownSymbol('species'); // `ArraySpeciesCreate` abstract operation + var SPECIES = wellKnownSymbol('species'); + // `ArraySpeciesCreate` abstract operation // https://tc39.github.io/ecma262/#sec-arrayspeciescreate module.exports = function (originalArray, length) { var C; if (isArray(originalArray)) { - C = originalArray.constructor; // cross-realm fallback + C = originalArray.constructor; + // cross-realm fallback if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; else if (isObject(C)) { C = C[SPECIES]; @@ -18459,15 +19048,17 @@ { '../internals/is-array': 90, '../internals/is-object': 92, - '../internals/well-known-symbol': 164 + '../internals/well-known-symbol': 166 } ], 44: [ function (_dereq_, module, exports) { - var anObject = _dereq_('../internals/an-object'); // call something on iterator step with safe closing on error + var anObject = _dereq_('../internals/an-object'); + // call something on iterator step with safe closing on error module.exports = function (iterator, fn, value, ENTRIES) { try { - return ENTRIES ? fn(anObject(value) [0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) + return ENTRIES ? fn(anObject(value) [0], value[1]) : fn(value); + // 7.4.6 IteratorClose(iterator, completion) } catch (error) { var returnMethod = iterator['return']; if (returnMethod !== undefined) anObject(returnMethod.call(iterator)); @@ -18498,12 +19089,12 @@ }; iteratorWithReturn[ITERATOR] = function () { return this; - }; // eslint-disable-next-line no-throw-literal + }; + // eslint-disable-next-line no-throw-literal Array.from(iteratorWithReturn, function () { throw 2; }); - } catch (error) { - /* empty */ + } catch (error) { /* empty */ } module.exports = function (exec, SKIP_CLOSING) { if (!SKIP_CLOSING && !SAFE_CLOSING) return false; @@ -18521,14 +19112,13 @@ }; }; exec(object); - } catch (error) { - /* empty */ + } catch (error) { /* empty */ } return ITERATION_SUPPORT; }; }, { - '../internals/well-known-symbol': 164 + '../internals/well-known-symbol': 166 } ], 46: [ @@ -18547,31 +19137,33 @@ var TO_STRING_TAG_SUPPORT = _dereq_('../internals/to-string-tag-support'); var classofRaw = _dereq_('../internals/classof-raw'); var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); - var TO_STRING_TAG = wellKnownSymbol('toStringTag'); // ES3 wrong here + var TO_STRING_TAG = wellKnownSymbol('toStringTag'); + // ES3 wrong here var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; - }()) == 'Arguments'; // fallback for IE11 Script Access Denied error + }()) == 'Arguments'; + // fallback for IE11 Script Access Denied error var tryGet = function (it, key) { try { return it[key]; - } catch (error) { - /* empty */ + } catch (error) { /* empty */ } - }; // getting tag from ES6+ `Object.prototype.toString` + }; + // getting tag from ES6+ `Object.prototype.toString` module.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) { var O, tag, result; - return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case - : typeof (tag = tryGet(O = Object(it), TO_STRING_TAG)) == 'string' ? tag // builtinTag case - : CORRECT_ARGUMENTS ? classofRaw(O) // ES3 arguments fallback + return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case + : typeof (tag = tryGet(O = Object(it), TO_STRING_TAG)) == 'string' ? tag // builtinTag case + : CORRECT_ARGUMENTS ? classofRaw(O) // ES3 arguments fallback : (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result; }; }, { '../internals/classof-raw': 46, - '../internals/to-string-tag-support': 157, - '../internals/well-known-symbol': 164 + '../internals/to-string-tag-support': 159, + '../internals/well-known-symbol': 166 } ], 48: [ @@ -18609,9 +19201,11 @@ var state = getInternalState(that); var entry = getEntry(that, key); var previous, - index; // change existing entry + index; + // change existing entry if (entry) { - entry.value = value; // create new entry + entry.value = value; + // create new entry } else { state.last = entry = { index: index = fastKey(key, true), @@ -18624,16 +19218,19 @@ if (!state.first) state.first = entry; if (previous) previous.next = entry; if (DESCRIPTORS) state.size++; - else that.size++; // add to index + else that.size++; + // add to index if (index !== 'F') state.index[index] = entry; } return that; }; var getEntry = function (that, key) { - var state = getInternalState(that); // fast case + var state = getInternalState(that); + // fast case var index = fastKey(key); var entry; - if (index !== 'F') return state.index[index]; // frozen object case + if (index !== 'F') return state.index[index]; + // frozen object case for (entry = state.first; entry; entry = entry.next) { if (entry.key == key) return entry; } @@ -18678,13 +19275,13 @@ }, // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) - forEach: function forEach(callbackfn /* , that = undefined */ - ) { + forEach: function forEach(callbackfn /* , that = undefined */ ) { var state = getInternalState(this); var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); var entry; while (entry = entry ? entry.next : state.first) { - boundFunction(entry.value, entry.key, this); // revert to the last existing entry + boundFunction(entry.value, entry.key, this); + // revert to the last existing entry while (entry && entry.removed) entry = entry.previous; } }, @@ -18721,7 +19318,8 @@ setStrong: function (C, CONSTRUCTOR_NAME, IS_MAP) { var ITERATOR_NAME = CONSTRUCTOR_NAME + ' Iterator'; var getInternalCollectionState = internalStateGetterFor(CONSTRUCTOR_NAME); - var getInternalIteratorState = internalStateGetterFor(ITERATOR_NAME); // add .keys, .values, .entries, [@@iterator] + var getInternalIteratorState = internalStateGetterFor(ITERATOR_NAME); + // add .keys, .values, .entries, [@@iterator] // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 defineIterator(C, CONSTRUCTOR_NAME, function (iterated, kind) { setInternalState(this, { @@ -18734,8 +19332,10 @@ }, function () { var state = getInternalIteratorState(this); var kind = state.kind; - var entry = state.last; // revert to the last existing entry - while (entry && entry.removed) entry = entry.previous; // get next entry + var entry = state.last; + // revert to the last existing entry + while (entry && entry.removed) entry = entry.previous; + // get next entry if (!state.target || !(state.last = entry = entry ? entry.next : state.state.first)) { // or finish the iteration state.target = undefined; @@ -18743,7 +19343,7 @@ value: undefined, done: true }; - } // return step by kind + } // return step by kind if (kind == 'keys') return { value: entry.key, @@ -18760,7 +19360,8 @@ ], done: false }; - }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); // add [@@species], 23.1.2.2, 23.2.2.2 + }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); + // add [@@species], 23.1.2.2, 23.2.2.2 setSpecies(CONSTRUCTOR_NAME); } }; @@ -18795,7 +19396,8 @@ var internalStateGetterFor = InternalStateModule.getterFor; var find = ArrayIterationModule.find; var findIndex = ArrayIterationModule.findIndex; - var id = 0; // fallback for uncaught frozen keys + var id = 0; + // fallback for uncaught frozen keys var uncaughtFrozenStore = function (store) { return store.frozen || (store.frozen = new UncaughtFrozenStore()); }; @@ -18949,7 +19551,8 @@ nativeMethod.call(this, key === 0 ? 0 : key, value); return this; }); - }; // eslint-disable-next-line max-len + }; + // eslint-disable-next-line max-len if (isForced(CONSTRUCTOR_NAME, typeof NativeConstructor != 'function' || !(IS_WEAK || NativePrototype.forEach && !fails(function () { new NativeConstructor().entries().next(); })))) { @@ -18957,17 +19560,21 @@ Constructor = common.getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER); InternalMetadataModule.REQUIRED = true; } else if (isForced(CONSTRUCTOR_NAME, true)) { - var instance = new Constructor(); // early implementations not supports chaining + var instance = new Constructor(); + // early implementations not supports chaining var HASNT_CHAINING = instance[ADDER](IS_WEAK ? { } - : - 0, 1) != instance; // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false + : - 0, 1) != instance; + // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); - }); // most early implementations doesn't supports iterables, most modern - not close it correctly + }); + // most early implementations doesn't supports iterables, most modern - not close it correctly // eslint-disable-next-line no-new var ACCEPT_ITERABLES = checkCorrectnessOfIteration(function (iterable) { new NativeConstructor(iterable); - }); // for early implementations -0 and +0 not the same + }); + // for early implementations -0 and +0 not the same var BUGGY_ZERO = !IS_WEAK && fails(function () { // V8 ~ Chromium 42- fails only with 5+ elements var $instance = new NativeConstructor(); @@ -18990,7 +19597,8 @@ fixMethod('has'); IS_MAP && fixMethod('get'); } - if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER); // weak collections should not contains .clear method + if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER); + // weak collections should not contains .clear method if (IS_WEAK && NativePrototype.clear) delete NativePrototype.clear; } exported[CONSTRUCTOR_NAME] = Constructor; @@ -19053,23 +19661,21 @@ try { regexp[MATCH] = false; return '/./'[METHOD_NAME](regexp); - } catch (f) { - /* empty */ + } catch (f) { /* empty */ } } return false; }; }, { - '../internals/well-known-symbol': 164 + '../internals/well-known-symbol': 166 } ], 53: [ function (_dereq_, module, exports) { var fails = _dereq_('../internals/fails'); module.exports = !fails(function () { - function F() { - /* empty */ + function F() { /* empty */ } F.prototype.constructor = null; return Object.getPrototypeOf(new F()) !== F.prototype; @@ -19082,7 +19688,8 @@ 54: [ function (_dereq_, module, exports) { var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); - var quot = /"/g; // B.2.3.2.1 CreateHTML(string, tag, attribute, value) + var quot = /"/g; + // B.2.3.2.1 CreateHTML(string, tag, attribute, value) // https://tc39.github.io/ecma262/#sec-createhtml module.exports = function (string, tag, attribute, value) { var S = String(requireObjectCoercible(string)); @@ -19172,7 +19779,7 @@ { '../internals/create-property-descriptor': 57, '../internals/object-define-property': 110, - '../internals/to-primitive': 156 + '../internals/to-primitive': 158 } ], 59: [ @@ -19229,7 +19836,8 @@ var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator; var CurrentIteratorPrototype, methods, - KEY; // fix native + KEY; + // fix native if (anyNativeIterator) { CurrentIteratorPrototype = getPrototypeOf(anyNativeIterator.call(new Iterable())); if (IteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) { @@ -19239,24 +19847,25 @@ } else if (typeof CurrentIteratorPrototype[ITERATOR] != 'function') { createNonEnumerableProperty(CurrentIteratorPrototype, ITERATOR, returnThis); } - } // Set @@toStringTag to native iterators + } // Set @@toStringTag to native iterators setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true, true); if (IS_PURE) Iterators[TO_STRING_TAG] = returnThis; } - } // fix Array#{values, @@iterator}.name in V8 / FF + } // fix Array#{values, @@iterator}.name in V8 / FF if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) { INCORRECT_VALUES_NAME = true; defaultIterator = function values() { return nativeIterator.call(this); }; - } // define iterator + } // define iterator if ((!IS_PURE || FORCED) && IterablePrototype[ITERATOR] !== defaultIterator) { createNonEnumerableProperty(IterablePrototype, ITERATOR, defaultIterator); } - Iterators[NAME] = defaultIterator; // export additional methods + Iterators[NAME] = defaultIterator; + // export additional methods if (DEFAULT) { methods = { values: getIterationMethod(VALUES), @@ -19287,7 +19896,7 @@ '../internals/object-set-prototype-of': 119, '../internals/redefine': 126, '../internals/set-to-string-tag': 135, - '../internals/well-known-symbol': 164 + '../internals/well-known-symbol': 166 } ], 60: [ @@ -19308,12 +19917,13 @@ '../internals/has': 78, '../internals/object-define-property': 110, '../internals/path': 122, - '../internals/well-known-symbol-wrapped': 163 + '../internals/well-known-symbol-wrapped': 165 } ], 61: [ function (_dereq_, module, exports) { - var fails = _dereq_('../internals/fails'); // Thank's IE8 for his funny defineProperty + var fails = _dereq_('../internals/fails'); + // Thank's IE8 for his funny defineProperty module.exports = !fails(function () { return Object.defineProperty({ }, 1, { @@ -19331,7 +19941,8 @@ function (_dereq_, module, exports) { var global = _dereq_('../internals/global'); var isObject = _dereq_('../internals/is-object'); - var document = global.document; // typeof document.createElement is 'object' in old IE + var document = global.document; + // typeof document.createElement is 'object' in old IE var EXISTS = isObject(document) && isObject(document.createElement); module.exports = function (it) { return EXISTS ? document.createElement(it) : { @@ -19492,15 +20103,16 @@ descriptor = getOwnPropertyDescriptor(target, key); targetProperty = descriptor && descriptor.value; } else targetProperty = target[key]; - FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); // contained in target + FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); + // contained in target if (!FORCED && targetProperty !== undefined) { if (typeof sourceProperty === typeof targetProperty) continue; copyConstructorProperties(sourceProperty, targetProperty); - } // add a flag to not completely full polyfills + } // add a flag to not completely full polyfills if (options.sham || targetProperty && targetProperty.sham) { createNonEnumerableProperty(sourceProperty, 'sham', true); - } // extend global + } // extend global redefine(target, key, sourceProperty, options); } @@ -19531,7 +20143,8 @@ ], 70: [ function (_dereq_, module, exports) { - 'use strict'; // TODO: Remove from `core-js@4` since it's moved to entry points + 'use strict'; + // TODO: Remove from `core-js@4` since it's moved to entry points _dereq_('../modules/es.regexp.exec'); var redefine = _dereq_('../internals/redefine'); var fails = _dereq_('../internals/fails'); @@ -19553,18 +20166,21 @@ return result; }; return ''.replace(re, '$') !== '7'; - }); // IE <= 11 replaces $0 with the whole match, as if it was $& + }); + // IE <= 11 replaces $0 with the whole match, as if it was $& // https://stackoverflow.com/questions/6024666/getting-ie-to-replace-a-regex-with-the-literal-string-0 var REPLACE_KEEPS_$0 = function () { return 'a'.replace(/./, '$0') === '$0'; }(); - var REPLACE = wellKnownSymbol('replace'); // Safari <= 13.0.3(?) substitutes nth capture where n>m with an empty string + var REPLACE = wellKnownSymbol('replace'); + // Safari <= 13.0.3(?) substitutes nth capture where n>m with an empty string var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = function () { if (/./[REPLACE]) { return /./[REPLACE]('a', '$0') === ''; } return false; - }(); // Chrome 51 has a buggy "split" implementation when RegExp#exec !== nativeExec + }(); + // Chrome 51 has a buggy "split" implementation when RegExp#exec !== nativeExec // Weex JS has frozen built-in prototypes, so use try / catch wrapper var SPLIT_WORKS_WITH_OVERWRITTEN_EXEC = !fails(function () { var re = /(?:)/; @@ -19595,7 +20211,8 @@ // and serious performance degradation in V8 // https://github.com/zloirock/core-js/issues/306 re = { - }; // RegExp[@@split] doesn't call the regex's exec method, but first creates + }; + // RegExp[@@split] doesn't call the regex's exec method, but first creates // a new one. We need to return the patched regex when creating the new one. re.constructor = { }; @@ -19640,11 +20257,11 @@ var stringMethod = methods[0]; var regexMethod = methods[1]; redefine(String.prototype, KEY, stringMethod); - redefine(RegExp.prototype, SYMBOL, length == 2 // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue) + redefine(RegExp.prototype, SYMBOL, length == 2 // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue) // 21.2.5.11 RegExp.prototype[@@split](string, limit) ? function (string, arg) { return regexMethod.call(string, this, arg); - } // 21.2.5.6 RegExp.prototype[@@match](string) + } // 21.2.5.6 RegExp.prototype[@@match](string) // 21.2.5.9 RegExp.prototype[@@search](string) : function (string) { @@ -19659,8 +20276,8 @@ '../internals/fails': 69, '../internals/redefine': 126, '../internals/regexp-exec': 128, - '../internals/well-known-symbol': 164, - '../modules/es.regexp.exec': 199 + '../internals/well-known-symbol': 166, + '../modules/es.regexp.exec': 205 } ], 71: [ @@ -19677,7 +20294,8 @@ ], 72: [ function (_dereq_, module, exports) { - var aFunction = _dereq_('../internals/a-function'); // optional / simple context binding + var aFunction = _dereq_('../internals/a-function'); + // optional / simple context binding module.exports = function (fn, that, length) { aFunction(fn); if (that === undefined) return fn; @@ -19699,8 +20317,8 @@ return fn.call(that, a, b, c); }; } - return function () /* ...args */ - { + return function /* ...args */ + () { return fn.apply(that, arguments); }; }; @@ -19721,18 +20339,19 @@ var construct = function (C, argsLength, args) { if (!(argsLength in factories)) { for (var list = [ - ], i = 0; i < argsLength; i++) list[i] = 'a[' + i + ']'; // eslint-disable-next-line no-new-func + ], i = 0; i < argsLength; i++) list[i] = 'a[' + i + ']'; + // eslint-disable-next-line no-new-func factories[argsLength] = Function('C,a', 'return new C(' + list.join(',') + ')'); } return factories[argsLength](C, args); - }; // `Function.prototype.bind` method implementation + }; + // `Function.prototype.bind` method implementation // https://tc39.github.io/ecma262/#sec-function.prototype.bind - module.exports = Function.bind || function bind(that /* , ...args */ - ) { + module.exports = Function.bind || function bind(that /* , ...args */ ) { var fn = aFunction(this); var partArgs = slice.call(arguments, 1); - var boundFunction = function bound() /* args... */ - { + var boundFunction = function bound( /* args... */ + ) { var args = partArgs.concat(slice.call(arguments)); return this instanceof boundFunction ? construct(fn, args.length, args) : fn.apply(that, args); }; @@ -19774,7 +20393,7 @@ { '../internals/classof': 47, '../internals/iterators': 97, - '../internals/well-known-symbol': 164 + '../internals/well-known-symbol': 166 } ], 76: [ @@ -19799,9 +20418,10 @@ (function (global) { var check = function (it) { return it && it.Math == Math && it; - }; // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 - module.exports = // eslint-disable-next-line no-undef - check(typeof globalThis == 'object' && globalThis) || check(typeof window == 'object' && window) || check(typeof self == 'object' && self) || check(typeof global == 'object' && global) || // eslint-disable-next-line no-new-func + }; + // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 + module.exports = // eslint-disable-next-line no-undef + check(typeof globalThis == 'object' && globalThis) || check(typeof window == 'object' && window) || check(typeof self == 'object' && self) || check(typeof global == 'object' && global) || // eslint-disable-next-line no-new-func Function('return this') (); }).call(this, typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : { }) @@ -19855,7 +20475,8 @@ function (_dereq_, module, exports) { var DESCRIPTORS = _dereq_('../internals/descriptors'); var fails = _dereq_('../internals/fails'); - var createElement = _dereq_('../internals/document-create-element'); // Thank's IE8 for his funny defineProperty + var createElement = _dereq_('../internals/document-create-element'); + // Thank's IE8 for his funny defineProperty module.exports = !DESCRIPTORS && !fails(function () { return Object.defineProperty(createElement('div'), 'a', { get: function () { @@ -19891,7 +20512,8 @@ var exponent, mantissa, c; - number = abs(number); // eslint-disable-next-line no-self-compare + number = abs(number); + // eslint-disable-next-line no-self-compare if (number != number || number === Infinity) { // eslint-disable-next-line no-self-compare mantissa = number != number ? 1 : 0; @@ -19967,7 +20589,8 @@ function (_dereq_, module, exports) { var fails = _dereq_('../internals/fails'); var classof = _dereq_('../internals/classof-raw'); - var split = ''.split; // fallback for non-array-like ES3 and non-enumerable old V8 strings + var split = ''.split; + // fallback for non-array-like ES3 and non-enumerable old V8 strings module.exports = fails(function () { // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346 // eslint-disable-next-line no-prototype-builtins @@ -19985,12 +20608,13 @@ 85: [ function (_dereq_, module, exports) { var isObject = _dereq_('../internals/is-object'); - var setPrototypeOf = _dereq_('../internals/object-set-prototype-of'); // makes subclassing work correct for wrapped built-ins + var setPrototypeOf = _dereq_('../internals/object-set-prototype-of'); + // makes subclassing work correct for wrapped built-ins module.exports = function ($this, dummy, Wrapper) { var NewTarget, NewTargetPrototype; - if ( // it can work only with native `setPrototypeOf` - setPrototypeOf && // we haven't completely correct pre-ES6 way for getting `new.target`, so use this + if ( // it can work only with native `setPrototypeOf` + setPrototypeOf && // we haven't completely correct pre-ES6 way for getting `new.target`, so use this typeof (NewTarget = dummy.constructor) == 'function' && NewTarget !== Wrapper && isObject(NewTargetPrototype = NewTarget.prototype) && NewTargetPrototype !== Wrapper.prototype) setPrototypeOf($this, NewTargetPrototype); return $this; }; @@ -20003,7 +20627,8 @@ 86: [ function (_dereq_, module, exports) { var store = _dereq_('../internals/shared-store'); - var functionToString = Function.toString; // this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper + var functionToString = Function.toString; + // this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper if (typeof store.inspectSource != 'function') { store.inspectSource = function (it) { return functionToString.call(it); @@ -20044,21 +20669,28 @@ if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if (!has(it, METADATA)) { // can't set metadata to uncaught frozen object - if (!isExtensible(it)) return 'F'; // not necessary to add metadata - if (!create) return 'E'; // add missing metadata - setMetadata(it); // return object ID + if (!isExtensible(it)) return 'F'; + // not necessary to add metadata + if (!create) return 'E'; + // add missing metadata + setMetadata(it); + // return object ID } return it[METADATA].objectID; }; var getWeakData = function (it, create) { if (!has(it, METADATA)) { // can't set metadata to uncaught frozen object - if (!isExtensible(it)) return true; // not necessary to add metadata - if (!create) return false; // add missing metadata - setMetadata(it); // return the store of weak collections IDs + if (!isExtensible(it)) return true; + // not necessary to add metadata + if (!create) return false; + // add missing metadata + setMetadata(it); + // return the store of weak collections IDs } return it[METADATA].weakData; - }; // add metadata on freeze-family methods calling + }; + // add metadata on freeze-family methods calling var onFreeze = function (it) { if (FREEZING && meta.REQUIRED && isExtensible(it) && !has(it, METADATA)) setMetadata(it); return it; @@ -20077,7 +20709,7 @@ '../internals/hidden-keys': 79, '../internals/is-object': 92, '../internals/object-define-property': 110, - '../internals/uid': 161 + '../internals/uid': 163 } ], 88: [ @@ -20160,19 +20792,21 @@ var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); var Iterators = _dereq_('../internals/iterators'); var ITERATOR = wellKnownSymbol('iterator'); - var ArrayPrototype = Array.prototype; // check on default Array iterator + var ArrayPrototype = Array.prototype; + // check on default Array iterator module.exports = function (it) { return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it); }; }, { '../internals/iterators': 97, - '../internals/well-known-symbol': 164 + '../internals/well-known-symbol': 166 } ], 90: [ function (_dereq_, module, exports) { - var classof = _dereq_('../internals/classof-raw'); // `IsArray` abstract operation + var classof = _dereq_('../internals/classof-raw'); + // `IsArray` abstract operation // https://tc39.github.io/ecma262/#sec-isarray module.exports = Array.isArray || function isArray(arg) { return classof(arg) == 'Array'; @@ -20224,7 +20858,8 @@ var isObject = _dereq_('../internals/is-object'); var classof = _dereq_('../internals/classof-raw'); var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); - var MATCH = wellKnownSymbol('match'); // `IsRegExp` abstract operation + var MATCH = wellKnownSymbol('match'); + // `IsRegExp` abstract operation // https://tc39.github.io/ecma262/#sec-isregexp module.exports = function (it) { var isRegExp; @@ -20234,7 +20869,7 @@ { '../internals/classof-raw': 46, '../internals/is-object': 92, - '../internals/well-known-symbol': 164 + '../internals/well-known-symbol': 166 } ], 95: [ @@ -20262,7 +20897,8 @@ iterator = iterable; } else { iterFn = getIteratorMethod(iterable); - if (typeof iterFn != 'function') throw TypeError('Target is not iterable'); // optimisation for array iterators + if (typeof iterFn != 'function') throw TypeError('Target is not iterable'); + // optimisation for array iterators if (isArrayIteratorMethod(iterFn)) { for (index = 0, length = toLength(iterable.length); length > index; index++) { result = AS_ENTRIES ? boundFunction(anObject(step = iterable[index]) [0], step[1]) : boundFunction(iterable[index]); @@ -20289,7 +20925,7 @@ '../internals/function-bind-context': 72, '../internals/get-iterator-method': 75, '../internals/is-array-iterator-method': 89, - '../internals/to-length': 152 + '../internals/to-length': 154 } ], 96: [ @@ -20304,14 +20940,16 @@ var BUGGY_SAFARI_ITERATORS = false; var returnThis = function () { return this; - }; // `%IteratorPrototype%` object + }; + // `%IteratorPrototype%` object // https://tc39.github.io/ecma262/#sec-%iteratorprototype%-object var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator; if ([].keys) { arrayIterator = [ - ].keys(); // Safari 8 has buggy iterators w/o `next` + ].keys(); + // Safari 8 has buggy iterators w/o `next` if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true; else { PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator)); @@ -20319,7 +20957,8 @@ } } if (IteratorPrototype == undefined) IteratorPrototype = { - }; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() + }; + // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() if (!IS_PURE && !has(IteratorPrototype, ITERATOR)) { createNonEnumerableProperty(IteratorPrototype, ITERATOR, returnThis); } @@ -20333,7 +20972,7 @@ '../internals/has': 78, '../internals/is-pure': 93, '../internals/object-get-prototype-of': 115, - '../internals/well-known-symbol': 164 + '../internals/well-known-symbol': 166 } ], 97: [ @@ -20366,7 +21005,8 @@ var MutationObserver = global.MutationObserver || global.WebKitMutationObserver; var process = global.process; var Promise = global.Promise; - var IS_NODE = classof(process) == 'process'; // Node.js 11 shows ExperimentalWarning on getting `queueMicrotask` + var IS_NODE = classof(process) == 'process'; + // Node.js 11 shows ExperimentalWarning on getting `queueMicrotask` var queueMicrotaskDescriptor = getOwnPropertyDescriptor(global, 'queueMicrotask'); var queueMicrotask = queueMicrotaskDescriptor && queueMicrotaskDescriptor.value; var flush, @@ -20376,7 +21016,8 @@ toggle, node, promise, - then; // modern engines have queueMicrotask method + then; + // modern engines have queueMicrotask method if (!queueMicrotask) { flush = function () { var parent, @@ -20395,11 +21036,13 @@ } last = undefined; if (parent) parent.enter(); - }; // Node.js + }; + // Node.js if (IS_NODE) { notify = function () { process.nextTick(flush); - }; // browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339 + }; + // browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339 } else if (MutationObserver && !IS_IOS) { toggle = true; node = document.createTextNode(''); @@ -20408,14 +21051,16 @@ }); notify = function () { node.data = toggle = !toggle; - }; // environments with maybe non-completely correct, but existent Promise + }; + // environments with maybe non-completely correct, but existent Promise } else if (Promise && Promise.resolve) { // Promise.resolve without an argument throws an error in LG WebOS 2 promise = Promise.resolve(undefined); then = promise.then; notify = function () { then.call(promise, flush); - }; // for other environments - macrotask based on: + }; + // for other environments - macrotask based on: // - setImmediate // - MessageChannel // - window.postMessag @@ -20446,7 +21091,7 @@ '../internals/engine-is-ios': 64, '../internals/global': 77, '../internals/object-get-own-property-descriptor': 111, - '../internals/task': 146 + '../internals/task': 148 } ], 100: [ @@ -20486,18 +21131,18 @@ searchParams['delete']('b'); result += key + value; }); - return IS_PURE && !url.toJSON || !searchParams.sort || url.href !== 'http://a/c%20d?a=1&c=3' || searchParams.get('c') !== '3' || String(new URLSearchParams('?a=1')) !== 'a=1' || !searchParams[ITERATOR] // throws in Edge - || new URL('https://a@b').username !== 'a' || new URLSearchParams(new URLSearchParams('a=b')).get('a') !== 'b' // not punycoded in Edge - || new URL('http://тест').host !== 'xn--e1aybc' // not escaped in Chrome 62- - || new URL('http://a#б').hash !== '#%D0%B1' // fails in Chrome 66- - || result !== 'a1c3' // throws in Safari + return IS_PURE && !url.toJSON || !searchParams.sort || url.href !== 'http://a/c%20d?a=1&c=3' || searchParams.get('c') !== '3' || String(new URLSearchParams('?a=1')) !== 'a=1' || !searchParams[ITERATOR] // throws in Edge + || new URL('https://a@b').username !== 'a' || new URLSearchParams(new URLSearchParams('a=b')).get('a') !== 'b' // not punycoded in Edge + || new URL('http://тест').host !== 'xn--e1aybc' // not escaped in Chrome 62- + || new URL('http://a#б').hash !== '#%D0%B1' // fails in Chrome 66- + || result !== 'a1c3' // throws in Safari || new URL('http://x', undefined).host !== 'x'; }); }, { '../internals/fails': 69, '../internals/is-pure': 93, - '../internals/well-known-symbol': 164 + '../internals/well-known-symbol': 166 } ], 103: [ @@ -20526,7 +21171,8 @@ }); this.resolve = aFunction(resolve); this.reject = aFunction(reject); - }; // 25.4.1.5 NewPromiseCapability(C) + }; + // 25.4.1.5 NewPromiseCapability(C) module.exports.f = function (C) { return new PromiseCapability(C); }; @@ -20552,7 +21198,8 @@ 106: [ function (_dereq_, module, exports) { var global = _dereq_('../internals/global'); - var globalIsFinite = global.isFinite; // `Number.isFinite` method + var globalIsFinite = global.isFinite; + // `Number.isFinite` method // https://tc39.github.io/ecma262/#sec-number.isfinite module.exports = Number.isFinite || function isFinite(it) { return typeof it == 'number' && globalIsFinite(it); @@ -20573,7 +21220,8 @@ var toObject = _dereq_('../internals/to-object'); var IndexedObject = _dereq_('../internals/indexed-object'); var nativeAssign = Object.assign; - var defineProperty = Object.defineProperty; // `Object.assign` method + var defineProperty = Object.defineProperty; + // `Object.assign` method // https://tc39.github.io/ecma262/#sec-object.assign module.exports = !nativeAssign || fails(function () { // should have correct order of operations (Edge bug) @@ -20590,11 +21238,13 @@ } }), { b: 2 - })).b !== 1) return true; // should work with symbols and should have deterministic property order (V8 bug) + })).b !== 1) return true; + // should work with symbols and should have deterministic property order (V8 bug) var A = { }; var B = { - }; // eslint-disable-next-line no-undef + }; + // eslint-disable-next-line no-undef var symbol = Symbol(); var alphabet = 'abcdefghijklmnopqrst'; A[symbol] = 7; @@ -20633,7 +21283,7 @@ '../internals/object-get-own-property-symbols': 114, '../internals/object-keys': 117, '../internals/object-property-is-enumerable': 118, - '../internals/to-object': 153 + '../internals/to-object': 155 } ], 108: [ @@ -20650,33 +21300,36 @@ var PROTOTYPE = 'prototype'; var SCRIPT = 'script'; var IE_PROTO = sharedKey('IE_PROTO'); - var EmptyConstructor = function () { - /* empty */ + var EmptyConstructor = function () { /* empty */ }; var scriptTag = function (content) { return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT; - }; // Create object with fake `null` prototype: use ActiveX Object with cleared prototype + }; + // Create object with fake `null` prototype: use ActiveX Object with cleared prototype var NullProtoObjectViaActiveX = function (activeXDocument) { activeXDocument.write(scriptTag('')); activeXDocument.close(); var temp = activeXDocument.parentWindow.Object; activeXDocument = null; // avoid memory leak return temp; - }; // Create object with fake `null` prototype: use iframe Object with cleared prototype + }; + // Create object with fake `null` prototype: use iframe Object with cleared prototype var NullProtoObjectViaIFrame = function () { // Thrash, waste and sodomy: IE GC bug var iframe = documentCreateElement('iframe'); var JS = 'java' + SCRIPT + ':'; var iframeDocument; iframe.style.display = 'none'; - html.appendChild(iframe); // https://github.com/zloirock/core-js/issues/475 + html.appendChild(iframe); + // https://github.com/zloirock/core-js/issues/475 iframe.src = String(JS); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(scriptTag('document.F=Object')); iframeDocument.close(); return iframeDocument.F; - }; // Check for document.domain and active x support + }; + // Check for document.domain and active x support // No need to use active x approach when document.domain is not set // see https://github.com/es-shims/es5-shim/issues/150 // variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346 @@ -20686,22 +21339,23 @@ try { /* global ActiveXObject */ activeXDocument = document.domain && new ActiveXObject('htmlfile'); - } catch (error) { - /* ignore */ + } catch (error) { /* ignore */ } NullProtoObject = activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) : NullProtoObjectViaIFrame(); var length = enumBugKeys.length; while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]]; return NullProtoObject(); }; - hiddenKeys[IE_PROTO] = true; // `Object.create` method + hiddenKeys[IE_PROTO] = true; + // `Object.create` method // https://tc39.github.io/ecma262/#sec-object.create module.exports = Object.create || function create(O, Properties) { var result; if (O !== null) { EmptyConstructor[PROTOTYPE] = anObject(O); result = new EmptyConstructor(); - EmptyConstructor[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill + EmptyConstructor[PROTOTYPE] = null; + // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = NullProtoObject(); return Properties === undefined ? result : defineProperties(result, Properties); @@ -20722,7 +21376,8 @@ var DESCRIPTORS = _dereq_('../internals/descriptors'); var definePropertyModule = _dereq_('../internals/object-define-property'); var anObject = _dereq_('../internals/an-object'); - var objectKeys = _dereq_('../internals/object-keys'); // `Object.defineProperties` method + var objectKeys = _dereq_('../internals/object-keys'); + // `Object.defineProperties` method // https://tc39.github.io/ecma262/#sec-object.defineproperties module.exports = DESCRIPTORS ? Object.defineProperties : function defineProperties(O, Properties) { anObject(O); @@ -20747,7 +21402,8 @@ var IE8_DOM_DEFINE = _dereq_('../internals/ie8-dom-define'); var anObject = _dereq_('../internals/an-object'); var toPrimitive = _dereq_('../internals/to-primitive'); - var nativeDefineProperty = Object.defineProperty; // `Object.defineProperty` method + var nativeDefineProperty = Object.defineProperty; + // `Object.defineProperty` method // https://tc39.github.io/ecma262/#sec-object.defineproperty exports.f = DESCRIPTORS ? nativeDefineProperty : function defineProperty(O, P, Attributes) { anObject(O); @@ -20755,8 +21411,7 @@ anObject(Attributes); if (IE8_DOM_DEFINE) try { return nativeDefineProperty(O, P, Attributes); - } catch (error) { - /* empty */ + } catch (error) { /* empty */ } if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported'); if ('value' in Attributes) O[P] = Attributes.value; @@ -20767,7 +21422,7 @@ '../internals/an-object': 28, '../internals/descriptors': 61, '../internals/ie8-dom-define': 82, - '../internals/to-primitive': 156 + '../internals/to-primitive': 158 } ], 111: [ @@ -20779,15 +21434,15 @@ var toPrimitive = _dereq_('../internals/to-primitive'); var has = _dereq_('../internals/has'); var IE8_DOM_DEFINE = _dereq_('../internals/ie8-dom-define'); - var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // `Object.getOwnPropertyDescriptor` method + var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + // `Object.getOwnPropertyDescriptor` method // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor exports.f = DESCRIPTORS ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) { O = toIndexedObject(O); P = toPrimitive(P, true); if (IE8_DOM_DEFINE) try { return nativeGetOwnPropertyDescriptor(O, P); - } catch (error) { - /* empty */ + } catch (error) { /* empty */ } if (has(O, P)) return createPropertyDescriptor(!propertyIsEnumerableModule.f.call(O, P), O[P]); }; @@ -20798,8 +21453,8 @@ '../internals/has': 78, '../internals/ie8-dom-define': 82, '../internals/object-property-is-enumerable': 118, - '../internals/to-indexed-object': 150, - '../internals/to-primitive': 156 + '../internals/to-indexed-object': 152, + '../internals/to-primitive': 158 } ], 112: [ @@ -20816,21 +21471,23 @@ } catch (error) { return windowNames.slice(); } - }; // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window + }; + // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window module.exports.f = function getOwnPropertyNames(it) { return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : nativeGetOwnPropertyNames(toIndexedObject(it)); }; }, { '../internals/object-get-own-property-names': 113, - '../internals/to-indexed-object': 150 + '../internals/to-indexed-object': 152 } ], 113: [ function (_dereq_, module, exports) { var internalObjectKeys = _dereq_('../internals/object-keys-internal'); var enumBugKeys = _dereq_('../internals/enum-bug-keys'); - var hiddenKeys = enumBugKeys.concat('length', 'prototype'); // `Object.getOwnPropertyNames` method + var hiddenKeys = enumBugKeys.concat('length', 'prototype'); + // `Object.getOwnPropertyNames` method // https://tc39.github.io/ecma262/#sec-object.getownpropertynames exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { return internalObjectKeys(O, hiddenKeys); @@ -20855,7 +21512,8 @@ var sharedKey = _dereq_('../internals/shared-key'); var CORRECT_PROTOTYPE_GETTER = _dereq_('../internals/correct-prototype-getter'); var IE_PROTO = sharedKey('IE_PROTO'); - var ObjectPrototype = Object.prototype; // `Object.getPrototypeOf` method + var ObjectPrototype = Object.prototype; + // `Object.getPrototypeOf` method // https://tc39.github.io/ecma262/#sec-object.getprototypeof module.exports = CORRECT_PROTOTYPE_GETTER ? Object.getPrototypeOf : function (O) { O = toObject(O); @@ -20870,7 +21528,7 @@ '../internals/correct-prototype-getter': 53, '../internals/has': 78, '../internals/shared-key': 136, - '../internals/to-object': 153 + '../internals/to-object': 155 } ], 116: [ @@ -20885,7 +21543,8 @@ var result = [ ]; var key; - for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key); // Don't enum bug & hidden keys + for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key); + // Don't enum bug & hidden keys while (names.length > i) if (has(O, key = names[i++])) { ~indexOf(result, key) || result.push(key); } @@ -20896,13 +21555,14 @@ '../internals/array-includes': 36, '../internals/has': 78, '../internals/hidden-keys': 79, - '../internals/to-indexed-object': 150 + '../internals/to-indexed-object': 152 } ], 117: [ function (_dereq_, module, exports) { var internalObjectKeys = _dereq_('../internals/object-keys-internal'); - var enumBugKeys = _dereq_('../internals/enum-bug-keys'); // `Object.keys` method + var enumBugKeys = _dereq_('../internals/enum-bug-keys'); + // `Object.keys` method // https://tc39.github.io/ecma262/#sec-object.keys module.exports = Object.keys || function keys(O) { return internalObjectKeys(O, enumBugKeys); @@ -20918,10 +21578,12 @@ 'use strict'; var nativePropertyIsEnumerable = { }.propertyIsEnumerable; - var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // Nashorn ~ JDK8 bug + var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + // Nashorn ~ JDK8 bug var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 - }, 1); // `Object.prototype.propertyIsEnumerable` method implementation + }, 1); + // `Object.prototype.propertyIsEnumerable` method implementation // https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) { var descriptor = getOwnPropertyDescriptor(this, V); @@ -20935,7 +21597,8 @@ 119: [ function (_dereq_, module, exports) { var anObject = _dereq_('../internals/an-object'); - var aPossiblePrototype = _dereq_('../internals/a-possible-prototype'); // `Object.setPrototypeOf` method + var aPossiblePrototype = _dereq_('../internals/a-possible-prototype'); + // `Object.setPrototypeOf` method // https://tc39.github.io/ecma262/#sec-object.setprototypeof // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ @@ -20951,8 +21614,7 @@ setter.call(test, [ ]); CORRECT_SETTER = test instanceof Array; - } catch (error) { - /* empty */ + } catch (error) { /* empty */ } return function setPrototypeOf(O, proto) { anObject(O); @@ -20972,7 +21634,8 @@ function (_dereq_, module, exports) { 'use strict'; var TO_STRING_TAG_SUPPORT = _dereq_('../internals/to-string-tag-support'); - var classof = _dereq_('../internals/classof'); // `Object.prototype.toString` method implementation + var classof = _dereq_('../internals/classof'); + // `Object.prototype.toString` method implementation // https://tc39.github.io/ecma262/#sec-object.prototype.tostring module.exports = TO_STRING_TAG_SUPPORT ? { }.toString : function toString() { @@ -20981,7 +21644,7 @@ }, { '../internals/classof': 47, - '../internals/to-string-tag-support': 157 + '../internals/to-string-tag-support': 159 } ], 121: [ @@ -20989,7 +21652,8 @@ var getBuiltIn = _dereq_('../internals/get-built-in'); var getOwnPropertyNamesModule = _dereq_('../internals/object-get-own-property-names'); var getOwnPropertySymbolsModule = _dereq_('../internals/object-get-own-property-symbols'); - var anObject = _dereq_('../internals/an-object'); // all object keys, includes non-enumerable and symbols + var anObject = _dereq_('../internals/an-object'); + // all object keys, includes non-enumerable and symbols module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) { var keys = getOwnPropertyNamesModule.f(anObject(it)); var getOwnPropertySymbols = getOwnPropertySymbolsModule.f; @@ -21092,7 +21756,8 @@ simple = true; } if (simple) O[key] = value; - else createNonEnumerableProperty(O, key, value); // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative + else createNonEnumerableProperty(O, key, value); + // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative }) (Function.prototype, 'toString', function toString() { return typeof this == 'function' && getInternalState(this).source || inspectSource(this); }); @@ -21109,7 +21774,8 @@ 127: [ function (_dereq_, module, exports) { var classof = _dereq_('./classof-raw'); - var regexpExec = _dereq_('./regexp-exec'); // `RegExpExec` abstract operation + var regexpExec = _dereq_('./regexp-exec'); + // `RegExpExec` abstract operation // https://tc39.github.io/ecma262/#sec-regexpexec module.exports = function (R, S) { var exec = R.exec; @@ -21136,7 +21802,8 @@ 'use strict'; var regexpFlags = _dereq_('./regexp-flags'); var stickyHelpers = _dereq_('./regexp-sticky-helpers'); - var nativeExec = RegExp.prototype.exec; // This always refers to the native implementation, because the + var nativeExec = RegExp.prototype.exec; + // This always refers to the native implementation, because the // String#replace polyfill uses ./fix-regexp-well-known-symbol-logic.js, // which loads this file before patching the method. var nativeReplace = String.prototype.replace; @@ -21148,7 +21815,8 @@ nativeExec.call(re2, 'a'); return re1.lastIndex !== 0 || re2.lastIndex !== 0; }(); - var UNSUPPORTED_Y = stickyHelpers.UNSUPPORTED_Y || stickyHelpers.BROKEN_CARET; // nonparticipating capturing group, copied from es5-shim's String#split patch. + var UNSUPPORTED_Y = stickyHelpers.UNSUPPORTED_Y || stickyHelpers.BROKEN_CARET; + // nonparticipating capturing group, copied from es5-shim's String#split patch. var NPCG_INCLUDED = /()??/.exec('') [1] !== undefined; var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED || UNSUPPORTED_Y; if (PATCH) { @@ -21168,12 +21836,13 @@ if (flags.indexOf('g') === - 1) { flags += 'g'; } - strCopy = String(str).slice(re.lastIndex); // Support anchored sticky behavior. + strCopy = String(str).slice(re.lastIndex); + // Support anchored sticky behavior. if (re.lastIndex > 0 && (!re.multiline || re.multiline && str[re.lastIndex - 1] !== '\n')) { source = '(?: ' + source + ')'; strCopy = ' ' + strCopy; charsAdded++; - } // ^(? + rx + ) is needed, in combination with some str slicing, to + } // ^(? + rx + ) is needed, in combination with some str slicing, to // simulate the 'y' flag. reCopy = new RegExp('^(?:' + source + ')', flags); @@ -21215,7 +21884,8 @@ 129: [ function (_dereq_, module, exports) { 'use strict'; - var anObject = _dereq_('../internals/an-object'); // `RegExp.prototype.flags` getter implementation + var anObject = _dereq_('../internals/an-object'); + // `RegExp.prototype.flags` getter implementation // https://tc39.github.io/ecma262/#sec-get-regexp.prototype.flags module.exports = function () { var that = anObject(this); @@ -21236,7 +21906,8 @@ 130: [ function (_dereq_, module, exports) { 'use strict'; - var fails = _dereq_('./fails'); // babel-minify transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError, + var fails = _dereq_('./fails'); + // babel-minify transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError, // so we use an intermediate function. function RE(s, f) { return RegExp(s, f); @@ -21325,7 +21996,7 @@ '../internals/descriptors': 61, '../internals/get-built-in': 74, '../internals/object-define-property': 110, - '../internals/well-known-symbol': 164 + '../internals/well-known-symbol': 166 } ], 135: [ @@ -21346,7 +22017,7 @@ { '../internals/has': 78, '../internals/object-define-property': 110, - '../internals/well-known-symbol': 164 + '../internals/well-known-symbol': 166 } ], 136: [ @@ -21360,7 +22031,7 @@ }, { '../internals/shared': 138, - '../internals/uid': 161 + '../internals/uid': 163 } ], 137: [ @@ -21401,7 +22072,8 @@ var anObject = _dereq_('../internals/an-object'); var aFunction = _dereq_('../internals/a-function'); var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); - var SPECIES = wellKnownSymbol('species'); // `SpeciesConstructor` abstract operation + var SPECIES = wellKnownSymbol('species'); + // `SpeciesConstructor` abstract operation // https://tc39.github.io/ecma262/#sec-speciesconstructor module.exports = function (O, defaultConstructor) { var C = anObject(O).constructor; @@ -21412,12 +22084,13 @@ { '../internals/a-function': 23, '../internals/an-object': 28, - '../internals/well-known-symbol': 164 + '../internals/well-known-symbol': 166 } ], 140: [ function (_dereq_, module, exports) { - var fails = _dereq_('../internals/fails'); // check the existence of a method, lowercase + var fails = _dereq_('../internals/fails'); + // check the existence of a method, lowercase // of a tag and escaping quotes in arguments module.exports = function (METHOD_NAME) { return fails(function () { @@ -21433,7 +22106,8 @@ 141: [ function (_dereq_, module, exports) { var toInteger = _dereq_('../internals/to-integer'); - var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); // `String.prototype.{ codePointAt, at }` methods implementation + var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); + // `String.prototype.{ codePointAt, at }` methods implementation var createMethod = function (CONVERT_TO_STRING) { return function ($this, pos) { var S = String(requireObjectCoercible($this)); @@ -21457,12 +22131,62 @@ }, { '../internals/require-object-coercible': 131, - '../internals/to-integer': 151 + '../internals/to-integer': 153 } ], 142: [ function (_dereq_, module, exports) { - 'use strict'; // based on https://github.com/bestiejs/punycode.js/blob/master/punycode.js + // https://github.com/zloirock/core-js/issues/280 + var userAgent = _dereq_('../internals/engine-user-agent'); + // eslint-disable-next-line unicorn/no-unsafe-regex + module.exports = /Version\/10\.\d+(\.\d+)?( Mobile\/\w+)? Safari\//.test(userAgent); + }, + { + '../internals/engine-user-agent': 65 + } + ], + 143: [ + function (_dereq_, module, exports) { + // https://github.com/tc39/proposal-string-pad-start-end + var toLength = _dereq_('../internals/to-length'); + var repeat = _dereq_('../internals/string-repeat'); + var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); + var ceil = Math.ceil; + // `String.prototype.{ padStart, padEnd }` methods implementation + var createMethod = function (IS_END) { + return function ($this, maxLength, fillString) { + var S = String(requireObjectCoercible($this)); + var stringLength = S.length; + var fillStr = fillString === undefined ? ' ' : String(fillString); + var intMaxLength = toLength(maxLength); + var fillLen, + stringFiller; + if (intMaxLength <= stringLength || fillStr == '') return S; + fillLen = intMaxLength - stringLength; + stringFiller = repeat.call(fillStr, ceil(fillLen / fillStr.length)); + if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen); + return IS_END ? S + stringFiller : stringFiller + S; + }; + }; + module.exports = { + // `String.prototype.padStart` method + // https://tc39.github.io/ecma262/#sec-string.prototype.padstart + start: createMethod(false), + // `String.prototype.padEnd` method + // https://tc39.github.io/ecma262/#sec-string.prototype.padend + end: createMethod(true) + }; + }, + { + '../internals/require-object-coercible': 131, + '../internals/string-repeat': 145, + '../internals/to-length': 154 + } + ], + 144: [ + function (_dereq_, module, exports) { + 'use strict'; + // based on https://github.com/bestiejs/punycode.js/blob/master/punycode.js var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 var base = 36; var tMin = 1; @@ -21538,14 +22262,18 @@ // eslint-disable-next-line max-statements var encode = function (input) { var output = [ - ]; // Convert the input in UCS-2 to an array of Unicode code points. - input = ucs2decode(input); // Cache the length. - var inputLength = input.length; // Initialize the state. + ]; + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + // Cache the length. + var inputLength = input.length; + // Initialize the state. var n = initialN; var delta = 0; var bias = initialBias; var i, - currentValue; // Handle the basic code points. + currentValue; + // Handle the basic code points. for (i = 0; i < input.length; i++) { currentValue = input[i]; if (currentValue < 128) { @@ -21557,7 +22285,7 @@ // Finish the basic string with a delimiter unless it's empty. if (basicLength) { output.push(delimiter); - } // Main encoding loop: + } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next larger one: @@ -21567,7 +22295,7 @@ if (currentValue >= n && currentValue < m) { m = currentValue; } - } // Increase `delta` enough to advance the decoder's state to , but guard against overflow. + } // Increase `delta` enough to advance the decoder's state to , but guard against overflow. var handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { @@ -21583,8 +22311,8 @@ if (currentValue == n) { // Represent delta as a generalized variable-length integer. var q = delta; - for (var k = base; ; /* no condition */ - k += base) { + for /* no condition */ + (var k = base; ; k += base) { var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; if (q < t) break; var qMinusT = q - t; @@ -21619,11 +22347,12 @@ { } ], - 143: [ + 145: [ function (_dereq_, module, exports) { 'use strict'; var toInteger = _dereq_('../internals/to-integer'); - var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); // `String.prototype.repeat` method implementation + var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); + // `String.prototype.repeat` method implementation // https://tc39.github.io/ecma262/#sec-string.prototype.repeat module.exports = ''.repeat || function repeat(count) { var str = String(requireObjectCoercible(this)); @@ -21636,14 +22365,15 @@ }, { '../internals/require-object-coercible': 131, - '../internals/to-integer': 151 + '../internals/to-integer': 153 } ], - 144: [ + 146: [ function (_dereq_, module, exports) { var fails = _dereq_('../internals/fails'); var whitespaces = _dereq_('../internals/whitespaces'); - var non = '​…᠎'; // check that a method works with the correct list + var non = '​…᠎'; + // check that a method works with the correct list // of whitespaces and has a correct name module.exports = function (METHOD_NAME) { return fails(function () { @@ -21653,16 +22383,17 @@ }, { '../internals/fails': 69, - '../internals/whitespaces': 165 + '../internals/whitespaces': 167 } ], - 145: [ + 147: [ function (_dereq_, module, exports) { var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); var whitespaces = _dereq_('../internals/whitespaces'); var whitespace = '[' + whitespaces + ']'; var ltrim = RegExp('^' + whitespace + whitespace + '*'); - var rtrim = RegExp(whitespace + whitespace + '*$'); // `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation + var rtrim = RegExp(whitespace + whitespace + '*$'); + // `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation var createMethod = function (TYPE) { return function ($this) { var string = String(requireObjectCoercible($this)); @@ -21685,10 +22416,10 @@ }, { '../internals/require-object-coercible': 131, - '../internals/whitespaces': 165 + '../internals/whitespaces': 167 } ], - 146: [ + 148: [ function (_dereq_, module, exports) { var global = _dereq_('../internals/global'); var fails = _dereq_('../internals/fails'); @@ -21729,7 +22460,8 @@ var post = function (id) { // old engines have not location.origin global.postMessage(id + '', location.protocol + '//' + location.host); - }; // Node.js 0.9+ & IE10+ has setImmediate, otherwise: + }; + // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if (!set || !clear) { set = function setImmediate(fn) { var args = [ @@ -21745,32 +22477,38 @@ }; clear = function clearImmediate(id) { delete queue[id]; - }; // Node.js 0.8- + }; + // Node.js 0.8- if (classof(process) == 'process') { defer = function (id) { process.nextTick(runner(id)); - }; // Sphere (JS game engine) Dispatch API + }; + // Sphere (JS game engine) Dispatch API } else if (Dispatch && Dispatch.now) { defer = function (id) { Dispatch.now(runner(id)); - }; // Browsers with MessageChannel, includes WebWorkers + }; + // Browsers with MessageChannel, includes WebWorkers // except iOS - https://github.com/zloirock/core-js/issues/624 } else if (MessageChannel && !IS_IOS) { channel = new MessageChannel(); port = channel.port2; channel.port1.onmessage = listener; - defer = bind(port.postMessage, port, 1); // Browsers with postMessage, skip WebWorkers + defer = bind(port.postMessage, port, 1); + // Browsers with postMessage, skip WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts && !fails(post) && location.protocol !== 'file:') { defer = post; - global.addEventListener('message', listener, false); // IE8- + global.addEventListener('message', listener, false); + // IE8- } else if (ONREADYSTATECHANGE in createElement('script')) { defer = function (id) { html.appendChild(createElement('script')) [ONREADYSTATECHANGE] = function () { html.removeChild(this); run(id); }; - }; // Rest old browsers + }; + // Rest old browsers } else { defer = function (id) { setTimeout(runner(id), 0); @@ -21792,9 +22530,10 @@ '../internals/html': 81 } ], - 147: [ + 149: [ function (_dereq_, module, exports) { - var classof = _dereq_('../internals/classof-raw'); // `thisNumberValue` abstract operation + var classof = _dereq_('../internals/classof-raw'); + // `thisNumberValue` abstract operation // https://tc39.github.io/ecma262/#sec-thisnumbervalue module.exports = function (value) { if (typeof value != 'number' && classof(value) != 'Number') { @@ -21807,11 +22546,12 @@ '../internals/classof-raw': 46 } ], - 148: [ + 150: [ function (_dereq_, module, exports) { var toInteger = _dereq_('../internals/to-integer'); var max = Math.max; - var min = Math.min; // Helper for a popular repeating case of the spec: + var min = Math.min; + // Helper for a popular repeating case of the spec: // Let integer be ? ToInteger(index). // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length). module.exports = function (index, length) { @@ -21820,13 +22560,14 @@ }; }, { - '../internals/to-integer': 151 + '../internals/to-integer': 153 } ], - 149: [ + 151: [ function (_dereq_, module, exports) { var toInteger = _dereq_('../internals/to-integer'); - var toLength = _dereq_('../internals/to-length'); // `ToIndex` abstract operation + var toLength = _dereq_('../internals/to-length'); + // `ToIndex` abstract operation // https://tc39.github.io/ecma262/#sec-toindex module.exports = function (it) { if (it === undefined) return 0; @@ -21837,11 +22578,11 @@ }; }, { - '../internals/to-integer': 151, - '../internals/to-length': 152 + '../internals/to-integer': 153, + '../internals/to-length': 154 } ], - 150: [ + 152: [ function (_dereq_, module, exports) { // toObject with fallback for non-array-like ES3 strings var IndexedObject = _dereq_('../internals/indexed-object'); @@ -21855,10 +22596,11 @@ '../internals/require-object-coercible': 131 } ], - 151: [ + 153: [ function (_dereq_, module, exports) { var ceil = Math.ceil; - var floor = Math.floor; // `ToInteger` abstract operation + var floor = Math.floor; + // `ToInteger` abstract operation // https://tc39.github.io/ecma262/#sec-tointeger module.exports = function (argument) { return isNaN(argument = + argument) ? 0 : (argument > 0 ? floor : ceil) (argument); @@ -21867,22 +22609,24 @@ { } ], - 152: [ + 154: [ function (_dereq_, module, exports) { var toInteger = _dereq_('../internals/to-integer'); - var min = Math.min; // `ToLength` abstract operation + var min = Math.min; + // `ToLength` abstract operation // https://tc39.github.io/ecma262/#sec-tolength module.exports = function (argument) { return argument > 0 ? min(toInteger(argument), 9007199254740991) : 0; // 2 ** 53 - 1 == 9007199254740991 }; }, { - '../internals/to-integer': 151 + '../internals/to-integer': 153 } ], - 153: [ + 155: [ function (_dereq_, module, exports) { - var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); // `ToObject` abstract operation + var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); + // `ToObject` abstract operation // https://tc39.github.io/ecma262/#sec-toobject module.exports = function (argument) { return Object(requireObjectCoercible(argument)); @@ -21892,7 +22636,7 @@ '../internals/require-object-coercible': 131 } ], - 154: [ + 156: [ function (_dereq_, module, exports) { var toPositiveInteger = _dereq_('../internals/to-positive-integer'); module.exports = function (it, BYTES) { @@ -21902,10 +22646,10 @@ }; }, { - '../internals/to-positive-integer': 155 + '../internals/to-positive-integer': 157 } ], - 155: [ + 157: [ function (_dereq_, module, exports) { var toInteger = _dereq_('../internals/to-integer'); module.exports = function (it) { @@ -21915,12 +22659,13 @@ }; }, { - '../internals/to-integer': 151 + '../internals/to-integer': 153 } ], - 156: [ + 158: [ function (_dereq_, module, exports) { - var isObject = _dereq_('../internals/is-object'); // `ToPrimitive` abstract operation + var isObject = _dereq_('../internals/is-object'); + // `ToPrimitive` abstract operation // https://tc39.github.io/ecma262/#sec-toprimitive // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string @@ -21938,7 +22683,7 @@ '../internals/is-object': 92 } ], - 157: [ + 159: [ function (_dereq_, module, exports) { var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); var TO_STRING_TAG = wellKnownSymbol('toStringTag'); @@ -21948,10 +22693,10 @@ module.exports = String(test) === '[object z]'; }, { - '../internals/well-known-symbol': 164 + '../internals/well-known-symbol': 166 } ], - 158: [ + 160: [ function (_dereq_, module, exports) { 'use strict'; var $ = _dereq_('../internals/export'); @@ -22021,7 +22766,7 @@ return isTypedArrayIndex(target, key = toPrimitive(key, true)) ? createPropertyDescriptor(2, target[key]) : nativeGetOwnPropertyDescriptor(target, key); }; var wrappedDefineProperty = function defineProperty(target, key, descriptor) { - if (isTypedArrayIndex(target, key = toPrimitive(key, true)) && isObject(descriptor) && has(descriptor, 'value') && !has(descriptor, 'get') && !has(descriptor, 'set') // TODO: add validation descriptor w/o calling accessors + if (isTypedArrayIndex(target, key = toPrimitive(key, true)) && isObject(descriptor) && has(descriptor, 'value') && !has(descriptor, 'get') && !has(descriptor, 'set') // TODO: add validation descriptor w/o calling accessors && !descriptor.configurable && (!has(descriptor, 'writable') || descriptor.writable) && (!has(descriptor, 'enumerable') || descriptor.enumerable)) { target[key] = descriptor.value; return target; @@ -22154,8 +22899,7 @@ } setSpecies(CONSTRUCTOR_NAME); }; - } else module.exports = function () { - /* empty */ + } else module.exports = function () { /* empty */ }; }, { @@ -22179,15 +22923,15 @@ '../internals/object-get-own-property-names': 113, '../internals/object-set-prototype-of': 119, '../internals/set-species': 134, - '../internals/to-index': 149, - '../internals/to-length': 152, - '../internals/to-offset': 154, - '../internals/to-primitive': 156, - '../internals/typed-array-constructors-require-wrappers': 159, - '../internals/typed-array-from': 160 + '../internals/to-index': 151, + '../internals/to-length': 154, + '../internals/to-offset': 156, + '../internals/to-primitive': 158, + '../internals/typed-array-constructors-require-wrappers': 161, + '../internals/typed-array-from': 162 } ], - 159: [ + 161: [ function (_dereq_, module, exports) { /* eslint-disable no-new */ var global = _dereq_('../internals/global'); @@ -22217,7 +22961,7 @@ '../internals/global': 77 } ], - 160: [ + 162: [ function (_dereq_, module, exports) { var toObject = _dereq_('../internals/to-object'); var toLength = _dereq_('../internals/to-length'); @@ -22225,8 +22969,7 @@ var isArrayIteratorMethod = _dereq_('../internals/is-array-iterator-method'); var bind = _dereq_('../internals/function-bind-context'); var aTypedArrayConstructor = _dereq_('../internals/array-buffer-view-core').aTypedArrayConstructor; - module.exports = function from(source /* , mapfn, thisArg */ - ) { + module.exports = function from(source /* , mapfn, thisArg */ ) { var O = toObject(source); var argumentsLength = arguments.length; var mapfn = argumentsLength > 1 ? arguments[1] : undefined; @@ -22263,11 +23006,11 @@ '../internals/function-bind-context': 72, '../internals/get-iterator-method': 75, '../internals/is-array-iterator-method': 89, - '../internals/to-length': 152, - '../internals/to-object': 153 + '../internals/to-length': 154, + '../internals/to-object': 155 } ], - 161: [ + 163: [ function (_dereq_, module, exports) { var id = 0; var postfix = Math.random(); @@ -22278,27 +23021,27 @@ { } ], - 162: [ + 164: [ function (_dereq_, module, exports) { var NATIVE_SYMBOL = _dereq_('../internals/native-symbol'); - module.exports = NATIVE_SYMBOL // eslint-disable-next-line no-undef - && !Symbol.sham // eslint-disable-next-line no-undef + module.exports = NATIVE_SYMBOL // eslint-disable-next-line no-undef + && !Symbol.sham // eslint-disable-next-line no-undef && typeof Symbol.iterator == 'symbol'; }, { '../internals/native-symbol': 101 } ], - 163: [ + 165: [ function (_dereq_, module, exports) { var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); exports.f = wellKnownSymbol; }, { - '../internals/well-known-symbol': 164 + '../internals/well-known-symbol': 166 } ], - 164: [ + 166: [ function (_dereq_, module, exports) { var global = _dereq_('../internals/global'); var shared = _dereq_('../internals/shared'); @@ -22322,11 +23065,11 @@ '../internals/has': 78, '../internals/native-symbol': 101, '../internals/shared': 138, - '../internals/uid': 161, - '../internals/use-symbol-as-uid': 162 + '../internals/uid': 163, + '../internals/use-symbol-as-uid': 164 } ], - 165: [ + 167: [ function (_dereq_, module, exports) { // a string of all valid unicode whitespaces // eslint-disable-next-line max-len @@ -22335,7 +23078,7 @@ { } ], - 166: [ + 168: [ function (_dereq_, module, exports) { 'use strict'; var $ = _dereq_('../internals/export'); @@ -22344,7 +23087,8 @@ var setSpecies = _dereq_('../internals/set-species'); var ARRAY_BUFFER = 'ArrayBuffer'; var ArrayBuffer = arrayBufferModule[ARRAY_BUFFER]; - var NativeArrayBuffer = global[ARRAY_BUFFER]; // `ArrayBuffer` constructor + var NativeArrayBuffer = global[ARRAY_BUFFER]; + // `ArrayBuffer` constructor // https://tc39.github.io/ecma262/#sec-arraybuffer-constructor $({ global: true, @@ -22361,7 +23105,7 @@ '../internals/set-species': 134 } ], - 167: [ + 169: [ function (_dereq_, module, exports) { 'use strict'; var $ = _dereq_('../internals/export'); @@ -22377,7 +23121,8 @@ var V8_VERSION = _dereq_('../internals/engine-v8-version'); var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable'); var MAX_SAFE_INTEGER = 9007199254740991; - var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded'; // We can't use this feature detection in V8 since it causes + var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded'; + // We can't use this feature detection in V8 since it causes // deoptimization and serious performance degradation // https://github.com/zloirock/core-js/issues/679 var IS_CONCAT_SPREADABLE_SUPPORT = V8_VERSION >= 51 || !fails(function () { @@ -22392,7 +23137,8 @@ var spreadable = O[IS_CONCAT_SPREADABLE]; return spreadable !== undefined ? !!spreadable : isArray(O); }; - var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT; // `Array.prototype.concat` method + var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT; + // `Array.prototype.concat` method // https://tc39.github.io/ecma262/#sec-array.prototype.concat // with adding support of @@isConcatSpreadable and @@species $({ @@ -22435,23 +23181,25 @@ '../internals/fails': 69, '../internals/is-array': 90, '../internals/is-object': 92, - '../internals/to-length': 152, - '../internals/to-object': 153, - '../internals/well-known-symbol': 164 + '../internals/to-length': 154, + '../internals/to-object': 155, + '../internals/well-known-symbol': 166 } ], - 168: [ + 170: [ function (_dereq_, module, exports) { var $ = _dereq_('../internals/export'); var copyWithin = _dereq_('../internals/array-copy-within'); - var addToUnscopables = _dereq_('../internals/add-to-unscopables'); // `Array.prototype.copyWithin` method + var addToUnscopables = _dereq_('../internals/add-to-unscopables'); + // `Array.prototype.copyWithin` method // https://tc39.github.io/ecma262/#sec-array.prototype.copywithin $({ target: 'Array', proto: true }, { copyWithin: copyWithin - }); // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables + }); + // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables addToUnscopables('copyWithin'); }, { @@ -22460,7 +23208,7 @@ '../internals/export': 68 } ], - 169: [ + 171: [ function (_dereq_, module, exports) { 'use strict'; var $ = _dereq_('../internals/export'); @@ -22468,15 +23216,15 @@ var arrayMethodIsStrict = _dereq_('../internals/array-method-is-strict'); var arrayMethodUsesToLength = _dereq_('../internals/array-method-uses-to-length'); var STRICT_METHOD = arrayMethodIsStrict('every'); - var USES_TO_LENGTH = arrayMethodUsesToLength('every'); // `Array.prototype.every` method + var USES_TO_LENGTH = arrayMethodUsesToLength('every'); + // `Array.prototype.every` method // https://tc39.github.io/ecma262/#sec-array.prototype.every $({ target: 'Array', proto: true, forced: !STRICT_METHOD || !USES_TO_LENGTH }, { - every: function every(callbackfn /* , thisArg */ - ) { + every: function every(callbackfn /* , thisArg */ ) { return $every(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); @@ -22488,18 +23236,20 @@ '../internals/export': 68 } ], - 170: [ + 172: [ function (_dereq_, module, exports) { var $ = _dereq_('../internals/export'); var fill = _dereq_('../internals/array-fill'); - var addToUnscopables = _dereq_('../internals/add-to-unscopables'); // `Array.prototype.fill` method + var addToUnscopables = _dereq_('../internals/add-to-unscopables'); + // `Array.prototype.fill` method // https://tc39.github.io/ecma262/#sec-array.prototype.fill $({ target: 'Array', proto: true }, { fill: fill - }); // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables + }); + // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables addToUnscopables('fill'); }, { @@ -22508,15 +23258,17 @@ '../internals/export': 68 } ], - 171: [ + 173: [ function (_dereq_, module, exports) { 'use strict'; var $ = _dereq_('../internals/export'); var $filter = _dereq_('../internals/array-iteration').filter; var arrayMethodHasSpeciesSupport = _dereq_('../internals/array-method-has-species-support'); var arrayMethodUsesToLength = _dereq_('../internals/array-method-uses-to-length'); - var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('filter'); // Edge 14- issue - var USES_TO_LENGTH = arrayMethodUsesToLength('filter'); // `Array.prototype.filter` method + var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('filter'); + // Edge 14- issue + var USES_TO_LENGTH = arrayMethodUsesToLength('filter'); + // `Array.prototype.filter` method // https://tc39.github.io/ecma262/#sec-array.prototype.filter // with adding support of @@species $({ @@ -22524,8 +23276,7 @@ proto: true, forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH }, { - filter: function filter(callbackfn /* , thisArg */ - ) { + filter: function filter(callbackfn /* , thisArg */ ) { return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); @@ -22537,11 +23288,48 @@ '../internals/export': 68 } ], - 172: [ + 174: [ function (_dereq_, module, exports) { 'use strict'; var $ = _dereq_('../internals/export'); - var forEach = _dereq_('../internals/array-for-each'); // `Array.prototype.forEach` method + var $findIndex = _dereq_('../internals/array-iteration').findIndex; + var addToUnscopables = _dereq_('../internals/add-to-unscopables'); + var arrayMethodUsesToLength = _dereq_('../internals/array-method-uses-to-length'); + var FIND_INDEX = 'findIndex'; + var SKIPS_HOLES = true; + var USES_TO_LENGTH = arrayMethodUsesToLength(FIND_INDEX); + // Shouldn't skip holes + if (FIND_INDEX in [ + ]) Array(1) [FIND_INDEX](function () { + SKIPS_HOLES = false; + }); + // `Array.prototype.findIndex` method + // https://tc39.github.io/ecma262/#sec-array.prototype.findindex + $({ + target: 'Array', + proto: true, + forced: SKIPS_HOLES || !USES_TO_LENGTH + }, { + findIndex: function findIndex(callbackfn /* , that = undefined */ ) { + return $findIndex(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } + }); + // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables + addToUnscopables(FIND_INDEX); + }, + { + '../internals/add-to-unscopables': 25, + '../internals/array-iteration': 37, + '../internals/array-method-uses-to-length': 41, + '../internals/export': 68 + } + ], + 175: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var forEach = _dereq_('../internals/array-for-each'); + // `Array.prototype.forEach` method // https://tc39.github.io/ecma262/#sec-array.prototype.foreach $({ target: 'Array', @@ -22557,14 +23345,15 @@ '../internals/export': 68 } ], - 173: [ + 176: [ function (_dereq_, module, exports) { var $ = _dereq_('../internals/export'); var from = _dereq_('../internals/array-from'); var checkCorrectnessOfIteration = _dereq_('../internals/check-correctness-of-iteration'); var INCORRECT_ITERATION = !checkCorrectnessOfIteration(function (iterable) { Array.from(iterable); - }); // `Array.from` method + }); + // `Array.from` method // https://tc39.github.io/ecma262/#sec-array.from $({ target: 'Array', @@ -22580,7 +23369,7 @@ '../internals/export': 68 } ], - 174: [ + 177: [ function (_dereq_, module, exports) { 'use strict'; var $ = _dereq_('../internals/export'); @@ -22590,18 +23379,19 @@ var USES_TO_LENGTH = arrayMethodUsesToLength('indexOf', { ACCESSORS: true, 1: 0 - }); // `Array.prototype.includes` method + }); + // `Array.prototype.includes` method // https://tc39.github.io/ecma262/#sec-array.prototype.includes $({ target: 'Array', proto: true, forced: !USES_TO_LENGTH }, { - includes: function includes(el /* , fromIndex = 0 */ - ) { + includes: function includes(el /* , fromIndex = 0 */ ) { return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); } - }); // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables + }); + // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables addToUnscopables('includes'); }, { @@ -22611,7 +23401,7 @@ '../internals/export': 68 } ], - 175: [ + 178: [ function (_dereq_, module, exports) { 'use strict'; var $ = _dereq_('../internals/export'); @@ -22627,16 +23417,16 @@ var USES_TO_LENGTH = arrayMethodUsesToLength('indexOf', { ACCESSORS: true, 1: 0 - }); // `Array.prototype.indexOf` method + }); + // `Array.prototype.indexOf` method // https://tc39.github.io/ecma262/#sec-array.prototype.indexof $({ target: 'Array', proto: true, forced: NEGATIVE_ZERO || !STRICT_METHOD || !USES_TO_LENGTH }, { - indexOf: function indexOf(searchElement /* , fromIndex = 0 */ - ) { - return NEGATIVE_ZERO // convert -0 to +0 + indexOf: function indexOf(searchElement /* , fromIndex = 0 */ ) { + return NEGATIVE_ZERO // convert -0 to +0 ? nativeIndexOf.apply(this, arguments) || 0 : $indexOf(this, searchElement, arguments.length > 1 ? arguments[1] : undefined); } }); @@ -22648,7 +23438,7 @@ '../internals/export': 68 } ], - 176: [ + 179: [ function (_dereq_, module, exports) { 'use strict'; var toIndexedObject = _dereq_('../internals/to-indexed-object'); @@ -22658,7 +23448,8 @@ var defineIterator = _dereq_('../internals/define-iterator'); var ARRAY_ITERATOR = 'Array Iterator'; var setInternalState = InternalStateModule.set; - var getInternalState = InternalStateModule.getterFor(ARRAY_ITERATOR); // `Array.prototype.entries` method + var getInternalState = InternalStateModule.getterFor(ARRAY_ITERATOR); + // `Array.prototype.entries` method // https://tc39.github.io/ecma262/#sec-array.prototype.entries // `Array.prototype.keys` method // https://tc39.github.io/ecma262/#sec-array.prototype.keys @@ -22676,7 +23467,8 @@ index: 0, // next index kind: kind // kind - }); // `%ArrayIteratorPrototype%.next` method + }); + // `%ArrayIteratorPrototype%.next` method // https://tc39.github.io/ecma262/#sec-%arrayiteratorprototype%.next }, function () { var state = getInternalState(this); @@ -22705,10 +23497,12 @@ ], done: false }; - }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% + }, 'values'); + // argumentsList[@@iterator] is %ArrayProto_values% // https://tc39.github.io/ecma262/#sec-createunmappedargumentsobject // https://tc39.github.io/ecma262/#sec-createmappedargumentsobject - Iterators.Arguments = Iterators.Array; // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables + Iterators.Arguments = Iterators.Array; + // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); @@ -22718,10 +23512,10 @@ '../internals/define-iterator': 59, '../internals/internal-state': 88, '../internals/iterators': 97, - '../internals/to-indexed-object': 150 + '../internals/to-indexed-object': 152 } ], - 177: [ + 180: [ function (_dereq_, module, exports) { 'use strict'; var $ = _dereq_('../internals/export'); @@ -22731,7 +23525,8 @@ var nativeJoin = [ ].join; var ES3_STRINGS = IndexedObject != Object; - var STRICT_METHOD = arrayMethodIsStrict('join', ','); // `Array.prototype.join` method + var STRICT_METHOD = arrayMethodIsStrict('join', ','); + // `Array.prototype.join` method // https://tc39.github.io/ecma262/#sec-array.prototype.join $({ target: 'Array', @@ -22747,13 +23542,14 @@ '../internals/array-method-is-strict': 40, '../internals/export': 68, '../internals/indexed-object': 84, - '../internals/to-indexed-object': 150 + '../internals/to-indexed-object': 152 } ], - 178: [ + 181: [ function (_dereq_, module, exports) { var $ = _dereq_('../internals/export'); - var lastIndexOf = _dereq_('../internals/array-last-index-of'); // `Array.prototype.lastIndexOf` method + var lastIndexOf = _dereq_('../internals/array-last-index-of'); + // `Array.prototype.lastIndexOf` method // https://tc39.github.io/ecma262/#sec-array.prototype.lastindexof $({ target: 'Array', @@ -22768,15 +23564,17 @@ '../internals/export': 68 } ], - 179: [ + 182: [ function (_dereq_, module, exports) { 'use strict'; var $ = _dereq_('../internals/export'); var $map = _dereq_('../internals/array-iteration').map; var arrayMethodHasSpeciesSupport = _dereq_('../internals/array-method-has-species-support'); var arrayMethodUsesToLength = _dereq_('../internals/array-method-uses-to-length'); - var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('map'); // FF49- issue - var USES_TO_LENGTH = arrayMethodUsesToLength('map'); // `Array.prototype.map` method + var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('map'); + // FF49- issue + var USES_TO_LENGTH = arrayMethodUsesToLength('map'); + // `Array.prototype.map` method // https://tc39.github.io/ecma262/#sec-array.prototype.map // with adding support of @@species $({ @@ -22784,8 +23582,7 @@ proto: true, forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH }, { - map: function map(callbackfn /* , thisArg */ - ) { + map: function map(callbackfn /* , thisArg */ ) { return $map(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); @@ -22797,7 +23594,7 @@ '../internals/export': 68 } ], - 180: [ + 183: [ function (_dereq_, module, exports) { 'use strict'; var $ = _dereq_('../internals/export'); @@ -22819,7 +23616,8 @@ var SPECIES = wellKnownSymbol('species'); var nativeSlice = [ ].slice; - var max = Math.max; // `Array.prototype.slice` method + var max = Math.max; + // `Array.prototype.slice` method // https://tc39.github.io/ecma262/#sec-array.prototype.slice // fallback for not array-like ES3 strings and DOM objects $({ @@ -22831,12 +23629,14 @@ var O = toIndexedObject(this); var length = toLength(O.length); var k = toAbsoluteIndex(start, length); - var fin = toAbsoluteIndex(end === undefined ? length : end, length); // inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible + var fin = toAbsoluteIndex(end === undefined ? length : end, length); + // inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible var Constructor, result, n; if (isArray(O)) { - Constructor = O.constructor; // cross-realm fallback + Constructor = O.constructor; + // cross-realm fallback if (typeof Constructor == 'function' && (Constructor === Array || isArray(Constructor.prototype))) { Constructor = undefined; } else if (isObject(Constructor)) { @@ -22861,13 +23661,13 @@ '../internals/export': 68, '../internals/is-array': 90, '../internals/is-object': 92, - '../internals/to-absolute-index': 148, - '../internals/to-indexed-object': 150, - '../internals/to-length': 152, - '../internals/well-known-symbol': 164 + '../internals/to-absolute-index': 150, + '../internals/to-indexed-object': 152, + '../internals/to-length': 154, + '../internals/well-known-symbol': 166 } ], - 181: [ + 184: [ function (_dereq_, module, exports) { 'use strict'; var $ = _dereq_('../internals/export'); @@ -22875,15 +23675,15 @@ var arrayMethodIsStrict = _dereq_('../internals/array-method-is-strict'); var arrayMethodUsesToLength = _dereq_('../internals/array-method-uses-to-length'); var STRICT_METHOD = arrayMethodIsStrict('some'); - var USES_TO_LENGTH = arrayMethodUsesToLength('some'); // `Array.prototype.some` method + var USES_TO_LENGTH = arrayMethodUsesToLength('some'); + // `Array.prototype.some` method // https://tc39.github.io/ecma262/#sec-array.prototype.some $({ target: 'Array', proto: true, forced: !STRICT_METHOD || !USES_TO_LENGTH }, { - some: function some(callbackfn /* , thisArg */ - ) { + some: function some(callbackfn /* , thisArg */ ) { return $some(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); @@ -22895,7 +23695,7 @@ '../internals/export': 68 } ], - 182: [ + 185: [ function (_dereq_, module, exports) { 'use strict'; var $ = _dereq_('../internals/export'); @@ -22916,7 +23716,8 @@ var max = Math.max; var min = Math.min; var MAX_SAFE_INTEGER = 9007199254740991; - var MAXIMUM_ALLOWED_LENGTH_EXCEEDED = 'Maximum allowed length exceeded'; // `Array.prototype.splice` method + var MAXIMUM_ALLOWED_LENGTH_EXCEEDED = 'Maximum allowed length exceeded'; + // `Array.prototype.splice` method // https://tc39.github.io/ecma262/#sec-array.prototype.splice // with adding support of @@species $({ @@ -22924,8 +23725,7 @@ proto: true, forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH }, { - splice: function splice(start, deleteCount /* , ...items */ - ) { + splice: function splice(start, deleteCount /* , ...items */ ) { var O = toObject(this); var len = toLength(O.length); var actualStart = toAbsoluteIndex(start, len); @@ -22984,20 +23784,21 @@ '../internals/array-species-create': 43, '../internals/create-property': 58, '../internals/export': 68, - '../internals/to-absolute-index': 148, - '../internals/to-integer': 151, - '../internals/to-length': 152, - '../internals/to-object': 153 + '../internals/to-absolute-index': 150, + '../internals/to-integer': 153, + '../internals/to-length': 154, + '../internals/to-object': 155 } ], - 183: [ + 186: [ function (_dereq_, module, exports) { var DESCRIPTORS = _dereq_('../internals/descriptors'); var defineProperty = _dereq_('../internals/object-define-property').f; var FunctionPrototype = Function.prototype; var FunctionPrototypeToString = FunctionPrototype.toString; var nameRE = /^\s*function ([^ (]*)/; - var NAME = 'name'; // Function instances `.name` property + var NAME = 'name'; + // Function instances `.name` property // https://tc39.github.io/ecma262/#sec-function-instances-name if (DESCRIPTORS && !(NAME in FunctionPrototype)) { defineProperty(FunctionPrototype, NAME, { @@ -23017,11 +23818,12 @@ '../internals/object-define-property': 110 } ], - 184: [ + 187: [ function (_dereq_, module, exports) { 'use strict'; var collection = _dereq_('../internals/collection'); - var collectionStrong = _dereq_('../internals/collection-strong'); // `Map` constructor + var collectionStrong = _dereq_('../internals/collection-strong'); + // `Map` constructor // https://tc39.github.io/ecma262/#sec-map-objects module.exports = collection('Map', function (init) { return function Map() { @@ -23034,14 +23836,16 @@ '../internals/collection-strong': 48 } ], - 185: [ + 188: [ function (_dereq_, module, exports) { var $ = _dereq_('../internals/export'); var $hypot = Math.hypot; var abs = Math.abs; - var sqrt = Math.sqrt; // Chrome 77 bug + var sqrt = Math.sqrt; + // Chrome 77 bug // https://bugs.chromium.org/p/v8/issues/detail?id=9546 - var BUGGY = !!$hypot && $hypot(Infinity, NaN) !== Infinity; // `Math.hypot` method + var BUGGY = !!$hypot && $hypot(Infinity, NaN) !== Infinity; + // `Math.hypot` method // https://tc39.github.io/ecma262/#sec-math.hypot $({ target: 'Math', @@ -23075,10 +23879,31 @@ '../internals/export': 68 } ], - 186: [ + 189: [ function (_dereq_, module, exports) { var $ = _dereq_('../internals/export'); - var sign = _dereq_('../internals/math-sign'); // `Math.sign` method + var log = Math.log; + var LN2 = Math.LN2; + // `Math.log2` method + // https://tc39.github.io/ecma262/#sec-math.log2 + $({ + target: 'Math', + stat: true + }, { + log2: function log2(x) { + return log(x) / LN2; + } + }); + }, + { + '../internals/export': 68 + } + ], + 190: [ + function (_dereq_, module, exports) { + var $ = _dereq_('../internals/export'); + var sign = _dereq_('../internals/math-sign'); + // `Math.sign` method // https://tc39.github.io/ecma262/#sec-math.sign $({ target: 'Math', @@ -23092,7 +23917,7 @@ '../internals/math-sign': 98 } ], - 187: [ + 191: [ function (_dereq_, module, exports) { 'use strict'; var DESCRIPTORS = _dereq_('../internals/descriptors'); @@ -23111,8 +23936,10 @@ var trim = _dereq_('../internals/string-trim').trim; var NUMBER = 'Number'; var NativeNumber = global[NUMBER]; - var NumberPrototype = NativeNumber.prototype; // Opera ~12 has broken Object#toString - var BROKEN_CLASSOF = classof(create(NumberPrototype)) == NUMBER; // `ToNumber` abstract operation + var NumberPrototype = NativeNumber.prototype; + // Opera ~12 has broken Object#toString + var BROKEN_CLASSOF = classof(create(NumberPrototype)) == NUMBER; + // `ToNumber` abstract operation // https://tc39.github.io/ecma262/#sec-tonumber var toNumber = function (argument) { var it = toPrimitive(argument, false); @@ -23150,7 +23977,8 @@ digits = it.slice(2); length = digits.length; for (index = 0; index < length; index++) { - code = digits.charCodeAt(index); // parseInt parses a string to a first unavailable symbol + code = digits.charCodeAt(index); + // parseInt parses a string to a first unavailable symbol // but ToNumber should return NaN if a string contains unavailable symbols if (code < 48 || code > maxCode) return NaN; } @@ -23158,19 +23986,20 @@ } } return + it; - }; // `Number` constructor + }; + // `Number` constructor // https://tc39.github.io/ecma262/#sec-number-constructor if (isForced(NUMBER, !NativeNumber(' 0o1') || !NativeNumber('0b1') || NativeNumber('+0x1'))) { var NumberWrapper = function Number(value) { var it = arguments.length < 1 ? 0 : value; var dummy = this; - return dummy instanceof NumberWrapper // check on 1..constructor(foo) case + return dummy instanceof NumberWrapper // check on 1..constructor(foo) case && (BROKEN_CLASSOF ? fails(function () { NumberPrototype.valueOf.call(dummy); }) : classof(dummy) != NUMBER) ? inheritIfRequired(new NativeNumber(toNumber(it)), dummy, NumberWrapper) : toNumber(it); }; - for (var keys = DESCRIPTORS ? getOwnPropertyNames(NativeNumber) : ( // ES3: - 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + // ES2015 (in case, if modules with ES2015 Number statics required before): + for (var keys = DESCRIPTORS ? getOwnPropertyNames(NativeNumber) : ( // ES3: + 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + // ES2015 (in case, if modules with ES2015 Number statics required before): 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger').split(','), j = 0, key; keys.length > j; j++) { if (has(NativeNumber, key = keys[j]) && !has(NumberWrapper, key)) { defineProperty(NumberWrapper, key, getOwnPropertyDescriptor(NativeNumber, key)); @@ -23194,14 +24023,15 @@ '../internals/object-get-own-property-descriptor': 111, '../internals/object-get-own-property-names': 113, '../internals/redefine': 126, - '../internals/string-trim': 145, - '../internals/to-primitive': 156 + '../internals/string-trim': 147, + '../internals/to-primitive': 158 } ], - 188: [ + 192: [ function (_dereq_, module, exports) { var $ = _dereq_('../internals/export'); - var numberIsFinite = _dereq_('../internals/number-is-finite'); // `Number.isFinite` method + var numberIsFinite = _dereq_('../internals/number-is-finite'); + // `Number.isFinite` method // https://tc39.github.io/ecma262/#sec-number.isfinite $({ target: 'Number', @@ -23215,7 +24045,7 @@ '../internals/number-is-finite': 106 } ], - 189: [ + 193: [ function (_dereq_, module, exports) { 'use strict'; var $ = _dereq_('../internals/export'); @@ -23245,7 +24075,8 @@ // V8 ~ Android 4.3- nativeToFixed.call({ }); - }); // `Number.prototype.toFixed` method + }); + // `Number.prototype.toFixed` method // https://tc39.github.io/ecma262/#sec-number.prototype.tofixed $({ target: 'Number', @@ -23299,7 +24130,8 @@ } return s; }; - if (fractDigits < 0 || fractDigits > 20) throw RangeError('Incorrect fraction digits'); // eslint-disable-next-line no-self-compare + if (fractDigits < 0 || fractDigits > 20) throw RangeError('Incorrect fraction digits'); + // eslint-disable-next-line no-self-compare if (number != number) return 'NaN'; if (number <= - 1e+21 || number >= 1e+21) return String(number); if (number < 0) { @@ -23347,15 +24179,16 @@ { '../internals/export': 68, '../internals/fails': 69, - '../internals/string-repeat': 143, - '../internals/this-number-value': 147, - '../internals/to-integer': 151 + '../internals/string-repeat': 145, + '../internals/this-number-value': 149, + '../internals/to-integer': 153 } ], - 190: [ + 194: [ function (_dereq_, module, exports) { var $ = _dereq_('../internals/export'); - var assign = _dereq_('../internals/object-assign'); // `Object.assign` method + var assign = _dereq_('../internals/object-assign'); + // `Object.assign` method // https://tc39.github.io/ecma262/#sec-object.assign $({ target: 'Object', @@ -23370,7 +24203,34 @@ '../internals/object-assign': 107 } ], - 191: [ + 195: [ + function (_dereq_, module, exports) { + var $ = _dereq_('../internals/export'); + var iterate = _dereq_('../internals/iterate'); + var createProperty = _dereq_('../internals/create-property'); + // `Object.fromEntries` method + // https://github.com/tc39/proposal-object-from-entries + $({ + target: 'Object', + stat: true + }, { + fromEntries: function fromEntries(iterable) { + var obj = { + }; + iterate(iterable, function (k, v) { + createProperty(obj, k, v); + }, undefined, true); + return obj; + } + }); + }, + { + '../internals/create-property': 58, + '../internals/export': 68, + '../internals/iterate': 95 + } + ], + 196: [ function (_dereq_, module, exports) { var $ = _dereq_('../internals/export'); var fails = _dereq_('../internals/fails'); @@ -23380,7 +24240,8 @@ var FAILS_ON_PRIMITIVES = fails(function () { nativeGetOwnPropertyDescriptor(1); }); - var FORCED = !DESCRIPTORS || FAILS_ON_PRIMITIVES; // `Object.getOwnPropertyDescriptor` method + var FORCED = !DESCRIPTORS || FAILS_ON_PRIMITIVES; + // `Object.getOwnPropertyDescriptor` method // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor $({ target: 'Object', @@ -23398,17 +24259,18 @@ '../internals/export': 68, '../internals/fails': 69, '../internals/object-get-own-property-descriptor': 111, - '../internals/to-indexed-object': 150 + '../internals/to-indexed-object': 152 } ], - 192: [ + 197: [ function (_dereq_, module, exports) { var $ = _dereq_('../internals/export'); var fails = _dereq_('../internals/fails'); var nativeGetOwnPropertyNames = _dereq_('../internals/object-get-own-property-names-external').f; var FAILS_ON_PRIMITIVES = fails(function () { return !Object.getOwnPropertyNames(1); - }); // `Object.getOwnPropertyNames` method + }); + // `Object.getOwnPropertyNames` method // https://tc39.github.io/ecma262/#sec-object.getownpropertynames $({ target: 'Object', @@ -23424,7 +24286,7 @@ '../internals/object-get-own-property-names-external': 112 } ], - 193: [ + 198: [ function (_dereq_, module, exports) { var $ = _dereq_('../internals/export'); var fails = _dereq_('../internals/fails'); @@ -23433,7 +24295,8 @@ var CORRECT_PROTOTYPE_GETTER = _dereq_('../internals/correct-prototype-getter'); var FAILS_ON_PRIMITIVES = fails(function () { nativeGetPrototypeOf(1); - }); // `Object.getPrototypeOf` method + }); + // `Object.getPrototypeOf` method // https://tc39.github.io/ecma262/#sec-object.getprototypeof $({ target: 'Object', @@ -23451,10 +24314,10 @@ '../internals/export': 68, '../internals/fails': 69, '../internals/object-get-prototype-of': 115, - '../internals/to-object': 153 + '../internals/to-object': 155 } ], - 194: [ + 199: [ function (_dereq_, module, exports) { var $ = _dereq_('../internals/export'); var toObject = _dereq_('../internals/to-object'); @@ -23462,7 +24325,8 @@ var fails = _dereq_('../internals/fails'); var FAILS_ON_PRIMITIVES = fails(function () { nativeKeys(1); - }); // `Object.keys` method + }); + // `Object.keys` method // https://tc39.github.io/ecma262/#sec-object.keys $({ target: 'Object', @@ -23478,14 +24342,15 @@ '../internals/export': 68, '../internals/fails': 69, '../internals/object-keys': 117, - '../internals/to-object': 153 + '../internals/to-object': 155 } ], - 195: [ + 200: [ function (_dereq_, module, exports) { var TO_STRING_TAG_SUPPORT = _dereq_('../internals/to-string-tag-support'); var redefine = _dereq_('../internals/redefine'); - var toString = _dereq_('../internals/object-to-string'); // `Object.prototype.toString` method + var toString = _dereq_('../internals/object-to-string'); + // `Object.prototype.toString` method // https://tc39.github.io/ecma262/#sec-object.prototype.tostring if (!TO_STRING_TAG_SUPPORT) { redefine(Object.prototype, 'toString', toString, { @@ -23496,10 +24361,10 @@ { '../internals/object-to-string': 120, '../internals/redefine': 126, - '../internals/to-string-tag-support': 157 + '../internals/to-string-tag-support': 159 } ], - 196: [ + 201: [ function (_dereq_, module, exports) { 'use strict'; var $ = _dereq_('../internals/export'); @@ -23560,34 +24425,34 @@ // V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 // We can't detect it synchronously, so just check versions - if (V8_VERSION === 66) return true; // Unhandled rejections tracking support, NodeJS Promise without it fails @@species test + if (V8_VERSION === 66) return true; + // Unhandled rejections tracking support, NodeJS Promise without it fails @@species test if (!IS_NODE && typeof PromiseRejectionEvent != 'function') return true; - } // We need Promise#finally in the pure version for preventing prototype pollution + } // We need Promise#finally in the pure version for preventing prototype pollution - if (IS_PURE && !PromiseConstructor.prototype['finally']) return true; // We can't use @@species feature detection in V8 since it causes + if (IS_PURE && !PromiseConstructor.prototype['finally']) return true; + // We can't use @@species feature detection in V8 since it causes // deoptimization and performance degradation // https://github.com/zloirock/core-js/issues/679 - if (V8_VERSION >= 51 && /native code/.test(PromiseConstructor)) return false; // Detect correctness of subclassing with @@species support + if (V8_VERSION >= 51 && /native code/.test(PromiseConstructor)) return false; + // Detect correctness of subclassing with @@species support var promise = PromiseConstructor.resolve(1); var FakePromise = function (exec) { - exec(function () { - /* empty */ - }, function () { - /* empty */ + exec(function () { /* empty */ + }, function () { /* empty */ }); }; var constructor = promise.constructor = { }; constructor[SPECIES] = FakePromise; - return !(promise.then(function () { - /* empty */ + return !(promise.then(function () { /* empty */ }) instanceof FakePromise); }); var INCORRECT_ITERATION = FORCED || !checkCorrectnessOfIteration(function (iterable) { - PromiseConstructor.all(iterable) ['catch'](function () { - /* empty */ + PromiseConstructor.all(iterable) ['catch'](function () { /* empty */ }); - }); // helpers + }); + // helpers var isThenable = function (it) { var then; return isObject(it) && typeof (then = it.then) == 'function' ? then : false; @@ -23599,7 +24464,8 @@ microtask(function () { var value = state.value; var ok = state.state == FULFILLED; - var index = 0; // variable length - can't use forEach + var index = 0; + // variable length - can't use forEach while (chain.length > index) { var reaction = chain[index++]; var handler = ok ? reaction.ok : reaction.fail; @@ -23667,7 +24533,8 @@ if (IS_NODE) { process.emit('unhandledRejection', value, promise); } else dispatchEvent(UNHANDLED_REJECTION, promise, value); - }); // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should + }); + // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should state.rejection = IS_NODE || isUnhandled(state) ? UNHANDLED : HANDLED; if (result.error) throw result.value; } @@ -23724,7 +24591,8 @@ done: false }, error, state); } - }; // constructor polyfill + }; + // constructor polyfill if (FORCED) { // 25.4.3.1 Promise(executor) PromiseConstructor = function Promise(executor) { @@ -23737,7 +24605,8 @@ } catch (error) { internalReject(this, state, error); } - }; // eslint-disable-next-line no-unused-vars + }; + // eslint-disable-next-line no-unused-vars Internal = function Promise(executor) { setInternalState(this, { type: PROMISE, @@ -23782,23 +24651,25 @@ return C === PromiseConstructor || C === PromiseWrapper ? new OwnPromiseCapability(C) : newGenericPromiseCapability(C); }; if (!IS_PURE && typeof NativePromise == 'function') { - nativeThen = NativePromise.prototype.then; // wrap native Promise#then for native async functions + nativeThen = NativePromise.prototype.then; + // wrap native Promise#then for native async functions redefine(NativePromise.prototype, 'then', function then(onFulfilled, onRejected) { var that = this; return new PromiseConstructor(function (resolve, reject) { nativeThen.call(that, resolve, reject); - }).then(onFulfilled, onRejected); // https://github.com/zloirock/core-js/issues/640 + }).then(onFulfilled, onRejected); + // https://github.com/zloirock/core-js/issues/640 }, { unsafe: true - }); // wrap fetch result + }); + // wrap fetch result if (typeof $fetch == 'function') $({ global: true, enumerable: true, forced: true }, { // eslint-disable-next-line no-unused-vars - fetch: function fetch(input /* , init */ - ) { + fetch: function fetch(input /* , init */ ) { return promiseResolve(PromiseConstructor, $fetch.apply(global, arguments)); } }); @@ -23813,7 +24684,8 @@ }); setToStringTag(PromiseConstructor, PROMISE, false, true); setSpecies(PROMISE); - PromiseWrapper = getBuiltIn(PROMISE); // statics + PromiseWrapper = getBuiltIn(PROMISE); + // statics $({ target: PROMISE, stat: true, @@ -23916,11 +24788,11 @@ '../internals/set-species': 134, '../internals/set-to-string-tag': 135, '../internals/species-constructor': 139, - '../internals/task': 146, - '../internals/well-known-symbol': 164 + '../internals/task': 148, + '../internals/well-known-symbol': 166 } ], - 197: [ + 202: [ function (_dereq_, module, exports) { var $ = _dereq_('../internals/export'); var getBuiltIn = _dereq_('../internals/get-built-in'); @@ -23930,22 +24802,20 @@ var create = _dereq_('../internals/object-create'); var bind = _dereq_('../internals/function-bind'); var fails = _dereq_('../internals/fails'); - var nativeConstruct = getBuiltIn('Reflect', 'construct'); // `Reflect.construct` method + var nativeConstruct = getBuiltIn('Reflect', 'construct'); + // `Reflect.construct` method // https://tc39.github.io/ecma262/#sec-reflect.construct // MS Edge supports only 2 arguments and argumentsList argument is optional // FF Nightly sets third argument as `new.target`, but does not create `this` from it var NEW_TARGET_BUG = fails(function () { - function F() { - /* empty */ + function F() { /* empty */ } - return !(nativeConstruct(function () { - /* empty */ + return !(nativeConstruct(function () { /* empty */ }, [ ], F) instanceof F); }); var ARGS_BUG = !fails(function () { - nativeConstruct(function () { - /* empty */ + nativeConstruct(function () { /* empty */ }); }); var FORCED = NEW_TARGET_BUG || ARGS_BUG; @@ -23955,8 +24825,7 @@ forced: FORCED, sham: FORCED }, { - construct: function construct(Target, args /* , newTarget */ - ) { + construct: function construct(Target, args /* , newTarget */ ) { aFunction(Target); anObject(args); var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]); @@ -23974,14 +24843,14 @@ return new Target(args[0], args[1], args[2]); case 4: return new Target(args[0], args[1], args[2], args[3]); - } // w/o altered newTarget, lot of arguments case + } // w/o altered newTarget, lot of arguments case var $args = [ null ]; $args.push.apply($args, args); return new (bind.apply(Target, $args)) (); - } // with altered newTarget, not support built-in constructors + } // with altered newTarget, not support built-in constructors var proto = newTarget.prototype; var instance = create(isObject(proto) ? proto : Object.prototype); @@ -24001,7 +24870,41 @@ '../internals/object-create': 108 } ], - 198: [ + 203: [ + function (_dereq_, module, exports) { + var $ = _dereq_('../internals/export'); + var isObject = _dereq_('../internals/is-object'); + var anObject = _dereq_('../internals/an-object'); + var has = _dereq_('../internals/has'); + var getOwnPropertyDescriptorModule = _dereq_('../internals/object-get-own-property-descriptor'); + var getPrototypeOf = _dereq_('../internals/object-get-prototype-of'); + // `Reflect.get` method + // https://tc39.github.io/ecma262/#sec-reflect.get + function get(target, propertyKey /* , receiver */ ) { + var receiver = arguments.length < 3 ? target : arguments[2]; + var descriptor, + prototype; + if (anObject(target) === receiver) return target[propertyKey]; + if (descriptor = getOwnPropertyDescriptorModule.f(target, propertyKey)) return has(descriptor, 'value') ? descriptor.value : descriptor.get === undefined ? undefined : descriptor.get.call(receiver); + if (isObject(prototype = getPrototypeOf(target))) return get(prototype, propertyKey, receiver); + } + $({ + target: 'Reflect', + stat: true + }, { + get: get + }); + }, + { + '../internals/an-object': 28, + '../internals/export': 68, + '../internals/has': 78, + '../internals/is-object': 92, + '../internals/object-get-own-property-descriptor': 111, + '../internals/object-get-prototype-of': 115 + } + ], + 204: [ function (_dereq_, module, exports) { var DESCRIPTORS = _dereq_('../internals/descriptors'); var global = _dereq_('../internals/global'); @@ -24021,13 +24924,16 @@ var NativeRegExp = global.RegExp; var RegExpPrototype = NativeRegExp.prototype; var re1 = /a/g; - var re2 = /a/g; // "new" should create a new object, old webkit bug + var re2 = /a/g; + // "new" should create a new object, old webkit bug var CORRECT_NEW = new NativeRegExp(re1) !== re1; var UNSUPPORTED_Y = stickyHelpers.UNSUPPORTED_Y; var FORCED = DESCRIPTORS && isForced('RegExp', !CORRECT_NEW || UNSUPPORTED_Y || fails(function () { - re2[MATCH] = false; // RegExp constructor can alter flags and IsRegExp works correct with @@match + re2[MATCH] = false; + // RegExp constructor can alter flags and IsRegExp works correct with @@match return NativeRegExp(re1) != re1 || NativeRegExp(re2) == re2 || NativeRegExp(re1, 'i') != '/a/i'; - })); // `RegExp` constructor + })); + // `RegExp` constructor // https://tc39.github.io/ecma262/#sec-regexp-constructor if (FORCED) { var RegExpWrapper = function RegExp(pattern, flags) { @@ -24071,7 +24977,7 @@ RegExpPrototype.constructor = RegExpWrapper; RegExpWrapper.prototype = RegExpPrototype; redefine(global, 'RegExp', RegExpWrapper); - } // https://tc39.github.io/ecma262/#sec-get-regexp-@@species + } // https://tc39.github.io/ecma262/#sec-get-regexp-@@species setSpecies('RegExp'); }, @@ -24089,10 +24995,10 @@ '../internals/regexp-flags': 129, '../internals/regexp-sticky-helpers': 130, '../internals/set-species': 134, - '../internals/well-known-symbol': 164 + '../internals/well-known-symbol': 166 } ], - 199: [ + 205: [ function (_dereq_, module, exports) { 'use strict'; var $ = _dereq_('../internals/export'); @@ -24110,7 +25016,7 @@ '../internals/regexp-exec': 128 } ], - 200: [ + 206: [ function (_dereq_, module, exports) { 'use strict'; var redefine = _dereq_('../internals/redefine'); @@ -24125,8 +25031,10 @@ source: 'a', flags: 'b' }) != '/a/b'; - }); // FF44- RegExp#toString has a wrong name - var INCORRECT_NAME = nativeToString.name != TO_STRING; // `RegExp.prototype.toString` method + }); + // FF44- RegExp#toString has a wrong name + var INCORRECT_NAME = nativeToString.name != TO_STRING; + // `RegExp.prototype.toString` method // https://tc39.github.io/ecma262/#sec-regexp.prototype.tostring if (NOT_GENERIC || INCORRECT_NAME) { redefine(RegExp.prototype, TO_STRING, function toString() { @@ -24147,11 +25055,12 @@ '../internals/regexp-flags': 129 } ], - 201: [ + 207: [ function (_dereq_, module, exports) { 'use strict'; var collection = _dereq_('../internals/collection'); - var collectionStrong = _dereq_('../internals/collection-strong'); // `Set` constructor + var collectionStrong = _dereq_('../internals/collection-strong'); + // `Set` constructor // https://tc39.github.io/ecma262/#sec-set-objects module.exports = collection('Set', function (init) { return function Set() { @@ -24164,7 +25073,7 @@ '../internals/collection-strong': 48 } ], - 202: [ + 208: [ function (_dereq_, module, exports) { 'use strict'; var $ = _dereq_('../internals/export'); @@ -24176,19 +25085,20 @@ var IS_PURE = _dereq_('../internals/is-pure'); var nativeEndsWith = ''.endsWith; var min = Math.min; - var CORRECT_IS_REGEXP_LOGIC = correctIsRegExpLogic('endsWith'); // https://github.com/zloirock/core-js/pull/702 + var CORRECT_IS_REGEXP_LOGIC = correctIsRegExpLogic('endsWith'); + // https://github.com/zloirock/core-js/pull/702 var MDN_POLYFILL_BUG = !IS_PURE && !CORRECT_IS_REGEXP_LOGIC && !!function () { var descriptor = getOwnPropertyDescriptor(String.prototype, 'endsWith'); return descriptor && !descriptor.writable; - }(); // `String.prototype.endsWith` method + }(); + // `String.prototype.endsWith` method // https://tc39.github.io/ecma262/#sec-string.prototype.endswith $({ target: 'String', proto: true, forced: !MDN_POLYFILL_BUG && !CORRECT_IS_REGEXP_LOGIC }, { - endsWith: function endsWith(searchString /* , endPosition = @length */ - ) { + endsWith: function endsWith(searchString /* , endPosition = @length */ ) { var that = String(requireObjectCoercible(this)); notARegExp(searchString); var endPosition = arguments.length > 1 ? arguments[1] : undefined; @@ -24206,24 +25116,24 @@ '../internals/not-a-regexp': 105, '../internals/object-get-own-property-descriptor': 111, '../internals/require-object-coercible': 131, - '../internals/to-length': 152 + '../internals/to-length': 154 } ], - 203: [ + 209: [ function (_dereq_, module, exports) { 'use strict'; var $ = _dereq_('../internals/export'); var notARegExp = _dereq_('../internals/not-a-regexp'); var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); - var correctIsRegExpLogic = _dereq_('../internals/correct-is-regexp-logic'); // `String.prototype.includes` method + var correctIsRegExpLogic = _dereq_('../internals/correct-is-regexp-logic'); + // `String.prototype.includes` method // https://tc39.github.io/ecma262/#sec-string.prototype.includes $({ target: 'String', proto: true, forced: !correctIsRegExpLogic('includes') }, { - includes: function includes(searchString /* , position = 0 */ - ) { + includes: function includes(searchString /* , position = 0 */ ) { return !!~String(requireObjectCoercible(this)).indexOf(notARegExp(searchString), arguments.length > 1 ? arguments[1] : undefined); } }); @@ -24235,7 +25145,7 @@ '../internals/require-object-coercible': 131 } ], - 204: [ + 210: [ function (_dereq_, module, exports) { 'use strict'; var charAt = _dereq_('../internals/string-multibyte').charAt; @@ -24243,14 +25153,16 @@ var defineIterator = _dereq_('../internals/define-iterator'); var STRING_ITERATOR = 'String Iterator'; var setInternalState = InternalStateModule.set; - var getInternalState = InternalStateModule.getterFor(STRING_ITERATOR); // `String.prototype[@@iterator]` method + var getInternalState = InternalStateModule.getterFor(STRING_ITERATOR); + // `String.prototype[@@iterator]` method // https://tc39.github.io/ecma262/#sec-string.prototype-@@iterator defineIterator(String, 'String', function (iterated) { setInternalState(this, { type: STRING_ITERATOR, string: String(iterated), index: 0 - }); // `%StringIteratorPrototype%.next` method + }); + // `%StringIteratorPrototype%.next` method // https://tc39.github.io/ecma262/#sec-%stringiteratorprototype%.next }, function next() { var state = getInternalState(this); @@ -24275,7 +25187,7 @@ '../internals/string-multibyte': 141 } ], - 205: [ + 211: [ function (_dereq_, module, exports) { 'use strict'; var fixRegExpWellKnownSymbolLogic = _dereq_('../internals/fix-regexp-well-known-symbol-logic'); @@ -24283,15 +25195,17 @@ var toLength = _dereq_('../internals/to-length'); var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); var advanceStringIndex = _dereq_('../internals/advance-string-index'); - var regExpExec = _dereq_('../internals/regexp-exec-abstract'); // @@match logic + var regExpExec = _dereq_('../internals/regexp-exec-abstract'); + // @@match logic fixRegExpWellKnownSymbolLogic('match', 1, function (MATCH, nativeMatch, maybeCallNative) { - return [ // `String.prototype.match` method + return [ // `String.prototype.match` method // https://tc39.github.io/ecma262/#sec-string.prototype.match function match(regexp) { var O = requireObjectCoercible(this); var matcher = regexp == undefined ? undefined : regexp[MATCH]; return matcher !== undefined ? matcher.call(regexp, O) : new RegExp(regexp) [MATCH](String(O)); - }, // `RegExp.prototype[@@match]` method + }, + // `RegExp.prototype[@@match]` method // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@match function (regexp) { var res = maybeCallNative(nativeMatch, regexp, this); @@ -24322,13 +25236,38 @@ '../internals/fix-regexp-well-known-symbol-logic': 70, '../internals/regexp-exec-abstract': 127, '../internals/require-object-coercible': 131, - '../internals/to-length': 152 + '../internals/to-length': 154 } ], - 206: [ + 212: [ function (_dereq_, module, exports) { + 'use strict'; var $ = _dereq_('../internals/export'); - var repeat = _dereq_('../internals/string-repeat'); // `String.prototype.repeat` method + var $padStart = _dereq_('../internals/string-pad').start; + var WEBKIT_BUG = _dereq_('../internals/string-pad-webkit-bug'); + // `String.prototype.padStart` method + // https://tc39.github.io/ecma262/#sec-string.prototype.padstart + $({ + target: 'String', + proto: true, + forced: WEBKIT_BUG + }, { + padStart: function padStart(maxLength /* , fillString = ' ' */ ) { + return $padStart(this, maxLength, arguments.length > 1 ? arguments[1] : undefined); + } + }); + }, + { + '../internals/export': 68, + '../internals/string-pad': 143, + '../internals/string-pad-webkit-bug': 142 + } + ], + 213: [ + function (_dereq_, module, exports) { + var $ = _dereq_('../internals/export'); + var repeat = _dereq_('../internals/string-repeat'); + // `String.prototype.repeat` method // https://tc39.github.io/ecma262/#sec-string.prototype.repeat $({ target: 'String', @@ -24339,10 +25278,10 @@ }, { '../internals/export': 68, - '../internals/string-repeat': 143 + '../internals/string-repeat': 145 } ], - 207: [ + 214: [ function (_dereq_, module, exports) { 'use strict'; var fixRegExpWellKnownSymbolLogic = _dereq_('../internals/fix-regexp-well-known-symbol-logic'); @@ -24360,18 +25299,20 @@ var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d\d?)/g; var maybeToString = function (it) { return it === undefined ? it : String(it); - }; // @@replace logic + }; + // @@replace logic fixRegExpWellKnownSymbolLogic('replace', 2, function (REPLACE, nativeReplace, maybeCallNative, reason) { var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = reason.REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE; var REPLACE_KEEPS_$0 = reason.REPLACE_KEEPS_$0; var UNSAFE_SUBSTITUTE = REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE ? '$' : '$0'; - return [ // `String.prototype.replace` method + return [ // `String.prototype.replace` method // https://tc39.github.io/ecma262/#sec-string.prototype.replace function replace(searchValue, replaceValue) { var O = requireObjectCoercible(this); var replacer = searchValue == undefined ? undefined : searchValue[REPLACE]; return replacer !== undefined ? replacer.call(searchValue, O, replaceValue) : nativeReplace.call(String(O), searchValue, replaceValue); - }, // `RegExp.prototype[@@replace]` method + }, + // `RegExp.prototype[@@replace]` method // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@replace function (regexp, replaceValue) { if (!REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE && REPLACE_KEEPS_$0 || typeof replaceValue === 'string' && replaceValue.indexOf(UNSAFE_SUBSTITUTE) === - 1) { @@ -24404,7 +25345,8 @@ var matched = String(result[0]); var position = max(min(toInteger(result.index), S.length), 0); var captures = [ - ]; // NOTE: This is equivalent to + ]; + // NOTE: This is equivalent to // captures = result.slice(1).map(maybeToString) // but for some reason `nativeSlice.call(result, 1, result.length)` (called in // the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and @@ -24427,7 +25369,8 @@ } return accumulatedResult + S.slice(nextSourcePosition); } - ]; // https://tc39.github.io/ecma262/#sec-getsubstitution + ]; + // https://tc39.github.io/ecma262/#sec-getsubstitution function getSubstitution(matched, str, position, captures, namedCaptures, replacement) { var tailPos = position + matched.length; var m = captures.length; @@ -24473,27 +25416,29 @@ '../internals/fix-regexp-well-known-symbol-logic': 70, '../internals/regexp-exec-abstract': 127, '../internals/require-object-coercible': 131, - '../internals/to-integer': 151, - '../internals/to-length': 152, - '../internals/to-object': 153 + '../internals/to-integer': 153, + '../internals/to-length': 154, + '../internals/to-object': 155 } ], - 208: [ + 215: [ function (_dereq_, module, exports) { 'use strict'; var fixRegExpWellKnownSymbolLogic = _dereq_('../internals/fix-regexp-well-known-symbol-logic'); var anObject = _dereq_('../internals/an-object'); var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); var sameValue = _dereq_('../internals/same-value'); - var regExpExec = _dereq_('../internals/regexp-exec-abstract'); // @@search logic + var regExpExec = _dereq_('../internals/regexp-exec-abstract'); + // @@search logic fixRegExpWellKnownSymbolLogic('search', 1, function (SEARCH, nativeSearch, maybeCallNative) { - return [ // `String.prototype.search` method + return [ // `String.prototype.search` method // https://tc39.github.io/ecma262/#sec-string.prototype.search function search(regexp) { var O = requireObjectCoercible(this); var searcher = regexp == undefined ? undefined : regexp[SEARCH]; return searcher !== undefined ? searcher.call(regexp, O) : new RegExp(regexp) [SEARCH](String(O)); - }, // `RegExp.prototype[@@search]` method + }, + // `RegExp.prototype[@@search]` method // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@search function (regexp) { var res = maybeCallNative(nativeSearch, regexp, this); @@ -24517,7 +25462,7 @@ '../internals/same-value': 132 } ], - 209: [ + 216: [ function (_dereq_, module, exports) { 'use strict'; var fixRegExpWellKnownSymbolLogic = _dereq_('../internals/fix-regexp-well-known-symbol-logic'); @@ -24533,10 +25478,12 @@ var arrayPush = [ ].push; var min = Math.min; - var MAX_UINT32 = 4294967295; // babel-minify transpiles RegExp('x', 'y') -> /x/y and it causes SyntaxError + var MAX_UINT32 = 4294967295; + // babel-minify transpiles RegExp('x', 'y') -> /x/y and it causes SyntaxError var SUPPORTS_Y = !fails(function () { return !RegExp(MAX_UINT32, 'y'); - }); // @@split logic + }); + // @@split logic fixRegExpWellKnownSymbolLogic('split', 2, function (SPLIT, nativeSplit, maybeCallNative) { var internalSplit; if ('abbc'.split(/(b)*/) [1] == 'c' || 'test'.split(/(?:)/, - 1).length != 4 || 'ab'.split(/(?:ab)*/).length != 2 || '.'.split(/(.?)(.?)/).length != 4 || '.'.split(/()()/).length > 1 || ''.split(/.?/).length) { @@ -24545,14 +25492,16 @@ var string = String(requireObjectCoercible(this)); var lim = limit === undefined ? MAX_UINT32 : limit >>> 0; if (lim === 0) return []; - if (separator === undefined) return [string]; // If `separator` is not a regex, use native split + if (separator === undefined) return [string]; + // If `separator` is not a regex, use native split if (!isRegExp(separator)) { return nativeSplit.call(string, separator, lim); } var output = [ ]; var flags = (separator.ignoreCase ? 'i' : '') + (separator.multiline ? 'm' : '') + (separator.unicode ? 'u' : '') + (separator.sticky ? 'y' : ''); - var lastLastIndex = 0; // Make `global` and avoid `lastIndex` issues by working with a copy + var lastLastIndex = 0; + // Make `global` and avoid `lastIndex` issues by working with a copy var separatorCopy = new RegExp(separator.source, flags + 'g'); var match, lastIndex, @@ -24572,20 +25521,22 @@ if (lastLength || !separatorCopy.test('')) output.push(''); } else output.push(string.slice(lastLastIndex)); return output.length > lim ? output.slice(0, lim) : output; - }; // Chakra, V8 + }; + // Chakra, V8 } else if ('0'.split(undefined, 0).length) { internalSplit = function (separator, limit) { return separator === undefined && limit === 0 ? [ ] : nativeSplit.call(this, separator, limit); }; } else internalSplit = nativeSplit; - return [ // `String.prototype.split` method + return [ // `String.prototype.split` method // https://tc39.github.io/ecma262/#sec-string.prototype.split function split(separator, limit) { var O = requireObjectCoercible(this); var splitter = separator == undefined ? undefined : separator[SPLIT]; return splitter !== undefined ? splitter.call(separator, O, limit) : internalSplit.call(String(O), separator, limit); - }, // `RegExp.prototype[@@split]` method + }, + // `RegExp.prototype[@@split]` method // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@split // // NOTE: This cannot be properly polyfilled in engines that don't support @@ -24597,7 +25548,8 @@ var S = String(this); var C = speciesConstructor(rx, RegExp); var unicodeMatching = rx.unicode; - var flags = (rx.ignoreCase ? 'i' : '') + (rx.multiline ? 'm' : '') + (rx.unicode ? 'u' : '') + (SUPPORTS_Y ? 'y' : 'g'); // ^(? + rx + ) is needed, in combination with some S slicing, to + var flags = (rx.ignoreCase ? 'i' : '') + (rx.multiline ? 'm' : '') + (rx.unicode ? 'u' : '') + (SUPPORTS_Y ? 'y' : 'g'); + // ^(? + rx + ) is needed, in combination with some S slicing, to // simulate the 'y' flag. var splitter = new C(SUPPORTS_Y ? rx : '^(?:' + rx.source + ')', flags); var lim = limit === undefined ? MAX_UINT32 : limit >>> 0; @@ -24642,15 +25594,60 @@ '../internals/regexp-exec-abstract': 127, '../internals/require-object-coercible': 131, '../internals/species-constructor': 139, - '../internals/to-length': 152 + '../internals/to-length': 154 } ], - 210: [ + 217: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var getOwnPropertyDescriptor = _dereq_('../internals/object-get-own-property-descriptor').f; + var toLength = _dereq_('../internals/to-length'); + var notARegExp = _dereq_('../internals/not-a-regexp'); + var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); + var correctIsRegExpLogic = _dereq_('../internals/correct-is-regexp-logic'); + var IS_PURE = _dereq_('../internals/is-pure'); + var nativeStartsWith = ''.startsWith; + var min = Math.min; + var CORRECT_IS_REGEXP_LOGIC = correctIsRegExpLogic('startsWith'); + // https://github.com/zloirock/core-js/pull/702 + var MDN_POLYFILL_BUG = !IS_PURE && !CORRECT_IS_REGEXP_LOGIC && !!function () { + var descriptor = getOwnPropertyDescriptor(String.prototype, 'startsWith'); + return descriptor && !descriptor.writable; + }(); + // `String.prototype.startsWith` method + // https://tc39.github.io/ecma262/#sec-string.prototype.startswith + $({ + target: 'String', + proto: true, + forced: !MDN_POLYFILL_BUG && !CORRECT_IS_REGEXP_LOGIC + }, { + startsWith: function startsWith(searchString /* , position = 0 */ ) { + var that = String(requireObjectCoercible(this)); + notARegExp(searchString); + var index = toLength(min(arguments.length > 1 ? arguments[1] : undefined, that.length)); + var search = String(searchString); + return nativeStartsWith ? nativeStartsWith.call(that, search, index) : that.slice(index, index + search.length) === search; + } + }); + }, + { + '../internals/correct-is-regexp-logic': 52, + '../internals/export': 68, + '../internals/is-pure': 93, + '../internals/not-a-regexp': 105, + '../internals/object-get-own-property-descriptor': 111, + '../internals/require-object-coercible': 131, + '../internals/to-length': 154 + } + ], + 218: [ function (_dereq_, module, exports) { 'use strict'; var $ = _dereq_('../internals/export'); var createHTML = _dereq_('../internals/create-html'); - var forcedStringHTMLMethod = _dereq_('../internals/string-html-forced'); // `String.prototype.sub` method + var forcedStringHTMLMethod = _dereq_('../internals/string-html-forced'); + // `String.prototype.sub` method // https://tc39.github.io/ecma262/#sec-string.prototype.sub $({ target: 'String', @@ -24668,12 +25665,13 @@ '../internals/string-html-forced': 140 } ], - 211: [ + 219: [ function (_dereq_, module, exports) { 'use strict'; var $ = _dereq_('../internals/export'); var $trim = _dereq_('../internals/string-trim').trim; - var forcedStringTrimMethod = _dereq_('../internals/string-trim-forced'); // `String.prototype.trim` method + var forcedStringTrimMethod = _dereq_('../internals/string-trim-forced'); + // `String.prototype.trim` method // https://tc39.github.io/ecma262/#sec-string.prototype.trim $({ target: 'String', @@ -24687,11 +25685,11 @@ }, { '../internals/export': 68, - '../internals/string-trim': 145, - '../internals/string-trim-forced': 144 + '../internals/string-trim': 147, + '../internals/string-trim-forced': 146 } ], - 212: [ + 220: [ function (_dereq_, module, exports) { // `Symbol.prototype.description` getter // https://tc39.github.io/ecma262/#sec-symbol.prototype.description @@ -24704,13 +25702,14 @@ var defineProperty = _dereq_('../internals/object-define-property').f; var copyConstructorProperties = _dereq_('../internals/copy-constructor-properties'); var NativeSymbol = global.Symbol; - if (DESCRIPTORS && typeof NativeSymbol == 'function' && (!('description' in NativeSymbol.prototype) || // Safari 12 bug + if (DESCRIPTORS && typeof NativeSymbol == 'function' && (!('description' in NativeSymbol.prototype) || // Safari 12 bug NativeSymbol().description !== undefined)) { var EmptyStringDescriptionStore = { - }; // wrap Symbol constructor for correct work with undefined description + }; + // wrap Symbol constructor for correct work with undefined description var SymbolWrapper = function Symbol() { var description = arguments.length < 1 || arguments[0] === undefined ? undefined : String(arguments[0]); - var result = this instanceof SymbolWrapper ? new NativeSymbol(description) // in Edge 13, String(Symbol(undefined)) === 'Symbol(undefined)' + var result = this instanceof SymbolWrapper ? new NativeSymbol(description) // in Edge 13, String(Symbol(undefined)) === 'Symbol(undefined)' : description === undefined ? NativeSymbol() : NativeSymbol(description); if (description === '') EmptyStringDescriptionStore[result] = true; return result; @@ -24749,9 +25748,10 @@ '../internals/object-define-property': 110 } ], - 213: [ + 221: [ function (_dereq_, module, exports) { - var defineWellKnownSymbol = _dereq_('../internals/define-well-known-symbol'); // `Symbol.iterator` well-known symbol + var defineWellKnownSymbol = _dereq_('../internals/define-well-known-symbol'); + // `Symbol.iterator` well-known symbol // https://tc39.github.io/ecma262/#sec-symbol.iterator defineWellKnownSymbol('iterator'); }, @@ -24759,7 +25759,7 @@ '../internals/define-well-known-symbol': 60 } ], - 214: [ + 222: [ function (_dereq_, module, exports) { 'use strict'; var $ = _dereq_('../internals/export'); @@ -24816,8 +25816,10 @@ var StringToSymbolRegistry = shared('string-to-symbol-registry'); var SymbolToStringRegistry = shared('symbol-to-string-registry'); var WellKnownSymbolsStore = shared('wks'); - var QObject = global.QObject; // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 - var USE_SETTER = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 + var QObject = global.QObject; + // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 + var USE_SETTER = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; + // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 var setSymbolDescriptor = DESCRIPTORS && fails(function () { return nativeObjectCreate(nativeDefineProperty({ }, 'a', { @@ -24920,7 +25922,8 @@ } }); return result; - }; // `Symbol` constructor + }; + // `Symbol` constructor // https://tc39.github.io/ecma262/#sec-symbol-constructor if (!NATIVE_SYMBOL) { $Symbol = function Symbol() { @@ -25036,7 +26039,8 @@ // `Object.getOwnPropertySymbols` method // https://tc39.github.io/ecma262/#sec-object.getownpropertysymbols getOwnPropertySymbols: $getOwnPropertySymbols - }); // Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives + }); + // Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives // https://bugs.chromium.org/p/v8/issues/detail?id=3443 $({ target: 'Object', @@ -25048,15 +26052,17 @@ getOwnPropertySymbols: function getOwnPropertySymbols(it) { return getOwnPropertySymbolsModule.f(toObject(it)); } - }); // `JSON.stringify` method behavior with symbols + }); + // `JSON.stringify` method behavior with symbols // https://tc39.github.io/ecma262/#sec-json.stringify if ($stringify) { var FORCED_JSON_STRINGIFY = !NATIVE_SYMBOL || fails(function () { - var symbol = $Symbol(); // MS Edge converts symbol values to JSON as {} - return $stringify([symbol]) != '[null]' // WebKit converts symbol values to JSON as null + var symbol = $Symbol(); + // MS Edge converts symbol values to JSON as {} + return $stringify([symbol]) != '[null]' // WebKit converts symbol values to JSON as null || $stringify({ a: symbol - }) != '{}' // V8 throws on boxed symbols + }) != '{}' // V8 throws on boxed symbols || $stringify(Object(symbol)) != '{}'; }); $({ @@ -25082,12 +26088,12 @@ return $stringify.apply(null, args); } }); - } // `Symbol.prototype[@@toPrimitive]` method + } // `Symbol.prototype[@@toPrimitive]` method // https://tc39.github.io/ecma262/#sec-symbol.prototype-@@toprimitive if (!$Symbol[PROTOTYPE][TO_PRIMITIVE]) { createNonEnumerableProperty($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); - } // `Symbol.prototype[@@toStringTag]` property + } // `Symbol.prototype[@@toStringTag]` property // https://tc39.github.io/ecma262/#sec-symbol.prototype-@@tostringtag setToStringTag($Symbol, SYMBOL); @@ -25123,25 +26129,25 @@ '../internals/set-to-string-tag': 135, '../internals/shared': 138, '../internals/shared-key': 136, - '../internals/to-indexed-object': 150, - '../internals/to-object': 153, - '../internals/to-primitive': 156, - '../internals/uid': 161, - '../internals/use-symbol-as-uid': 162, - '../internals/well-known-symbol': 164, - '../internals/well-known-symbol-wrapped': 163 + '../internals/to-indexed-object': 152, + '../internals/to-object': 155, + '../internals/to-primitive': 158, + '../internals/uid': 163, + '../internals/use-symbol-as-uid': 164, + '../internals/well-known-symbol': 166, + '../internals/well-known-symbol-wrapped': 165 } ], - 215: [ + 223: [ function (_dereq_, module, exports) { 'use strict'; var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); var $copyWithin = _dereq_('../internals/array-copy-within'); var aTypedArray = ArrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.copyWithin` method + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.copyWithin` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.copywithin - exportTypedArrayMethod('copyWithin', function copyWithin(target, start /* , end */ - ) { + exportTypedArrayMethod('copyWithin', function copyWithin(target, start /* , end */ ) { return $copyWithin.call(aTypedArray(this), target, start, arguments.length > 2 ? arguments[2] : undefined); }); }, @@ -25150,16 +26156,16 @@ '../internals/array-copy-within': 32 } ], - 216: [ + 224: [ function (_dereq_, module, exports) { 'use strict'; var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); var $every = _dereq_('../internals/array-iteration').every; var aTypedArray = ArrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.every` method + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.every` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.every - exportTypedArrayMethod('every', function every(callbackfn /* , thisArg */ - ) { + exportTypedArrayMethod('every', function every(callbackfn /* , thisArg */ ) { return $every(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); }); }, @@ -25168,17 +26174,17 @@ '../internals/array-iteration': 37 } ], - 217: [ + 225: [ function (_dereq_, module, exports) { 'use strict'; var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); var $fill = _dereq_('../internals/array-fill'); var aTypedArray = ArrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.fill` method + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.fill` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.fill // eslint-disable-next-line no-unused-vars - exportTypedArrayMethod('fill', function fill(value /* , start, end */ - ) { + exportTypedArrayMethod('fill', function fill(value /* , start, end */ ) { return $fill.apply(aTypedArray(this), arguments); }); }, @@ -25187,7 +26193,7 @@ '../internals/array-fill': 33 } ], - 218: [ + 226: [ function (_dereq_, module, exports) { 'use strict'; var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); @@ -25195,10 +26201,10 @@ var speciesConstructor = _dereq_('../internals/species-constructor'); var aTypedArray = ArrayBufferViewCore.aTypedArray; var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor; - var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.filter` method + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.filter` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.filter - exportTypedArrayMethod('filter', function filter(callbackfn /* , thisArg */ - ) { + exportTypedArrayMethod('filter', function filter(callbackfn /* , thisArg */ ) { var list = $filter(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); var C = speciesConstructor(this, this.constructor); var index = 0; @@ -25214,16 +26220,16 @@ '../internals/species-constructor': 139 } ], - 219: [ + 227: [ function (_dereq_, module, exports) { 'use strict'; var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); var $findIndex = _dereq_('../internals/array-iteration').findIndex; var aTypedArray = ArrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.findIndex` method + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.findIndex` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.findindex - exportTypedArrayMethod('findIndex', function findIndex(predicate /* , thisArg */ - ) { + exportTypedArrayMethod('findIndex', function findIndex(predicate /* , thisArg */ ) { return $findIndex(aTypedArray(this), predicate, arguments.length > 1 ? arguments[1] : undefined); }); }, @@ -25232,16 +26238,16 @@ '../internals/array-iteration': 37 } ], - 220: [ + 228: [ function (_dereq_, module, exports) { 'use strict'; var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); var $find = _dereq_('../internals/array-iteration').find; var aTypedArray = ArrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.find` method + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.find` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.find - exportTypedArrayMethod('find', function find(predicate /* , thisArg */ - ) { + exportTypedArrayMethod('find', function find(predicate /* , thisArg */ ) { return $find(aTypedArray(this), predicate, arguments.length > 1 ? arguments[1] : undefined); }); }, @@ -25250,9 +26256,10 @@ '../internals/array-iteration': 37 } ], - 221: [ + 229: [ function (_dereq_, module, exports) { - var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); // `Float32Array` constructor + var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); + // `Float32Array` constructor // https://tc39.github.io/ecma262/#sec-typedarray-objects createTypedArrayConstructor('Float32', function (init) { return function Float32Array(data, byteOffset, length) { @@ -25261,12 +26268,13 @@ }); }, { - '../internals/typed-array-constructor': 158 + '../internals/typed-array-constructor': 160 } ], - 222: [ + 230: [ function (_dereq_, module, exports) { - var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); // `Float64Array` constructor + var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); + // `Float64Array` constructor // https://tc39.github.io/ecma262/#sec-typedarray-objects createTypedArrayConstructor('Float64', function (init) { return function Float64Array(data, byteOffset, length) { @@ -25275,19 +26283,19 @@ }); }, { - '../internals/typed-array-constructor': 158 + '../internals/typed-array-constructor': 160 } ], - 223: [ + 231: [ function (_dereq_, module, exports) { 'use strict'; var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); var $forEach = _dereq_('../internals/array-iteration').forEach; var aTypedArray = ArrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.forEach` method + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.forEach` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.foreach - exportTypedArrayMethod('forEach', function forEach(callbackfn /* , thisArg */ - ) { + exportTypedArrayMethod('forEach', function forEach(callbackfn /* , thisArg */ ) { $forEach(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); }); }, @@ -25296,16 +26304,16 @@ '../internals/array-iteration': 37 } ], - 224: [ + 232: [ function (_dereq_, module, exports) { 'use strict'; var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); var $includes = _dereq_('../internals/array-includes').includes; var aTypedArray = ArrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.includes` method + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.includes` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.includes - exportTypedArrayMethod('includes', function includes(searchElement /* , fromIndex */ - ) { + exportTypedArrayMethod('includes', function includes(searchElement /* , fromIndex */ ) { return $includes(aTypedArray(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); }); }, @@ -25314,16 +26322,16 @@ '../internals/array-includes': 36 } ], - 225: [ + 233: [ function (_dereq_, module, exports) { 'use strict'; var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); var $indexOf = _dereq_('../internals/array-includes').indexOf; var aTypedArray = ArrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.indexOf` method + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.indexOf` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.indexof - exportTypedArrayMethod('indexOf', function indexOf(searchElement /* , fromIndex */ - ) { + exportTypedArrayMethod('indexOf', function indexOf(searchElement /* , fromIndex */ ) { return $indexOf(aTypedArray(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); }); }, @@ -25332,9 +26340,10 @@ '../internals/array-includes': 36 } ], - 226: [ + 234: [ function (_dereq_, module, exports) { - var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); // `Int16Array` constructor + var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); + // `Int16Array` constructor // https://tc39.github.io/ecma262/#sec-typedarray-objects createTypedArrayConstructor('Int16', function (init) { return function Int16Array(data, byteOffset, length) { @@ -25343,12 +26352,13 @@ }); }, { - '../internals/typed-array-constructor': 158 + '../internals/typed-array-constructor': 160 } ], - 227: [ + 235: [ function (_dereq_, module, exports) { - var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); // `Int32Array` constructor + var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); + // `Int32Array` constructor // https://tc39.github.io/ecma262/#sec-typedarray-objects createTypedArrayConstructor('Int32', function (init) { return function Int32Array(data, byteOffset, length) { @@ -25357,10 +26367,10 @@ }); }, { - '../internals/typed-array-constructor': 158 + '../internals/typed-array-constructor': 160 } ], - 228: [ + 236: [ function (_dereq_, module, exports) { 'use strict'; var global = _dereq_('../internals/global'); @@ -25378,35 +26388,40 @@ var CORRECT_ITER_NAME = !!nativeTypedArrayIterator && (nativeTypedArrayIterator.name == 'values' || nativeTypedArrayIterator.name == undefined); var typedArrayValues = function values() { return arrayValues.call(aTypedArray(this)); - }; // `%TypedArray%.prototype.entries` method + }; + // `%TypedArray%.prototype.entries` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.entries exportTypedArrayMethod('entries', function entries() { return arrayEntries.call(aTypedArray(this)); - }); // `%TypedArray%.prototype.keys` method + }); + // `%TypedArray%.prototype.keys` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.keys exportTypedArrayMethod('keys', function keys() { return arrayKeys.call(aTypedArray(this)); - }); // `%TypedArray%.prototype.values` method + }); + // `%TypedArray%.prototype.values` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.values - exportTypedArrayMethod('values', typedArrayValues, !CORRECT_ITER_NAME); // `%TypedArray%.prototype[@@iterator]` method + exportTypedArrayMethod('values', typedArrayValues, !CORRECT_ITER_NAME); + // `%TypedArray%.prototype[@@iterator]` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype-@@iterator exportTypedArrayMethod(ITERATOR, typedArrayValues, !CORRECT_ITER_NAME); }, { '../internals/array-buffer-view-core': 30, '../internals/global': 77, - '../internals/well-known-symbol': 164, - '../modules/es.array.iterator': 176 + '../internals/well-known-symbol': 166, + '../modules/es.array.iterator': 179 } ], - 229: [ + 237: [ function (_dereq_, module, exports) { 'use strict'; var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; var $join = [ - ].join; // `%TypedArray%.prototype.join` method + ].join; + // `%TypedArray%.prototype.join` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.join // eslint-disable-next-line no-unused-vars exportTypedArrayMethod('join', function join(separator) { @@ -25417,17 +26432,17 @@ '../internals/array-buffer-view-core': 30 } ], - 230: [ + 238: [ function (_dereq_, module, exports) { 'use strict'; var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); var $lastIndexOf = _dereq_('../internals/array-last-index-of'); var aTypedArray = ArrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.lastIndexOf` method + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.lastIndexOf` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.lastindexof // eslint-disable-next-line no-unused-vars - exportTypedArrayMethod('lastIndexOf', function lastIndexOf(searchElement /* , fromIndex */ - ) { + exportTypedArrayMethod('lastIndexOf', function lastIndexOf(searchElement /* , fromIndex */ ) { return $lastIndexOf.apply(aTypedArray(this), arguments); }); }, @@ -25436,7 +26451,7 @@ '../internals/array-last-index-of': 38 } ], - 231: [ + 239: [ function (_dereq_, module, exports) { 'use strict'; var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); @@ -25444,10 +26459,10 @@ var speciesConstructor = _dereq_('../internals/species-constructor'); var aTypedArray = ArrayBufferViewCore.aTypedArray; var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor; - var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.map` method + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.map` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.map - exportTypedArrayMethod('map', function map(mapfn /* , thisArg */ - ) { + exportTypedArrayMethod('map', function map(mapfn /* , thisArg */ ) { return $map(aTypedArray(this), mapfn, arguments.length > 1 ? arguments[1] : undefined, function (O, length) { return new (aTypedArrayConstructor(speciesConstructor(O, O.constructor))) (length); }); @@ -25459,16 +26474,16 @@ '../internals/species-constructor': 139 } ], - 232: [ + 240: [ function (_dereq_, module, exports) { 'use strict'; var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); var $reduceRight = _dereq_('../internals/array-reduce').right; var aTypedArray = ArrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.reduceRicht` method + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.reduceRicht` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reduceright - exportTypedArrayMethod('reduceRight', function reduceRight(callbackfn /* , initialValue */ - ) { + exportTypedArrayMethod('reduceRight', function reduceRight(callbackfn /* , initialValue */ ) { return $reduceRight(aTypedArray(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined); }); }, @@ -25477,16 +26492,16 @@ '../internals/array-reduce': 42 } ], - 233: [ + 241: [ function (_dereq_, module, exports) { 'use strict'; var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); var $reduce = _dereq_('../internals/array-reduce').left; var aTypedArray = ArrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.reduce` method + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.reduce` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reduce - exportTypedArrayMethod('reduce', function reduce(callbackfn /* , initialValue */ - ) { + exportTypedArrayMethod('reduce', function reduce(callbackfn /* , initialValue */ ) { return $reduce(aTypedArray(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined); }); }, @@ -25495,13 +26510,14 @@ '../internals/array-reduce': 42 } ], - 234: [ + 242: [ function (_dereq_, module, exports) { 'use strict'; var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; - var floor = Math.floor; // `%TypedArray%.prototype.reverse` method + var floor = Math.floor; + // `%TypedArray%.prototype.reverse` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reverse exportTypedArrayMethod('reverse', function reverse() { var that = this; @@ -25521,7 +26537,7 @@ '../internals/array-buffer-view-core': 30 } ], - 235: [ + 243: [ function (_dereq_, module, exports) { 'use strict'; var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); @@ -25535,10 +26551,10 @@ // eslint-disable-next-line no-undef new Int8Array(1).set({ }); - }); // `%TypedArray%.prototype.set` method + }); + // `%TypedArray%.prototype.set` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.set - exportTypedArrayMethod('set', function set(arrayLike /* , offset */ - ) { + exportTypedArrayMethod('set', function set(arrayLike /* , offset */ ) { aTypedArray(this); var offset = toOffset(arguments.length > 1 ? arguments[1] : undefined, 1); var length = this.length; @@ -25552,12 +26568,12 @@ { '../internals/array-buffer-view-core': 30, '../internals/fails': 69, - '../internals/to-length': 152, - '../internals/to-object': 153, - '../internals/to-offset': 154 + '../internals/to-length': 154, + '../internals/to-object': 155, + '../internals/to-offset': 156 } ], - 236: [ + 244: [ function (_dereq_, module, exports) { 'use strict'; var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); @@ -25571,7 +26587,8 @@ var FORCED = fails(function () { // eslint-disable-next-line no-undef new Int8Array(1).slice(); - }); // `%TypedArray%.prototype.slice` method + }); + // `%TypedArray%.prototype.slice` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.slice exportTypedArrayMethod('slice', function slice(start, end) { var list = $slice.call(aTypedArray(this), start, end); @@ -25589,16 +26606,16 @@ '../internals/species-constructor': 139 } ], - 237: [ + 245: [ function (_dereq_, module, exports) { 'use strict'; var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); var $some = _dereq_('../internals/array-iteration').some; var aTypedArray = ArrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.some` method + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.some` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.some - exportTypedArrayMethod('some', function some(callbackfn /* , thisArg */ - ) { + exportTypedArrayMethod('some', function some(callbackfn /* , thisArg */ ) { return $some(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); }); }, @@ -25607,14 +26624,15 @@ '../internals/array-iteration': 37 } ], - 238: [ + 246: [ function (_dereq_, module, exports) { 'use strict'; var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; var $sort = [ - ].sort; // `%TypedArray%.prototype.sort` method + ].sort; + // `%TypedArray%.prototype.sort` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.sort exportTypedArrayMethod('sort', function sort(comparefn) { return $sort.call(aTypedArray(this), comparefn); @@ -25624,7 +26642,7 @@ '../internals/array-buffer-view-core': 30 } ], - 239: [ + 247: [ function (_dereq_, module, exports) { 'use strict'; var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); @@ -25632,7 +26650,8 @@ var toAbsoluteIndex = _dereq_('../internals/to-absolute-index'); var speciesConstructor = _dereq_('../internals/species-constructor'); var aTypedArray = ArrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; // `%TypedArray%.prototype.subarray` method + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.subarray` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.subarray exportTypedArrayMethod('subarray', function subarray(begin, end) { var O = aTypedArray(this); @@ -25644,11 +26663,11 @@ { '../internals/array-buffer-view-core': 30, '../internals/species-constructor': 139, - '../internals/to-absolute-index': 148, - '../internals/to-length': 152 + '../internals/to-absolute-index': 150, + '../internals/to-length': 154 } ], - 240: [ + 248: [ function (_dereq_, module, exports) { 'use strict'; var global = _dereq_('../internals/global'); @@ -25660,7 +26679,8 @@ var $toLocaleString = [ ].toLocaleString; var $slice = [ - ].slice; // iOS Safari 6.x fails here + ].slice; + // iOS Safari 6.x fails here var TO_LOCALE_STRING_BUG = !!Int8Array && fails(function () { $toLocaleString.call(new Int8Array(1)); }); @@ -25671,7 +26691,8 @@ }) || !fails(function () { Int8Array.prototype.toLocaleString.call([1, 2]); - }); // `%TypedArray%.prototype.toLocaleString` method + }); + // `%TypedArray%.prototype.toLocaleString` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.tolocalestring exportTypedArrayMethod('toLocaleString', function toLocaleString() { return $toLocaleString.apply(TO_LOCALE_STRING_BUG ? $slice.call(aTypedArray(this)) : aTypedArray(this), arguments); @@ -25683,7 +26704,7 @@ '../internals/global': 77 } ], - 241: [ + 249: [ function (_dereq_, module, exports) { 'use strict'; var exportTypedArrayMethod = _dereq_('../internals/array-buffer-view-core').exportTypedArrayMethod; @@ -25704,7 +26725,8 @@ return arrayJoin.call(this); }; } - var IS_NOT_ARRAY_METHOD = Uint8ArrayPrototype.toString != arrayToString; // `%TypedArray%.prototype.toString` method + var IS_NOT_ARRAY_METHOD = Uint8ArrayPrototype.toString != arrayToString; + // `%TypedArray%.prototype.toString` method // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.tostring exportTypedArrayMethod('toString', arrayToString, IS_NOT_ARRAY_METHOD); }, @@ -25714,9 +26736,10 @@ '../internals/global': 77 } ], - 242: [ + 250: [ function (_dereq_, module, exports) { - var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); // `Uint16Array` constructor + var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); + // `Uint16Array` constructor // https://tc39.github.io/ecma262/#sec-typedarray-objects createTypedArrayConstructor('Uint16', function (init) { return function Uint16Array(data, byteOffset, length) { @@ -25725,12 +26748,13 @@ }); }, { - '../internals/typed-array-constructor': 158 + '../internals/typed-array-constructor': 160 } ], - 243: [ + 251: [ function (_dereq_, module, exports) { - var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); // `Uint32Array` constructor + var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); + // `Uint32Array` constructor // https://tc39.github.io/ecma262/#sec-typedarray-objects createTypedArrayConstructor('Uint32', function (init) { return function Uint32Array(data, byteOffset, length) { @@ -25739,12 +26763,13 @@ }); }, { - '../internals/typed-array-constructor': 158 + '../internals/typed-array-constructor': 160 } ], - 244: [ + 252: [ function (_dereq_, module, exports) { - var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); // `Uint8Array` constructor + var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); + // `Uint8Array` constructor // https://tc39.github.io/ecma262/#sec-typedarray-objects createTypedArrayConstructor('Uint8', function (init) { return function Uint8Array(data, byteOffset, length) { @@ -25753,12 +26778,13 @@ }); }, { - '../internals/typed-array-constructor': 158 + '../internals/typed-array-constructor': 160 } ], - 245: [ + 253: [ function (_dereq_, module, exports) { - var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); // `Uint8ClampedArray` constructor + var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); + // `Uint8ClampedArray` constructor // https://tc39.github.io/ecma262/#sec-typedarray-objects createTypedArrayConstructor('Uint8', function (init) { return function Uint8ClampedArray(data, byteOffset, length) { @@ -25767,10 +26793,10 @@ }, true); }, { - '../internals/typed-array-constructor': 158 + '../internals/typed-array-constructor': 160 } ], - 246: [ + 254: [ function (_dereq_, module, exports) { 'use strict'; var global = _dereq_('../internals/global'); @@ -25788,9 +26814,11 @@ return function WeakMap() { return init(this, arguments.length ? arguments[0] : undefined); }; - }; // `WeakMap` constructor + }; + // `WeakMap` constructor // https://tc39.github.io/ecma262/#sec-weakmap-constructor - var $WeakMap = module.exports = collection('WeakMap', wrapper, collectionWeak); // IE11 WeakMap frozen keys fix + var $WeakMap = module.exports = collection('WeakMap', wrapper, collectionWeak); + // IE11 WeakMap frozen keys fix // We can't use feature detection because it crash some old IE builds // https://github.com/zloirock/core-js/issues/485 if (NATIVE_WEAK_MAP && IS_IE11) { @@ -25848,7 +26876,7 @@ '../internals/redefine-all': 125 } ], - 247: [ + 255: [ function (_dereq_, module, exports) { var global = _dereq_('../internals/global'); var DOMIterables = _dereq_('../internals/dom-iterables'); @@ -25856,7 +26884,8 @@ var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property'); for (var COLLECTION_NAME in DOMIterables) { var Collection = global[COLLECTION_NAME]; - var CollectionPrototype = Collection && Collection.prototype; // some Chrome versions have non-configurable methods on DOMTokenList + var CollectionPrototype = Collection && Collection.prototype; + // some Chrome versions have non-configurable methods on DOMTokenList if (CollectionPrototype && CollectionPrototype.forEach !== forEach) try { createNonEnumerableProperty(CollectionPrototype, 'forEach', forEach); } catch (error) { @@ -25871,7 +26900,7 @@ '../internals/global': 77 } ], - 248: [ + 256: [ function (_dereq_, module, exports) { var global = _dereq_('../internals/global'); var DOMIterables = _dereq_('../internals/dom-iterables'); @@ -25909,13 +26938,14 @@ '../internals/create-non-enumerable-property': 56, '../internals/dom-iterables': 63, '../internals/global': 77, - '../internals/well-known-symbol': 164, - '../modules/es.array.iterator': 176 + '../internals/well-known-symbol': 166, + '../modules/es.array.iterator': 179 } ], - 249: [ + 257: [ function (_dereq_, module, exports) { - 'use strict'; // TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env` + 'use strict'; + // TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env` _dereq_('../modules/es.array.iterator'); var $ = _dereq_('../internals/export'); var getBuiltIn = _dereq_('../internals/get-built-in'); @@ -26026,10 +27056,11 @@ ]; } return step; - }); // `URLSearchParams` constructor + }); + // `URLSearchParams` constructor // https://url.spec.whatwg.org/#interface-urlsearchparams - var URLSearchParamsConstructor = function URLSearchParams() /* init */ - { + var URLSearchParamsConstructor = function URLSearchParams( /* init */ + ) { anInstance(this, URLSearchParamsConstructor, URL_SEARCH_PARAMS); var init = arguments.length > 0 ? arguments[0] : undefined; var that = this; @@ -26047,8 +27078,7 @@ setInternalState(that, { type: URL_SEARCH_PARAMS, entries: entries, - updateURL: function () { - /* empty */ + updateURL: function () { /* empty */ }, updateSearchParams: updateSearchParams }); @@ -26172,7 +27202,8 @@ // https://url.spec.whatwg.org/#dom-urlsearchparams-sort sort: function sort() { var state = getInternalParamsState(this); - var entries = state.entries; // Array#sort is not stable in some engines + var entries = state.entries; + // Array#sort is not stable in some engines var slice = entries.slice(); var entry, entriesIndex, @@ -26191,8 +27222,7 @@ state.updateURL(); }, // `URLSearchParams.prototype.forEach` method - forEach: function forEach(callback /* , thisArg */ - ) { + forEach: function forEach(callback /* , thisArg */ ) { var entries = getInternalParamsState(this).entries; var boundFunction = bind(callback, arguments.length > 1 ? arguments[1] : undefined, 3); var index = 0; @@ -26216,8 +27246,10 @@ } }, { enumerable: true - }); // `URLSearchParams.prototype[@@iterator]` method - redefine(URLSearchParamsPrototype, ITERATOR, URLSearchParamsPrototype.entries); // `URLSearchParams.prototype.toString` method + }); + // `URLSearchParams.prototype[@@iterator]` method + redefine(URLSearchParamsPrototype, ITERATOR, URLSearchParamsPrototype.entries); + // `URLSearchParams.prototype.toString` method // https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior redefine(URLSearchParamsPrototype, 'toString', function toString() { var entries = getInternalParamsState(this).entries; @@ -26239,7 +27271,8 @@ forced: !USE_NATIVE_URL }, { URLSearchParams: URLSearchParamsConstructor - }); // Wrap `fetch` for correct work with polyfilled `URLSearchParams` + }); + // Wrap `fetch` for correct work with polyfilled `URLSearchParams` // https://github.com/zloirock/core-js/issues/674 if (!USE_NATIVE_URL && typeof $fetch == 'function' && typeof Headers == 'function') { $({ @@ -26247,8 +27280,7 @@ enumerable: true, forced: true }, { - fetch: function fetch(input /* , init */ - ) { + fetch: function fetch(input /* , init */ ) { var args = [ input ]; @@ -26300,13 +27332,14 @@ '../internals/redefine': 126, '../internals/redefine-all': 125, '../internals/set-to-string-tag': 135, - '../internals/well-known-symbol': 164, - '../modules/es.array.iterator': 176 + '../internals/well-known-symbol': 166, + '../modules/es.array.iterator': 179 } ], - 250: [ + 258: [ function (_dereq_, module, exports) { - 'use strict'; // TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env` + 'use strict'; + // TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env` _dereq_('../modules/es.string.iterator'); var $ = _dereq_('../internals/export'); var DESCRIPTORS = _dereq_('../internals/descriptors'); @@ -26340,10 +27373,14 @@ var HEX_START = /^(0x|0X)/; var OCT = /^[0-7]+$/; var DEC = /^\d+$/; - var HEX = /^[\dA-Fa-f]+$/; // eslint-disable-next-line no-control-regex - var FORBIDDEN_HOST_CODE_POINT = /[\u0000\u0009\u000A\u000D #%/:?@[\\]]/; // eslint-disable-next-line no-control-regex - var FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT = /[\u0000\u0009\u000A\u000D #/:?@[\\]]/; // eslint-disable-next-line no-control-regex - var LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE = /^[\u0000-\u001F ]+|[\u0000-\u001F ]+$/g; // eslint-disable-next-line no-control-regex + var HEX = /^[\dA-Fa-f]+$/; + // eslint-disable-next-line no-control-regex + var FORBIDDEN_HOST_CODE_POINT = /[\u0000\u0009\u000A\u000D #%/:?@[\\]]/; + // eslint-disable-next-line no-control-regex + var FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT = /[\u0000\u0009\u000A\u000D #/:?@[\\]]/; + // eslint-disable-next-line no-control-regex + var LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE = /^[\u0000-\u001F ]+|[\u0000-\u001F ]+$/g; + // eslint-disable-next-line no-control-regex var TAB_AND_NEW_LINE = /[\u0009\u000A\u000D]/g; var EOF; var parseHost = function (url, input) { @@ -26354,7 +27391,8 @@ if (input.charAt(input.length - 1) != ']') return INVALID_HOST; result = parseIPv6(input.slice(1, - 1)); if (!result) return INVALID_HOST; - url.host = result; // opaque host + url.host = result; + // opaque host } else if (!isSpecial(url)) { if (FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT.test(input)) return INVALID_HOST; result = ''; @@ -26414,7 +27452,8 @@ ipv4 += numbers[index] * pow(256, 3 - index); } return ipv4; - }; // eslint-disable-next-line max-statements + }; + // eslint-disable-next-line max-statements var parseIPv6 = function (input) { var address = [ 0, @@ -26532,7 +27571,8 @@ var result, index, compress, - ignore0; // ipv4 + ignore0; + // ipv4 if (typeof host == 'number') { result = [ ]; @@ -26540,7 +27580,8 @@ result.unshift(host % 256); host = floor(host / 256); } - return result.join('.'); // ipv6 + return result.join('.'); + // ipv6 } else if (typeof host == 'object') { result = ''; compress = findLongestZeroSequence(host); @@ -26631,7 +27672,8 @@ var isDoubleDot = function (segment) { segment = segment.toLowerCase(); return segment === '..' || segment === '%2e.' || segment === '.%2e' || segment === '%2e%2e'; - }; // States: + }; + // States: var SCHEME_START = { }; var SCHEME = { @@ -26673,7 +27715,8 @@ var QUERY = { }; var FRAGMENT = { - }; // eslint-disable-next-line max-statements + }; + // eslint-disable-next-line max-statements var parseURL = function (url, input, stateOverride, base) { var state = stateOverride || SCHEME_START; var pointer = 0; @@ -27043,10 +28086,10 @@ } pointer++; } - }; // `URL` constructor + }; + // `URL` constructor // https://url.spec.whatwg.org/#url-class - var URLConstructor = function URL(url /* , base */ - ) { + var URLConstructor = function URL(url /* , base */ ) { var that = anInstance(this, URLConstructor, 'URL'); var base = arguments.length > 1 ? arguments[1] : undefined; var urlString = String(url); @@ -27275,14 +28318,15 @@ parseURL(url, hash, FRAGMENT); }) }); - } // `URL.prototype.toJSON` method + } // `URL.prototype.toJSON` method // https://url.spec.whatwg.org/#dom-url-tojson redefine(URLPrototype, 'toJSON', function toJSON() { return serializeURL.call(this); }, { enumerable: true - }); // `URL.prototype.toString` method + }); + // `URL.prototype.toString` method // https://url.spec.whatwg.org/#URL-stringification-behavior redefine(URLPrototype, 'toString', function toString() { return serializeURL.call(this); @@ -27291,12 +28335,14 @@ }); if (NativeURL) { var nativeCreateObjectURL = NativeURL.createObjectURL; - var nativeRevokeObjectURL = NativeURL.revokeObjectURL; // `URL.createObjectURL` method + var nativeRevokeObjectURL = NativeURL.revokeObjectURL; + // `URL.createObjectURL` method // https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL // eslint-disable-next-line no-unused-vars if (nativeCreateObjectURL) redefine(URLConstructor, 'createObjectURL', function createObjectURL(blob) { return nativeCreateObjectURL.apply(NativeURL, arguments); - }); // `URL.revokeObjectURL` method + }); + // `URL.revokeObjectURL` method // https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL // eslint-disable-next-line no-unused-vars if (nativeRevokeObjectURL) redefine(URLConstructor, 'revokeObjectURL', function revokeObjectURL(url) { @@ -27326,12 +28372,12 @@ '../internals/redefine': 126, '../internals/set-to-string-tag': 135, '../internals/string-multibyte': 141, - '../internals/string-punycode-to-ascii': 142, - '../modules/es.string.iterator': 204, - '../modules/web.url-search-params': 249 + '../internals/string-punycode-to-ascii': 144, + '../modules/es.string.iterator': 210, + '../modules/web.url-search-params': 257 } ], - 251: [ + 259: [ function (_dereq_, module, exports) { // This file can be required in Browserify and Node.js for automatic polyfill // To use it: require('es6-promise/auto'); @@ -27339,10 +28385,10 @@ module.exports = _dereq_('./').polyfill(); }, { - './': 252 + './': 260 } ], - 252: [ + 260: [ function (_dereq_, module, exports) { (function (process, global) { /*! @@ -27401,15 +28447,17 @@ }; 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 + }.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 + } // vertx function useVertxTimer() { if (typeof vertxNext !== 'undefined') { @@ -27429,7 +28477,7 @@ return function () { node.data = iterations = ++iterations % 2; }; - } // web worker + } // web worker function useMessageChannel() { var channel = new MessageChannel(); @@ -27466,7 +28514,8 @@ return useSetTimeout(); } } - var scheduleFlush = void 0; // Decide what async method to use to triggering processing of queued callbacks: + var scheduleFlush = void 0; + // Decide what async method to use to triggering processing of queued callbacks: if (isNode) { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { @@ -27697,7 +28746,8 @@ } else { value = detail; } - if (promise._state !== PENDING) { // noop + if (promise._state !== PENDING) { + // noop } else if (hasCallback && succeeded) { resolve(promise, value); } else if (succeeded === false) { @@ -28382,14 +29432,15 @@ var promiseToString = null; try { promiseToString = Object.prototype.toString.call(P.resolve()); - } catch (e) { // silently ignored + } catch (e) { + // silently ignored } if (promiseToString === '[object Promise]' && !P.cast) { return; } } local.Promise = Promise$1; - } // Strange compat.. + } // Strange compat.. Promise$1.polyfill = polyfill; Promise$1.Promise = Promise$1; @@ -28399,10 +29450,10 @@ }) }, { - '_process': 265 + '_process': 273 } ], - 253: [ + 261: [ function (_dereq_, module, exports) { (function (global, factory) { if (typeof define === 'function' && define.amd) { @@ -28446,7 +29497,8 @@ function fetchJsonp(_url) { var options = arguments.length <= 1 || arguments[1] === undefined ? { } - : arguments[1]; // to avoid param reassign + : arguments[1]; + // to avoid param reassign var url = _url; var timeout = options.timeout || defaultOptions.timeout; var jsonpCallback = options.jsonpCallback || defaultOptions.jsonpCallback; @@ -28465,7 +29517,8 @@ 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 + }; + // 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); @@ -28481,7 +29534,8 @@ window[callbackFunction] = function () { clearFunction(callbackFunction); }; - }, timeout); // Caught if got 404/500 + }, timeout); + // Caught if got 404/500 jsonpScript.onerror = function () { reject(new Error('JSONP request to ' + _url + ' failed')); clearFunction(callbackFunction); @@ -28489,7 +29543,7 @@ if (timeoutId) clearTimeout(timeoutId); }; }); - } // export as global function + } // export as global function /* let local; if (typeof global !== 'undefined') { @@ -28512,7 +29566,7 @@ { } ], - 254: [ + 262: [ function (_dereq_, module, exports) { /* FileSaver.js * A saveAs() FileSaver implementation. @@ -28527,17 +29581,18 @@ /*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 + '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 + 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, + can_use_save_link = ('download' in save_link), click = function (node) { var event = new MouseEvent('click'); node.dispatchEvent(event); @@ -28549,7 +29604,7 @@ throw ex; }, 0); }, - force_saveable_type = 'application/octet-stream' // the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to + 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 , @@ -28594,7 +29649,7 @@ 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 + } // First try a.download, then web filesystem, then object URLs var filesaver = this, type = blob.type, @@ -28602,7 +29657,7 @@ object_url, dispatch_all = function () { dispatch(filesaver, 'writestart progress write writeend'.split(' ')); - } // on any filesys errors revert to saving with object URLs + } // on any filesys errors revert to saving with object URLs , fs_error = function () { if ((is_chrome_ios || force && is_safari) && view.FileReader) { @@ -28619,7 +29674,7 @@ reader.readAsDataURL(blob); filesaver.readyState = filesaver.INIT; return; - } // don't create more object URLs than needed + } // don't create more object URLs than needed if (!object_url) { object_url = get_URL().createObjectURL(blob); @@ -28655,7 +29710,8 @@ 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) + }; + // IE 10+ (native saveAs) if (typeof navigator !== 'undefined' && navigator.msSaveOrOpenBlob) { return function (blob, name, no_auto_bom) { name = name || blob.name || 'download'; @@ -28672,7 +29728,8 @@ 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 + }(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) { @@ -28686,7 +29743,7 @@ { } ], - 255: [ + 263: [ function (_dereq_, module, exports) { var __defProp = Object.defineProperty; var __markAsModule = target=>__defProp(target, '__esModule', { @@ -28697,7 +29754,8 @@ get: all[name], enumerable: true }); - }; // src/index.js + }; + // src/index.js __markAsModule(exports); __export(exports, { GIFEncoder: () =>GIFEncoder, @@ -28710,7 +29768,8 @@ prequantize: () =>prequantize, quantize: () =>quantize, snapColorsToPalette: () =>snapColorsToPalette - }); // src/constants.js + }); + // src/constants.js var constants_default = { signature: 'GIF', version: '89a', @@ -28734,7 +29793,8 @@ interlaceFlagMask: 64, idSortFlagMask: 32, localColorTableSizeMask: 7 - }; // src/stream.js + }; + // src/stream.js function createStream(initialCapacity = 256) { let cursor = 0; let contents = new Uint8Array(initialCapacity); @@ -28778,7 +29838,7 @@ contents = new Uint8Array(newCapacity); if (cursor > 0) contents.set(oldContents.subarray(0, cursor), 0); } - } // src/lzwEncode.js + } // src/lzwEncode.js var BITS = 12; var DEFAULT_HSIZE = 5003; @@ -28906,7 +29966,8 @@ } } } - var lzwEncode_default = lzwEncode; // src/rgb-packing.js + var lzwEncode_default = lzwEncode; + // src/rgb-packing.js function rgb888_to_rgb565(r, g, b) { return r << 8 & 63488 | g << 2 & 992 | b >> 3; } @@ -28915,7 +29976,7 @@ } function rgb888_to_rgb444(r, g, b) { return r >> 4 << 8 | g & 240 | b >> 4; - } // src/pnnquant2.js + } // src/pnnquant2.js function clamp(value, min, max) { return value < min ? min : value > max ? max : value; @@ -29152,7 +30213,7 @@ if (matchesRGB && matchesAlpha) return true; } return false; - } // src/color.js + } // src/color.js function euclideanDistanceSquared(a, b) { var sum = 0; @@ -29162,7 +30223,7 @@ sum += dx * dx; } return sum; - } // src/palettize.js + } // src/palettize.js function roundStep(byte, step) { return step > 1 ? Math.round(byte / step) * step : byte; @@ -29333,7 +30394,7 @@ } function nearestColor(colors, pixel, distanceFn = euclideanDistanceSquared) { return colors[nearestColorIndex(colors, pixel, distanceFn)]; - } // src/index.js + } // src/index.js function GIFEncoder(opt = { }) { @@ -29516,7 +30577,7 @@ { } ], - 256: [ + 264: [ function (_dereq_, module, exports) { 'use strict'; function _interopDefault(ex) { @@ -29720,7 +30781,7 @@ checkWhitelist: true }; } - var Browser = /*#__PURE__*/ + var Browser = /*#__PURE__*/ function () { function Browser(services) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { @@ -29816,11 +30877,11 @@ module.exports = Browser; }, { - '@babel/runtime/helpers/classCallCheck': 257, - '@babel/runtime/helpers/createClass': 258 + '@babel/runtime/helpers/classCallCheck': 265, + '@babel/runtime/helpers/createClass': 266 } ], - 257: [ + 265: [ function (_dereq_, module, exports) { arguments[4][5][0].apply(exports, arguments) }, @@ -29828,7 +30889,7 @@ 'dup': 5 } ], - 258: [ + 266: [ function (_dereq_, module, exports) { arguments[4][6][0].apply(exports, arguments) }, @@ -29836,7 +30897,7 @@ 'dup': 6 } ], - 259: [ + 267: [ function (_dereq_, module, exports) { 'use strict'; function _interopDefault(ex) { @@ -29869,7 +30930,7 @@ if (console && console[type]) (_console = console) [type].apply(_console, _toConsumableArray(args)); } }; - var Logger = /*#__PURE__*/ + var Logger = /*#__PURE__*/ function () { function Logger(concreteLogger) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { @@ -29952,7 +31013,7 @@ return Logger; }(); var baseLogger = new Logger(); - var EventEmitter = /*#__PURE__*/ + var EventEmitter = /*#__PURE__*/ function () { function EventEmitter() { _classCallCheck(this, EventEmitter); @@ -30011,7 +31072,8 @@ } ]); return EventEmitter; - }(); // http://lea.verou.me/2016/12/resolve-promises-externally-with-this-one-weird-trick/ + }(); + // http://lea.verou.me/2016/12/resolve-promises-externally-with-this-one-weird-trick/ function defer() { var res; var rej; @@ -30124,7 +31186,7 @@ } return data; } - var ResourceStore = /*#__PURE__*/ + var ResourceStore = /*#__PURE__*/ function (_EventEmitter) { _inherits(ResourceStore, _EventEmitter); function ResourceStore(data) { @@ -30306,7 +31368,7 @@ }; var checkedLoadedFor = { }; - var Translator = /*#__PURE__*/ + var Translator = /*#__PURE__*/ function (_EventEmitter) { _inherits(Translator, _EventEmitter); function Translator(services) { @@ -30379,7 +31441,7 @@ } if (!options) options = { }; // non valid keys handling - if (keys === undefined || keys === null /* || keys === ''*/ + if (keys === undefined || keys === null /* || keys === ''*/ ) return ''; if (!Array.isArray(keys)) keys = [ String(keys) @@ -30632,7 +31694,7 @@ function capitalize(string) { return string.charAt(0).toUpperCase() + string.slice(1); } - var LanguageUtil = /*#__PURE__*/ + var LanguageUtil = /*#__PURE__*/ function () { function LanguageUtil(options) { _classCallCheck(this, LanguageUtil); @@ -31202,7 +32264,7 @@ }); return rules; } - var PluralResolver = /*#__PURE__*/ + var PluralResolver = /*#__PURE__*/ function () { function PluralResolver(languageUtils) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { @@ -31272,10 +32334,10 @@ if (suffix === 1) return ''; if (typeof suffix === 'number') return '_plural_'.concat(suffix.toString()); return returnSuffix(); - } else if ( /* v2 */ + } else if ( /* v2 */ this.options.compatibilityJSON === 'v2') { return returnSuffix(); - } else if ( /* v3 - gettext index */ + } else if ( /* v3 - gettext index */ this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) { return returnSuffix(); } @@ -31288,7 +32350,7 @@ ]); return PluralResolver; }(); - var Interpolator = /*#__PURE__*/ + var Interpolator = /*#__PURE__*/ function () { function Interpolator() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { @@ -31471,7 +32533,7 @@ found = arr.indexOf(what); } } - var Connector = /*#__PURE__*/ + var Connector = /*#__PURE__*/ function (_EventEmitter) { _inherits(Connector, _EventEmitter); function Connector(backend, store, services) { @@ -31500,7 +32562,8 @@ { key: 'queueLoad', value: function queueLoad(languages, namespaces, options, callback) { - var _this2 = this; // find what needs to be loaded + var _this2 = this; + // find what needs to be loaded var toLoad = [ ]; var pending = [ @@ -31603,8 +32666,7 @@ if (!lng.length) return callback(null, { }); // noting to load return this.backend[fcName](lng, ns, function (err, data) { - if (err && data /* = retryFlag */ - && tried < 5) { + if (err && data /* = retryFlag */ && tried < 5) { setTimeout(function () { _this3.read.call(_this3, lng, ns, fcName, tried + 1, wait * 2, callback); }, wait); @@ -31683,8 +32745,7 @@ if (key === undefined || key === null || key === '') return; if (this.backend && this.backend.create) { - this.backend.create(languages, namespace, key, fallbackValue, null /* unused callback */ - , _objectSpread({ + this.backend.create(languages, namespace, key, fallbackValue, null /* unused callback */ , _objectSpread({ }, options, { isUpdate: isUpdate })); @@ -31809,7 +32870,7 @@ } function noop() { } - var I18n = /*#__PURE__*/ + var I18n = /*#__PURE__*/ function (_EventEmitter) { _inherits(I18n, _EventEmitter); function I18n() { @@ -32330,7 +33391,7 @@ '@babel/runtime/helpers/typeof': 19 } ], - 260: [ + 268: [ function (_dereq_, module, exports) { exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, @@ -32416,7 +33477,7 @@ { } ], - 261: [ + 269: [ function (_dereq_, module, exports) { /* @@ -33577,7 +34638,7 @@ { } ], - 262: [ + 270: [ function (_dereq_, module, exports) { // (c) Dean McNamee , 2013. // @@ -33619,7 +34680,7 @@ throw new Error('Invalid code/color length, must be power of 2 and 2 .. 256.'); } return num_colors; - } // - Header. + } // - Header. buf[p++] = 71; buf[p++] = 73; @@ -33637,20 +34698,22 @@ --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 + 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. + } // - Logical Screen Descriptor. // NOTE(deanm): w/h apparently ignored by implementations, but set anyway. buf[p++] = width & 255; buf[p++] = width >> 8 & 255; buf[p++] = height & 255; - buf[p++] = height >> 8 & 255; // NOTE: Indicates 0-bpp original color resolution (unused?). - buf[p++] = (global_palette !== null ? 128 : 0) | // Global Color Table Flag. + buf[p++] = height >> 8 & 255; + // NOTE: Indicates 0-bpp original color resolution (unused?). + buf[p++] = (global_palette !== null ? 128 : 0) | // Global Color Table Flag. gp_num_colors_pow2; // NOTE: No sort flag (unused?). buf[p++] = background; // Background Color Index. buf[p++] = 0; // Pixel aspect ratio (unused?). @@ -33665,10 +34728,12 @@ } 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. + if (loop_count < 0 || loop_count > 65535) throw new Error('Loop count invalid.'); + // Extension code, label, and length. buf[p++] = 33; buf[p++] = 255; - buf[p++] = 11; // NETSCAPE2.0 + buf[p++] = 11; + // NETSCAPE2.0 buf[p++] = 78; buf[p++] = 69; buf[p++] = 84; @@ -33679,7 +34744,8 @@ buf[p++] = 69; buf[p++] = 50; buf[p++] = 46; - buf[p++] = 48; // Sub-block + buf[p++] = 48; + // Sub-block buf[p++] = 3; buf[p++] = 1; buf[p++] = loop_count & 255; @@ -33695,7 +34761,8 @@ opts = opts === undefined ? { } - : opts; // TODO(deanm): Bounds check x, y. Do they need to be within the virtual + : 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.'); @@ -33707,11 +34774,13 @@ 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 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: + 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 @@ -33725,7 +34794,7 @@ // 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. + if (disposal < 0 || disposal > 3) // 4-7 is reserved. throw new Error('Disposal out of range.'); var use_transparency = false; var transparent_index = 0; @@ -33744,7 +34813,7 @@ buf[p++] = delay >> 8 & 255; buf[p++] = transparent_index; // Transparent color index. buf[p++] = 0; // Block Terminator. - } // - Image Descriptor + } // - Image Descriptor buf[p++] = 44; // Image Seperator. buf[p++] = x & 255; @@ -33754,9 +34823,11 @@ buf[p++] = w & 255; buf[p++] = w >> 8 & 255; buf[p++] = h & 255; - buf[p++] = h >> 8 & 255; // NOTE: No sort flag (unused?). + buf[p++] = h >> 8 & 255; + // NOTE: No sort flag (unused?). // TODO(deanm): Support interlace. - buf[p++] = using_local_palette === true ? 128 | min_code_size - 1 : 0; // - Local Color Table + buf[p++] = using_local_palette === true ? 128 | min_code_size - 1 : 0; + // - Local Color Table if (using_local_palette === true) { for (var i = 0, il = palette.length; i < il; ++i) { var rgb = palette[i]; @@ -33787,7 +34858,7 @@ this.setOutputBufferPosition = function (v) { p = v; }; - } // Main compression routine, palette indexes -> LZW code stream. + } // 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) { @@ -33798,7 +34869,8 @@ 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 + 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) { @@ -33817,7 +34889,7 @@ 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. + } // 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 @@ -33912,7 +34984,8 @@ 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 + 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) { @@ -33926,10 +34999,11 @@ return p; } function GifReader(buf) { - var p = 0; // - Header (GIF87a or GIF89a). + var p = 0; + // - Header (GIF87a or GIF89a). if (buf[p++] !== 71 || buf[p++] !== 73 || buf[p++] !== 70 || buf[p++] !== 56 || (buf[p++] + 1 & 253) !== 56 || buf[p++] !== 97) { throw new Error('Invalid GIF 87a/89a header.'); - } // - Logical Screen Descriptor. + } // - Logical Screen Descriptor. var width = buf[p++] | buf[p++] << 8; var height = buf[p++] | buf[p++] << 8; @@ -33963,9 +35037,9 @@ case 255: // Application specific block // Try if it's a Netscape block (with animation loop counter). - if (buf[p] !== 11 || // 21 FF already read, check block size. + if (buf[p] !== 11 || // 21 FF already read, check block size. // NETSCAPE2.0 - buf[p + 1] == 78 && buf[p + 2] == 69 && buf[p + 3] == 84 && buf[p + 4] == 83 && buf[p + 5] == 67 && buf[p + 6] == 65 && buf[p + 7] == 80 && buf[p + 8] == 69 && buf[p + 9] == 50 && buf[p + 10] == 46 && buf[p + 11] == 48 && // Sub-block + buf[p + 1] == 78 && buf[p + 2] == 69 && buf[p + 3] == 84 && buf[p + 4] == 83 && buf[p + 5] == 67 && buf[p + 6] == 65 && buf[p + 7] == 80 && buf[p + 8] == 69 && buf[p + 9] == 50 && buf[p + 10] == 46 && buf[p + 11] == 48 && // Sub-block buf[p + 12] == 3 && buf[p + 13] == 1 && buf[p + 16] == 0) { p += 14; loop_count = buf[p++] | buf[p++] << 8; @@ -33975,7 +35049,8 @@ p += 12; while (true) { // Seek through subblocks. - var block_size = buf[p++]; // Bad block size (ex: undefined from an out of bounds read). + 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; @@ -33996,7 +35071,8 @@ // Comment Extension. while (true) { // Seek through subblocks. - var block_size = buf[p++]; // Bad block size (ex: undefined from an out of bounds read). + 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')); @@ -34030,7 +35106,8 @@ var data_offset = p; p++; // codesize while (true) { - var block_size = buf[p++]; // Bad block size (ex: undefined from an out of bounds read). + 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; @@ -34075,11 +35152,13 @@ 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 + 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. + 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; @@ -34089,7 +35168,8 @@ 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 + 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. @@ -34103,7 +35183,8 @@ 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. + scanstride = framestride * 4 + width * 4 * (interlaceskip - 1); + // interlaceskip / 2 * 4 is interlaceskip << 1. op = opbeg + (framewidth + framestride) * (interlaceskip << 1); interlaceskip >>= 1; } @@ -34121,17 +35202,20 @@ } --xleft; } - }; // I will go to copy and paste hell one day... + }; + // 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 + 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. + 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; @@ -34141,7 +35225,8 @@ 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 + 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. @@ -34155,7 +35240,8 @@ 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. + scanstride = framestride * 4 + width * 4 * (interlaceskip - 1); + // interlaceskip / 2 * 4 is interlaceskip << 1. op = opbeg + (framewidth + framestride) * (interlaceskip << 1); interlaceskip >>= 1; } @@ -34187,7 +35273,8 @@ 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 + 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. @@ -34204,13 +35291,14 @@ } else { --subblock_size; } - } // TODO(deanm): We should never really get here, we should have received + } // 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, + 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) { @@ -34219,12 +35307,13 @@ // 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 ? + 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 + } // 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 @@ -34243,7 +35332,8 @@ // 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_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) { @@ -34255,12 +35345,12 @@ 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. + } // 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. + if (chase_code !== code) // The case of emitting {CODE-1} + k. output[op++] = k; chase = chase_code; while (chase_length--) { @@ -34269,7 +35359,8 @@ 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 + 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 @@ -34285,7 +35376,7 @@ console.log('Warning, gif stream shorter than expected.'); } return output; - } // CommonJS. + } // CommonJS. try { exports.GifWriter = GifWriter; @@ -34296,7 +35387,7 @@ { } ], - 263: [ + 271: [ function (_dereq_, module, exports) { (function (Buffer) { /** @@ -34326,21 +35417,22 @@ throw TypeError(); } var string = String(this); - var size = string.length; // `ToInteger` + var size = string.length; + // `ToInteger` var index = position ? Number(position) : 0; if (index != index) { // better `isNaN` index = 0; - } // Account for out-of-bounds indices: + } // Account for out-of-bounds indices: if (index < 0 || index >= size) { return undefined; - } // Get the first code unit + } // Get the first code unit var first = string.charCodeAt(index); var second; - if ( // check if it’s the start of a surrogate pair - first >= 55296 && first <= 56319 && // high surrogate + if ( // check if it’s the start of a surrogate pair + first >= 55296 && first <= 56319 && // high surrogate size > index + 1 // there is a next code unit ) { second = string.charCodeAt(index + 1); @@ -34366,10 +35458,8 @@ 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 */ + 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; @@ -34378,10 +35468,8 @@ this.bitcount = 0; this.dest = dest; this.destLen = 0; - this.ltree = new Tree(); - /* dynamic length/symbol tree */ - this.dtree = new Tree(); - /* dynamic distance tree */ + this.ltree = new Tree(); /* dynamic length/symbol tree */ + this.dtree = new Tree(); /* dynamic distance tree */ } /* --------------------------------------------------- * * -- uninitialized global data (static structures) -- * * --------------------------------------------------- */ @@ -34717,7 +35805,8 @@ /* fix a special case */ length_bits[28] = 0; length_base[28] = 258; - var tinyInflate = tinf_uncompress; // The Bounding Box object + 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; } /** @@ -34806,7 +35895,8 @@ * @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 + 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, @@ -34885,7 +35975,8 @@ 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 + }; + // 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`. @@ -35175,10 +36266,11 @@ var newPath = document.createElementNS('http://www.w3.org/2000/svg', 'path'); newPath.setAttribute('d', temporaryPath); return newPath; - }; // Run-time checking of preconditions. + }; + // Run-time checking of preconditions. function fail(message) { throw new Error(message); - } // Precondition function that checks if the given predicate is true. + } // Precondition function that checks if the given predicate is true. // If not, it will throw an error. function argument(predicate, message) { @@ -35190,7 +36282,8 @@ fail: fail, argument: argument, assert: argument - }; // Data types used in the OpenType font file. + }; + // 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 /** @@ -35210,12 +36303,13 @@ * @class */ var sizeOf = { - }; // Return a function that always returns the same value. + }; + // Return a function that always returns the same value. function constant(v) { return function () { return v; }; - } // OpenType data types ////////////////////////////////////////////////////// + } // OpenType data types ////////////////////////////////////////////////////// /** * Convert an 8-bit unsigned integer to a list of 1 byte. * @param {number} @@ -35389,7 +36483,8 @@ * @constant * @type {number} */ - sizeOf.TAG = constant(4); // CFF data types /////////////////////////////////////////////////////////// + sizeOf.TAG = constant(4); + // CFF data types /////////////////////////////////////////////////////////// encode.Card8 = encode.BYTE; sizeOf.Card8 = sizeOf.BYTE; encode.Card16 = encode.USHORT; @@ -35397,7 +36492,8 @@ 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. + 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} @@ -35467,7 +36563,8 @@ * @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) + 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) { @@ -35558,7 +36655,8 @@ */ sizeOf.UTF16 = function (v) { return v.length * 2; - }; // Data for converting old eight-bit Macintosh encodings to Unicode. + }; + // 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 @@ -35572,25 +36670,25 @@ * @private */ var eightBitMacEncodings = { - 'x-mac-croatian': // Python: 'mac_croatian' + 'x-mac-croatian': // Python: 'mac_croatian' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø' + '¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ', - 'x-mac-cyrillic': // Python: 'mac_cyrillic' + 'x-mac-cyrillic': // Python: 'mac_cyrillic' 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњ' + 'јЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю', - 'x-mac-gaelic': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/GAELIC.TXT + 'x-mac-gaelic': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/GAELIC.TXT 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæø' + 'ṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ', - 'x-mac-greek': // Python: 'mac_greek' + 'x-mac-greek': // Python: 'mac_greek' 'Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩ' + 'άΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­', - 'x-mac-icelandic': // Python: 'mac_iceland' + 'x-mac-icelandic': // Python: 'mac_iceland' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', - 'x-mac-inuit': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/INUIT.TXT + 'x-mac-inuit': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/INUIT.TXT 'ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗ' + 'ᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł', - 'x-mac-ce': // Python: 'mac_latin2' + 'x-mac-ce': // Python: 'mac_latin2' 'ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅ' + 'ņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ', - macintosh: // Python: 'mac_roman' + macintosh: // Python: 'mac_roman' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', - 'x-mac-romanian': // Python: 'mac_romanian' + 'x-mac-romanian': // Python: 'mac_romanian' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș' + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', - 'x-mac-turkish': // Python: 'mac_turkish' + 'x-mac-turkish': // Python: 'mac_turkish' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ' }; /** @@ -35611,7 +36709,8 @@ } 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 + var c = dataView.getUint8(offset + i); + // In all eight-bit Mac encodings, the characters 0x00..0x7F are // mapped to U+0000..U+007F; we only need to look up the others. if (c <= 127) { result += String.fromCharCode(c); @@ -35620,7 +36719,8 @@ } } return result; - }; // Helper function for encode.MACSTRING. Returns a dictionary for mapping + }; + // 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. @@ -35634,15 +36734,14 @@ macEncodingCacheKeys = { }; for (var e in eightBitMacEncodings) { - /*jshint -W053 */ - // Suppress "Do not use String as a constructor." + /*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: + } // 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. @@ -35684,7 +36783,8 @@ 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 + var c = str.charCodeAt(i); + // In all eight-bit Mac encodings, the characters 0x00..0x7F are // mapped to U+0000..U+007F; we only need to look up the others. if (c >= 128) { c = table[c]; @@ -35694,7 +36794,8 @@ return undefined; } } - result[i] = c; // result.push(c); + result[i] = c; + // result.push(c); } return result; }; @@ -35710,10 +36811,11 @@ } else { return 0; } - }; // Helper for encode.VARDELTAS + }; + // Helper for encode.VARDELTAS function isByteEncodable(value) { return value >= - 128 && value <= 127; - } // Helper for encode.VARDELTAS + } // Helper for encode.VARDELTAS function encodeVarDeltaRunAsZeroes(deltas, pos, result) { var runLength = 0; @@ -35724,7 +36826,7 @@ } result.push(128 | runLength - 1); return pos; - } // Helper for encode.VARDELTAS + } // Helper for encode.VARDELTAS function encodeVarDeltaRunAsBytes(deltas, offset, result) { var runLength = 0; @@ -35734,7 +36836,7 @@ var value = deltas[pos]; if (!isByteEncodable(value)) { break; - } // Within a byte-encoded run of deltas, a single zero is best + } // 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] @@ -35753,14 +36855,15 @@ result.push(deltas[i] + 256 & 255); } return pos; - } // Helper for encode.VARDELTAS + } // 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 + 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 @@ -35768,7 +36871,7 @@ // 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 + } // 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 @@ -35815,7 +36918,8 @@ } } return result; - }; // Convert a list of values to a CFF INDEX structure. + }; + // Convert a list of values to a CFF INDEX structure. // The values should be objects containing name / type / value. /** * @param {Array} l @@ -35881,7 +36985,8 @@ 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. + var v = m[k]; + // Value comes before the key. d = d.concat(encode.OPERAND(v.value, v.type)); d = d.concat(encode.OPERATOR(k)); } @@ -35931,13 +37036,15 @@ } else if (type === 'real') { d = d.concat(encode.REAL(v)); } else { - throw new Error('Unknown operand type ' + type); // FIXME Add support for booleans + 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 + 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. @@ -35970,7 +37077,8 @@ */ sizeOf.CHARSTRING = function (ops) { return encode.CHARSTRING(ops).length; - }; // Utility functions //////////////////////////////////////////////////////// + }; + // Utility functions //////////////////////////////////////////////////////// /** * Convert an object containing name / type / value to bytes. * @param {Object} @@ -36048,7 +37156,8 @@ if (value === undefined) { value = field.value; } - numBytes += sizeOfFunction(value); // Subtables take 2 more bytes for offsets. + numBytes += sizeOfFunction(value); + // Subtables take 2 more bytes for offsets. if (field.type === 'TABLE') { numBytes += 2; } @@ -36056,13 +37165,15 @@ return numBytes; }; encode.RECORD = encode.TABLE; - sizeOf.RECORD = sizeOf.TABLE; // Merge in a list of bytes. + 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 + }; + // Table metadata /** * @exports opentype.Table * @class @@ -36162,7 +37273,7 @@ fields = fields.concat(itemCallback(records[i], i)); } return fields; - } // Common Layout Tables + } // Common Layout Tables /** * @exports opentype.Coverage * @class @@ -36305,7 +37416,8 @@ })); } 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) + 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, @@ -36317,33 +37429,34 @@ ushortList: ushortList, tableList: tableList, recordList: recordList - }; // Parsing utility functions + }; + // 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. + } // 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. + } // 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. + } // 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. + } // 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. + } // Retrieve a 4-character tag from the DataView. // Tags are used to identify tables. function getTag(dataView, offset) { @@ -36352,7 +37465,7 @@ tag += String.fromCharCode(dataView.getInt8(i)); } return tag; - } // Retrieve an offset from the DataView. + } // Retrieve an offset from the DataView. // Offsets are 1 to 4 bytes in length, depending on the offSize argument. function getOffset(dataView, offset, offSize) { @@ -36362,7 +37475,7 @@ v += dataView.getUint8(offset + i); } return v; - } // Retrieve a number of bytes from start offset to the end offset from the DataView. + } // Retrieve a number of bytes from start offset to the end offset from the DataView. function getBytes(dataView, startOffset, endOffset) { var bytes = [ @@ -36371,7 +37484,7 @@ bytes.push(dataView.getUint8(i)); } return bytes; - } // Convert the list of bytes to a string. + } // Convert the list of bytes to a string. function bytesToString(bytes) { var s = ''; @@ -36388,7 +37501,8 @@ fixed: 4, longDateTime: 8, tag: 4 - }; // A stateful parser that changes the offset whenever a value is retrieved. + }; + // A stateful parser that changes the offset whenever a value is retrieved. // The data is a DataView. function Parser(data, offset) { this.data = data; @@ -36447,19 +37561,22 @@ }; Parser.prototype.parseTag = function () { return this.parseString(4); - }; // LONGDATETIME is a 64-bit integer. + }; + // 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 + 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 + 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); @@ -36474,7 +37591,8 @@ amount = 1; } this.relativeOffset += typeOffsets[type] * amount; - }; ///// Parsing lists and records /////////////////////////////// + }; + ///// Parsing lists and records /////////////////////////////// // Parse a list of 32 bit unsigned integers. Parser.prototype.parseULongList = function (count) { if (count === undefined) { @@ -36489,7 +37607,8 @@ } 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 + }; + // 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) { @@ -36504,7 +37623,8 @@ } this.relativeOffset += count * 2; return offsets; - }; // Parses a list of 16 bit signed integers. + }; + // Parses a list of 16 bit signed integers. Parser.prototype.parseShortList = function (count) { var list = new Array(count); var dataView = this.data; @@ -36515,7 +37635,8 @@ } this.relativeOffset += count * 2; return list; - }; // Parses a list of bytes. + }; + // Parses a list of bytes. Parser.prototype.parseByteList = function (count) { var list = new Array(count); var dataView = this.data; @@ -36561,7 +37682,8 @@ * 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. + var this$1 = this; + // If the count argument is absent, read it in the stream. if (!recordDescription) { recordDescription = count; count = this.parseUShort(); @@ -36581,7 +37703,8 @@ return records; }; Parser.prototype.parseRecordList32 = function (count, recordDescription) { - var this$1 = this; // If the count argument is absent, read it in the stream. + var this$1 = this; + // If the count argument is absent, read it in the stream. if (!recordDescription) { recordDescription = count; count = this.parseULong(); @@ -36599,7 +37722,8 @@ records[i] = rec; } return records; - }; // Parse a data structure into an object + }; + // 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; @@ -36644,7 +37768,7 @@ } if (valueFormat & 8) { valueRecord.yAdvance = this.parseShort(); - } // Device table (non-variable font) / VariationIndex table (variable font) not supported + } // Device table (non-variable font) / VariationIndex table (variable font) not supported // https://docs.microsoft.com/fr-fr/typography/opentype/spec/chapter2#devVarIdxTbls if (valueFormat & 16) { @@ -36732,7 +37856,8 @@ } this.relativeOffset = relativeOffset; return list; - }; ///// Complex tables parsing ////////////////////////////////// + }; + ///// 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. @@ -36761,7 +37886,8 @@ }; } 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. + }; + // 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; @@ -36783,7 +37909,8 @@ }; } throw new Error('0x' + startOffset.toString(16) + ': ClassDef format must be 1 or 2.'); - }; ///// Static methods /////////////////////////////////// + }; + ///// 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 () { @@ -36823,7 +37950,8 @@ Parser.uLongList = Parser.prototype.parseULongList; Parser.struct = Parser.prototype.parseStruct; Parser.coverage = Parser.prototype.parseCoverage; - Parser.classDef = Parser.prototype.parseClassDef; ///// Script, Feature, Lookup lists /////////////////////////////////////////////// + Parser.classDef = Parser.prototype.parseClassDef; + ///// Script, Feature, Lookup lists /////////////////////////////////////////////// // https://www.microsoft.com/typography/OTSPEC/chapter2.htm var langSysTable = { reserved: Parser.uShort, @@ -36894,10 +38022,12 @@ getBytes: getBytes, bytesToString: bytesToString, Parser: Parser - }; // The `cmap` table stores the mappings from characters to glyphs. + }; + // 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. + p.parseUShort(); + // Length in bytes of the sub-tables. cmap.length = p.parseULong(); cmap.language = p.parseULong(); var groupCount; @@ -36917,10 +38047,13 @@ 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. + 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.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); @@ -36938,8 +38071,10 @@ 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 = 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) { @@ -36951,7 +38086,7 @@ cmap.glyphIndexMap[c] = glyphIndex; } } - } // Parse the `cmap` table. This table stores the mappings from characters to glyphs. + } // 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. @@ -36959,7 +38094,8 @@ 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. + 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; @@ -37002,12 +38138,13 @@ delta: 1, offset: 0 }); - } // Make cmap table, format 4 by default, 12 if needed only + } // 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 + 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) { @@ -37026,7 +38163,8 @@ name: 'numTables', type: 'USHORT', value: isPlan0Only ? 1 : 2 - }, // CMAP 4 header + }, + // CMAP 4 header { name: 'platformID', type: 'USHORT', @@ -37044,12 +38182,13 @@ } ]; if (!isPlan0Only) { - cmapTable = cmapTable.concat([ // CMAP 12 header + cmapTable = cmapTable.concat([ // CMAP 12 header { name: 'cmap12PlatformID', type: 'USHORT', value: 3 - }, // We encode only for PlatformID = 3 (Windows) because it is supported everywhere + }, + // We encode only for PlatformID = 3 (Windows) because it is supported everywhere { name: 'cmap12EncodingID', type: 'USHORT', @@ -37062,7 +38201,7 @@ } ]); } - cmapTable = cmapTable.concat([ // CMAP 4 Subtable + cmapTable = cmapTable.concat([ // CMAP 4 Subtable { name: 'format', type: 'USHORT', @@ -37113,7 +38252,8 @@ } addTerminatorSegment(t); var segCount = t.segments.length; - var segCountToRemove = 0; // CMAP 4 + var segCountToRemove = 0; + // CMAP 4 // Set up parallel segment arrays. var endCounts = [ ]; @@ -37124,14 +38264,17 @@ var idRangeOffsets = [ ]; var glyphIds = [ - ]; // CMAP 12 + ]; + // CMAP 12 var cmap12Groups = [ - ]; // Reminder this loop is not following the specification at 100% + ]; + // 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 + var segment = t.segments[i]; + // CMAP 4 if (segment.end <= 65535 && segment.start <= 65535) { endCounts = endCounts.concat({ name: 'end_' + i, @@ -37163,7 +38306,7 @@ } else { // Skip Unicode > 65535 (16bit unsigned max) for CMAP 4, will be added in CMAP 12 segCountToRemove += 1; - } // CMAP 12 + } // CMAP 12 // Skip Terminator Segment if (!isPlan0Only && segment.glyphIndex !== undefined) { @@ -37183,7 +38326,7 @@ value: segment.glyphIndex }); } - } // CMAP 4 Subtable + } // CMAP 4 Subtable t.segCountX2 = (segCount - segCountToRemove) * 2; t.searchRange = Math.pow(2, Math.floor(Math.log(segCount - segCountToRemove) / Math.log(2))) * 2; @@ -37199,12 +38342,12 @@ 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 + 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 + var cmap12Length = 16 + // Subtable header cmap12Groups.length * 4; t.cmap12Offset = 12 + 2 * 2 + 4 + t.cmap4Length; t.fields = t.fields.concat([{ @@ -37240,7 +38383,8 @@ var cmap = { parse: parseCmapTable, make: makeCmapTable - }; // Glyph encoding + }; + // Glyph encoding var cffStandardStrings = [ '.notdef', 'space', @@ -38547,7 +39691,7 @@ glyph.name = font.glyphNames.glyphIndexToName(i$1); } } - } // Drawing utility functions. + } // 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) { @@ -38558,7 +39702,8 @@ } var draw = { line: line - }; // The Glyph object + }; + // 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(); @@ -38607,13 +39752,15 @@ */ Glyph.prototype.bindConstructorValues = function (options) { - this.index = options.index || 0; // These three values cannot be deferred for memory optimization: + 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 + ]; + // 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; @@ -38629,7 +39776,7 @@ } if (options.advanceWidth) { this.advanceWidth = options.advanceWidth; - } // The path for a glyph is the most memory intensive, and is bound as a value + } // 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. @@ -38675,14 +39822,16 @@ 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 + 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 + y = Math.round(y); + // TODO in case of hinting xyScaling is not yet supported xScale = yScale = 1; } else { commands = this.path.commands; @@ -38866,24 +40015,29 @@ y = y !== undefined ? y : 0; fontSize = fontSize !== undefined ? fontSize : 24; scale = 1 / this.path.unitsPerEm * fontSize; - ctx.lineWidth = 1; // Draw the origin + 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 + 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 + 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 + 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 + }; + // 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, { @@ -39009,7 +40163,8 @@ glyphLoader: glyphLoader, ttfGlyphLoader: ttfGlyphLoader, cffGlyphLoader: cffGlyphLoader - }; // The `CFF` table contains the glyph outlines in PostScript format. + }; + // 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) { @@ -39027,7 +40182,7 @@ } else { return false; } - } // Subroutines are encoded using the negative half of the number space. + } // Subroutines are encoded using the negative half of the number space. // See type 2 chapter 4.7 "Subroutine operators". function calcCFFSubroutineBias(subrs) { @@ -39040,7 +40195,7 @@ bias = 32768; } return bias; - } // Parse a `CFF` INDEX array. + } // 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) { @@ -39058,7 +40213,7 @@ 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. + } // The total size of the index array is 4 header bytes + the value of the last offset. endOffset = objectOffset + offsets[count]; } else { @@ -39076,7 +40231,7 @@ startOffset: start, endOffset: endOffset }; - } // Parse a `CFF` DICT real value. + } // Parse a `CFF` DICT real value. function parseFloatOperand(parser) { var s = ''; @@ -39112,7 +40267,7 @@ s += lookup[n2]; } return parseFloat(s); - } // Parse a `CFF` DICT operand. + } // Parse a `CFF` DICT operand. function parseOperand(parser, b0) { var b1; @@ -39146,7 +40301,7 @@ return - (b0 - 251) * 256 - b1 - 108; } throw new Error('Invalid b0 ' + b0); - } // Convert the entries returned by `parseDict` to a proper dictionary. + } // Convert the entries returned by `parseDict` to a proper dictionary. // If a value is a list of one, it is unpacked. function entriesToObject(entries) { @@ -39167,7 +40322,7 @@ o[key] = value; } return o; - } // Parse a `CFF` DICT object. + } // Parse a `CFF` DICT object. // A dictionary contains key-value pairs in a compact tokenized format. function parseCFFDict(data, start, size) { @@ -39179,7 +40334,8 @@ ]; 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). + 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. @@ -39197,7 +40353,7 @@ } } return entriesToObject(entries); - } // Given a String Index (SID), return the value of the string. + } // 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) { @@ -39207,13 +40363,14 @@ index = strings[index - 391]; } return index; - } // Interpret a dictionary and return a new dictionary with readable keys and values for missing entries. + } // 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 + 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]; @@ -39244,7 +40401,7 @@ } } return newDict; - } // Parse the CFF header. + } // Parse the CFF header. function parseCFFHeader(data, start) { var header = { @@ -39481,17 +40638,18 @@ type: 'number', value: 0 } - ]; // Parse the CFF top dictionary. A CFF table can contain multiple fonts, each with their own top dictionary. + ]; + // 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. + } // 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. + } // 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. @@ -39533,14 +40691,15 @@ topDictArray.push(topDict); } return topDictArray; - } // Parse the CFF charset table, which contains internal names for all the glyphs. + } // 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. + var parser = new parse.Parser(data, start); + // The .notdef glyph is not included, so subtract 1. nGlyphs -= 1; var charset = [ '.notdef' @@ -39573,7 +40732,7 @@ throw new Error('Unknown charset format ' + format); } return charset; - } // Parse the CFF encoding data. Only one encoding can be specified per font. + } // 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) { @@ -39603,7 +40762,7 @@ throw new Error('Unknown encoding format ' + format); } return new CffEncoding(enc, charset); - } // Take in charstring code and return a Glyph object. + } // 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 @@ -39646,7 +40805,8 @@ open = true; } function parseStems() { - var hasWidthArg; // The number of stem operators on the stack is always even. + 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) { @@ -40065,7 +41225,7 @@ 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. + } // Parse the `CFF` table, which contains the glyph outlines in PostScript format. function parseCFFTable(data, start, font) { font.tables.cff = { @@ -40116,7 +41276,7 @@ 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. + } // 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; @@ -40129,7 +41289,7 @@ font.cffEncoding = new CffEncoding(cffExpertEncoding, charset); } else { font.cffEncoding = parseCFFEncoding(data, start + topDict.encoding, charset); - } // Prefer the CMAP encoding to the CFF encoding. + } // Prefer the CMAP encoding to the CFF encoding. font.encoding = font.encoding || font.cffEncoding; font.glyphs = new glyphset.GlyphSet(font); @@ -40137,15 +41297,16 @@ var charString = charStringsIndex.objects[i]; font.glyphs.push(i, glyphset.cffGlyphLoader(font, i, parseCFFCharstring, charString)); } - } // Convert a string to a String ID (SID). + } // 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 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? + } // Is the string already in the string index? i = strings.indexOf(s); if (i >= 0) { @@ -40199,7 +41360,7 @@ }); } return t; - } // Given a dictionary's metadata, create a DICT structure. + } // Given a dictionary's metadata, create a DICT structure. function makeDict(meta, attrs, strings) { var m = { @@ -40219,7 +41380,7 @@ } } return m; - } // The Top DICT houses the global font attributes. + } // The Top DICT houses the global font attributes. function makeTopDict(attrs, strings) { var t = new table.Record('Top DICT', [ @@ -40319,7 +41480,8 @@ 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. + 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, @@ -40414,7 +41576,7 @@ }); x = Math.round(cmd.x); y = Math.round(cmd.y); - } // Contours are closed automatically. + } // Contours are closed automatically. } ops.push({ @@ -40491,7 +41653,8 @@ type: 'RECORD' } ]); - var fontScale = 1 / options.unitsPerEm; // We use non-zero values for the offsets so that the DICT encodes them. + 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 = { @@ -40525,7 +41688,8 @@ }; var glyphNames = [ ]; - var glyph; // Skip first glyph (.notdef) + var glyph; + // Skip first glyph (.notdef) for (var i = 1; i < glyphs.length; i += 1) { glyph = glyphs.get(i); glyphNames.push(glyph.name); @@ -40539,13 +41703,16 @@ 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.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.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. + 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; @@ -40553,7 +41720,8 @@ var cff = { parse: parseCFFTable, make: makeCFFTable - }; // The `head` table contains global information about the font. + }; + // The `head` table contains global information about the font. // Parse the header `head` table function parseHeadTable(data, start) { var head = { @@ -40677,7 +41845,8 @@ var head = { parse: parseHeadTable, make: makeHeadTable - }; // The `hhea` table contains information for horizontal layout. + }; + // The `hhea` table contains information for horizontal layout. // Parse the horizontal header `hhea` table function parseHheaTable(data, start) { var hhea = { @@ -40791,7 +41960,8 @@ var hhea = { parse: parseHheaTable, make: makeHheaTable - }; // The `hmtx` table contains the horizontal metrics for all glyphs. + }; + // 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) { @@ -40832,7 +42002,8 @@ var hmtx = { parse: parseHmtxTable, make: makeHmtxTable - }; // The `ltag` table stores IETF BCP-47 language tags. It allows supporting + }; + // The `ltag` table stores IETF BCP-47 language tags. It allows supporting function makeLtagTable(tags) { var result = new table.Table('ltag', [ { @@ -40880,7 +42051,8 @@ 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. + 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 = [ @@ -40899,7 +42071,8 @@ var ltag = { make: makeLtagTable, parse: parseLtagTable - }; // The `maxp` table establishes the memory requirements for the font. + }; + // The `maxp` table establishes the memory requirements for the font. // Parse the maximum profile `maxp` table. function parseMaxpTable(data, start) { var maxp = { @@ -40941,31 +42114,54 @@ var maxp = { parse: parseMaxpTable, make: makeMaxpTable - }; // The `name` naming table. + }; + // 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 + '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 = { @@ -41088,7 +42284,8 @@ 149: 'kl', 150: 'az', 151: 'nn' - }; // MacOS language ID → MacOS script ID + }; + // 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 @@ -41338,7 +42535,8 @@ 150: 0, // langAzerbaijanRoman → smRoman 151: 0 // langNynorsk → smRoman - }; // While Microsoft indicates a region/country for all its language + }; + // 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 @@ -41567,7 +42765,8 @@ 1157: 'sah', 1144: 'ii', 1130: 'yo' - }; // Returns a IETF BCP 47 language code, for example 'zh-Hant' + }; + // Returns a IETF BCP 47 language code, for example 'zh-Hant' // for 'Chinese in the traditional script'. function getLanguageCode(platformID, languageID, ltag) { switch (platformID) { @@ -41588,7 +42787,8 @@ } return undefined; } - var utf16 = 'utf-16'; // MacOS script ID → encoding. This table stores the default case, + var utf16 = 'utf-16'; + // MacOS script ID → encoding. This table stores the default case, // which can be overridden by macLanguageEncodings. var macScriptEncodings = { 0: 'macintosh', @@ -41648,7 +42848,8 @@ 30: 'x-mac-vietnamese', // smVietnamese 31: 'x-mac-extarabic' // smExtArabic - }; // MacOS language ID → encoding. This table stores the exceptional + }; + // 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. @@ -41701,7 +42902,7 @@ break; } return undefined; - } // Parse the naming `name` table. + } // 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']. @@ -41745,7 +42946,7 @@ langTagCount = p.parseUShort(); } return name; - } // {23: 'foo'} → {'foo': 23} + } // {23: 'foo'} → {'foo': 23} // ['bar', 'baz'] → {'bar': 0, 'baz': 1} function reverseDict(dict) { @@ -41789,7 +42990,7 @@ value: offset } ]); - } // Finds the position of needle in haystack, or -1 if not there. + } // Finds the position of needle in haystack, or -1 if not there. // Like String.indexOf(), but for arrays. function findSubArray(needle, haystack) { @@ -41848,7 +43049,8 @@ 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 + 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; @@ -41924,496 +43126,619 @@ var _name = { parse: parseNameTable, make: makeNameTable - }; // The `OS/2` table contains metrics required in OpenType fonts. + }; + // The `OS/2` table contains metrics required in OpenType fonts. var unicodeRanges = [ { begin: 0, end: 127 - }, // Basic Latin + }, + // Basic Latin { begin: 128, end: 255 - }, // Latin-1 Supplement + }, + // Latin-1 Supplement { begin: 256, end: 383 - }, // Latin Extended-A + }, + // Latin Extended-A { begin: 384, end: 591 - }, // Latin Extended-B + }, + // Latin Extended-B { begin: 592, end: 687 - }, // IPA Extensions + }, + // IPA Extensions { begin: 688, end: 767 - }, // Spacing Modifier Letters + }, + // Spacing Modifier Letters { begin: 768, end: 879 - }, // Combining Diacritical Marks + }, + // Combining Diacritical Marks { begin: 880, end: 1023 - }, // Greek and Coptic + }, + // Greek and Coptic { begin: 11392, end: 11519 - }, // Coptic + }, + // Coptic { begin: 1024, end: 1279 - }, // Cyrillic + }, + // Cyrillic { begin: 1328, end: 1423 - }, // Armenian + }, + // Armenian { begin: 1424, end: 1535 - }, // Hebrew + }, + // Hebrew { begin: 42240, end: 42559 - }, // Vai + }, + // Vai { begin: 1536, end: 1791 - }, // Arabic + }, + // Arabic { begin: 1984, end: 2047 - }, // NKo + }, + // NKo { begin: 2304, end: 2431 - }, // Devanagari + }, + // Devanagari { begin: 2432, end: 2559 - }, // Bengali + }, + // Bengali { begin: 2560, end: 2687 - }, // Gurmukhi + }, + // Gurmukhi { begin: 2688, end: 2815 - }, // Gujarati + }, + // Gujarati { begin: 2816, end: 2943 - }, // Oriya + }, + // Oriya { begin: 2944, end: 3071 - }, // Tamil + }, + // Tamil { begin: 3072, end: 3199 - }, // Telugu + }, + // Telugu { begin: 3200, end: 3327 - }, // Kannada + }, + // Kannada { begin: 3328, end: 3455 - }, // Malayalam + }, + // Malayalam { begin: 3584, end: 3711 - }, // Thai + }, + // Thai { begin: 3712, end: 3839 - }, // Lao + }, + // Lao { begin: 4256, end: 4351 - }, // Georgian + }, + // Georgian { begin: 6912, end: 7039 - }, // Balinese + }, + // Balinese { begin: 4352, end: 4607 - }, // Hangul Jamo + }, + // Hangul Jamo { begin: 7680, end: 7935 - }, // Latin Extended Additional + }, + // Latin Extended Additional { begin: 7936, end: 8191 - }, // Greek Extended + }, + // Greek Extended { begin: 8192, end: 8303 - }, // General Punctuation + }, + // General Punctuation { begin: 8304, end: 8351 - }, // Superscripts And Subscripts + }, + // Superscripts And Subscripts { begin: 8352, end: 8399 - }, // Currency Symbol + }, + // Currency Symbol { begin: 8400, end: 8447 - }, // Combining Diacritical Marks For Symbols + }, + // Combining Diacritical Marks For Symbols { begin: 8448, end: 8527 - }, // Letterlike Symbols + }, + // Letterlike Symbols { begin: 8528, end: 8591 - }, // Number Forms + }, + // Number Forms { begin: 8592, end: 8703 - }, // Arrows + }, + // Arrows { begin: 8704, end: 8959 - }, // Mathematical Operators + }, + // Mathematical Operators { begin: 8960, end: 9215 - }, // Miscellaneous Technical + }, + // Miscellaneous Technical { begin: 9216, end: 9279 - }, // Control Pictures + }, + // Control Pictures { begin: 9280, end: 9311 - }, // Optical Character Recognition + }, + // Optical Character Recognition { begin: 9312, end: 9471 - }, // Enclosed Alphanumerics + }, + // Enclosed Alphanumerics { begin: 9472, end: 9599 - }, // Box Drawing + }, + // Box Drawing { begin: 9600, end: 9631 - }, // Block Elements + }, + // Block Elements { begin: 9632, end: 9727 - }, // Geometric Shapes + }, + // Geometric Shapes { begin: 9728, end: 9983 - }, // Miscellaneous Symbols + }, + // Miscellaneous Symbols { begin: 9984, end: 10175 - }, // Dingbats + }, + // Dingbats { begin: 12288, end: 12351 - }, // CJK Symbols And Punctuation + }, + // CJK Symbols And Punctuation { begin: 12352, end: 12447 - }, // Hiragana + }, + // Hiragana { begin: 12448, end: 12543 - }, // Katakana + }, + // Katakana { begin: 12544, end: 12591 - }, // Bopomofo + }, + // Bopomofo { begin: 12592, end: 12687 - }, // Hangul Compatibility Jamo + }, + // Hangul Compatibility Jamo { begin: 43072, end: 43135 - }, // Phags-pa + }, + // Phags-pa { begin: 12800, end: 13055 - }, // Enclosed CJK Letters And Months + }, + // Enclosed CJK Letters And Months { begin: 13056, end: 13311 - }, // CJK Compatibility + }, + // CJK Compatibility { begin: 44032, end: 55215 - }, // Hangul Syllables + }, + // Hangul Syllables { begin: 55296, end: 57343 - }, // Non-Plane 0 * + }, + // Non-Plane 0 * { begin: 67840, end: 67871 - }, // Phoenicia + }, + // Phoenicia { begin: 19968, end: 40959 - }, // CJK Unified Ideographs + }, + // CJK Unified Ideographs { begin: 57344, end: 63743 - }, // Private Use Area (plane 0) + }, + // Private Use Area (plane 0) { begin: 12736, end: 12783 - }, // CJK Strokes + }, + // CJK Strokes { begin: 64256, end: 64335 - }, // Alphabetic Presentation Forms + }, + // Alphabetic Presentation Forms { begin: 64336, end: 65023 - }, // Arabic Presentation Forms-A + }, + // Arabic Presentation Forms-A { begin: 65056, end: 65071 - }, // Combining Half Marks + }, + // Combining Half Marks { begin: 65040, end: 65055 - }, // Vertical Forms + }, + // Vertical Forms { begin: 65104, end: 65135 - }, // Small Form Variants + }, + // Small Form Variants { begin: 65136, end: 65279 - }, // Arabic Presentation Forms-B + }, + // Arabic Presentation Forms-B { begin: 65280, end: 65519 - }, // Halfwidth And Fullwidth Forms + }, + // Halfwidth And Fullwidth Forms { begin: 65520, end: 65535 - }, // Specials + }, + // Specials { begin: 3840, end: 4095 - }, // Tibetan + }, + // Tibetan { begin: 1792, end: 1871 - }, // Syriac + }, + // Syriac { begin: 1920, end: 1983 - }, // Thaana + }, + // Thaana { begin: 3456, end: 3583 - }, // Sinhala + }, + // Sinhala { begin: 4096, end: 4255 - }, // Myanmar + }, + // Myanmar { begin: 4608, end: 4991 - }, // Ethiopic + }, + // Ethiopic { begin: 5024, end: 5119 - }, // Cherokee + }, + // Cherokee { begin: 5120, end: 5759 - }, // Unified Canadian Aboriginal Syllabics + }, + // Unified Canadian Aboriginal Syllabics { begin: 5760, end: 5791 - }, // Ogham + }, + // Ogham { begin: 5792, end: 5887 - }, // Runic + }, + // Runic { begin: 6016, end: 6143 - }, // Khmer + }, + // Khmer { begin: 6144, end: 6319 - }, // Mongolian + }, + // Mongolian { begin: 10240, end: 10495 - }, // Braille Patterns + }, + // Braille Patterns { begin: 40960, end: 42127 - }, // Yi Syllables + }, + // Yi Syllables { begin: 5888, end: 5919 - }, // Tagalog + }, + // Tagalog { begin: 66304, end: 66351 - }, // Old Italic + }, + // Old Italic { begin: 66352, end: 66383 - }, // Gothic + }, + // Gothic { begin: 66560, end: 66639 - }, // Deseret + }, + // Deseret { begin: 118784, end: 119039 - }, // Byzantine Musical Symbols + }, + // Byzantine Musical Symbols { begin: 119808, end: 120831 - }, // Mathematical Alphanumeric Symbols + }, + // Mathematical Alphanumeric Symbols { begin: 1044480, end: 1048573 - }, // Private Use (plane 15) + }, + // Private Use (plane 15) { begin: 65024, end: 65039 - }, // Variation Selectors + }, + // Variation Selectors { begin: 917504, end: 917631 - }, // Tags + }, + // Tags { begin: 6400, end: 6479 - }, // Limbu + }, + // Limbu { begin: 6480, end: 6527 - }, // Tai Le + }, + // Tai Le { begin: 6528, end: 6623 - }, // New Tai Lue + }, + // New Tai Lue { begin: 6656, end: 6687 - }, // Buginese + }, + // Buginese { begin: 11264, end: 11359 - }, // Glagolitic + }, + // Glagolitic { begin: 11568, end: 11647 - }, // Tifinagh + }, + // Tifinagh { begin: 19904, end: 19967 - }, // Yijing Hexagram Symbols + }, + // Yijing Hexagram Symbols { begin: 43008, end: 43055 - }, // Syloti Nagri + }, + // Syloti Nagri { begin: 65536, end: 65663 - }, // Linear B Syllabary + }, + // Linear B Syllabary { begin: 65856, end: 65935 - }, // Ancient Greek Numbers + }, + // Ancient Greek Numbers { begin: 66432, end: 66463 - }, // Ugaritic + }, + // Ugaritic { begin: 66464, end: 66527 - }, // Old Persian + }, + // Old Persian { begin: 66640, end: 66687 - }, // Shavian + }, + // Shavian { begin: 66688, end: 66735 - }, // Osmanya + }, + // Osmanya { begin: 67584, end: 67647 - }, // Cypriot Syllabary + }, + // Cypriot Syllabary { begin: 68096, end: 68191 - }, // Kharoshthi + }, + // Kharoshthi { begin: 119552, end: 119647 - }, // Tai Xuan Jing Symbols + }, + // Tai Xuan Jing Symbols { begin: 73728, end: 74751 - }, // Cuneiform + }, + // Cuneiform { begin: 119648, end: 119679 - }, // Counting Rod Numerals + }, + // Counting Rod Numerals { begin: 7040, end: 7103 - }, // Sundanese + }, + // Sundanese { begin: 7168, end: 7247 - }, // Lepcha + }, + // Lepcha { begin: 7248, end: 7295 - }, // Ol Chiki + }, + // Ol Chiki { begin: 43136, end: 43231 - }, // Saurashtra + }, + // Saurashtra { begin: 43264, end: 43311 - }, // Kayah Li + }, + // Kayah Li { begin: 43312, end: 43359 - }, // Rejang + }, + // Rejang { begin: 43520, end: 43615 - }, // Cham + }, + // Cham { begin: 65936, end: 65999 - }, // Ancient Symbols + }, + // Ancient Symbols { begin: 66000, end: 66047 - }, // Phaistos Disc + }, + // Phaistos Disc { begin: 66208, end: 66271 - }, // Carian + }, + // Carian { begin: 127024, end: 127135 @@ -42428,7 +43753,7 @@ } } return - 1; - } // Parse the OS/2 and Windows metrics `OS/2` table + } // Parse the OS/2 and Windows metrics `OS/2` table function parseOS2Table(data, start) { var os2 = { @@ -42720,7 +44045,8 @@ make: makeOS2Table, unicodeRanges: unicodeRanges, getUnicodeRange: getUnicodeRange - }; // The `post` table stores additional PostScript information, such as glyph names. + }; + // The `post` table stores additional PostScript information, such as glyph names. // Parse the PostScript `post` table function parsePostTable(data, start) { var post = { @@ -42816,7 +44142,8 @@ var post = { parse: parsePostTable, make: makePostTable - }; // The `GSUB` table contains ligatures, among other things. + }; + // 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() { @@ -42836,7 +44163,8 @@ }; } 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 + }; + // 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'); @@ -42845,7 +44173,8 @@ coverage: this.parsePointer(Parser.coverage), sequences: this.parseListOfLists() }; - }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#AS + }; + // 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'); @@ -42854,7 +44183,8 @@ coverage: this.parsePointer(Parser.coverage), alternateSets: this.parseListOfLists() }; - }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#LS + }; + // 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'); @@ -42872,7 +44202,8 @@ var lookupRecordDesc = { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort - }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CSF + }; + // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CSF subtableParsers[5] = function parseLookup5() { var start = this.offset + this.relativeOffset; var substFormat = this.parseUShort(); @@ -42913,7 +44244,8 @@ }; } 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 + }; + // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CC subtableParsers[6] = function parseLookup6() { var start = this.offset + this.relativeOffset; var substFormat = this.parseUShort(); @@ -42956,7 +44288,8 @@ }; } 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 + }; + // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#ES subtableParsers[7] = function parseLookup7() { // Extension Substitution subtable var substFormat = this.parseUShort(); @@ -42968,7 +44301,8 @@ lookupType: extensionLookupType, extension: subtableParsers[extensionLookupType].call(extensionParser) }; - }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#RCCS + }; + // 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'); @@ -42979,7 +44313,8 @@ lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), substitutes: this.parseUShortList() }; - }; // https://www.microsoft.com/typography/OTSPEC/gsub.htm + }; + // https://www.microsoft.com/typography/OTSPEC/gsub.htm function parseGsubTable(data, start) { start = start || 0; var p = new Parser(data, start); @@ -43001,7 +44336,7 @@ variations: p.parseFeatureVariationsList() }; } - } // GSUB Writing ////////////////////////////////////////////// + } // GSUB Writing ////////////////////////////////////////////// var subtableMakers = new Array(9); subtableMakers[1] = function makeLookup1(subtable) { @@ -43108,7 +44443,8 @@ var gsub = { parse: parseGsubTable, make: makeGsubTable - }; // The `GPOS` table contains kerning pairs, among other things. + }; + // 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) { @@ -43184,7 +44520,8 @@ var meta = { parse: parseMetaTable, make: makeMetaTable - }; // The `sfnt` wrapper provides organization for the tables in the font. + }; + // The `sfnt` wrapper provides organization for the tables in the font. function log2(v) { return Math.log(v) / Math.log(2) | 0; } @@ -43295,7 +44632,7 @@ value: 0 }); } - } // Table records need to be sorted alphabetically. + } // Table records need to be sorted alphabetically. recordFields.sort(function (r1, r2) { if (r1.value.tag > r2.value.tag) { @@ -43307,7 +44644,7 @@ 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 + } // 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. @@ -43327,7 +44664,7 @@ sum += vs[i]; } return sum / vs.length; - } // Convert the font object to a SFNT data structure. + } // 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) { @@ -43377,7 +44714,7 @@ ulUnicodeRange4 |= 1 << position - 96; } else { throw new Error('Unicode ranges bits > 123 are reserved for internal usage'); - } // Skip non-important characters. + } // Skip non-important characters. if (glyph.name === '.notdef') { continue; @@ -43505,7 +44842,8 @@ 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 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, @@ -43519,7 +44857,7 @@ ]; if (ltagTable) { tables.push(ltagTable); - } // Optional tables + } // Optional tables if (font.tables.gsub) { tables.push(gsub.make(font.tables.gsub)); @@ -43527,7 +44865,8 @@ if (metaTable) { tables.push(metaTable); } - var sfntTable = makeSfntTable(tables); // Compute the font's checkSum and store it in head.checkSumAdjustment. + 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; @@ -43548,7 +44887,8 @@ make: makeSfntTable, fontToTable: fontToSfntTable, computeCheckSum: computeCheckSum - }; // The Layout object is the prototype of Substitution objects, and provides + }; + // The Layout object is the prototype of Substitution objects, and provides function searchTag(arr, tag) { /* jshint bitwise: false */ var imin = 0; @@ -43563,7 +44903,7 @@ } else { imax = imid - 1; } - } // Not found: return -1-insertion point + } // Not found: return -1-insertion point return - imin - 1; } @@ -43581,10 +44921,10 @@ } else { imax = imid - 1; } - } // Not found: return -1-insertion point + } // Not found: return -1-insertion point return - imin - 1; - } // binary search in a list of ranges (coverage, class definition) + } // binary search in a list of ranges (coverage, class definition) function searchRange(ranges, value) { // jshint bitwise: false @@ -43771,7 +45111,8 @@ 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, + 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]]; @@ -43780,7 +45121,8 @@ } } if (create) { - var index = allFeatures.length; // Automatic ordering of features would require to shift feature indexes in the script list. + 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, @@ -43813,7 +45155,8 @@ 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. + 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) { @@ -43898,7 +45241,8 @@ return glyphs; } } - }; // The Position object provides utility methods to manipulate + }; + // The Position object provides utility methods to manipulate /** * @exports opentype.Position * @class @@ -43968,7 +45312,8 @@ if (this.font.tables.gpos) { return this.getLookupTables(script, language, 'kern', 2); } - }; // The Substitution object provides utility methods to manipulate + }; + // The Substitution object provides utility methods to manipulate /** * @exports opentype.Substitution * @class @@ -43978,7 +45323,7 @@ */ function Substitution(font) { Layout.call(this, font, 'gsub'); - } // Check if 2 arrays of primitives are equal. + } // Check if 2 arrays of primitives are equal. function arraysEqual(ar1, ar2) { var n = ar1.length; @@ -43991,7 +45336,7 @@ } } return true; - } // Find the first subtable of a lookup table in a particular format. + } // Find the first subtable of a lookup table in a particular format. function getSubstFormat(lookupTable, format, defaultSubtable) { var subtables = lookupTable.subtables; @@ -44243,7 +45588,7 @@ if (arraysEqual(ligatureSet[i].components, ligComponents)) { return; } - } // ligature does not exist: add it. + } // ligature does not exist: add it. ligatureSet.push(ligatureTable); } else { @@ -44327,14 +45672,15 @@ if (!expression) { throw message; } - } // The `glyf` table describes the glyphs in TrueType outline format. + } // 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. + 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; } @@ -44350,7 +45696,7 @@ } } return v; - } // Parse a TrueType glyph. + } // Parse a TrueType glyph. function parseGlyph(glyph, data, start) { var p = new parse.Parser(data, start); @@ -44379,7 +45725,8 @@ ]; 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. + 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) { @@ -44392,7 +45739,8 @@ 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. + 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]; @@ -44497,7 +45845,7 @@ } } } - } // Transform an array of points and return a new array. + } // Transform an array of points and return a new array. function transformPoints(points, transform) { var newPoints = [ @@ -44530,7 +45878,7 @@ } check.argument(currentContour.length === 0, 'There are still points left in the current contour.'); return contours; - } // Convert the TrueType glyph outline to a Path. + } // Convert the TrueType glyph outline to a Path. function getPath(points) { var p = new Path(); @@ -44590,7 +45938,8 @@ 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. + var componentGlyph = glyphs.get(component.glyphIndex); + // Force the ttfGlyphLoader to parse the glyph. componentGlyph.getPath(); if (componentGlyph.points) { var transformedPoints = void 0; @@ -44622,10 +45971,11 @@ } } return getPath(glyph.points); - } // Parse all the glyphs according to the offsets from the `loca` table. + } // 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. + 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]; @@ -44683,8 +46033,10 @@ this.font = font; this.getCommands = function (hPoints) { return glyf.getPath(hPoints).commands; - }; // cached states - this._fpgmState = this._prepState = undefined; // errorState + }; + // cached states + this._fpgmState = this._prepState = undefined; + // errorState // 0 ... all okay // 1 ... had an error in a glyf, // continue working but stop spamming @@ -44744,7 +46096,8 @@ } v += threshold - phase; v = Math.trunc(v / period) * period; - v += phase; // according to http://xgridfit.sourceforge.net/round.html + v += phase; + // according to http://xgridfit.sourceforge.net/round.html if (v < 0) { return phase * sign; } @@ -45122,7 +46475,7 @@ 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. + } // Received a fatal error, don't do any hinting anymore. if (this._errorState > 2) { return; @@ -45150,13 +46503,14 @@ this._errorState = 3; return; } - } // Executes the prep program for this ppem setting. + } // 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 + 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) { @@ -45230,7 +46584,8 @@ console.log('---EXEC COMP ' + i + '---'); state.step = - 1; } - execComponent(cg, state, xScale, yScale); // appends the computed points to the result array + 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); @@ -45252,7 +46607,8 @@ // 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 + 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) { @@ -45276,13 +46632,14 @@ var gZone = state.gZone = state.z0 = state.z1 = state.z2 = [ ]; var contours = state.contours = [ - ]; // Scales the original points and + ]; + // 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. + } // Chain links the contours. var sp; // start point var np; // next point @@ -45312,7 +46669,8 @@ } } gZone.push(new HPoint(0, 0), new HPoint(Math.round(glyph.advanceWidth * xScale), 0)); - exec(state); // Removes the extra points. + exec(state); + // Removes the extra points. gZone.length -= 2; if (exports.DEBUG) { console.log('FINISHED GLYPH', state.stack); @@ -45339,7 +46697,8 @@ if (!ins) { throw new Error('unknown instruction: 0x' + Number(prog[state.ip]).toString(16)); } - ins(state); // very extensive debugging for each step + ins(state); + // very extensive debugging for each step /* if (exports.DEBUG) { var da; @@ -45387,7 +46746,8 @@ * refers to the twilight zone. */ function initTZone(state) { - var tZone = state.tZone = new Array(state.gZone.length); // no idea if this is actually correct... + 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); } @@ -45403,25 +46763,25 @@ var ins; do { ins = prog[++ip]; - if (ins === 88) // IF + if (ins === 88) // IF { nesting++; - } else if (ins === 89) // EIF + } else if (ins === 89) // EIF { nesting--; - } else if (ins === 64) // NPUSHB + } else if (ins === 64) // NPUSHB { ip += prog[ip + 1] + 1; - } else if (ins === 65) // NPUSHW + } else if (ins === 65) // NPUSHW { ip += 2 * prog[ip + 1] + 1; - } else if (ins >= 176 && ins <= 183) // PUSHB + } else if (ins >= 176 && ins <= 183) // PUSHB { ip += ins - 176 + 1; - } else if (ins >= 184 && ins <= 191) // PUSHW + } else if (ins >= 184 && ins <= 191) // PUSHW { ip += (ins - 184 + 1) * 2; - } else if (handleElse && nesting === 1 && ins === 27) // ELSE + } else if (handleElse && nesting === 1 && ins === 27) // ELSE { break; } @@ -45438,7 +46798,7 @@ console.log(state.step, 'SVTCA[' + v.axis + ']'); } state.fv = state.pv = state.dpv = v; - } // SPVTCA[a] Set Projection Vector to Coordinate Axis + } // SPVTCA[a] Set Projection Vector to Coordinate Axis // 0x02-0x03 function SPVTCA(v, state) { @@ -45446,7 +46806,7 @@ console.log(state.step, 'SPVTCA[' + v.axis + ']'); } state.pv = state.dpv = v; - } // SFVTCA[a] Set Freedom Vector to Coordinate Axis + } // SFVTCA[a] Set Freedom Vector to Coordinate Axis // 0x04-0x05 function SFVTCA(v, state) { @@ -45454,7 +46814,7 @@ console.log(state.step, 'SFVTCA[' + v.axis + ']'); } state.fv = v; - } // SPVTL[a] Set Projection Vector To Line + } // SPVTL[a] Set Projection Vector To Line // 0x06-0x07 function SPVTL(a, state) { @@ -45476,7 +46836,7 @@ dy = p1.x - p2.x; } state.pv = state.dpv = getUnitVector(dx, dy); - } // SFVTL[a] Set Freedom Vector To Line + } // SFVTL[a] Set Freedom Vector To Line // 0x08-0x09 function SFVTL(a, state) { @@ -45498,7 +46858,7 @@ dy = p1.x - p2.x; } state.fv = getUnitVector(dx, dy); - } // SPVFS[] Set Projection Vector From Stack + } // SPVFS[] Set Projection Vector From Stack // 0x0A function SPVFS(state) { @@ -45509,7 +46869,7 @@ console.log(state.step, 'SPVFS[]', y, x); } state.pv = state.dpv = getUnitVector(x, y); - } // SFVFS[] Set Freedom Vector From Stack + } // SFVFS[] Set Freedom Vector From Stack // 0x0B function SFVFS(state) { @@ -45520,7 +46880,7 @@ console.log(state.step, 'SPVFS[]', y, x); } state.fv = getUnitVector(x, y); - } // GPV[] Get Projection Vector + } // GPV[] Get Projection Vector // 0x0C function GPV(state) { @@ -45531,7 +46891,7 @@ } stack.push(pv.x * 16384); stack.push(pv.y * 16384); - } // GFV[] Get Freedom Vector + } // GFV[] Get Freedom Vector // 0x0C function GFV(state) { @@ -45542,7 +46902,7 @@ } stack.push(fv.x * 16384); stack.push(fv.y * 16384); - } // SFVTPV[] Set Freedom Vector To Projection Vector + } // SFVTPV[] Set Freedom Vector To Projection Vector // 0x0E function SFVTPV(state) { @@ -45550,7 +46910,7 @@ if (exports.DEBUG) { console.log(state.step, 'SFVTPV[]'); } - } // ISECT[] moves point p to the InterSECTion of two lines + } // ISECT[] moves point p to the InterSECTion of two lines // 0x0F function ISECT(state) { @@ -45569,7 +46929,7 @@ var p = state.z2[pi]; if (exports.DEBUG) { console.log('ISECT[], ', pa0i, pa1i, pb0i, pb1i, pi); - } // math from + } // math from // en.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line var x1 = pa0.x; @@ -45585,7 +46945,7 @@ 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 + } // SRP0[] Set Reference Point 0 // 0x10 function SRP0(state) { @@ -45593,7 +46953,7 @@ if (exports.DEBUG) { console.log(state.step, 'SRP0[]', state.rp0); } - } // SRP1[] Set Reference Point 1 + } // SRP1[] Set Reference Point 1 // 0x11 function SRP1(state) { @@ -45601,7 +46961,7 @@ if (exports.DEBUG) { console.log(state.step, 'SRP1[]', state.rp1); } - } // SRP1[] Set Reference Point 2 + } // SRP1[] Set Reference Point 2 // 0x12 function SRP2(state) { @@ -45609,7 +46969,7 @@ if (exports.DEBUG) { console.log(state.step, 'SRP2[]', state.rp2); } - } // SZP0[] Set Zone Pointer 0 + } // SZP0[] Set Zone Pointer 0 // 0x13 function SZP0(state) { @@ -45631,7 +46991,7 @@ default: throw new Error('Invalid zone pointer'); } - } // SZP1[] Set Zone Pointer 1 + } // SZP1[] Set Zone Pointer 1 // 0x14 function SZP1(state) { @@ -45653,7 +47013,7 @@ default: throw new Error('Invalid zone pointer'); } - } // SZP2[] Set Zone Pointer 2 + } // SZP2[] Set Zone Pointer 2 // 0x15 function SZP2(state) { @@ -45675,7 +47035,7 @@ default: throw new Error('Invalid zone pointer'); } - } // SZPS[] Set Zone PointerS + } // SZPS[] Set Zone PointerS // 0x16 function SZPS(state) { @@ -45697,7 +47057,7 @@ default: throw new Error('Invalid zone pointer'); } - } // SLOOP[] Set LOOP variable + } // SLOOP[] Set LOOP variable // 0x17 function SLOOP(state) { @@ -45705,7 +47065,7 @@ if (exports.DEBUG) { console.log(state.step, 'SLOOP[]', state.loop); } - } // RTG[] Round To Grid + } // RTG[] Round To Grid // 0x18 function RTG(state) { @@ -45713,7 +47073,7 @@ console.log(state.step, 'RTG[]'); } state.round = roundToGrid; - } // RTHG[] Round To Half Grid + } // RTHG[] Round To Half Grid // 0x19 function RTHG(state) { @@ -45721,7 +47081,7 @@ console.log(state.step, 'RTHG[]'); } state.round = roundToHalfGrid; - } // SMD[] Set Minimum Distance + } // SMD[] Set Minimum Distance // 0x1A function SMD(state) { @@ -45730,7 +47090,7 @@ console.log(state.step, 'SMD[]', d); } state.minDis = d / 64; - } // ELSE[] ELSE clause + } // ELSE[] ELSE clause // 0x1B function ELSE(state) { @@ -45743,17 +47103,17 @@ console.log(state.step, 'ELSE[]'); } skip(state, false); - } // JMPR[] JuMP Relative + } // 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. + } // A jump by 1 would do nothing. state.ip += o - 1; - } // SCVTCI[] Set Control Value Table Cut-In + } // SCVTCI[] Set Control Value Table Cut-In // 0x1D function SCVTCI(state) { @@ -45762,7 +47122,7 @@ console.log(state.step, 'SCVTCI[]', n); } state.cvCutIn = n / 64; - } // DUP[] DUPlicate top stack element + } // DUP[] DUPlicate top stack element // 0x20 function DUP(state) { @@ -45771,7 +47131,7 @@ console.log(state.step, 'DUP[]'); } stack.push(stack[stack.length - 1]); - } // POP[] POP top stack element + } // POP[] POP top stack element // 0x21 function POP(state) { @@ -45779,7 +47139,7 @@ console.log(state.step, 'POP[]'); } state.stack.pop(); - } // CLEAR[] CLEAR the stack + } // CLEAR[] CLEAR the stack // 0x22 function CLEAR(state) { @@ -45787,7 +47147,7 @@ console.log(state.step, 'CLEAR[]'); } state.stack.length = 0; - } // SWAP[] SWAP the top two elements on the stack + } // SWAP[] SWAP the top two elements on the stack // 0x23 function SWAP(state) { @@ -45799,7 +47159,7 @@ } stack.push(a); stack.push(b); - } // DEPTH[] DEPTH of the stack + } // DEPTH[] DEPTH of the stack // 0x24 function DEPTH(state) { @@ -45808,7 +47168,7 @@ console.log(state.step, 'DEPTH[]'); } stack.push(stack.length); - } // LOOPCALL[] LOOPCALL function + } // LOOPCALL[] LOOPCALL function // 0x2A function LOOPCALL(state) { @@ -45817,39 +47177,42 @@ var c = stack.pop(); if (exports.DEBUG) { console.log(state.step, 'LOOPCALL[]', fn, c); - } // saves callers program + } // saves callers program var cip = state.ip; var cprog = state.prog; - state.prog = state.funcs[fn]; // executes the function + 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 + } // restores the callers program state.ip = cip; state.prog = cprog; - } // CALL[] CALL function + } // CALL[] CALL function // 0x2B function CALL(state) { var fn = state.stack.pop(); if (exports.DEBUG) { console.log(state.step, 'CALL[]', fn); - } // saves callers program + } // 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.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 + } // CINDEX[] Copy the INDEXed element to the top of the stack // 0x25 function CINDEX(state) { @@ -45857,11 +47220,11 @@ 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 + } // 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 + } // MINDEX[] Move the INDEXed element to the top of the stack // 0x26 function MINDEX(state) { @@ -45871,7 +47234,7 @@ console.log(state.step, 'MINDEX[]', k); } stack.push(stack.splice(stack.length - k, 1) [0]); - } // FDEF[] Function DEFinition + } // FDEF[] Function DEFinition // 0x2C function FDEF(state) { @@ -45890,7 +47253,7 @@ } state.ip = ip; state.funcs[fn] = prog.slice(ipBegin + 1, ip); - } // MDAP[a] Move Direct Absolute Point + } // MDAP[a] Move Direct Absolute Point // 0x2E-0x2F function MDAP(round, state) { @@ -45908,7 +47271,7 @@ fv.setRelative(p, HPZero, d, pv); fv.touch(p); state.rp0 = state.rp1 = pi; - } // IUP[a] Interpolate Untouched Points through the outline + } // IUP[a] Interpolate Untouched Points through the outline // 0x30 function IUP(v, state) { @@ -45926,7 +47289,8 @@ if (v.touched(cp)) { continue; } - pp = cp.prevTouched(v); // no point on the contour has been touched? + pp = cp.prevTouched(v); + // no point on the contour has been touched? if (pp === cp) { continue; } @@ -45938,7 +47302,7 @@ } v.interpolate(cp, pp, np, v); } - } // SHP[] SHift Point using reference point + } // SHP[] SHift Point using reference point // 0x32-0x33 function SHP(a, state) { @@ -45960,7 +47324,7 @@ } } state.loop = 1; - } // SHC[] SHift Contour using reference point + } // SHC[] SHift Contour using reference point // 0x36-0x37 function SHC(a, state) { @@ -45982,7 +47346,7 @@ } p = p.nextPointOnContour; } while (p !== sp); - } // SHZ[] SHift Zone using reference point + } // SHZ[] SHift Zone using reference point // 0x36-0x37 function SHZ(a, state) { @@ -46011,9 +47375,10 @@ 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); + fv.setRelative(p, p, d, pv); + //if (p !== rp) fv.setRelative(p, p, d, pv); } - } // SHPIX[] SHift point by a PIXel amount + } // SHPIX[] SHift point by a PIXel amount // 0x38 function SHPIX(state) { @@ -46032,7 +47397,7 @@ fv.touch(p); } state.loop = 1; - } // IP[] Interpolate Point + } // IP[] Interpolate Point // 0x39 function IP(state) { @@ -46055,7 +47420,7 @@ fv.touch(p); } state.loop = 1; - } // MSIRP[a] Move Stack Indirect Relative Point + } // MSIRP[a] Move Stack Indirect Relative Point // 0x3A-0x3B function MSIRP(a, state) { @@ -46076,7 +47441,7 @@ if (a) { state.rp0 = pi; } - } // ALIGNRP[] Align to reference point. + } // ALIGNRP[] Align to reference point. // 0x3C function ALIGNRP(state) { @@ -46097,7 +47462,7 @@ fv.touch(p); } state.loop = 1; - } // RTG[] Round To Double Grid + } // RTG[] Round To Double Grid // 0x3D function RTDG(state) { @@ -46105,7 +47470,7 @@ console.log(state.step, 'RTDG[]'); } state.round = roundToDoubleGrid; - } // MIAP[a] Move Indirect Absolute Point + } // MIAP[a] Move Indirect Absolute Point // 0x3E-0x3F function MIAP(round, state) { @@ -46133,7 +47498,7 @@ } fv.touch(p); state.rp0 = state.rp1 = pi; - } // NPUSB[] PUSH N Bytes + } // NPUSB[] PUSH N Bytes // 0x40 function NPUSHB(state) { @@ -46148,7 +47513,7 @@ stack.push(prog[++ip]); } state.ip = ip; - } // NPUSHW[] PUSH N Words + } // NPUSHW[] PUSH N Words // 0x41 function NPUSHW(state) { @@ -46167,7 +47532,7 @@ stack.push(w); } state.ip = ip; - } // WS[] Write Store + } // WS[] Write Store // 0x42 function WS(state) { @@ -46183,7 +47548,7 @@ console.log(state.step, 'WS', v, l); } store[l] = v; - } // RS[] Read Store + } // RS[] Read Store // 0x43 function RS(state) { @@ -46195,7 +47560,7 @@ } var v = store && store[l] || 0; stack.push(v); - } // WCVTP[] Write Control Value Table in Pixel units + } // WCVTP[] Write Control Value Table in Pixel units // 0x44 function WCVTP(state) { @@ -46206,7 +47571,7 @@ console.log(state.step, 'WCVTP', v, l); } state.cvt[l] = v / 64; - } // RCVT[] Read Control Value Table entry + } // RCVT[] Read Control Value Table entry // 0x45 function RCVT(state) { @@ -46216,7 +47581,7 @@ console.log(state.step, 'RCVT', cvte); } stack.push(state.cvt[cvte] * 64); - } // GC[] Get Coordinate projected onto the projection vector + } // GC[] Get Coordinate projected onto the projection vector // 0x46-0x47 function GC(a, state) { @@ -46227,7 +47592,7 @@ console.log(state.step, 'GC[' + a + ']', pi); } stack.push(state.dpv.distance(p, HPZero, a, false) * 64); - } // MD[a] Measure Distance + } // MD[a] Measure Distance // 0x49-0x4A function MD(a, state) { @@ -46241,7 +47606,7 @@ console.log(state.step, 'MD[' + a + ']', pi2, pi1, '->', d); } state.stack.push(Math.round(d * 64)); - } // MPPEM[] Measure Pixels Per EM + } // MPPEM[] Measure Pixels Per EM // 0x4B function MPPEM(state) { @@ -46249,7 +47614,7 @@ console.log(state.step, 'MPPEM[]'); } state.stack.push(state.ppem); - } // FLIPON[] set the auto FLIP Boolean to ON + } // FLIPON[] set the auto FLIP Boolean to ON // 0x4D function FLIPON(state) { @@ -46257,7 +47622,7 @@ console.log(state.step, 'FLIPON[]'); } state.autoFlip = true; - } // LT[] Less Than + } // LT[] Less Than // 0x50 function LT(state) { @@ -46268,7 +47633,7 @@ console.log(state.step, 'LT[]', e2, e1); } stack.push(e1 < e2 ? 1 : 0); - } // LTEQ[] Less Than or EQual + } // LTEQ[] Less Than or EQual // 0x53 function LTEQ(state) { @@ -46279,7 +47644,7 @@ console.log(state.step, 'LTEQ[]', e2, e1); } stack.push(e1 <= e2 ? 1 : 0); - } // GTEQ[] Greater Than + } // GTEQ[] Greater Than // 0x52 function GT(state) { @@ -46290,7 +47655,7 @@ console.log(state.step, 'GT[]', e2, e1); } stack.push(e1 > e2 ? 1 : 0); - } // GTEQ[] Greater Than or EQual + } // GTEQ[] Greater Than or EQual // 0x53 function GTEQ(state) { @@ -46301,7 +47666,7 @@ console.log(state.step, 'GTEQ[]', e2, e1); } stack.push(e1 >= e2 ? 1 : 0); - } // EQ[] EQual + } // EQ[] EQual // 0x54 function EQ(state) { @@ -46312,7 +47677,7 @@ console.log(state.step, 'EQ[]', e2, e1); } stack.push(e2 === e1 ? 1 : 0); - } // NEQ[] Not EQual + } // NEQ[] Not EQual // 0x55 function NEQ(state) { @@ -46323,7 +47688,7 @@ console.log(state.step, 'NEQ[]', e2, e1); } stack.push(e2 !== e1 ? 1 : 0); - } // ODD[] ODD + } // ODD[] ODD // 0x56 function ODD(state) { @@ -46333,7 +47698,7 @@ console.log(state.step, 'ODD[]', n); } stack.push(Math.trunc(n) % 2 ? 1 : 0); - } // EVEN[] EVEN + } // EVEN[] EVEN // 0x57 function EVEN(state) { @@ -46343,14 +47708,14 @@ console.log(state.step, 'EVEN[]', n); } stack.push(Math.trunc(n) % 2 ? 0 : 1); - } // IF[] IF test + } // 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 test is true it just continues // if not the ip is skipped until matching ELSE or EIF if (!test) { @@ -46359,7 +47724,7 @@ console.log(state.step, 'EIF[]'); } } - } // EIF[] End IF + } // EIF[] End IF // 0x59 function EIF(state) { @@ -46369,7 +47734,7 @@ if (exports.DEBUG) { console.log(state.step, 'EIF[]'); } - } // AND[] logical AND + } // AND[] logical AND // 0x5A function AND(state) { @@ -46380,7 +47745,7 @@ console.log(state.step, 'AND[]', e2, e1); } stack.push(e2 && e1 ? 1 : 0); - } // OR[] logical OR + } // OR[] logical OR // 0x5B function OR(state) { @@ -46391,7 +47756,7 @@ console.log(state.step, 'OR[]', e2, e1); } stack.push(e2 || e1 ? 1 : 0); - } // NOT[] logical NOT + } // NOT[] logical NOT // 0x5C function NOT(state) { @@ -46401,7 +47766,7 @@ console.log(state.step, 'NOT[]', e); } stack.push(e ? 0 : 1); - } // DELTAP1[] DELTA exception P1 + } // DELTAP1[] DELTA exception P1 // DELTAP2[] DELTA exception P2 // DELTAP3[] DELTA exception P3 // 0x5D, 0x71, 0x72 @@ -46435,7 +47800,7 @@ var p = z0[pi]; fv.setRelative(p, p, mag * ds, pv); } - } // SDB[] Set Delta Base in the graphics state + } // SDB[] Set Delta Base in the graphics state // 0x5E function SDB(state) { @@ -46445,7 +47810,7 @@ console.log(state.step, 'SDB[]', n); } state.deltaBase = n; - } // SDS[] Set Delta Shift in the graphics state + } // SDS[] Set Delta Shift in the graphics state // 0x5F function SDS(state) { @@ -46455,7 +47820,7 @@ console.log(state.step, 'SDS[]', n); } state.deltaShift = Math.pow(0.5, n); - } // ADD[] ADD + } // ADD[] ADD // 0x60 function ADD(state) { @@ -46466,7 +47831,7 @@ console.log(state.step, 'ADD[]', n2, n1); } stack.push(n1 + n2); - } // SUB[] SUB + } // SUB[] SUB // 0x61 function SUB(state) { @@ -46477,7 +47842,7 @@ console.log(state.step, 'SUB[]', n2, n1); } stack.push(n1 - n2); - } // DIV[] DIV + } // DIV[] DIV // 0x62 function DIV(state) { @@ -46488,7 +47853,7 @@ console.log(state.step, 'DIV[]', n2, n1); } stack.push(n1 * 64 / n2); - } // MUL[] MUL + } // MUL[] MUL // 0x63 function MUL(state) { @@ -46499,7 +47864,7 @@ console.log(state.step, 'MUL[]', n2, n1); } stack.push(n1 * n2 / 64); - } // ABS[] ABSolute value + } // ABS[] ABSolute value // 0x64 function ABS(state) { @@ -46509,7 +47874,7 @@ console.log(state.step, 'ABS[]', n); } stack.push(Math.abs(n)); - } // NEG[] NEGate + } // NEG[] NEGate // 0x65 function NEG(state) { @@ -46519,7 +47884,7 @@ console.log(state.step, 'NEG[]', n); } stack.push( - n); - } // FLOOR[] FLOOR + } // FLOOR[] FLOOR // 0x66 function FLOOR(state) { @@ -46529,7 +47894,7 @@ console.log(state.step, 'FLOOR[]', n); } stack.push(Math.floor(n / 64) * 64); - } // CEILING[] CEILING + } // CEILING[] CEILING // 0x67 function CEILING(state) { @@ -46539,7 +47904,7 @@ console.log(state.step, 'CEILING[]', n); } stack.push(Math.ceil(n / 64) * 64); - } // ROUND[ab] ROUND value + } // ROUND[ab] ROUND value // 0x68-0x6B function ROUND(dt, state) { @@ -46549,7 +47914,7 @@ console.log(state.step, 'ROUND[]'); } stack.push(state.round(n / 64) * 64); - } // WCVTF[] Write Control Value Table in Funits + } // WCVTF[] Write Control Value Table in Funits // 0x70 function WCVTF(state) { @@ -46560,7 +47925,7 @@ console.log(state.step, 'WCVTF[]', v, l); } state.cvt[l] = v * state.ppem / state.font.unitsPerEm; - } // DELTAC1[] DELTA exception C1 + } // DELTAC1[] DELTA exception C1 // DELTAC2[] DELTA exception C2 // DELTAC3[] DELTA exception C3 // 0x73, 0x74, 0x75 @@ -46591,7 +47956,7 @@ } state.cvt[c] += delta; } - } // SROUND[] Super ROUND + } // SROUND[] Super ROUND // 0x76 function SROUND(state) { @@ -46637,7 +48002,7 @@ } else { state.srThreshold = (n / 8 - 0.5) * period; } - } // S45ROUND[] Super ROUND 45 degrees + } // S45ROUND[] Super ROUND 45 degrees // 0x77 function S45ROUND(state) { @@ -46683,7 +48048,7 @@ } else { state.srThreshold = (n / 8 - 0.5) * period; } - } // ROFF[] Round Off + } // ROFF[] Round Off // 0x7A function ROFF(state) { @@ -46691,7 +48056,7 @@ console.log(state.step, 'ROFF[]'); } state.round = roundOff; - } // RUTG[] Round Up To Grid + } // RUTG[] Round Up To Grid // 0x7C function RUTG(state) { @@ -46699,7 +48064,7 @@ console.log(state.step, 'RUTG[]'); } state.round = roundUpToGrid; - } // RDTG[] Round Down To Grid + } // RDTG[] Round Down To Grid // 0x7D function RDTG(state) { @@ -46707,15 +48072,16 @@ console.log(state.step, 'RDTG[]'); } state.round = roundDownToGrid; - } // SCANCTRL[] SCAN conversion ConTRoL + } // SCANCTRL[] SCAN conversion ConTRoL // 0x85 function SCANCTRL(state) { - var n = state.stack.pop(); // ignored by opentype.js + 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 + } // SDPVTL[a] Set Dual Projection Vector To Line // 0x86-0x87 function SDPVTL(a, state) { @@ -46737,7 +48103,7 @@ dy = p1.x - p2.x; } state.dpv = getUnitVector(dx, dy); - } // GETINFO[] GET INFOrmation + } // GETINFO[] GET INFOrmation // 0x88 function GETINFO(state) { @@ -46746,11 +48112,11 @@ var r = 0; if (exports.DEBUG) { console.log(state.step, 'GETINFO[]', sel); - } // v35 as in no subpixel hinting + } // v35 as in no subpixel hinting if (sel & 1) { r = 35; - } // TODO rotation and stretch currently not supported + } // TODO rotation and stretch currently not supported // and thus those GETINFO are always 0. // opentype.js is always gray scaling @@ -46758,7 +48124,7 @@ r |= 4096; } stack.push(r); - } // ROLL[] ROLL the top three stack elements + } // ROLL[] ROLL the top three stack elements // 0x8A function ROLL(state) { @@ -46772,7 +48138,7 @@ stack.push(b); stack.push(a); stack.push(c); - } // MAX[] MAXimum of top two stack elements + } // MAX[] MAXimum of top two stack elements // 0x8B function MAX(state) { @@ -46783,7 +48149,7 @@ console.log(state.step, 'MAX[]', e2, e1); } stack.push(Math.max(e1, e2)); - } // MIN[] MINimum of top two stack elements + } // MIN[] MINimum of top two stack elements // 0x8C function MIN(state) { @@ -46794,15 +48160,16 @@ console.log(state.step, 'MIN[]', e2, e1); } stack.push(Math.min(e1, e2)); - } // SCANTYPE[] SCANTYPE + } // SCANTYPE[] SCANTYPE // 0x8D function SCANTYPE(state) { - var n = state.stack.pop(); // ignored by opentype.js + var n = state.stack.pop(); + // ignored by opentype.js if (exports.DEBUG) { console.log(state.step, 'SCANTYPE[]', n); } - } // INSTCTRL[] INSTCTRL + } // INSTCTRL[] INSTCTRL // 0x8D function INSTCTRL(state) { @@ -46821,7 +48188,7 @@ default: throw new Error('invalid INSTCTRL[] selector'); } - } // PUSHB[abc] PUSH Bytes + } // PUSHB[abc] PUSH Bytes // 0xB0-0xB7 function PUSHB(n, state) { @@ -46835,7 +48202,7 @@ stack.push(prog[++ip]); } state.ip = ip; - } // PUSHW[abc] PUSH Words + } // PUSHW[abc] PUSH Words // 0xB8-0xBF function PUSHW(n, state) { @@ -46853,7 +48220,7 @@ stack.push(w); } state.ip = ip; - } // MDRP[abcde] Move Direct Relative Point + } // MDRP[abcde] Move Direct Relative Point // 0xD0-0xEF // (if indirect is 0) // @@ -46907,519 +48274,70 @@ * 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 + 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 + undefined, + // TODO SSW /* 0x20 */ - DUP, - /* 0x21 */ - POP, - /* 0x22 */ - CLEAR, - /* 0x23 */ - SWAP, - /* 0x24 */ - DEPTH, - /* 0x25 */ - CINDEX, - /* 0x26 */ - MINDEX, - /* 0x27 */ - undefined, // TODO ALIGNPTS + DUP, /* 0x21 */ POP, /* 0x22 */ CLEAR, /* 0x23 */ SWAP, /* 0x24 */ DEPTH, /* 0x25 */ CINDEX, /* 0x26 */ MINDEX, /* 0x27 */ undefined, + // TODO ALIGNPTS /* 0x28 */ - undefined, - /* 0x29 */ - undefined, // TODO UTP + undefined, /* 0x29 */ undefined, + // TODO UTP /* 0x2A */ - LOOPCALL, - /* 0x2B */ - CALL, - /* 0x2C */ - FDEF, - /* 0x2D */ - undefined, // ENDF (eaten by FDEF) + 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 + 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 + MD.bind(undefined, 0), /* 0x4A */ MD.bind(undefined, 1), /* 0x4B */ MPPEM, /* 0x4C */ undefined, + // TODO MPS /* 0x4D */ - FLIPON, - /* 0x4E */ - undefined, // TODO FLIPOFF + FLIPON, /* 0x4E */ undefined, + // TODO FLIPOFF /* 0x4F */ - undefined, // TODO DEBUG + 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] + 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] + undefined, + // TODO NROUND[ab] /* 0x6E */ - undefined, // TODO NROUND[ab] + undefined, + // TODO NROUND[ab] /* 0x6F */ - undefined, // TODO NROUND[ab] + 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[] + 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 + // 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 + POP, + // actually AA, supposed to do only a pop though /* 0x80 */ - undefined, // TODO FLIPPT + undefined, + // TODO FLIPPT /* 0x81 */ - undefined, // TODO FLIPRGON - /* 0x82 */ - undefined, // TODO FLIPRGOFF - /* 0x83 */ undefined, - /* 0x84 */ + // TODO FLIPRGON + /* 0x82 */ undefined, - /* 0x85 */ - SCANCTRL, - /* 0x86 */ - SDPVTL.bind(undefined, 0), - /* 0x87 */ - SDPVTL.bind(undefined, 1), - /* 0x88 */ - GETINFO, - /* 0x89 */ - undefined, // TODO IDEF + // 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) + 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 @@ -47647,7 +48565,8 @@ 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. + 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 || ' ' @@ -47769,7 +48688,8 @@ */ Font.prototype.stringToGlyphs = function (s, options) { var this$1 = this; - options = options || this.defaultRenderOptions; // Get glyph indexes + options = options || this.defaultRenderOptions; + // Get glyph indexes var chars = arrayFromString(s); var indexes = [ ]; @@ -47777,7 +48697,8 @@ var c = chars[i]; indexes.push(this$1.charToGlyphIndex(c)); } - var length = indexes.length; // Apply substitutions on glyph indexes + var length = indexes.length; + // Apply substitutions on glyph indexes if (options.features) { var script = options.script || this.substitution.getDefaultScriptName(); var manyToOne = [ @@ -47803,7 +48724,7 @@ } } } - } // convert glyph indexes to glyph objects + } // convert glyph indexes to glyph objects var glyphs = new Array(length); var notdef = this.glyphs.get(0); @@ -47859,7 +48780,7 @@ var gposKerning = this.position.defaultKerningTables; if (gposKerning) { return this.position.getKerningValue(gposKerning, leftGlyph, rightGlyph); - } // "kern" table + } // "kern" table return this.kerningPairs[leftGlyph + ',' + rightGlyph] || 0; }; @@ -48042,13 +48963,14 @@ function assertNamePresent(name) { var englishName = _this.getEnglishName(name); assert(englishName && englishName.trim().length > 0, 'No English ' + name + ' specified.'); - } // Identification information + } // Identification information assertNamePresent('fontFamily'); assertNamePresent('weightName'); assertNamePresent('manufacturer'); assertNamePresent('copyright'); - assertNamePresent('version'); // Dimension information + assertNamePresent('version'); + // Dimension information assert(this.unitsPerEm > 0, 'No unitsPerEm specified.'); }; /** @@ -48166,7 +49088,8 @@ BOLD: 700, EXTRA_BOLD: 800, BLACK: 900 - }; // The `fvar` table stores font variation axes and instances. + }; + // The `fvar` table stores font variation axes and instances. function addName(name, names) { var nameString = JSON.stringify(name); var nameID = 256; @@ -48321,7 +49244,8 @@ var p = new parse.Parser(data, start); var tableVersion = p.parseULong(); check.argument(tableVersion === 65536, 'Unsupported fvar table version.'); - var offsetToData = p.parseOffset16(); // Skip countSizePairs. + var offsetToData = p.parseOffset16(); + // Skip countSizePairs. p.skip('uShort', 1); var axisCount = p.parseUShort(); var axisSize = p.parseUShort(); @@ -48346,7 +49270,8 @@ var fvar = { make: makeFvarTable, parse: parseFvarTable - }; // The `GPOS` table contains kerning pairs, among other things. + }; + // 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 @@ -48367,7 +49292,8 @@ }; } 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 + }; + // 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(); @@ -48449,7 +49375,8 @@ return { error: 'GPOS Lookup 9 not supported' }; - }; // https://docs.microsoft.com/en-us/typography/opentype/spec/gpos + }; + // https://docs.microsoft.com/en-us/typography/opentype/spec/gpos function parseGposTable(data, start) { start = start || 0; var p = new Parser(data, start); @@ -48471,7 +49398,7 @@ variations: p.parseFeatureVariationsList() }; } - } // GPOS Writing ////////////////////////////////////////////// + } // GPOS Writing ////////////////////////////////////////////// // NOT SUPPORTED var subtableMakers$1 = new Array(10); @@ -48502,15 +49429,19 @@ var gpos = { parse: parseGposTable, make: makeGposTable - }; // The `kern` table contains kerning pairs. + }; + // The `kern` table contains kerning pairs. function parseWindowsKernTable(p) { var pairs = { - }; // Skip nTables. + }; + // Skip nTables. p.skip('uShort'); var subtableVersion = p.parseUShort(); - check.argument(subtableVersion === 0, 'Unsupported kern sub-table version.'); // Skip subtableLength, subtableCoverage + check.argument(subtableVersion === 0, 'Unsupported kern sub-table version.'); + // Skip subtableLength, subtableCoverage p.skip('uShort', 2); - var nPairs = p.parseUShort(); // Skip searchRange, entrySelector, rangeShift. + var nPairs = p.parseUShort(); + // Skip searchRange, entrySelector, rangeShift. p.skip('uShort', 3); for (var i = 0; i < nPairs; i += 1) { var leftIndex = p.parseUShort(); @@ -48522,10 +49453,12 @@ } 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. + }; + // 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 + ').'); + 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.'); } @@ -48534,7 +49467,8 @@ var subtableVersion = coverage & 255; p.skip('uShort'); if (subtableVersion === 0) { - var nPairs = p.parseUShort(); // Skip searchRange, entrySelector, rangeShift. + var nPairs = p.parseUShort(); + // Skip searchRange, entrySelector, rangeShift. p.skip('uShort', 3); for (var i = 0; i < nPairs; i += 1) { var leftIndex = p.parseUShort(); @@ -48544,7 +49478,7 @@ } } return pairs; - } // Parse the `kern` table which contains kerning pairs. + } // Parse the `kern` table which contains kerning pairs. function parseKernTable(data, start) { var p = new parse.Parser(data, start); @@ -48559,7 +49493,8 @@ } var kern = { parse: parseKernTable - }; // The `loca` table stores the offsets to the locations of the glyphs in the font. + }; + // 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) @@ -48568,7 +49503,8 @@ // (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. + 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 = [ ]; @@ -48584,7 +49520,8 @@ } var loca = { parse: parseLocaTable - }; // opentype.js + }; + // opentype.js /** * The opentype library. * @namespace opentype @@ -48626,7 +49563,7 @@ callback('Font could not be loaded'); }; request.send(); - } // Table Directory Entries ////////////////////////////////////////////// + } // Table Directory Entries ////////////////////////////////////////////// /** * Parses OpenType table entries. * @param {DataView} @@ -48716,7 +49653,7 @@ offset: tableEntry.offset }; } - } // Public API /////////////////////////////////////////////////////////// + } // 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. @@ -48726,11 +49663,13 @@ function parseBuffer(buffer) { var indexToLocFormat; - var ltagTable; // Since the constructor can also be called to create new fonts from scratch, we indicate this + 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. + }); + // 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); @@ -48960,7 +49899,7 @@ 'fs': 21 } ], - 264: [ + 272: [ function (_dereq_, module, exports) { (function (process) { // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1, @@ -49003,7 +49942,7 @@ parts.splice(i, 1); up--; } - } // if the path is allowed to go above the root, restore leading ..s + } // if the path is allowed to go above the root, restore leading ..s if (allowAboveRoot) { for (; up--; up) { @@ -49011,14 +49950,15 @@ } } return parts; - } // path.resolve([from ...], to) + } // 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 + 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) { @@ -49026,7 +49966,7 @@ } resolvedPath = path + '/' + resolvedPath; resolvedAbsolute = path.charAt(0) === '/'; - } // At this point the path should be resolved to a full absolute path, but + } // 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 @@ -49034,11 +49974,13 @@ return !!p; }), !resolvedAbsolute).join('/'); return (resolvedAbsolute ? '/' : '') + resolvedPath || '.'; - }; // path.normalize(path) + }; + // path.normalize(path) // posix version exports.normalize = function (path) { var isAbsolute = exports.isAbsolute(path), - trailingSlash = substr(path, - 1) === '/'; // Normalize the path + trailingSlash = substr(path, - 1) === '/'; + // Normalize the path path = normalizeArray(filter(path.split('/'), function (p) { return !!p; }), !isAbsolute).join('/'); @@ -49049,10 +49991,12 @@ path += '/'; } return (isAbsolute ? '/' : '') + path; - }; // posix version + }; + // posix version exports.isAbsolute = function (path) { return path.charAt(0) === '/'; - }; // posix version + }; + // posix version exports.join = function () { var paths = Array.prototype.slice.call(arguments, 0); return exports.normalize(filter(paths, function (p, index) { @@ -49061,7 +50005,8 @@ } return p; }).join('/')); - }; // path.relative(from, to) + }; + // path.relative(from, to) // posix version exports.relative = function (from, to) { from = exports.resolve(from).substr(1); @@ -49102,14 +50047,12 @@ if (typeof path !== 'string') path = path + ''; if (path.length === 0) return '.'; var code = path.charCodeAt(0); - var hasRoot = code === 47 /*/*/ - ; + 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 (code === 47 /*/*/ ) { if (!matchedSlash) { end = i; break; @@ -49134,8 +50077,7 @@ var matchedSlash = true; var i; for (i = path.length - 1; i >= 0; --i) { - if (path.charCodeAt(i) === 47 /*/*/ - ) { + 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) { @@ -49151,7 +50093,7 @@ } if (end === - 1) return ''; return path.slice(start, end); - } // Uses a mixed approach for backwards-compatibility, as ext behavior changed + } // 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) { @@ -49166,13 +50108,13 @@ 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 + 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 (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) { @@ -49187,8 +50129,7 @@ matchedSlash = false; end = i + 1; } - if (code === 46 /*.*/ - ) { + 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; @@ -49198,8 +50139,8 @@ 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 '..' + 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 ''; } @@ -49213,7 +50154,7 @@ if (f(xs[i], i, xs)) res.push(xs[i]); } return res; - } // String.prototype.substr - negative index don't work in IE8 + } // 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); @@ -49225,14 +50166,15 @@ }).call(this, _dereq_('_process')) }, { - '_process': 265 + '_process': 273 } ], - 265: [ + 273: [ 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 + }; + // 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. @@ -49267,7 +50209,7 @@ if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); - } // if setTimeout wasn't available but was latter defined + } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; @@ -49290,7 +50232,7 @@ if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); - } // if clearTimeout wasn't available but was latter defined + } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; @@ -49363,7 +50305,8 @@ if (queue.length === 1 && !draining) { runTimeout(drainQueue); } - }; // v8 likes predictible objects + }; + // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; @@ -49410,7 +50353,7 @@ { } ], - 266: [ + 274: [ function (_dereq_, module, exports) { /** * Copyright (c) 2014-present, Facebook, Inc. @@ -49433,12 +50376,14 @@ var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; var generator = Object.create(protoGenerator.prototype); var context = new Context(tryLocsList || [ - ]); // The ._invoke method unifies the implementations of the .next, + ]); + // The ._invoke method unifies the implementations of the .next, // .throw, and .return methods. generator._invoke = makeInvokeMethod(innerFn, self, context); return generator; } - exports.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion + exports.wrap = wrap; + // Try/catch helper to minimize deoptimizations. Returns a completion // record like context.tryEntries[i].completion. This interface could // have been (and was previously) designed to take a closure to be // invoked without arguments, but in all the cases we care about we @@ -49464,10 +50409,12 @@ var GenStateSuspendedStart = 'suspendedStart'; var GenStateSuspendedYield = 'suspendedYield'; var GenStateExecuting = 'executing'; - var GenStateCompleted = 'completed'; // Returning this object from the innerFn has the same effect as + var GenStateCompleted = 'completed'; + // Returning this object from the innerFn has the same effect as // breaking out of the dispatch switch statement. var ContinueSentinel = { - }; // Dummy constructor functions that we use as the .constructor and + }; + // Dummy constructor functions that we use as the .constructor and // .constructor.prototype properties for functions that return Generator // objects. For full spec compliance, you may wish to configure your // minifier not to mangle the names of these two functions. @@ -49476,7 +50423,7 @@ function GeneratorFunction() { } function GeneratorFunctionPrototype() { - } // This is a polyfill for %IteratorPrototype% for environments that + } // This is a polyfill for %IteratorPrototype% for environments that // don't natively support it. var IteratorPrototype = { @@ -49494,7 +50441,8 @@ var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor = GeneratorFunction; - GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = 'GeneratorFunction'; // Helper for defining the .next, .throw, and .return methods of the + GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = 'GeneratorFunction'; + // Helper for defining the .next, .throw, and .return methods of the // Iterator interface in terms of a single ._invoke method. function defineIteratorMethods(prototype) { [ @@ -49509,7 +50457,7 @@ } exports.isGeneratorFunction = function (genFun) { var ctor = typeof genFun === 'function' && genFun.constructor; - return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can + return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can // do is to check its .name property. (ctor.displayName || ctor.name) === 'GeneratorFunction' : false; }; @@ -49524,7 +50472,8 @@ } genFun.prototype = Object.create(Gp); return genFun; - }; // Within the body of any async function, `await x` is transformed to + }; + // Within the body of any async function, `await x` is transformed to // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test // `hasOwn.call(value, "__await")` to determine if the yielded value is // meant to be awaited. @@ -49568,7 +50517,7 @@ invoke(method, arg, resolve, reject); }); } - return previousPromise = // If enqueue has been called before, then we want to wait until + return previousPromise = // If enqueue has been called before, then we want to wait until // all previous Promises have been resolved before calling invoke, // so that results are always delivered in the correct order. If // enqueue has not been called before, then it is important to @@ -49580,10 +50529,10 @@ // execute code before the first await. Since we implement simple // async functions in terms of async generators, it is especially // important to get this right, even though it requires care. - previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later + previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later // invocations of the iterator. callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); - } // Define the unified helper method that is used to implement .next, + } // Define the unified helper method that is used to implement .next, // .throw, and .return (see defineIteratorMethods). this._invoke = enqueue; @@ -49592,7 +50541,8 @@ AsyncIterator.prototype[asyncIteratorSymbol] = function () { return this; }; - exports.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of + exports.AsyncIterator = AsyncIterator; + // Note that simple async functions are implemented on top of // AsyncIterator objects; they just return a Promise for the value of // the final result produced by the iterator. exports.async = function (innerFn, outerFn, self, tryLocsList) { @@ -49611,7 +50561,7 @@ if (state === GenStateCompleted) { if (method === 'throw') { throw arg; - } // Be forgiving, per 25.3.3.3.3 of the spec: + } // Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return doneResult(); @@ -49654,14 +50604,15 @@ done: context.done }; } else if (record.type === 'throw') { - state = GenStateCompleted; // Dispatch the exception by looping back around to the + state = GenStateCompleted; + // Dispatch the exception by looping back around to the // context.dispatchException(context.arg) call above. context.method = 'throw'; context.arg = record.arg; } } }; - } // Call delegate.iterator[context.method](context.arg) and handle the + } // Call delegate.iterator[context.method](context.arg) and handle the // result, either by returning a { value, done } result from the // delegate iterator, or by modifying context.method and context.arg, // setting context.delegate to null, and returning the ContinueSentinel. @@ -49708,8 +50659,10 @@ if (info.done) { // Assign the result of the finished delegate to the temporary // variable specified by delegate.resultName (see delegateYield). - context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield). - context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the + context[delegate.resultName] = info.value; + // Resume execution at the desired location (see delegateYield). + context.next = delegate.nextLoc; + // If context.method was "throw" but the delegate handled the // exception, let the outer generator proceed normally. If // context.method was "next", forget context.arg since it has been // "consumed" by the delegate iterator. If context.method was @@ -49722,16 +50675,17 @@ } else { // Re-yield the result returned by the delegate method. return info; - } // The delegate iterator is finished, so forget it and continue with + } // The delegate iterator is finished, so forget it and continue with // the outer generator. context.delegate = null; return ContinueSentinel; - } // Define Generator.prototype.{next,throw,return} in terms of the + } // Define Generator.prototype.{next,throw,return} in terms of the // unified ._invoke helper method. defineIteratorMethods(Gp); - Gp[toStringTagSymbol] = 'Generator'; // A Generator should always return itself as the iterator object when the + Gp[toStringTagSymbol] = 'Generator'; + // A Generator should always return itself as the iterator object when the // @@iterator function is called on it. Some browsers' implementations of the // iterator prototype chain incorrectly implement this, causing the Generator // object to not be returned from this call. This ensures that doesn't happen. @@ -49780,7 +50734,8 @@ for (var key in object) { keys.push(key); } - keys.reverse(); // Rather than returning an object with a next method, we keep + keys.reverse(); + // Rather than returning an object with a next method, we keep // things simple and return the next function itself. return function next() { while (keys.length) { @@ -49790,7 +50745,7 @@ next.done = false; return next; } - } // To avoid creating an additional object, we just hang the .value + } // To avoid creating an additional object, we just hang the .value // and .done properties off the next function object itself. This // also ensures that the minifier will not anonymize the function. @@ -49823,7 +50778,7 @@ }; return next.next = next; } - } // Return an iterator with no values. + } // Return an iterator with no values. return { next: doneResult @@ -49840,7 +50795,8 @@ constructor: Context, reset: function (skipTempReset) { this.prev = 0; - this.next = 0; // Resetting context._sent for legacy support of Babel's + this.next = 0; + // Resetting context._sent for legacy support of Babel's // function.sent implementation. this.sent = this._sent = undefined; this.done = false; @@ -49975,7 +50931,7 @@ } return thrown; } - } // The context.catch method must only be called with a location + } // The context.catch method must only be called with a location // argument that corresponds to a known catch block. throw new Error('illegal catch attempt'); @@ -49993,12 +50949,13 @@ } return ContinueSentinel; } - }; // Regardless of whether this script is executing as a CommonJS module + }; + // Regardless of whether this script is executing as a CommonJS module // or not, return the runtime object so that we can declare the variable // regeneratorRuntime in the outer scope, which allows this module to be // injected easily by `bin/regenerator --include-runtime script.js`. return exports; - }( // If this script is executing as a CommonJS module, use module.exports + }( // If this script is executing as a CommonJS module, use module.exports // as the regeneratorRuntime namespace. Otherwise create a new empty // object. Either way, the resulting object will be used to initialize // the regeneratorRuntime variable at the top of this file. @@ -50022,7 +50979,7 @@ { } ], - 267: [ + 275: [ function (_dereq_, module, exports) { (function (self) { 'use strict'; @@ -50076,7 +51033,7 @@ value = String(value); } return value; - } // Build a destructive iterator for the value list + } // Build a destructive iterator for the value list function iteratorFor(items) { var iterator = { @@ -50226,7 +51183,8 @@ } 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._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); @@ -50291,7 +51249,7 @@ return this.text().then(JSON.parse); }; return this; - } // HTTP methods whose capitalization should be normalized + } // HTTP methods whose capitalization should be normalized var methods = [ 'DELETE', @@ -50357,7 +51315,8 @@ 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 + 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) { @@ -50463,7 +51422,7 @@ { } ], - 268: [ + 276: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.function.name'); @@ -50495,7 +51454,8 @@ */ //stores the original hsb values - var originalHSB; //stores values for color name exceptions + var originalHSB; + //stores values for color name exceptions var colorExceptions = [ { h: 0, @@ -50521,7 +51481,8 @@ b: 1, name: 'light pink' } - ]; //stores values for color names + ]; + //stores values for color names var colorLookUp = [ { h: 0, @@ -51099,22 +52060,27 @@ b: 1, name: 'magenta' } - ]; //returns text with color name + ]; + //returns text with color name function _calculateColor(hsb) { - var colortext; //round hue + 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 + 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 + 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 only has two digits if (hue.length === 2) { - hue[0] = parseInt(hue[0]); //if last is greater than 7.5 + 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; @@ -51128,9 +52094,10 @@ hsb[0] = hue[last]; } } - } //map brightness from 0 to 1 + } //map brightness from 0 to 1 - hsb[2] = hsb[2] / 255; //round saturation and brightness + 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; @@ -51139,14 +52106,14 @@ } else { hsb[i] = 1; } - } //after rounding, if the values are hue 0, saturation 0 and brightness 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 + } //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]) { @@ -51167,12 +52134,14 @@ } } return colortext; - } //gets rgba and returs a color name + } //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 + 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]]); @@ -51181,16 +52150,16 @@ exports.default = _default; }, { - '../color/color_conversion': 274, - '../core/main': 290, - 'core-js/modules/es.function.name': 183, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.exec': 199, - 'core-js/modules/es.regexp.to-string': 200, - 'core-js/modules/es.string.split': 209 + '../color/color_conversion': 282, + '../core/main': 298, + 'core-js/modules/es.function.name': 186, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.split': 216 } ], - 269: [ + 277: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.array.concat'); @@ -51227,72 +52196,122 @@ 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. + * Creates a screen reader-accessible description for the canvas. + * + * The first parameter, `text`, is the description of the canvas. * - * describe(text, LABEL) displays - * the description to all users as a - * tombstone or exhibit label/caption in a div - * adjacent to the canvas. You can style it as you wish in your CSS. + * The second parameter, `display`, is optional. It determines how the + * description is displayed. If `LABEL` is passed, as in + * `describe('A description.', LABEL)`, the description will be visible in + * a div element next to the canvas. If `FALLBACK` is passed, as in + * `describe('A description.', FALLBACK)`, the description will only be + * visible to screen readers. This is the default mode. * - * describe(text, FALLBACK) makes the - * description accessible to screen-reader users only, in - * - * a sub DOM inside the canvas element. If a second parameter is not - * specified, by default, the description will only be available to - * screen-reader users. + * Read + * How to label your p5.js code to + * learn more about making sketches accessible. * * @method describe - * @param {String} text description of the canvas - * @param {Constant} [display] either LABEL or FALLBACK + * @param {String} text description of the canvas. + * @param {Constant} [display] either LABEL or FALLBACK. * * @example *
* - * describe('pink square with red heart in the bottom right corner'); - * background('pink'); - * fill('red'); - * noStroke(); - * ellipse(67, 67, 20, 20); - * ellipse(83, 67, 20, 20); - * triangle(91, 73, 75, 95, 59, 73); + * function setup() { + * background('pink'); + * + * // Draw a heart. + * fill('red'); + * noStroke(); + * circle(67, 67, 20); + * circle(83, 67, 20); + * triangle(91, 73, 75, 95, 59, 73); + * + * // Add a general description of the canvas. + * describe('A pink square with a red heart in the bottom-right corner.'); + * } + * + *
+ * + *
+ * + * function setup() { + * background('pink'); + * + * // Draw a heart. + * fill('red'); + * noStroke(); + * circle(67, 67, 20); + * circle(83, 67, 20); + * triangle(91, 73, 75, 95, 59, 73); + * + * // Add a general description of the canvas + * // and display it for debugging. + * describe('A pink square with a red heart in the bottom-right corner.', LABEL); + * } * *
* *
* - * let x = 0; * function draw() { - * if (x > 100) { - * x = 0; - * } - * background(220); + * background(200); + * + * // The expression + * // frameCount % 100 + * // causes x to increase from 0 + * // to 99, then restart from 0. + * let x = frameCount % 100; + * + * // Draw the circle. * fill(0, 255, 0); - * ellipse(x, 50, 40, 40); - * x = x + 0.1; - * describe('green circle at x pos ' + round(x) + ' moving to the right'); + * circle(x, 50, 40); + * + * // Add a general description of the canvas. + * describe(`A green circle at (${x}, 50) moves from left to right on a gray square.`); * } * *
* + *
+ * + * function draw() { + * background(200); + * + * // The expression + * // frameCount % 100 + * // causes x to increase from 0 + * // to 99, then restart from 0. + * let x = frameCount % 100; + * + * // Draw the circle. + * fill(0, 255, 0); + * circle(x, 50, 40); + * + * // Add a general description of the canvas + * // and display it for debugging. + * describe(`A green circle at (${x}, 50) moves from left to right on a gray square.`, LABEL); + * } + * + *
*/ _main.default.prototype.describe = function (text, display) { _main.default._validateParameters('describe', arguments); if (typeof text !== 'string') { return; } - var cnvId = this.canvas.id; //calls function that adds punctuation for better screen reading - text = _descriptionText(text); //if there is no dummyDOM + 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 + } //check if html structure for description is ready if (this.descriptions.fallback) { //check if text is different from current description @@ -51303,7 +52322,7 @@ } else { //create fallback html structure this._describeHTML('fallback', text); - } //if display is LABEL + } //if display is LABEL if (display === this.LABEL) { //check if html structure for label is ready @@ -51320,45 +52339,83 @@ } }; /** - * 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. + * Creates a screen reader-accessible description for elements in the canvas. + * Elements are shapes or groups of shapes that create meaning together. * - * describeElement(name, text, LABEL) - * displays the element description to all users as a - * - * tombstone or exhibit label/caption in a div - * adjacent to the canvas. You can style it as you wish in your CSS. + * The first parameter, `name`, is the name of the element. * - * describeElement(name, text, FALLBACK) - * makes the element description accessible to screen-reader users - * only, in - * a sub DOM inside the canvas element. If a second parameter is not - * specified, by default, the element description will only be available - * to screen-reader users. + * The second parameter, `text`, is the description of the element. + * + * The third parameter, `display`, is optional. It determines how the + * description is displayed. If `LABEL` is passed, as in + * `describe('A description.', LABEL)`, the description will be visible in + * a div element next to the canvas. Using `LABEL` creates unhelpful + * duplicates for screen readers. Only use `LABEL` during development. If + * `FALLBACK` is passed, as in `describe('A description.', FALLBACK)`, the + * description will only be visible to screen readers. This is the default + * mode. + * + * Read + * How to label your p5.js code to + * learn more about making sketches accessible. * * @method describeElement - * @param {String} name name of the element - * @param {String} text description of the element - * @param {Constant} [display] either LABEL or FALLBACK + * @param {String} name name of the element. + * @param {String} text description of the element. + * @param {Constant} [display] either LABEL or FALLBACK. * * @example *
* - * describe('Heart and yellow circle over pink background'); - * noStroke(); - * background('pink'); - * describeElement('Circle', 'Yellow circle in the top left corner'); - * fill('yellow'); - * ellipse(25, 25, 40, 40); - * describeElement('Heart', 'red heart in the bottom right corner'); - * fill('red'); - * ellipse(66.6, 66.6, 20, 20); - * ellipse(83.2, 66.6, 20, 20); - * triangle(91.2, 72.6, 75, 95, 58.6, 72.6); + * function setup() { + * background('pink'); + * + * // Describe the first element + * // and draw it. + * describeElement('Circle', 'A yellow circle in the top-left corner.'); + * noStroke(); + * fill('yellow'); + * circle(25, 25, 40); + * + * // Describe the second element + * // and draw it. + * describeElement('Heart', 'A red heart in the bottom-right corner.'); + * fill('red'); + * circle(66.6, 66.6, 20); + * circle(83.2, 66.6, 20); + * triangle(91.2, 72.6, 75, 95, 58.6, 72.6); + * + * // Add a general description of the canvas. + * describe('A red heart and yellow circle over a pink background.'); + * } + * + *
+ * + *
+ * + * function setup() { + * background('pink'); + * + * // Describe the first element + * // and draw it. Display the + * // description for debugging. + * describeElement('Circle', 'A yellow circle in the top-left corner.', LABEL); + * noStroke(); + * fill('yellow'); + * circle(25, 25, 40); + * + * // Describe the second element + * // and draw it. Display the + * // description for debugging. + * describeElement('Heart', 'A red heart in the bottom-right corner.', LABEL); + * fill('red'); + * circle(66.6, 66.6, 20); + * circle(83.2, 66.6, 20); + * triangle(91.2, 72.6, 75, 95, 58.6, 72.6); + * + * // Add a general description of the canvas. + * describe('A red heart and yellow circle over a pink background.'); + * } * *
*/ @@ -51367,11 +52424,16 @@ if (typeof text !== 'string' || typeof name !== 'string') { return; } - var cnvId = this.canvas.id; //calls function that adds punctuation for better screen reading - text = _descriptionText(text); //calls function that adds punctuation for better screen reading - var elementName = _elementName(name); //remove any special characters from name to use it as html id - name = name.replace(/[^a-zA-Z0-9]/g, ''); //store element description - var inner = ''.concat(elementName, '').concat(text, ''); //if there is no dummyDOM + var cnvId = this.canvas.id; + //calls function that adds punctuation for better screen reading + text = _descriptionText(text); + //calls function that adds punctuation for better screen reading + var elementName = _elementName(name); + //remove any special characters from name to use it as html id + name = name.replace(/[^a-zA-Z0-9]/g, ''); + //store element description + var inner = ''.concat(elementName, '').concat(text, ''); + //if there is no dummyDOM if (!this.dummyDOM) { this.dummyDOM = document.getElementById(cnvId).parentNode; } @@ -51383,7 +52445,7 @@ } else if (!this.descriptions.fallbackElements) { this.descriptions.fallbackElements = { }; - } //check if html structure for element description is ready + } //check if html structure for element description is ready if (this.descriptions.fallbackElements[name]) { //if current element description is not the same as inner @@ -51394,13 +52456,13 @@ } else { //create fallback html structure this._describeElementHTML('fallback', name, inner); - } //if display is LABEL + } //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 html structure for label element description is ready if (this.descriptions.labelElements[name]) { //if label element description is different @@ -51423,7 +52485,7 @@ 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 string does not end with '.' if (!text.endsWith('.') && !text.endsWith(';') && !text.endsWith(',') && !text.endsWith('?') && !text.endsWith('!')) { //add '.' to the end of string @@ -51453,7 +52515,7 @@ //if describeElement() has already created the container and added a table of elements //create fallback description

before the table this.dummyDOM.querySelector('#' + cnvId + fallbackTableId).insertAdjacentHTML('beforebegin', '

')); - } //if the container for the description exists + } //if the container for the description exists this.descriptions.fallback = this.dummyDOM.querySelector('#'.concat(cnvId).concat(fallbackDescId)); this.descriptions.fallback.innerHTML = text; @@ -51461,7 +52523,8 @@ } else if (type === 'label') { //if there is no label container if (!this.dummyDOM.querySelector('#'.concat(cnvId + labelContainer))) { - var _html = '

'); //if there are no accessible outputs (see textOutput() and gridOutput()) + var _html = '

'); + //if there are no accessible outputs (see textOutput() and gridOutput()) if (!this.dummyDOM.querySelector('#'.concat(cnvId, 'accessibleOutputLabel'))) { //create label container +

for label description this.dummyDOM.querySelector('#' + cnvId).insertAdjacentHTML('afterend', _html); @@ -51486,7 +52549,7 @@ 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 ',' + } //check if last character of string n is '.', ';', or ',' if (name.endsWith('.') || name.endsWith(';') || name.endsWith(',')) { //replace last character with ':' @@ -51497,7 +52560,7 @@ name = name + ':'; } return name; - } //creates HTML structure for element descriptions + } //creates HTML structure for element descriptions _main.default.prototype._describeElementHTML = function (type, name, text) { var cnvId = this.canvas.id; @@ -51518,11 +52581,12 @@ //and there is no table create fallback table for element description after //fallback description this.dummyDOM.querySelector('#' + cnvId + fallbackDescId).insertAdjacentHTML('afterend', '
Canvas elements and their descriptions
')); - } //create a table row for the element + } //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.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; @@ -51546,11 +52610,12 @@ //and there is no table create label table for element description after //label description this.dummyDOM.querySelector('#' + cnvId + labelDescId).insertAdjacentHTML('afterend', '
')); - } //create a table row for the element label description + } //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.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; } @@ -51559,20 +52624,24 @@ exports.default = _default; }, { - '../core/main': 290, - 'core-js/modules/es.array.concat': 167, - 'core-js/modules/es.regexp.exec': 199, - 'core-js/modules/es.string.ends-with': 202, - 'core-js/modules/es.string.replace': 207 + '../core/main': 298, + 'core-js/modules/es.array.concat': 169, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.string.ends-with': 208, + 'core-js/modules/es.string.replace': 214 } ], - 270: [ + 278: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.from'); _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.string.iterator'); _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.from'); _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.string.iterator'); Object.defineProperty(exports, '__esModule', { value: true }); @@ -51597,35 +52666,38 @@ 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 + 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 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 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 + }; + //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 () { + var table = ''; + //create an array of arrays 10*10 of empty cells + var cells = Array.from(Array(10), function () { + return Array(10); }); - 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; @@ -51633,18 +52705,19 @@ fill = '').concat(ingredients[x][y].color, ' ').concat(x, ''); } else { fill = '').concat(ingredients[x][y].color, ' ').concat(x, ' midpoint'); - } //if empty cell of location of shape is undefined + } //if 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 + 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 + } //make table based on array for (var _r in cells) { var row = ''; @@ -51658,7 +52731,7 @@ table = table + row + ''; } return table; - } //creates grid summary + } //creates grid summary function _gridSummary(numShapes, background, width, height) { var text = ''.concat(background, ' canvas, ').concat(width, ' by ').concat(height, ' pixels, contains ').concat(numShapes[0]); @@ -51668,12 +52741,13 @@ text = ''.concat(text, ' shapes: ').concat(numShapes[1]); } return text; - } //creates list of shapes + } //creates list of shapes function _gridShapeDetails(idT, ingredients) { var shapeDetails = ''; var shapes = ''; - var totalShapes = 0; //goes trhough every shape type in ingredients + var totalShapes = 0; + //goes trhough every shape type in ingredients for (var x in ingredients) { var shapeNum = 0; for (var y in ingredients[x]) { @@ -51710,18 +52784,29 @@ exports.default = _default; }, { - '../core/main': 290, - 'core-js/modules/es.array.concat': 167, - 'core-js/modules/es.array.map': 179 + '../core/main': 298, + 'core-js/modules/es.array.concat': 169, + 'core-js/modules/es.array.from': 176, + 'core-js/modules/es.array.map': 182, + 'core-js/modules/es.string.iterator': 210 } ], - 271: [ + 279: [ function (_dereq_, module, exports) { 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); _dereq_('core-js/modules/es.array.concat'); _dereq_('core-js/modules/es.array.fill'); + _dereq_('core-js/modules/es.array.from'); + _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.map'); _dereq_('core-js/modules/es.number.to-fixed'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.iterator'); _dereq_('core-js/modules/es.array.concat'); _dereq_('core-js/modules/es.array.fill'); _dereq_('core-js/modules/es.array.map'); @@ -51736,160 +52821,298 @@ default: obj }; - } /** - * @module Environment - * @submodule Environment - * @for p5 - * @requires core - */ + } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + function _nonIterableSpread() { + throw new TypeError('Invalid attempt to spread non-iterable instance'); + } + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === '[object Arguments]') return Array.from(iter); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + return arr2; + } + } /** + * @module Environment + * @submodule Environment + * @for p5 + * @requires core + */ /** - * textOutput() creates a screenreader - * accessible output that describes the shapes present on the canvas. - * The general description of the canvas includes canvas size, - * canvas color, and number of elements in the canvas - * (example: 'Your output is a, 400 by 400 pixels, lavender blue - * canvas containing the following 4 shapes:'). This description - * is followed by a list of shapes where the color, position, and area - * of each shape are described (example: "orange ellipse at top left - * covering 1% of the canvas"). Each element can be selected to get - * more details. A table of elements is also provided. In this table, - * shape, color, location, coordinates and area are described - * (example: "orange ellipse location=top left area=2"). - * - * textOutput() and textOutput(FALLBACK) - * make the output available in - * a sub DOM inside the canvas element which is accessible to screen readers. - * textOutput(LABEL) creates an - * additional div with the output adjacent to the canvas, this is useful - * for non-screen reader users that might want to display the output outside - * of the canvas' sub DOM as they code. However, using LABEL will create - * unnecessary redundancy for screen reader users. We recommend using LABEL - * only as part of the development process of a sketch and removing it before - * publishing or sharing with screen reader users. + * Creates a screen reader-accessible description for shapes on the canvas. + * `textOutput()` adds a general description, list of shapes, and + * table of shapes to the web page. + * + * The general description includes the canvas size, canvas color, and number + * of shapes. For example, + * `Your output is a, 100 by 100 pixels, gray canvas containing the following 2 shapes:`. + * + * A list of shapes follows the general description. The list describes the + * color, location, and area of each shape. For example, + * `a red circle at middle covering 3% of the canvas`. Each shape can be + * selected to get more details. + * + * `textOutput()` uses its table of shapes as a list. The table describes the + * shape, color, location, coordinates and area. For example, + * `red circle location = middle area = 3%`. This is different from + * gridOutput(), which uses its table as a grid. + * + * The `display` parameter is optional. It determines how the description is + * displayed. If `LABEL` is passed, as in `textOutput(LABEL)`, the description + * will be visible in a div element next to the canvas. Using `LABEL` creates + * unhelpful duplicates for screen readers. Only use `LABEL` during + * development. If `FALLBACK` is passed, as in `textOutput(FALLBACK)`, the + * description will only be visible to screen readers. This is the default + * mode. + * + * Read + * How to label your p5.js code to + * learn more about making sketches accessible. * * @method textOutput - * @param {Constant} [display] either FALLBACK or LABEL + * @param {Constant} [display] either FALLBACK or LABEL. * * @example *

* - * textOutput(); - * background(148, 196, 0); - * fill(255, 0, 0); - * ellipse(20, 20, 20, 20); - * fill(0, 0, 255); - * rect(50, 50, 50, 50); + * function setup() { + * // Add the text description. + * textOutput(); + * + * // Draw a couple of shapes. + * background(200); + * fill(255, 0, 0); + * circle(20, 20, 20); + * fill(0, 0, 255); + * square(50, 50, 50); + * + * // Add a general description of the canvas. + * describe('A red circle and a blue square on a gray background.'); + * } * *
* + *
+ * + * function setup() { + * // Add the text description and + * // display it for debugging. + * textOutput(LABEL); + * + * // Draw a couple of shapes. + * background(200); + * fill(255, 0, 0); + * circle(20, 20, 20); + * fill(0, 0, 255); + * square(50, 50, 50); + * + * // Add a general description of the canvas. + * describe('A red circle and a blue square on a gray background.'); + * } + * + *
* *
* - * let x = 0; * function draw() { + * // Add the text description. * textOutput(); - * background(148, 196, 0); + * + * // Draw a moving circle. + * background(200); + * let x = frameCount * 0.1; * fill(255, 0, 0); - * ellipse(x, 20, 20, 20); + * circle(x, 20, 20); * fill(0, 0, 255); - * rect(50, 50, 50, 50); - * ellipse(20, 20, 20, 20); - * x += 0.1; + * square(50, 50, 50); + * + * // Add a general description of the canvas. + * describe('A red circle moves from left to right above a blue square.'); * } * *
* + *
+ * + * function draw() { + * // Add the text description and + * // display it for debugging. + * textOutput(LABEL); + * + * // Draw a moving circle. + * background(200); + * let x = frameCount * 0.1; + * fill(255, 0, 0); + * circle(x, 20, 20); + * fill(0, 0, 255); + * square(50, 50, 50); + * + * // Add a general description of the canvas. + * describe('A red circle moves from left to right above a blue square.'); + * } + * + *
*/ _main.default.prototype.textOutput = function (display) { - _main.default._validateParameters('textOutput', arguments); //if textOutput is already true + _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._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._accessibleOutputs.textLabel = true; + //create output for label this._createOutput('textOutput', 'Label'); } } }; /** - * gridOutput() lays out the - * content of the canvas in the form of a grid (html table) based - * on the spatial location of each shape. A brief - * description of the canvas is available before the table output. - * This description includes: color of the background, size of the canvas, - * number of objects, and object types (example: "lavender blue canvas is - * 200 by 200 and contains 4 objects - 3 ellipses 1 rectangle"). The grid - * describes the content spatially, each element is placed on a cell of the - * table depending on its position. Within each cell an element the color - * and type of shape of that element are available (example: "orange ellipse"). - * These descriptions can be selected individually to get more details. - * A list of elements where shape, color, location, and area are described - * (example: "orange ellipse location=top left area=1%") is also available. - * - * gridOutput() and gridOutput(FALLBACK) - * make the output available in - * a sub DOM inside the canvas element which is accessible to screen readers. - * gridOutput(LABEL) creates an - * additional div with the output adjacent to the canvas, this is useful - * for non-screen reader users that might want to display the output outside - * of the canvas' sub DOM as they code. However, using LABEL will create - * unnecessary redundancy for screen reader users. We recommend using LABEL - * only as part of the development process of a sketch and removing it before - * publishing or sharing with screen reader users. + * Creates a screen reader-accessible description for shapes on the canvas. + * `gridOutput()` adds a general description, table of shapes, and list of + * shapes to the web page. + * + * The general description includes the canvas size, canvas color, and number of + * shapes. For example, + * `gray canvas, 100 by 100 pixels, contains 2 shapes: 1 circle 1 square`. + * + * `gridOutput()` uses its table of shapes as a grid. Each shape in the grid + * is placed in a cell whose row and column correspond to the shape's location + * on the canvas. The grid cells describe the color and type of shape at that + * location. For example, `red circle`. These descriptions can be selected + * individually to get more details. This is different from + * textOutput(), which uses its table as a list. + * + * A list of shapes follows the table. The list describes the color, type, + * location, and area of each shape. For example, + * `red circle, location = middle, area = 3 %`. + * + * The `display` parameter is optional. It determines how the description is + * displayed. If `LABEL` is passed, as in `gridOutput(LABEL)`, the description + * will be visible in a div element next to the canvas. Using `LABEL` creates + * unhelpful duplicates for screen readers. Only use `LABEL` during + * development. If `FALLBACK` is passed, as in `gridOutput(FALLBACK)`, the + * description will only be visible to screen readers. This is the default + * mode. + * + * Read + * How to label your p5.js code to + * learn more about making sketches accessible. * * @method gridOutput - * @param {Constant} [display] either FALLBACK or LABEL + * @param {Constant} [display] either FALLBACK or LABEL. * * @example *
* - * gridOutput(); - * background(148, 196, 0); - * fill(255, 0, 0); - * ellipse(20, 20, 20, 20); - * fill(0, 0, 255); - * rect(50, 50, 50, 50); + * function setup() { + * // Add the grid description. + * gridOutput(); + * + * // Draw a couple of shapes. + * background(200); + * fill(255, 0, 0); + * circle(20, 20, 20); + * fill(0, 0, 255); + * square(50, 50, 50); + * + * // Add a general description of the canvas. + * describe('A red circle and a blue square on a gray background.'); + * } * *
* + *
+ * + * function setup() { + * // Add the grid description and + * // display it for debugging. + * gridOutput(LABEL); + * + * // Draw a couple of shapes. + * background(200); + * fill(255, 0, 0); + * circle(20, 20, 20); + * fill(0, 0, 255); + * square(50, 50, 50); + * + * // Add a general description of the canvas. + * describe('A red circle and a blue square on a gray background.'); + * } + * + *
* *
* - * let x = 0; * function draw() { + * // Add the grid description. * gridOutput(); - * background(148, 196, 0); + * + * // Draw a moving circle. + * background(200); + * let x = frameCount * 0.1; * fill(255, 0, 0); - * ellipse(x, 20, 20, 20); + * circle(x, 20, 20); * fill(0, 0, 255); - * rect(50, 50, 50, 50); - * ellipse(20, 20, 20, 20); - * x += 0.1; + * square(50, 50, 50); + * + * // Add a general description of the canvas. + * describe('A red circle moves from left to right above a blue square.'); * } * *
* + *
+ * + * function draw() { + * // Add the grid description and + * // display it for debugging. + * gridOutput(LABEL); + * + * // Draw a moving circle. + * background(200); + * let x = frameCount * 0.1; + * fill(255, 0, 0); + * circle(x, 20, 20); + * fill(0, 0, 255); + * square(50, 50, 50); + * + * // Add a general description of the canvas. + * describe('A red circle moves from left to right above a blue square.'); + * } + * + *
*/ _main.default.prototype.gridOutput = function (display) { - _main.default._validateParameters('gridOutput', arguments); //if gridOutput is already true + _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._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._accessibleOutputs.gridLabel = true; + //create output for label this._createOutput('gridOutput', 'Label'); } } - }; //helper function returns true when accessible outputs are true + }; + //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) { @@ -51901,9 +53124,11 @@ }; } return this._accessibleOutputs.grid || this._accessibleOutputs.text; - }; //helper function that creates html structure for accessible outputs + }; + //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 + 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: { @@ -51915,7 +53140,7 @@ }, pShapes: '' }; - } //if there is no dummyDOM create it + } //if there is no dummyDOM create it if (!this.dummyDOM) { this.dummyDOM = document.getElementById(cnvId).parentNode; @@ -51951,41 +53176,45 @@ this.dummyDOM.querySelector('#'.concat(cnvId, '_Label')).insertAdjacentHTML('afterend', '
')); } } - } //create an object to store the latest output. this object is used in _updateTextOutput() and _updateGridOutput() + } //create an object to store the latest output. this object is used in _updateTextOutput() and _updateGridOutput() this._accessibleOutputs[cIdT] = { }; if (type === 'textOutput') { query = '#'.concat(cnvId, 'gridOutput').concat(query); //query is used to check if gridOutput already exists - inner = '
Text Output

    '); //if gridOutput already exists + inner = '
    Text Output

      '); + //if gridOutput already exists if (this.dummyDOM.querySelector(query)) { //create textOutput before gridOutput this.dummyDOM.querySelector(query).insertAdjacentHTML('beforebegin', inner); } else { //create output inside of container this.dummyDOM.querySelector('#'.concat(container)).innerHTML = inner; - } //store output html elements + } //store output html elements this._accessibleOutputs[cIdT].list = this.dummyDOM.querySelector('#'.concat(cIdT, '_list')); } else if (type === 'gridOutput') { query = '#'.concat(cnvId, 'textOutput').concat(query); //query is used to check if textOutput already exists - inner = '
      Grid Output

      '); //if textOutput already exists + inner = '
      Grid Output

      '); + //if textOutput already exists if (this.dummyDOM.querySelector(query)) { //create gridOutput after textOutput this.dummyDOM.querySelector(query).insertAdjacentHTML('afterend', inner); } else { //create output inside of container this.dummyDOM.querySelector('#'.concat(container)).innerHTML = inner; - } //store output html elements + } //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 + }; + //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 + 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); @@ -52002,18 +53231,22 @@ this._updateGridOutput(cnvId + 'gridOutputLabel'); } } - }; //helper function that resets all ingredients when background is called + }; + //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.pShapes = JSON.stringify(this.ingredients.shapes); + //empty shapes JSON this.ingredients.shapes = { - }; //update background different + }; + //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 + }; + //helper function that gets fill and stroke of shapes _main.default.prototype._accsCanvasColors = function (f, args) { if (f === 'fill') { //update fill different @@ -52028,7 +53261,8 @@ this.ingredients.colors.stroke = this._rgbColorName(args); } } - }; //builds ingredients.shapes used for building outputs + }; + //builds ingredients.shapes used for building outputs _main.default.prototype._accsOutput = function (f, args) { if (f === 'ellipse' && args[2] === args[3]) { f = 'circle'; @@ -52041,16 +53275,16 @@ 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], - [ + include.color = this.ingredients.colors.stroke; + //get lenght + include.length = Math.round(this.dist(args[0], args[1], args[2], args[3])); + //get position of end points + var p1 = this._getPos(args[0], [ 1 - ]], this.width, this.height); - var p2 = _getPos([args[2], - [ + ]); + var p2 = this._getPos(args[2], [ 3 - ]], this.width, this.height); + ]); include.loc = _canvasLocator(middle, this.width, this.height); if (p1 === p2) { include.pos = 'at '.concat(p1); @@ -52063,19 +53297,22 @@ 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 + include.color = this.ingredients.colors.fill; + //get area of shape + include.area = this._getArea(f, args); + } //get middle of shapes //calculate position using middle of shape - include.pos = _getPos(middle, this.width, this.height); //calculate location using middle of shape + include.pos = this._getPos.apply(this, _toConsumableArray(middle)); + //calculate location using middle of shape include.loc = _canvasLocator(middle, this.width, this.height); - } //if it is the first time this shape is created + } //if 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 + ]; + //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]) { @@ -52083,13 +53320,14 @@ if (JSON.stringify(this.ingredients.shapes[f][y]) === JSON.stringify(include)) { add = false; } - } //add shape by pushing it to the end + } //add shape by pushing it to the end if (add === true) { this.ingredients.shapes[f].push(include); } } - }; //gets middle point / centroid of shape + }; + //gets middle point / centroid of shape function _getMiddle(f, args) { var x, y; @@ -52111,36 +53349,43 @@ } 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) { + } //gets position of shape in the canvas + + _main.default.prototype._getPos = function (x, y) { + var untransformedPosition = new DOMPointReadOnly(x, y); + var currentTransform = this._renderer.isP3D ? new DOMMatrix(this._renderer.uMVMatrix.mat4) : this.drawingContext.getTransform(); + var _untransformedPositio = untransformedPosition.matrixTransform(currentTransform), + transformedX = _untransformedPositio.x, + transformedY = _untransformedPositio.y; + var canvasWidth = this.width, + canvasHeight = this.height; + if (transformedX < 0.4 * canvasWidth) { + if (transformedY < 0.4 * canvasHeight) { return 'top left'; - } else if (args[1] > 0.6 * canvasHeight) { + } else if (transformedY > 0.6 * canvasHeight) { return 'bottom left'; } else { return 'mid left'; } - } else if (args[0] > 0.6 * canvasWidth) { - if (args[1] < 0.4 * canvasHeight) { + } else if (transformedX > 0.6 * canvasWidth) { + if (transformedY < 0.4 * canvasHeight) { return 'top right'; - } else if (args[1] > 0.6 * canvasHeight) { + } else if (transformedY > 0.6 * canvasHeight) { return 'bottom right'; } else { return 'mid right'; } } else { - if (args[1] < 0.4 * canvasHeight) { + if (transformedY < 0.4 * canvasHeight) { return 'top middle'; - } else if (args[1] > 0.6 * canvasHeight) { + } else if (transformedY > 0.6 * canvasHeight) { return 'bottom middle'; } else { return 'middle'; } } - } //locates shape in a 10*10 grid - + }; + //locates shape in a 10*10 grid function _canvasLocator(args, canvasWidth, canvasHeight) { var noRows = 10; var noCols = 10; @@ -52156,9 +53401,9 @@ locX: locX, locY: locY }; - } //calculates area of shape + } //calculates area of shape - function _getArea(objectType, shapeArgs, canvasWidth, canvasHeight) { + _main.default.prototype._getArea = function (objectType, shapeArgs) { var objectArea = 0; if (objectType === 'arc') { // area of full ellipse = PI * horizontal radius * vertical radius. @@ -52194,22 +53439,54 @@ } 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)); - } + objectArea = Math.abs(shapeArgs[0] * (shapeArgs[3] - shapeArgs[5]) + shapeArgs[2] * (shapeArgs[5] - shapeArgs[1]) + shapeArgs[4] * (shapeArgs[1] - shapeArgs[3])) / 2; + // (Ax( By − Cy) + Bx(Cy − Ay) + Cx(Ay − By ))/2 + } // Store the positions of the canvas corners + + var canvasWidth = this.width * this._pixelDensity; + var canvasHeight = this.height * this._pixelDensity; + var canvasCorners = [ + new DOMPoint(0, 0), + new DOMPoint(canvasWidth, 0), + new DOMPoint(canvasWidth, canvasHeight), + new DOMPoint(0, canvasHeight) + ]; + // Apply the inverse of the current transformations to the canvas corners + var currentTransform = this._renderer.isP3D ? new DOMMatrix(this._renderer.uMVMatrix.mat4) : this.drawingContext.getTransform(); + var invertedTransform = currentTransform.inverse(); + var tc = canvasCorners.map(function (corner) { + return corner.matrixTransform(invertedTransform); + }); + /* Use same shoelace formula used for quad area (above) to calculate + the area of the canvas with inverted transformation applied */ + var transformedCanvasArea = Math.abs((tc[3].x + tc[0].x) * (tc[3].y - tc[0].y) + (tc[0].x + tc[1].x) * (tc[0].y - tc[1].y) + (tc[1].x + tc[2].x) * (tc[1].y - tc[2].y) + (tc[2].x + tc[3].x) * (tc[2].y - tc[3].y)) / 2; + /* Compare area of shape (minus transformations) to area of canvas + with inverted transformation applied. + Return percentage */ + var untransformedArea = Math.round(objectArea * 100 / transformedCanvasArea); + return untransformedArea; + }; var _default = _main.default; exports.default = _default; }, { - '../core/main': 290, - 'core-js/modules/es.array.concat': 167, - 'core-js/modules/es.array.fill': 170, - 'core-js/modules/es.array.map': 179, - 'core-js/modules/es.number.to-fixed': 189 + '../core/main': 298, + 'core-js/modules/es.array.concat': 169, + 'core-js/modules/es.array.fill': 172, + 'core-js/modules/es.array.from': 176, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.map': 182, + 'core-js/modules/es.number.to-fixed': 193, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 272: [ + 280: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.array.concat'); @@ -52238,26 +53515,31 @@ 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 + 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 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 it is different from current shape details if (innerShapeDetails !== current.shapeDetails.innerHTML) { //update current.shapeDetails.innerHTML = innerShapeDetails; } this._accessibleOutputs[idT] = current; - }; //Builds textOutput summary + }; + //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) { @@ -52266,11 +53548,12 @@ text = ''.concat(text, ' ').concat(numShapes, ' shapes:'); } return text; - } //Builds textOutput table with shape details + } //Builds textOutput table with shape details function _shapeDetails(idT, ingredients) { var shapeDetails = ''; - var shapeNumber = 0; //goes trhough every shape type in ingredients + 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]) { @@ -52290,11 +53573,12 @@ } } return shapeDetails; - } //Builds textOutput shape list + } //Builds textOutput shape list function _shapeList(idT, ingredients) { var shapeList = ''; - var shapeNumber = 0; //goes trhough every shape type in ingredients + 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 @@ -52321,11 +53605,11 @@ exports.default = _default; }, { - '../core/main': 290, - 'core-js/modules/es.array.concat': 167 + '../core/main': 298, + 'core-js/modules/es.array.concat': 169 } ], - 273: [ + 281: [ function (_dereq_, module, exports) { 'use strict'; var _main = _interopRequireDefault(_dereq_('./core/main')); @@ -52395,11 +53679,13 @@ _dereq_('./webgl/loading'); _dereq_('./webgl/material'); _dereq_('./webgl/p5.Camera'); + _dereq_('./webgl/p5.DataArray'); _dereq_('./webgl/p5.Geometry'); _dereq_('./webgl/p5.Matrix'); _dereq_('./webgl/p5.RendererGL.Immediate'); _dereq_('./webgl/p5.RendererGL'); _dereq_('./webgl/p5.RendererGL.Retained'); + _dereq_('./webgl/p5.Framebuffer'); _dereq_('./webgl/p5.Shader'); _dereq_('./webgl/p5.RenderBuffer'); _dereq_('./webgl/p5.Texture'); @@ -52410,7 +53696,7 @@ default: obj }; - } // core + } // core //accessibility // color // data @@ -52427,86 +53713,88 @@ module.exports = _main.default; }, { - './accessibility/color_namer': 268, - './accessibility/describe': 269, - './accessibility/gridOutput': 270, - './accessibility/outputs': 271, - './accessibility/textOutput': 272, - './color/color_conversion': 274, - './color/creating_reading': 275, - './color/p5.Color': 276, - './color/setting': 277, - './core/constants': 278, - './core/environment': 279, - './core/friendly_errors/fes_core': 281, - './core/friendly_errors/file_errors': 282, - './core/friendly_errors/sketch_reader': 283, - './core/friendly_errors/stacktrace': 284, - './core/friendly_errors/validate_params': 285, - './core/helpers': 286, - './core/init': 287, - './core/legacy': 289, - './core/main': 290, - './core/p5.Element': 291, - './core/p5.Graphics': 292, - './core/p5.Renderer': 293, - './core/p5.Renderer2D': 294, - './core/preload': 295, - './core/rendering': 296, - './core/shape/2d_primitives': 297, - './core/shape/attributes': 298, - './core/shape/curves': 299, - './core/shape/vertex': 300, - './core/shim': 301, - './core/structure': 302, - './core/transform': 303, - './data/local_storage.js': 304, - './data/p5.TypedDict': 305, - './dom/dom': 306, - './events/acceleration': 307, - './events/keyboard': 308, - './events/mouse': 309, - './events/touch': 310, - './image/filters': 311, - './image/image': 312, - './image/loading_displaying': 313, - './image/p5.Image': 314, - './image/pixels': 315, - './io/files': 316, - './io/p5.Table': 317, - './io/p5.TableRow': 318, - './io/p5.XML': 319, - './math/calculation': 320, - './math/math': 321, - './math/noise': 322, - './math/p5.Vector': 323, - './math/random': 324, - './math/trigonometry': 325, - './typography/attributes': 326, - './typography/loading_displaying': 327, - './typography/p5.Font': 328, - './utilities/array_functions': 329, - './utilities/conversion': 330, - './utilities/string_functions': 331, - './utilities/time_date': 332, - './webgl/3d_primitives': 333, - './webgl/interaction': 334, - './webgl/light': 335, - './webgl/loading': 336, - './webgl/material': 337, - './webgl/p5.Camera': 338, - './webgl/p5.Geometry': 339, - './webgl/p5.Matrix': 340, - './webgl/p5.RenderBuffer': 341, - './webgl/p5.RendererGL': 344, - './webgl/p5.RendererGL.Immediate': 342, - './webgl/p5.RendererGL.Retained': 343, - './webgl/p5.Shader': 345, - './webgl/p5.Texture': 346, - './webgl/text': 347 + './accessibility/color_namer': 276, + './accessibility/describe': 277, + './accessibility/gridOutput': 278, + './accessibility/outputs': 279, + './accessibility/textOutput': 280, + './color/color_conversion': 282, + './color/creating_reading': 283, + './color/p5.Color': 284, + './color/setting': 285, + './core/constants': 286, + './core/environment': 287, + './core/friendly_errors/fes_core': 289, + './core/friendly_errors/file_errors': 290, + './core/friendly_errors/sketch_reader': 291, + './core/friendly_errors/stacktrace': 292, + './core/friendly_errors/validate_params': 293, + './core/helpers': 294, + './core/init': 295, + './core/legacy': 297, + './core/main': 298, + './core/p5.Element': 299, + './core/p5.Graphics': 300, + './core/p5.Renderer': 301, + './core/p5.Renderer2D': 302, + './core/preload': 303, + './core/rendering': 304, + './core/shape/2d_primitives': 305, + './core/shape/attributes': 306, + './core/shape/curves': 307, + './core/shape/vertex': 308, + './core/shim': 309, + './core/structure': 310, + './core/transform': 311, + './data/local_storage.js': 312, + './data/p5.TypedDict': 313, + './dom/dom': 314, + './events/acceleration': 315, + './events/keyboard': 316, + './events/mouse': 317, + './events/touch': 318, + './image/filters': 319, + './image/image': 320, + './image/loading_displaying': 321, + './image/p5.Image': 322, + './image/pixels': 323, + './io/files': 324, + './io/p5.Table': 325, + './io/p5.TableRow': 326, + './io/p5.XML': 327, + './math/calculation': 328, + './math/math': 329, + './math/noise': 330, + './math/p5.Vector': 331, + './math/random': 332, + './math/trigonometry': 333, + './typography/attributes': 334, + './typography/loading_displaying': 335, + './typography/p5.Font': 336, + './utilities/array_functions': 337, + './utilities/conversion': 338, + './utilities/string_functions': 339, + './utilities/time_date': 340, + './webgl/3d_primitives': 341, + './webgl/interaction': 343, + './webgl/light': 344, + './webgl/loading': 345, + './webgl/material': 346, + './webgl/p5.Camera': 347, + './webgl/p5.DataArray': 348, + './webgl/p5.Framebuffer': 349, + './webgl/p5.Geometry': 350, + './webgl/p5.Matrix': 351, + './webgl/p5.RenderBuffer': 352, + './webgl/p5.RendererGL': 355, + './webgl/p5.RendererGL.Immediate': 353, + './webgl/p5.RendererGL.Retained': 354, + './webgl/p5.Shader': 356, + './webgl/p5.Texture': 357, + './webgl/text': 358 } ], - 274: [ + 282: [ function (_dereq_, module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { @@ -52534,267 +53822,273 @@ */ _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. + /** + * Convert an HSBA array to HSLA. + */ + _hsbaToHSLA: function _hsbaToHSLA(hsba) { + var hue = hsba[0]; + var sat = hsba[1]; + var val = hsba[2]; + // Calculate lightness. + var li = (2 - sat) * val / 2; + // Convert saturation. + if (li !== 0) { + if (li === 1) { + sat = 0; + } else if (li < 0.5) { + sat = sat / (2 - sat); + } else { + sat = sat * val / (2 - li * 2); + } + } // Hue and alpha stay the same. - return [hue, - sat, - li, - hsba[3]]; - }; - /** - * Convert an HSBA array to RGBA. - */ - _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; + return [hue, + sat, + li, + hsba[3]]; + }, + /** + * Convert an HSBA array to RGBA. + */ + _hsbaToRGBA: function _hsbaToRGBA(hsba) { + var hue = hsba[0] * 6; // We will split hue into 6 sectors. + var sat = hsba[1]; + var val = hsba[2]; + var RGBA = [ + ]; + if (sat === 0) { + RGBA = [ + val, + val, + val, + hsba[3] + ]; // Return early if grayscale. } else { - // Red to yellow (sector could be 0 or 6). - red = val; - green = tint3; - blue = tint1; - } - RGBA = [ - red, + 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, - 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 { + blue; + if (sector === 1) { + // Yellow to green. + red = tint2; + green = val; + blue = tint1; + } else if (sector === 2) { + // Green to cyan. + red = tint1; + green = val; + blue = tint3; + } else if (sector === 3) { + // Cyan to blue. + red = tint1; + green = tint2; + blue = val; + } else if (sector === 4) { + // Blue to magenta. + red = tint3; + green = tint1; + blue = val; + } else if (sector === 5) { + // Magenta to red. + red = val; + green = tint1; + blue = tint2; + } else { + // Red to yellow (sector could be 0 or 6). + red = val; + green = tint3; + blue = tint1; + } + RGBA = [ + red, + green, + blue, + hsba[3] + ]; + } + return RGBA; + }, + /** + * Convert an HSLA array to HSBA. + */ + _hslaToHSBA: function _hslaToHSBA(hsla) { + var hue = hsla[0]; + var sat = hsla[1]; + var li = hsla[2]; // Calculate brightness. var val; if (li < 0.5) { val = (1 + sat) * li; } else { val = li + sat - li * sat; - } // Define zest. - - var zest = 2 * li - val; // Implement projection (project onto green by default). - var hzvToRGB = function hzvToRGB(hue, zest, val) { + } // Convert saturation. + + sat = 2 * (val - li) / val; + // Hue and alpha stay the same. + return [hue, + sat, + val, + hsla[3]]; + }, + /** + * Convert an HSLA array to RGBA. + * + * We need to change basis from HSLA to something that can be more easily be + * projected onto RGBA. We will choose hue and brightness as our first two + * components, and pick a convenient third one ('zest') so that we don't need + * to calculate formal HSBA saturation. + */ + _hslaToRGBA: function _hslaToRGBA(hsla) { + var hue = hsla[0] * 6; // We will split hue into 6 sectors. + var sat = hsla[1]; + var li = hsla[2]; + var RGBA = [ + ]; + if (sat === 0) { + RGBA = [ + li, + li, + li, + hsla[3] + ]; // Return early if grayscale. + } else { + // Calculate brightness. + var val; + if (li < 0.5) { + val = (1 + sat) * li; + } else { + val = li + sat - li * sat; + } // Define zest. + + var zest = 2 * li - val; + // Implement projection (project onto green by default). + var hzvToRGB = function hzvToRGB(hue, zest, val) { + if (hue < 0) { + // Hue must wrap to allow projection onto red and blue. + hue += 6; + } else if (hue >= 6) { + hue -= 6; + } + if (hue < 1) { + // Red to yellow (increasing green). + return zest + (val - zest) * hue; + } else if (hue < 3) { + // Yellow to cyan (greatest green). + return val; + } else if (hue < 4) { + // Cyan to blue (decreasing green). + return zest + (val - zest) * (4 - hue); + } else { + // Blue to red (least green). + return zest; + } + }; + // Perform projections, offsetting hue as necessary. + RGBA = [ + hzvToRGB(hue + 2, zest, val), + hzvToRGB(hue, zest, val), + hzvToRGB(hue - 2, zest, val), + hsla[3] + ]; + } + return RGBA; + }, + /** + * Convert an RGBA array to HSBA. + */ + _rgbaToHSBA: function _rgbaToHSBA(rgba) { + var red = rgba[0]; + var green = rgba[1]; + var blue = rgba[2]; + var val = Math.max(red, green, blue); + var chroma = val - Math.min(red, green, blue); + var hue, + sat; + if (chroma === 0) { + // Return early if grayscale. + hue = 0; + sat = 0; + } else { + sat = chroma / val; + if (red === val) { + // Magenta to yellow. + hue = (green - blue) / chroma; + } else if (green === val) { + // Yellow to cyan. + hue = 2 + (blue - red) / chroma; + } else if (blue === val) { + // Cyan to magenta. + hue = 4 + (red - green) / chroma; + } if (hue < 0) { - // Hue must wrap to allow projection onto red and blue. + // Confine hue to the interval [0, 1). 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); + } + return [hue / 6, + sat, + val, + rgba[3]]; + }, + /** + * Convert an RGBA array to HSLA. + */ + _rgbaToHSLA: function _rgbaToHSLA(rgba) { + var red = rgba[0]; + var green = rgba[1]; + var blue = rgba[2]; + var val = Math.max(red, green, blue); + var min = Math.min(red, green, blue); + var li = val + min; // We will halve this later. + var chroma = val - min; + var hue, + sat; + if (chroma === 0) { + // Return early if grayscale. + hue = 0; + sat = 0; + } else { + if (li < 1) { + sat = chroma / li; } else { - // 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] - ]; + 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]]; } - return RGBA; - }; - /** - * Convert an RGBA array to HSBA. - */ - _main.default.ColorConversion._rgbaToHSBA = function (rgba) { - var red = rgba[0]; - var green = rgba[1]; - var blue = rgba[2]; - var val = Math.max(red, green, blue); - var chroma = val - Math.min(red, green, blue); - var hue, - sat; - if (chroma === 0) { - // Return early if grayscale. - hue = 0; - sat = 0; - } else { - sat = chroma / val; - if (red === val) { - // Magenta to yellow. - hue = (green - blue) / chroma; - } else if (green === val) { - // Yellow to cyan. - hue = 2 + (blue - red) / chroma; - } else if (blue === val) { - // Cyan to magenta. - hue = 4 + (red - green) / chroma; - } - if (hue < 0) { - // Confine hue to the interval [0, 1). - hue += 6; - } else if (hue >= 6) { - hue -= 6; - } - } - return [hue / 6, - sat, - val, - rgba[3]]; - }; - /** - * Convert an RGBA array to HSLA. - */ - _main.default.ColorConversion._rgbaToHSLA = function (rgba) { - var red = rgba[0]; - var green = rgba[1]; - var blue = rgba[2]; - var val = Math.max(red, green, blue); - var min = Math.min(red, green, blue); - var li = val + min; // We will halve this later. - var chroma = val - min; - var hue, - sat; - if (chroma === 0) { - // Return early if grayscale. - hue = 0; - sat = 0; - } else { - if (li < 1) { - sat = chroma / li; - } else { - sat = chroma / (2 - li); - } - if (red === val) { - // Magenta to yellow. - hue = (green - blue) / chroma; - } else if (green === val) { - // Yellow to cyan. - hue = 2 + (blue - red) / chroma; - } else if (blue === val) { - // Cyan to magenta. - hue = 4 + (red - green) / chroma; - } - if (hue < 0) { - // Confine hue to the interval [0, 1). - hue += 6; - } else if (hue >= 6) { - hue -= 6; - } - } - return [hue / 6, - sat, - li / 2, - rgba[3]]; }; var _default = _main.default.ColorConversion; exports.default = _default; }, { - '../core/main': 290 + '../core/main': 298 } ], - 275: [ + 283: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -52896,24 +54190,27 @@ * @requires constants */ /** - * Extracts the alpha value from a color or pixel array. + * Extracts the alpha (transparency) value from a + * p5.Color object, array of color components, or + * CSS color string. * * @method alpha - * @param {p5.Color|Number[]|String} color p5.Color object, color components, - * or CSS color - * @return {Number} the alpha value + * @param {p5.Color|Number[]|String} color p5.Color object, array of + * color components, or CSS color string. + * @return {Number} the alpha value. * * @example *
      * * noStroke(); - * let c = color(0, 126, 255, 102); + * const c = color(0, 126, 255, 102); * fill(c); * rect(15, 15, 35, 70); - * let value = alpha(c); // Sets 'value' to 102 - * fill(value); + * // Sets 'alphaValue' to 102. + * const alphaValue = alpha(c); + * fill(alphaValue); * rect(50, 15, 35, 70); - * describe('Left half of canvas light blue and right half light charcoal grey.'); + * describe('Two rectangles. The left one is light blue and the right one is charcoal gray.'); * *
      */ @@ -52923,22 +54220,24 @@ return this.color(c)._getAlpha(); }; /** - * Extracts the blue value from a color or pixel array. + * Extracts the blue value from a p5.Color object, + * array of color components, or CSS color string. * * @method blue - * @param {p5.Color|Number[]|String} color p5.Color object, color components, - * or CSS color - * @return {Number} the blue value + * @param {p5.Color|Number[]|String} color p5.Color object, array of + * color components, or CSS color string. + * @return {Number} the blue value. * @example *
      * - * let c = color(175, 100, 220); + * const c = color(175, 100, 220); * fill(c); - * rect(15, 20, 35, 60); // Draw left rectangle - * let blueValue = blue(c); + * rect(15, 20, 35, 60); + * // Sets 'blueValue' to 220. + * const blueValue = blue(c); * fill(0, 0, blueValue); - * rect(50, 20, 35, 60); // Draw right rectangle - * describe('Left half of canvas light purple and right half a royal blue.'); + * rect(50, 20, 35, 60); + * describe('Two rectangles. The left one is light purple and the right one is royal blue.'); * *
      * @@ -52948,26 +54247,28 @@ return this.color(c)._getBlue(); }; /** - * Extracts the HSB brightness value from a color or pixel array. + * Extracts the HSB brightness value from a + * p5.Color object, array of color components, or + * CSS color string. * * @method brightness - * @param {p5.Color|Number[]|String} color p5.Color object, color components, - * or CSS color - * @return {Number} the brightness value + * @param {p5.Color|Number[]|String} color p5.Color object, array of + * color components, or CSS color string. + * @return {Number} the brightness value. * * @example *
      * * noStroke(); * colorMode(HSB, 255); - * let c = color(0, 126, 255); + * const c = color(0, 126, 255); * fill(c); * rect(15, 20, 35, 60); - * let value = brightness(c); // Sets 'value' to 255 - * fill(value); + * // Sets 'brightValue' to 255. + * const brightValue = brightness(c); + * fill(brightValue); * rect(50, 20, 35, 60); - * describe(`Left half of canvas salmon pink and the right half with its - * brightness colored white.`); + * describe('Two rectangles. The left one is salmon pink and the right one is white.'); * *
      * @@ -52975,14 +54276,14 @@ * * noStroke(); * colorMode(HSB, 255); - * let c = color('hsb(60, 100%, 50%)'); + * const 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); + * // Sets 'brightValue' to 127.5 (50% of 255) + * const brightValue = brightness(c); + * fill(brightValue); * rect(50, 20, 35, 60); - * describe(`Left half of canvas olive colored and the right half with its - * brightness color gray.`); + * describe('Two rectangles. The left one is olive and the right one is gray.'); * * */ @@ -52991,70 +54292,73 @@ return this.color(c)._getBrightness(); }; /** - * Creates colors for storing in variables of the color datatype. The - * parameters are interpreted as RGB or HSB values depending on the - * current colorMode(). The default mode is RGB values from 0 to 255 - * and, therefore, the function call color(255, 204, 0) will return a - * bright yellow color. + * Creates a p5.Color object. By default, the + * parameters are interpreted as RGB values. Calling `color(255, 204, 0)` will + * return a bright yellow color. The way these parameters are interpreted may + * be changed with the colorMode() function. + * + * The version of `color()` with one parameter interprets the value one of two + * ways. If the parameter is a number, it's interpreted as a grayscale value. + * If the parameter is a string, it's interpreted as a CSS color string. * - * Note that if only one value is provided to color(), it will be interpreted - * as a grayscale value. Add a second value, and it will be used for alpha - * transparency. When three values are specified, they are interpreted as - * either RGB or HSB values. Adding a fourth value applies alpha - * transparency. + * The version of `color()` with two parameters interprets the first one as a + * grayscale value. The second parameter sets the alpha (transparency) value. * - * 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. + * The version of `color()` with three parameters interprets them as RGB, HSB, + * or HSL colors, depending on the current `colorMode()`. + * + * The version of `color()` with four parameters interprets them as RGBA, HSBA, + * or HSLA colors, depending on the current `colorMode()`. The last parameter + * sets the alpha (transparency) value. * * @method color * @param {Number} gray number specifying value between white and black. * @param {Number} [alpha] alpha value relative to current color range - * (default is 0-255) - * @return {p5.Color} resulting color + * (default is 0-255). + * @return {p5.Color} resulting color. * * @example *
      * - * let c = color(255, 204, 0); + * const c = color(255, 204, 0); * fill(c); * noStroke(); * rect(30, 20, 55, 55); - * describe(`Yellow rect in middle right of canvas, - * with 55 pixel width and height.`); + * describe('A yellow rectangle on a gray canvas.'); * *
      * *
      * + * // RGB values. * 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. + * circle(25, 25, 80); + * // A grayscale value. * c = color(65); * fill(c); - * ellipse(75, 75, 80, 80); - * describe(`Yellow ellipse in top left of canvas, black ellipse in bottom - * right, both 80×80.`); + * circle(75, 75, 80); + * describe( + * 'Two ellipses. The circle in the top-left corner is yellow and the one at the bottom-right is gray.' + * ); * *
      * *
      * - * // You can use named SVG & CSS colors - * let c = color('magenta'); + * // A CSS named color. + * const c = color('magenta'); * fill(c); * noStroke(); - * rect(20, 20, 60, 60); - * describe('Bright fuchsia rect in middle of canvas, 60 pixel width and height.'); + * square(20, 20, 60); + * describe('A magenta square on a gray canvas.'); * *
      * *
      * - * // Example of hex color codes + * // CSS hex color codes. * noStroke(); * let c = color('#0f0'); * fill(c); @@ -53062,97 +54366,93 @@ * c = color('#00ff00'); * fill(c); * rect(55, 10, 45, 80); - * describe('Two bright green rects on opposite sides of the canvas, both 45×80.'); + * describe('Two bright green rectangles on a gray canvas.'); * *
      * *
      * - * // RGB and RGBA color strings are also supported - * // these all set to the same color (solid blue) - * let c; + * // RGB and RGBA color strings. * noStroke(); - * c = color('rgb(0,0,255)'); + * let c = color('rgb(0,0,255)'); * fill(c); - * rect(10, 10, 35, 35); // Draw rectangle + * square(10, 10, 35); * c = color('rgb(0%, 0%, 100%)'); * fill(c); - * rect(55, 10, 35, 35); // Draw rectangle + * square(55, 10, 35); * c = color('rgba(0, 0, 255, 1)'); * fill(c); - * rect(10, 55, 35, 35); // Draw rectangle + * square(10, 55, 35); * c = color('rgba(0%, 0%, 100%, 1)'); * fill(c); - * rect(55, 55, 35, 35); // Draw rectangle - * describe('Four blue rects in each corner of the canvas, each are 35×35.'); + * square(55, 55, 35); + * describe('Four blue squares in corners of a gray canvas.'); * *
      * *
      * - * // HSL color can also be specified by value + * // HSL and HSLA color strings. * let c = color('hsl(160, 100%, 50%)'); * noStroke(); * fill(c); - * rect(0, 10, 45, 80); // Draw rectangle + * rect(0, 10, 45, 80); * c = color('hsla(160, 100%, 50%, 0.5)'); * fill(c); - * rect(55, 10, 45, 80); // Draw rectangle - * describe(`Bright sea green rect on left and darker rect on right of canvas, - * both 45×80.`); + * rect(55, 10, 45, 80); + * describe('Two sea green rectangles. A darker rectangle on the left and a brighter one on the right.'); * *
      * *
      * - * // HSB color can also be specified + * // HSB and HSBA color strings. * let c = color('hsb(160, 100%, 50%)'); * noStroke(); * fill(c); - * rect(0, 10, 45, 80); // Draw rectangle + * rect(0, 10, 45, 80); * c = color('hsba(160, 100%, 50%, 0.5)'); * fill(c); - * rect(55, 10, 45, 80); // Draw rectangle - * describe(`Dark green rect on left and lighter green rect on right of canvas, - * both 45×80.`); + * rect(55, 10, 45, 80); + * describe('Two green rectangles. A darker rectangle on the left and a brighter one on the right.'); * *
      * *
      * + * // Changing color modes. * noStroke(); * let c = color(50, 55, 100); * fill(c); - * rect(0, 10, 45, 80); // Draw left rect + * rect(0, 10, 45, 80); * colorMode(HSB, 100); * c = color(50, 55, 100); * fill(c); * rect(55, 10, 45, 80); - * describe(`Dark blue rect on left and light teal rect on right of canvas, - * both 45×80.`); + * describe('Two blue rectangles. A darker rectangle on the left and a brighter one on the right.'); * *
      */ /** * @method color * @param {Number} v1 red or hue value relative to - * the current color range + * the current color range. * @param {Number} v2 green or saturation value - * relative to the current color range + * relative to the current color range. * @param {Number} v3 blue or brightness value - * relative to the current color range + * relative to the current color range. * @param {Number} [alpha] * @return {p5.Color} */ /** * @method color - * @param {String} value a color string + * @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 + * @param {Number[]} values an array containing the red, green, blue, + * and alpha components of the color. * @return {p5.Color} */ /** @@ -53169,25 +54469,24 @@ return new _main.default.Color(this, args); }; /** - * Extracts the green value from a color or pixel array. + * Extracts the green value from a p5.Color object, + * array of color components, or CSS color string. * * @method green - * @param {p5.Color|Number[]|String} color p5.Color object, color components, - * or CSS color - * @return {Number} the green value + * @param {p5.Color|Number[]|String} color p5.Color object, array of + * color components, or CSS color string. + * @return {Number} the green value. * @example *
      * - * let c = color(20, 75, 200); // Define color 'c' - * fill(c); // Use color variable 'c' as fill color - * rect(15, 20, 35, 60); // Draw left rectangle - * - * let greenValue = green(c); // Get green in 'c' - * print(greenValue); // Print "75.0" - * fill(0, greenValue, 0); // Use 'greenValue' in new fill - * rect(50, 20, 35, 60); // Draw right rectangle - * describe(`blue rect on left and green on right, both with black outlines - * & 35×60.`); + * const c = color(20, 75, 200); + * fill(c); + * rect(15, 20, 35, 60); + * // Sets 'greenValue' to 75. + * const greenValue = green(c); + * fill(0, greenValue, 0); + * rect(50, 20, 35, 60); + * describe('Two rectangles. The rectangle on the left is blue and the one on the right is green.'); * *
      */ @@ -53196,30 +54495,34 @@ return this.color(c)._getGreen(); }; /** - * Extracts the hue value from a color or pixel array. + * Extracts the hue value from a + * p5.Color object, array of color components, or + * CSS color string. * - * 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.) + * Hue exists in both HSB and HSL. It describes a color's position on the + * color wheel. By default, this function returns the HSL-normalized hue. If + * the colorMode() is set to HSB, it returns the + * HSB-normalized hue. * * @method hue - * @param {p5.Color|Number[]|String} color p5.Color object, color components, - * or CSS color + * @param {p5.Color|Number[]|String} color p5.Color object, array of + * color components, or CSS color string. * @return {Number} the hue * @example *
      * * noStroke(); * colorMode(HSB, 255); - * let c = color(0, 126, 255); + * const c = color(0, 126, 255); * fill(c); * rect(15, 20, 35, 60); - * let value = hue(c); // Sets 'value' to "0" - * fill(value); + * // Sets 'hueValue' to 0. + * const hueValue = hue(c); + * fill(hueValue); * rect(50, 20, 35, 60); - * describe('salmon pink rect on left and black on right, both 35×60.'); + * describe( + * 'Two rectangles. The rectangle on the left is salmon pink and the one on the right is black.' + * ); * *
      * @@ -53229,21 +54532,22 @@ return this.color(c)._getHue(); }; /** - * Blends two colors to find a third color somewhere between them. The amt - * parameter is the amount to interpolate between the two values where 0.0 - * is equal to the first color, 0.1 is very near the first color, 0.5 is halfway - * in between, etc. An amount below 0 will be treated as 0. Likewise, amounts - * above 1 will be capped at 1. This is different from the behavior of lerp(), - * but necessary because otherwise numbers outside the range will produce - * strange and unexpected colors. + * Blends two colors to find a third color between them. The `amt` parameter + * specifies the amount to interpolate between the two values. 0 is equal to + * the first color, 0.1 is very near the first color, 0.5 is halfway between + * the two colors, and so on. Negative numbers are set to 0. Numbers greater + * than 1 are set to 1. This differs from the behavior of + * lerp. It's necessary because numbers outside of the + * interval [0, 1] will produce strange and unexpected colors. * - * The way that colors are interpolated depends on the current color mode. + * The way that colors are interpolated depends on the current + * colorMode(). * * @method lerpColor - * @param {p5.Color} c1 interpolate from this color - * @param {p5.Color} c2 interpolate to this color - * @param {Number} amt number between 0 and 1 - * @return {p5.Color} interpolated color + * @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 *
      @@ -53251,11 +54555,11 @@ * 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); + * const from = color(218, 165, 32); + * const to = color(72, 61, 139); + * colorMode(RGB); + * const interA = lerpColor(from, to, 0.33); + * const interB = lerpColor(from, to, 0.66); * fill(from); * rect(10, 20, 20, 60); * fill(interA); @@ -53264,8 +54568,9 @@ * rect(50, 20, 20, 60); * fill(to); * rect(70, 20, 20, 60); - * describe(`4 rects one tan, brown, brownish purple, purple, with white - * outlines & 20×60`); + * describe( + * 'Four rectangles with white edges. From left to right, the rectangles are tan, brown, brownish purple, and purple.' + * ); * *
      */ @@ -53298,20 +54603,22 @@ toArray = c2.hsla; } else { throw new Error(''.concat(mode, 'cannot be used for interpolation.')); - } // Prevent extrapolation. + } // Prevent extrapolation. - amt = Math.max(Math.min(amt, 1), 0); // Define lerp here itself if user isn't using math module. + 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. + } // 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. + l3 = this.lerp(fromArray[3], toArray[3], amt); + // Scale components. l0 *= maxes[mode][0]; l1 *= maxes[mode][1]; l2 *= maxes[mode][2]; @@ -53319,11 +54626,13 @@ return this.color(l0, l1, l2, l3); }; /** - * Extracts the HSL lightness value from a color or pixel array. + * Extracts the HSL lightness value from a + * p5.Color object, array of color components, or + * CSS color string. * * @method lightness - * @param {p5.Color|Number[]|String} color p5.Color object, color components, - * or CSS color + * @param {p5.Color|Number[]|String} color p5.Color object, array of + * color components, or CSS color string. * @return {Number} the lightness * * @example @@ -53331,14 +54640,14 @@ * * noStroke(); * colorMode(HSL); - * let c = color(156, 100, 50, 1); + * const c = color(156, 100, 50, 1); * fill(c); * rect(15, 20, 35, 60); - * let value = lightness(c); // Sets 'value' to 50 - * fill(value); + * // Sets 'lightValue' to 50. + * const lightValue = lightness(c); + * fill(lightValue); * rect(50, 20, 35, 60); - * describe(`light pastel green rect on left and dark grey rect on right, - * both 35×60.`); + * describe('Two rectangles. The rectangle on the left is light green and the one on the right is gray.'); * * */ @@ -53347,36 +54656,27 @@ return this.color(c)._getLightness(); }; /** - * Extracts the red value from a color or pixel array. + * Extracts the red value from a + * p5.Color object, array of color components, or + * CSS color string. * * @method red - * @param {p5.Color|Number[]|String} color p5.Color object, color components, - * or CSS color - * @return {Number} the red value + * @param {p5.Color|Number[]|String} color p5.Color object, array of + * color components, or CSS color string. + * @return {Number} the red value. * @example *
      * - * let c = color(255, 204, 0); // Define color 'c' - * fill(c); // Use color variable 'c' as fill color - * rect(15, 20, 35, 60); // Draw left rectangle - * - * let redValue = red(c); // Get red in 'c' - * print(redValue); // Print "255.0" - * fill(redValue, 0, 0); // Use 'redValue' in new fill - * rect(50, 20, 35, 60); // Draw right rectangle - * describe(`yellow rect on left and red rect on right, both with black - * outlines and 35×60.`); - * - *
      - * - *
      - * - * colorMode(RGB, 255); // Sets the range for red, green, and blue to 255 - * let c = color(127, 255, 0); - * colorMode(RGB, 1); // Sets the range for red, green, and blue to 1 - * let myColor = red(c); - * print(myColor); // 0.4980392156862745 - * describe('grey canvas'); + * const c = color(255, 204, 0); + * fill(c); + * rect(15, 20, 35, 60); + * // Sets 'redValue' to 255. + * const redValue = red(c); + * fill(redValue, 0, 0); + * rect(50, 20, 35, 60); + * describe( + * 'Two rectangles with black edges. The rectangle on the left is yellow and the one on the right is red.' + * ); * *
      */ @@ -53385,29 +54685,33 @@ return this.color(c)._getRed(); }; /** - * Extracts the saturation value from a color or pixel array. + * Extracts the saturation value from a + * p5.Color object, array of color components, or + * CSS color string. * - * 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. + * Saturation is scaled differently in HSB and HSL. By default, this function + * returns the HSL saturation. If the colorMode() + * is set to HSB, it returns the HSB saturation. * * @method saturation - * @param {p5.Color|Number[]|String} color p5.Color object, color components, - * or CSS color + * @param {p5.Color|Number[]|String} color p5.Color object, array of + * color components, or CSS color string. * @return {Number} the saturation value * @example *
      * * noStroke(); * colorMode(HSB, 255); - * let c = color(0, 126, 255); + * const c = color(0, 126, 255); * fill(c); * rect(15, 20, 35, 60); - * let value = saturation(c); // Sets 'value' to 126 - * fill(value); + * // Sets 'satValue' to 126. + * const satValue = saturation(c); + * fill(satValue); * rect(50, 20, 35, 60); - * describe('deep pink rect on left and grey rect on right, both 35×60.'); + * describe( + * 'Two rectangles. The rectangle on the left is deep pink and the one on the right is gray.' + * ); * *
      */ @@ -53419,30 +54723,31 @@ exports.default = _default; }, { - '../core/constants': 278, - '../core/friendly_errors/fes_core': 281, - '../core/friendly_errors/file_errors': 282, - '../core/friendly_errors/validate_params': 285, - '../core/main': 290, - './p5.Color': 276, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.map': 179, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + '../core/constants': 286, + '../core/friendly_errors/fes_core': 289, + '../core/friendly_errors/file_errors': 290, + '../core/friendly_errors/validate_params': 293, + '../core/main': 298, + './p5.Color': 284, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.map': 182, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 276: [ + 284: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); _dereq_('core-js/modules/es.symbol.description'); _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.includes'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.join'); _dereq_('core-js/modules/es.array.map'); @@ -53452,6 +54757,7 @@ _dereq_('core-js/modules/es.regexp.constructor'); _dereq_('core-js/modules/es.regexp.exec'); _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.includes'); _dereq_('core-js/modules/es.string.iterator'); _dereq_('core-js/modules/es.string.trim'); _dereq_('core-js/modules/es.weak-map'); @@ -53480,6 +54786,7 @@ } return _typeof(obj); } + _dereq_('core-js/modules/es.array.includes'); _dereq_('core-js/modules/es.array.join'); _dereq_('core-js/modules/es.array.map'); _dereq_('core-js/modules/es.array.slice'); @@ -53487,6 +54794,7 @@ _dereq_('core-js/modules/es.regexp.constructor'); _dereq_('core-js/modules/es.regexp.exec'); _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.includes'); _dereq_('core-js/modules/es.string.trim'); Object.defineProperty(exports, '__esModule', { value: true @@ -53541,311 +54849,37 @@ default: obj }; - } /** - * @module Color - * @submodule Creating & Reading - * @for p5 - * @requires core - * @requires constants - * @requires color_conversion - */ - /** - * Each color stores the color mode and level maxes that were applied at the - * time of its construction. These are used to interpret the input arguments - * (at construction and later for that instance of color) and to format the - * output e.g. when saturation() is requested. - * - * Internally, we store an array representing the ideal RGBA values in floating - * point form, normalized from 0 to 1. From this we calculate the closest - * screen color (RGBA levels from 0 to 255) and expose this to the renderer. - * - * We also cache normalized, floating-point components of the color in various - * representations as they are calculated. This is done to prevent repeating a - * conversion that has already been performed. - * - * @class p5.Color - * @constructor - */ - - _main.default.Color = function (pInst, vals) { - // Record color mode and maxes at time of construction. - this._storeModeAndMaxes(pInst._colorMode, pInst._colorMaxes); // Calculate normalized RGBA values. - if (this.mode !== constants.RGB && this.mode !== constants.HSL && this.mode !== constants.HSB) { - throw new Error(''.concat(this.mode, ' is an invalid colorMode.')); - } else { - this._array = _main.default.Color._parseInputs.apply(this, vals); - } // Expose closest screen color. - - this._calculateLevels(); - return this; - }; - /** - * This method returns the color formatted as a string. This can be useful - * for debugging, or for using p5.js with other libraries. - * - * @method toString - * @param {String} [format] How the color string will be formatted. - * Leaving this empty formats the string as rgba(r, g, b, a). - * '#rgb' '#rgba' '#rrggbb' and '#rrggbbaa' format as hexadecimal color codes. - * 'rgb' 'hsb' and 'hsl' return the color formatted in the specified color mode. - * 'rgba' 'hsba' and 'hsla' are the same as above but with alpha channels. - * 'rgb%' 'hsb%' 'hsl%' 'rgba%' 'hsba%' and 'hsla%' format as percentages. - * @return {String} the formatted string - * - * @example - *
      - * - * 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); - * describe('A canvas with 3 text representation of their color.'); - * - *
      - * - *
      - * - * let myColor = color(100, 130, 250); - * text(myColor.toString('#rrggbb'), 25, 25); - * - *
      - */ - _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[3].toString(16)) : a[3].toString(16)); - case '#rgb': - return '#'.concat(Math.round(f[0] * 15).toString(16), Math.round(f[1] * 15).toString(16), Math.round(f[2] * 15).toString(16)); - case '#rgba': - return '#'.concat(Math.round(f[0] * 15).toString(16), Math.round(f[1] * 15).toString(16), Math.round(f[2] * 15).toString(16), Math.round(f[3] * 15).toString(16)); - case 'rgb': - return 'rgb('.concat(a[0], ', ', a[1], ', ', a[2], ')'); - case 'rgb%': - return 'rgb('.concat((100 * f[0]).toPrecision(3), '%, ', (100 * f[1]).toPrecision(3), '%, ', (100 * f[2]).toPrecision(3), '%)'); - case 'rgba%': - return 'rgba('.concat((100 * f[0]).toPrecision(3), '%, ', (100 * f[1]).toPrecision(3), '%, ', (100 * f[2]).toPrecision(3), '%, ', (100 * f[3]).toPrecision(3), '%)'); - case 'hsb': - case 'hsv': - if (!this.hsba) this.hsba = _color_conversion.default._rgbaToHSBA(this._array); - return 'hsb('.concat(this.hsba[0] * this.maxes[constants.HSB][0], ', ', this.hsba[1] * this.maxes[constants.HSB][1], ', ', this.hsba[2] * this.maxes[constants.HSB][2], ')'); - case 'hsb%': - case 'hsv%': - if (!this.hsba) this.hsba = _color_conversion.default._rgbaToHSBA(this._array); - return 'hsb('.concat((100 * this.hsba[0]).toPrecision(3), '%, ', (100 * this.hsba[1]).toPrecision(3), '%, ', (100 * this.hsba[2]).toPrecision(3), '%)'); - case 'hsba': - case 'hsva': - if (!this.hsba) this.hsba = _color_conversion.default._rgbaToHSBA(this._array); - return 'hsba('.concat(this.hsba[0] * this.maxes[constants.HSB][0], ', ', this.hsba[1] * this.maxes[constants.HSB][1], ', ', this.hsba[2] * this.maxes[constants.HSB][2], ', ', alpha, ')'); - case 'hsba%': - case 'hsva%': - if (!this.hsba) this.hsba = _color_conversion.default._rgbaToHSBA(this._array); - return 'hsba('.concat((100 * this.hsba[0]).toPrecision(3), '%, ', (100 * this.hsba[1]).toPrecision(3), '%, ', (100 * this.hsba[2]).toPrecision(3), '%, ', (100 * alpha).toPrecision(3), '%)'); - case 'hsl': - if (!this.hsla) this.hsla = _color_conversion.default._rgbaToHSLA(this._array); - return 'hsl('.concat(this.hsla[0] * this.maxes[constants.HSL][0], ', ', this.hsla[1] * this.maxes[constants.HSL][1], ', ', this.hsla[2] * this.maxes[constants.HSL][2], ')'); - case 'hsl%': - if (!this.hsla) this.hsla = _color_conversion.default._rgbaToHSLA(this._array); - return 'hsl('.concat((100 * this.hsla[0]).toPrecision(3), '%, ', (100 * this.hsla[1]).toPrecision(3), '%, ', (100 * this.hsla[2]).toPrecision(3), '%)'); - case 'hsla': - if (!this.hsla) this.hsla = _color_conversion.default._rgbaToHSLA(this._array); - return 'hsla('.concat(this.hsla[0] * this.maxes[constants.HSL][0], ', ', this.hsla[1] * this.maxes[constants.HSL][1], ', ', this.hsla[2] * this.maxes[constants.HSL][2], ', ', alpha, ')'); - case 'hsla%': - if (!this.hsla) this.hsla = _color_conversion.default._rgbaToHSLA(this._array); - return 'hsl('.concat((100 * this.hsla[0]).toPrecision(3), '%, ', (100 * this.hsla[1]).toPrecision(3), '%, ', (100 * this.hsla[2]).toPrecision(3), '%, ', (100 * alpha).toPrecision(3), '%)'); - case 'rgba': - default: - return 'rgba('.concat(a[0], ',', a[1], ',', a[2], ',', alpha, ')'); - } - }; - /** - * The setRed method 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 - *
      - * - * let backgroundColor; - * - * function setup() { - * backgroundColor = color(100, 50, 150); - * } - * - * function draw() { - * backgroundColor.setRed(128 + 128 * sin(millis() / 1000)); - * background(backgroundColor); - * describe('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 method sets the green component of a color. - * The range depends on your color mode, in the default RGB mode it's between 0 and 255. - * @method setGreen - * @param {Number} green the new green value - * @example - *
      - * - * let backgroundColor = color(100, 50, 150); - * function draw() { - * backgroundColor.setGreen(128 + 128 * sin(millis() / 1000)); - * background(backgroundColor); - * describe('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 method sets the blue component of a color. - * The range depends on your color mode, in the default RGB mode it's between 0 and 255. - * @method setBlue - * @param {Number} blue the new blue value - * @example - *
      - * - * let backgroundColor = color(100, 50, 150); - * function draw() { - * backgroundColor.setBlue(128 + 128 * sin(millis() / 1000)); - * background(backgroundColor); - * describe('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 method sets the transparency (alpha) value of a color. - * The range depends on your color mode, in the default RGB mode it's between 0 and 255. - * @method setAlpha - * @param {Number} alpha the new alpha value - * @example - *
      - * - * 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); - * describe('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); - } // Clear cached HSL/HSB values - - this.hsla = null; - this.hsba = null; - }; - _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); + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); } - 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]; + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); } - }; + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } /** + * @module Color + * @submodule Creating & Reading + * @for p5 + * @requires core + * @requires constants + * @requires color_conversion + */ /** * CSS named colors. */ + var namedColors = { aliceblue: '#f0f8ff', antiquewhite: '#faebd7', @@ -54094,244 +55128,639 @@ '\\)$'].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. + * A class to describe a color. Each `p5.Color` object stores the color mode + * and level maxes that were active during its construction. These values are + * used to interpret the arguments passed to the object's constructor. They + * also determine output formatting such as when + * saturation() is called. * - * @private - * @param {Array} [...args] An 'array-like' object that represents a list of - * arguments - * @return {Number[]} a color formatted as [r, g, b, a] - * Example: - * input ==> output - * g ==> [g, g, g, 255] - * g,a ==> [g, g, g, a] - * r, g, b ==> [r, g, b, 255] - * r, g, b, a ==> [r, g, b, a] - * [g] ==> [g, g, g, 255] - * [g, a] ==> [g, g, g, a] - * [r, g, b] ==> [r, g, b, 255] - * [r, g, b, a] ==> [r, g, b, a] - * @example - *
      - * - * // todo - * // - * // describe(''); - * - *
      - */ - _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); + * Color is stored internally as an array of ideal RGBA values in floating + * point form, normalized from 0 to 1. These values are used to calculate the + * closest screen colors, which are RGBA levels from 0 to 255. Screen colors + * are sent to the renderer. + * + * When different color representations are calculated, the results are cached + * for performance. These values are normalized, floating-point numbers. + * + * color() is the recommended way to create an instance + * of this class. + * + * @class p5.Color + * @constructor + * @param {p5} [pInst] pointer to p5 instance. + * + * @param {Number[]|String} vals an array containing the color values + * for red, green, blue and alpha channel + * or CSS color. + */ + _main.default.Color = /*#__PURE__*/ function () { + function Color(pInst, vals) { + _classCallCheck(this, Color); + // Record color mode and maxes at time of construction. + this._storeModeAndMaxes(pInst._colorMode, pInst._colorMaxes); + // Calculate normalized RGBA values. + if (![constants.RGB, + constants.HSL, + constants.HSB].includes(this.mode)) { + throw new Error(''.concat(this.mode, ' is an invalid colorMode.')); } else { - 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. + this._array = Color._parseInputs.apply(this, vals); + } // Expose closest screen color. - 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; + this._calculateLevels(); + } /** + * Returns the color formatted as a string. Doing so 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 + *
      + * + * createCanvas(200, 100); + * stroke(255); + * const 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); + * describe('Three text representation of a color written sideways.'); + * + *
      + * + *
      + * + * const myColor = color(100, 130, 250); + * text(myColor.toString('#rrggbb'), 25, 25); + * describe('A hexadecimal representation of a color.'); + * + *
      + */ + + _createClass(Color, [ + { + key: 'toString', + value: function toString(format) { + var a = this.levels; + var f = this._array; + var alpha = f[3]; // String representation uses normalized alpha + switch (format) { + case '#rrggbb': + return '#'.concat(a[0] < 16 ? '0'.concat(a[0].toString(16)) : a[0].toString(16), a[1] < 16 ? '0'.concat(a[1].toString(16)) : a[1].toString(16), a[2] < 16 ? '0'.concat(a[2].toString(16)) : a[2].toString(16)); + case '#rrggbbaa': + return '#'.concat(a[0] < 16 ? '0'.concat(a[0].toString(16)) : a[0].toString(16), a[1] < 16 ? '0'.concat(a[1].toString(16)) : a[1].toString(16), a[2] < 16 ? '0'.concat(a[2].toString(16)) : a[2].toString(16), a[3] < 16 ? '0'.concat(a[3].toString(16)) : a[3].toString(16)); + case '#rgb': + return '#'.concat(Math.round(f[0] * 15).toString(16), Math.round(f[1] * 15).toString(16), Math.round(f[2] * 15).toString(16)); + case '#rgba': + return '#'.concat(Math.round(f[0] * 15).toString(16), Math.round(f[1] * 15).toString(16), Math.round(f[2] * 15).toString(16), Math.round(f[3] * 15).toString(16)); + case 'rgb': + return 'rgb('.concat(a[0], ', ', a[1], ', ', a[2], ')'); + case 'rgb%': + return 'rgb('.concat((100 * f[0]).toPrecision(3), '%, ', (100 * f[1]).toPrecision(3), '%, ', (100 * f[2]).toPrecision(3), '%)'); + case 'rgba%': + return 'rgba('.concat((100 * f[0]).toPrecision(3), '%, ', (100 * f[1]).toPrecision(3), '%, ', (100 * f[2]).toPrecision(3), '%, ', (100 * f[3]).toPrecision(3), '%)'); + case 'hsb': + case 'hsv': + if (!this.hsba) this.hsba = _color_conversion.default._rgbaToHSBA(this._array); + return 'hsb('.concat(this.hsba[0] * this.maxes[constants.HSB][0], ', ', this.hsba[1] * this.maxes[constants.HSB][1], ', ', this.hsba[2] * this.maxes[constants.HSB][2], ')'); + case 'hsb%': + case 'hsv%': + if (!this.hsba) this.hsba = _color_conversion.default._rgbaToHSBA(this._array); + return 'hsb('.concat((100 * this.hsba[0]).toPrecision(3), '%, ', (100 * this.hsba[1]).toPrecision(3), '%, ', (100 * this.hsba[2]).toPrecision(3), '%)'); + case 'hsba': + case 'hsva': + if (!this.hsba) this.hsba = _color_conversion.default._rgbaToHSBA(this._array); + return 'hsba('.concat(this.hsba[0] * this.maxes[constants.HSB][0], ', ', this.hsba[1] * this.maxes[constants.HSB][1], ', ', this.hsba[2] * this.maxes[constants.HSB][2], ', ', alpha, ')'); + case 'hsba%': + case 'hsva%': + if (!this.hsba) this.hsba = _color_conversion.default._rgbaToHSBA(this._array); + return 'hsba('.concat((100 * this.hsba[0]).toPrecision(3), '%, ', (100 * this.hsba[1]).toPrecision(3), '%, ', (100 * this.hsba[2]).toPrecision(3), '%, ', (100 * alpha).toPrecision(3), '%)'); + case 'hsl': + if (!this.hsla) this.hsla = _color_conversion.default._rgbaToHSLA(this._array); + return 'hsl('.concat(this.hsla[0] * this.maxes[constants.HSL][0], ', ', this.hsla[1] * this.maxes[constants.HSL][1], ', ', this.hsla[2] * this.maxes[constants.HSL][2], ')'); + case 'hsl%': + if (!this.hsla) this.hsla = _color_conversion.default._rgbaToHSLA(this._array); + return 'hsl('.concat((100 * this.hsla[0]).toPrecision(3), '%, ', (100 * this.hsla[1]).toPrecision(3), '%, ', (100 * this.hsla[2]).toPrecision(3), '%)'); + case 'hsla': + if (!this.hsla) this.hsla = _color_conversion.default._rgbaToHSLA(this._array); + return 'hsla('.concat(this.hsla[0] * this.maxes[constants.HSL][0], ', ', this.hsla[1] * this.maxes[constants.HSL][1], ', ', this.hsla[2] * this.maxes[constants.HSL][2], ', ', alpha, ')'); + case 'hsla%': + if (!this.hsla) this.hsla = _color_conversion.default._rgbaToHSLA(this._array); + return 'hsl('.concat((100 * this.hsla[0]).toPrecision(3), '%, ', (100 * this.hsla[1]).toPrecision(3), '%, ', (100 * this.hsla[2]).toPrecision(3), '%, ', (100 * alpha).toPrecision(3), '%)'); + case 'rgba': + default: + return 'rgba('.concat(a[0], ',', a[1], ',', a[2], ',', alpha, ')'); } - 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); + } /** + * Sets the red component of a color. The range depends on the + * colorMode(). In the default RGB mode it's + * between 0 and 255. + * + * @method setRed + * @param {Number} red the new red value. + * + * @example + *
      + * + * let backgroundColor; + * + * function setup() { + * backgroundColor = color(100, 50, 150); + * } + * + * function draw() { + * backgroundColor.setRed(128 + 128 * sin(millis() / 1000)); + * background(backgroundColor); + * describe('A canvas with a gradually changing background color.'); + * } + * + *
      + */ + + }, + { + key: 'setRed', + value: function setRed(new_red) { + this._array[0] = new_red / this.maxes[constants.RGB][0]; + this._calculateLevels(); + } /** + * Sets the green component of a color. The range depends on the + * colorMode(). In the default RGB mode it's + * between 0 and 255. + * + * @method setGreen + * @param {Number} green the new green value. + * + * @example + *
      + * + * let backgroundColor; + * + * function setup() { + * backgroundColor = color(100, 50, 150); + * } + * + * function draw() { + * backgroundColor.setGreen(128 + 128 * sin(millis() / 1000)); + * background(backgroundColor); + * describe('A canvas with a gradually changing background color.'); + * } + * + *
      + **/ + + }, + { + key: 'setGreen', + value: function setGreen(new_green) { + this._array[1] = new_green / this.maxes[constants.RGB][1]; + this._calculateLevels(); + } /** + * Sets the blue component of a color. The range depends on the + * colorMode(). In the default RGB mode it's + * between 0 and 255. + * + * @method setBlue + * @param {Number} blue the new blue value. + * + * @example + *
      + * + * let backgroundColor; + * + * function setup() { + * backgroundColor = color(100, 50, 150); + * } + * + * function draw() { + * backgroundColor.setBlue(128 + 128 * sin(millis() / 1000)); + * background(backgroundColor); + * describe('A canvas with a gradually changing background color.'); + * } + * + *
      + **/ + + }, + { + key: 'setBlue', + value: function setBlue(new_blue) { + this._array[2] = new_blue / this.maxes[constants.RGB][2]; + this._calculateLevels(); + } /** + * Sets the alpha (transparency) value of a color. The range depends on the + * colorMode(). In the default RGB mode it's + * between 0 and 255. + * + * @method setAlpha + * @param {Number} alpha the new alpha value. + * + * @example + *
      + * + * function draw() { + * clear(); + * background(200); + * const squareColor = color(100, 50, 100); + * squareColor.setAlpha(128 + 128 * sin(millis() / 1000)); + * fill(squareColor); + * rect(13, 13, width - 26, height - 26); + * describe( + * 'A purple square with gradually changing opacity drawn on a gray background.' + * ); + * } + * + *
      + **/ + + }, + { + key: 'setAlpha', + value: function setAlpha(new_alpha) { + this._array[3] = new_alpha / this.maxes[this.mode][3]; + this._calculateLevels(); + } // calculates and stores the closest screen levels + + }, + { + key: '_calculateLevels', + value: function _calculateLevels() { + var array = this._array; + // (loop backwards for performance) + var levels = this.levels = new Array(array.length); + for (var i = array.length - 1; i >= 0; --i) { + levels[i] = Math.round(array[i] * 255); + } // Clear cached HSL/HSB values + + this.hsla = null; + this.hsba = null; + } + }, + { + key: '_getAlpha', + value: function _getAlpha() { + return this._array[3] * this.maxes[this.mode][3]; + } // stores the color mode and maxes in this instance of Color + // for later use (by _parseInputs()) + + }, + { + key: '_storeModeAndMaxes', + value: function _storeModeAndMaxes(new_mode, new_maxes) { + this.mode = new_mode; + this.maxes = new_maxes; + } + }, + { + key: '_getMode', + value: function _getMode() { + return this.mode; + } + }, + { + key: '_getMaxes', + value: function _getMaxes() { + return this.maxes; + } + }, + { + key: '_getBlue', + value: function _getBlue() { + return this._array[2] * this.maxes[constants.RGB][2]; + } + }, + { + key: '_getBrightness', + value: function _getBrightness() { + if (!this.hsba) { + this.hsba = _color_conversion.default._rgbaToHSBA(this._array); } - return 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. + return this.hsba[2] * this.maxes[constants.HSB][2]; + } + }, + { + key: '_getGreen', + value: function _getGreen() { + return this._array[1] * this.maxes[constants.RGB][1]; + } /** + * Hue is the same in HSB and HSL, but the maximum value may be different. + * This function will return the HSB-normalized saturation when supplied with + * an HSB color object, but will default to the HSL-normalized saturation + * otherwise. + */ - 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; + }, + { + key: '_getHue', + value: function _getHue() { + if (this.mode === constants.HSB) { + if (!this.hsba) { + this.hsba = _color_conversion.default._rgbaToHSBA(this._array); + } + return this.hsba[0] * this.maxes[constants.HSB][0]; + } else { + if (!this.hsla) { + this.hsla = _color_conversion.default._rgbaToHSLA(this._array); + } + return this.hsla[0] * this.maxes[constants.HSL][0]; } - 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); + } + }, + { + key: '_getLightness', + value: function _getLightness() { + if (!this.hsla) { + this.hsla = _color_conversion.default._rgbaToHSLA(this._array); } - 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 this.hsla[2] * this.maxes[constants.HSL][2]; } - 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. + }, + { + key: '_getRed', + value: function _getRed() { + return this._array[0] * this.maxes[constants.RGB][0]; + } /** + * Saturation is scaled differently in HSB and HSL. This function will return + * the HSB saturation when supplied with an HSB color object, but will default + * to the HSL saturation otherwise. */ - 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; - }; + }, + { + key: '_getSaturation', + value: function _getSaturation() { + if (this.mode === constants.HSB) { + if (!this.hsba) { + this.hsba = _color_conversion.default._rgbaToHSBA(this._array); + } + return this.hsba[1] * this.maxes[constants.HSB][1]; + } else { + if (!this.hsla) { + this.hsla = _color_conversion.default._rgbaToHSLA(this._array); + } + return this.hsla[1] * this.maxes[constants.HSL][1]; + } + } /** + * For a number of different inputs, returns a color formatted as [r, g, b, a] + * arrays, with each component normalized between 0 and 1. + * + * @private + * @param {Array} [...args] An 'array-like' object that represents a list of + * arguments + * @return {Number[]} a color formatted as [r, g, b, a] + * Example: + * input ==> output + * g ==> [g, g, g, 255] + * g,a ==> [g, g, g, a] + * r, g, b ==> [r, g, b, 255] + * r, g, b, a ==> [r, g, b, a] + * [g] ==> [g, g, g, 255] + * [g, a] ==> [g, g, g, a] + * [r, g, b] ==> [r, g, b, 255] + * [r, g, b, a] ==> [r, g, b, a] + * @example + *
      + * + * // todo + * // + * // describe(''); + * + *
      + */ + + } + ], [ + { + key: '_parseInputs', + value: function _parseInputs(r, g, b, a) { + var numArgs = arguments.length; + var mode = this.mode; + var maxes = this.maxes[mode]; + var results = [ + ]; + var i; + if (numArgs >= 3) { + // Argument is a list of component values. + results[0] = r / maxes[0]; + results[1] = g / maxes[1]; + results[2] = b / maxes[2]; + // Alpha may be undefined, so default it to 100%. + if (typeof a === 'number') { + results[3] = a / maxes[3]; + } else { + results[3] = 1; + } // Constrain components to the range [0,1]. + // (loop backwards for performance) + + for (i = results.length - 1; i >= 0; --i) { + var result = results[i]; + if (result < 0) { + results[i] = 0; + } else if (result > 1) { + results[i] = 1; + } + } // Convert to RGBA and return. + + if (mode === constants.HSL) { + return _color_conversion.default._hslaToRGBA(results); + } else if (mode === constants.HSB) { + return _color_conversion.default._hsbaToRGBA(results); + } else { + return results; + } + } else if (numArgs === 1 && typeof r === 'string') { + var str = r.trim().toLowerCase(); + // Return if string is a named colour. + if (namedColors[str]) { + return Color._parseInputs.call(this, namedColors[str]); + } // Try RGBA pattern matching. + + if (colorPatterns.HEX3.test(str)) { + // #rgb + results = colorPatterns.HEX3.exec(str).slice(1).map(function (color) { + return parseInt(color + color, 16) / 255; + }); + results[3] = 1; + return results; + } else if (colorPatterns.HEX6.test(str)) { + // #rrggbb + results = colorPatterns.HEX6.exec(str).slice(1).map(function (color) { + return parseInt(color, 16) / 255; + }); + results[3] = 1; + return results; + } else if (colorPatterns.HEX4.test(str)) { + // #rgba + results = colorPatterns.HEX4.exec(str).slice(1).map(function (color) { + return parseInt(color + color, 16) / 255; + }); + return results; + } else if (colorPatterns.HEX8.test(str)) { + // #rrggbbaa + results = colorPatterns.HEX8.exec(str).slice(1).map(function (color) { + return parseInt(color, 16) / 255; + }); + return results; + } else if (colorPatterns.RGB.test(str)) { + // rgb(R,G,B) + results = colorPatterns.RGB.exec(str).slice(1).map(function (color) { + return color / 255; + }); + results[3] = 1; + return results; + } else if (colorPatterns.RGB_PERCENT.test(str)) { + // rgb(R%,G%,B%) + results = colorPatterns.RGB_PERCENT.exec(str).slice(1).map(function (color) { + return parseFloat(color) / 100; + }); + results[3] = 1; + return results; + } else if (colorPatterns.RGBA.test(str)) { + // rgba(R,G,B,A) + results = colorPatterns.RGBA.exec(str).slice(1).map(function (color, idx) { + if (idx === 3) { + return parseFloat(color); + } + return color / 255; + }); + return results; + } else if (colorPatterns.RGBA_PERCENT.test(str)) { + // rgba(R%,G%,B%,A%) + results = colorPatterns.RGBA_PERCENT.exec(str).slice(1).map(function (color, idx) { + if (idx === 3) { + return parseFloat(color); + } + return parseFloat(color) / 100; + }); + return results; + } // Try HSLA pattern matching. + + if (colorPatterns.HSL.test(str)) { + // hsl(H,S,L) + results = colorPatterns.HSL.exec(str).slice(1).map(function (color, idx) { + if (idx === 0) { + return parseInt(color, 10) / 360; + } + return parseInt(color, 10) / 100; + }); + results[3] = 1; + } else if (colorPatterns.HSLA.test(str)) { + // hsla(H,S,L,A) + results = colorPatterns.HSLA.exec(str).slice(1).map(function (color, idx) { + if (idx === 0) { + return parseInt(color, 10) / 360; + } else if (idx === 3) { + return parseFloat(color); + } + return parseInt(color, 10) / 100; + }); + } + results = results.map(function (value) { + return Math.max(Math.min(value, 1), 0); + }); + if (results.length) { + return _color_conversion.default._hslaToRGBA(results); + } // Try HSBA pattern matching. + + if (colorPatterns.HSB.test(str)) { + // hsb(H,S,B) + results = colorPatterns.HSB.exec(str).slice(1).map(function (color, idx) { + if (idx === 0) { + return parseInt(color, 10) / 360; + } + return parseInt(color, 10) / 100; + }); + results[3] = 1; + } else if (colorPatterns.HSBA.test(str)) { + // hsba(H,S,B,A) + results = colorPatterns.HSBA.exec(str).slice(1).map(function (color, idx) { + if (idx === 0) { + return parseInt(color, 10) / 360; + } else if (idx === 3) { + return parseFloat(color); + } + return parseInt(color, 10) / 100; + }); + } + if (results.length) { + // (loop backwards for performance) + for (i = results.length - 1; i >= 0; --i) { + results[i] = Math.max(Math.min(results[i], 1), 0); + } + return _color_conversion.default._hsbaToRGBA(results); + } // Input did not match any CSS color pattern: default to white. + + results = [ + 1, + 1, + 1, + 1 + ]; + } else if ((numArgs === 1 || numArgs === 2) && typeof r === 'number') { + // 'Grayscale' mode. + /** + * For HSB and HSL, interpret the gray level as a brightness/lightness + * value (they are equivalent when chroma is zero). For RGB, normalize the + * gray level according to the blue maximum. + */ + results[0] = r / maxes[2]; + results[1] = r / maxes[2]; + results[2] = r / maxes[2]; + // Alpha may be undefined, so default it to 100%. + if (typeof g === 'number') { + results[3] = g / maxes[3]; + } else { + results[3] = 1; + } // Constrain components to the range [0,1]. + + results = results.map(function (value) { + return Math.max(Math.min(value, 1), 0); + }); + } else { + throw new Error(''.concat(arguments, 'is not a valid color representation.')); + } + return results; + } + } + ]); + return Color; + }(); var _default = _main.default.Color; exports.default = _default; }, { - '../core/constants': 278, - '../core/main': 290, - './color_conversion': 274, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.join': 177, - 'core-js/modules/es.array.map': 179, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.constructor': 198, - 'core-js/modules/es.regexp.exec': 199, - 'core-js/modules/es.regexp.to-string': 200, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.string.trim': 211, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + '../core/constants': 286, + '../core/main': 298, + './color_conversion': 282, + 'core-js/modules/es.array.includes': 177, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.join': 180, + 'core-js/modules/es.array.map': 182, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.constructor': 204, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.includes': 209, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.string.trim': 219, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 277: [ + 285: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -54430,25 +55859,229 @@ * @requires constants */ /** - * The background() function sets the color used - * for the background of the p5.js canvas. The default background is transparent. - * This function is typically used within draw() to clear - * the display window at the beginning of each frame, but it can be used inside - * setup() to set the background on the first frame of - * animation or if the background need only be set once. + * Start defining a shape that will mask subsequent things drawn to the canvas. + * Only opaque regions of the mask shape will allow content to be drawn. + * Any shapes drawn between this and endClip() will + * contribute to the mask shape. + * + * The mask will apply to anything drawn after this call. To draw without a mask, contain + * the code to apply the mask and to draw the masked content between + * push() and pop(). + * + * Alternatively, rather than drawing the mask between this and + * endClip(), draw the mask in a callback function + * passed to clip(). + * + * Options can include: + * - `invert`: A boolean specifying whether or not to mask the areas *not* filled by the mask shape. Defaults to false. + * + * @method beginClip + * @param {Object} [options] An object containing clip settings. + * + * @example + *
      + * + * noStroke(); + * + * // Mask in some shapes + * push(); + * beginClip(); + * triangle(15, 37, 30, 13, 43, 37); + * circle(45, 45, 7); + * endClip(); + * + * fill('red'); + * rect(5, 5, 45, 45); + * pop(); + * + * translate(50, 50); + * + * // Mask out the same shapes + * push(); + * beginClip({ invert: true }); + * triangle(15, 37, 30, 13, 43, 37); + * circle(45, 45, 7); + * endClip(); + * + * fill('red'); + * rect(5, 5, 45, 45); + * pop(); + * + *
      + * + * @alt + * In the top left, a red triangle and circle. In the bottom right, a red + * square with a triangle and circle cut out of it. + * + * @example + *
      + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * } + * + * function draw() { + * background(255); + * noStroke(); + * + * beginClip(); + * push(); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * scale(0.5); + * torus(30, 15); + * pop(); + * endClip(); + * + * beginShape(QUAD_STRIP); + * fill(0, 255, 255); + * vertex(-width/2, -height/2); + * vertex(width/2, -height/2); + * fill(100, 0, 100); + * vertex(-width/2, height/2); + * vertex(width/2, height/2); + * endShape(); + * } + * + *
      + * + * @alt + * A silhouette of a rotating torus colored with a gradient from + * cyan to purple + */ + + _main.default.prototype.beginClip = function () { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { + }; + this._renderer.beginClip(options); + }; + /** + * Finishes defining a shape that will mask subsequent things drawn to the canvas. + * Only opaque regions of the mask shape will allow content to be drawn. + * Any shapes drawn between beginClip() and this + * will contribute to the mask shape. + * + * @method endClip + */ + _main.default.prototype.endClip = function () { + this._renderer.endClip(); + }; + /** + * Use the shape drawn by a callback function to mask subsequent things drawn to the canvas. + * Only opaque regions of the mask shape will allow content to be drawn. + * + * The mask will apply to anything drawn after this call. To draw without a mask, contain + * the code to apply the mask and to draw the masked content between + * push() and pop(). + * + * Alternatively, rather than drawing the mask shape in a function, draw the + * shape between beginClip() and endClip(). + * + * Options can include: + * - `invert`: A boolean specifying whether or not to mask the areas *not* filled by the mask shape. Defaults to false. + * + * @method clip + * @param {Function} callback A function that draws the mask shape. + * @param {Object} [options] An object containing clip settings. + * + * @example + *
      + * + * noStroke(); + * + * // Mask in some shapes + * push(); + * clip(() => { + * triangle(15, 37, 30, 13, 43, 37); + * circle(45, 45, 7); + * }); + * + * fill('red'); + * rect(5, 5, 45, 45); + * pop(); + * + * translate(50, 50); + * + * // Mask out the same shapes + * push(); + * clip(() => { + * triangle(15, 37, 30, 13, 43, 37); + * circle(45, 45, 7); + * }, { invert: true }); + * + * fill('red'); + * rect(5, 5, 45, 45); + * pop(); + * + *
      + * + * @alt + * In the top left, a red triangle and circle. In the bottom right, a red + * square with a triangle and circle cut out of it. + * + * @example + *
      + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * } + * + * function draw() { + * background(255); + * noStroke(); + * + * clip(() => { + * push(); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * scale(0.5); + * torus(30, 15); + * pop(); + * }); + * + * beginShape(QUAD_STRIP); + * fill(0, 255, 255); + * vertex(-width/2, -height/2); + * vertex(width/2, -height/2); + * fill(100, 0, 100); + * vertex(-width/2, height/2); + * vertex(width/2, height/2); + * endShape(); + * } + * + *
      * - * The color is either specified in terms of the RGB, HSB, or HSL color depending - * on the current colorMode. (The default color space - * is RGB, with each value in the range from 0 to 255). The alpha range by default - * is also 0 to 255.

      + * @alt + * A silhouette of a rotating torus colored with a gradient from + * cyan to purple + */ + _main.default.prototype.clip = function (callback, options) { + this._renderer.beginClip(options); + callback(); + this._renderer.endClip(options); + }; + /** + * Sets the color used for the background of the canvas. By default, the + * background is transparent. This function is typically used within + * draw() to clear the display window at the beginning + * of each frame. It can also be used inside setup() to + * set the background on the first frame of animation. * - * 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. + * The version of `background()` with one parameter interprets the value one of four + * ways. If the parameter is a number, it's interpreted as a grayscale value. + * If the parameter is a string, it's interpreted as a CSS color string. RGB, RGBA, + * HSL, HSLA, hex, and named color strings are supported. If the parameter is a + * p5.Color object, it will be used as the background color. + * If the parameter is a p5.Image object, it will be used as + * the background image. * - * A p5.Color object can also be provided to set the background color. + * The version of `background()` with two parameters interprets the first one as a + * grayscale value. The second parameter sets the alpha (transparency) value. * - * A p5.Image can also be provided to set the background image. + * The version of `background()` with three parameters interprets them as RGB, HSB, + * or HSL colors, depending on the current colorMode(). + * By default, colors are specified in RGB values. Calling background(255, 204, 0) + * sets the background a bright yellow color. * * @method background * @param {p5.Color} color any value created by the color() function @@ -54457,90 +56090,99 @@ * @example *
      * - * // Grayscale integer value + * // A grayscale integer value. * background(51); - * describe('canvas with darkest charcoal grey background'); + * describe('A canvas with a dark charcoal gray background.'); + * + *
      + * + *
      + * + * // A grayscale integer value and an alpha value. + * background(51, 0.4); + * describe('A canvas with a transparent gray background.'); * *
      * *
      * - * // R, G & B integer values + * // R, G & B integer values. * background(255, 204, 0); - * describe('canvas with yellow background'); + * describe('A canvas with a yellow background.'); * *
      * *
      * - * // H, S & B integer values + * // H, S & B integer values. * colorMode(HSB); * background(255, 204, 100); - * describe('canvas with royal blue background'); + * describe('A canvas with a royal blue background.'); * *
      * *
      * - * // Named SVG/CSS color string + * // A CSS named color. * background('red'); - * describe('canvas with red background'); + * describe('A canvas with a red background.'); * *
      * *
      * - * // three-digit hexadecimal RGB notation + * // Three-digit hex RGB notation. * background('#fae'); - * describe('canvas with pink background'); + * describe('A canvas with a pink background.'); * *
      * *
      * - * // six-digit hexadecimal RGB notation + * // Six-digit hex RGB notation. * background('#222222'); - * describe('canvas with black background'); + * describe('A canvas with a black background.'); * *
      * *
      * - * // integer RGB notation + * // Integer RGB notation. * background('rgb(0,255,0)'); - * describe('canvas with bright green background'); + * describe('A canvas with a bright green background.'); * *
      * *
      * - * // integer RGBA notation + * // Integer RGBA notation. * background('rgba(0,255,0, 0.25)'); - * describe('canvas with soft green background'); + * describe('A canvas with a transparent green background.'); * *
      * *
      * - * // percentage RGB notation + * // Percentage RGB notation. * background('rgb(100%,0%,10%)'); - * describe('canvas with red background'); + * describe('A canvas with a red background.'); * *
      * *
      * - * // percentage RGBA notation + * // Percentage RGBA notation. * background('rgba(100%,0%,100%,0.5)'); - * describe('canvas with light purple background'); + * describe('A canvas with a transparent purple background.'); * *
      * *
      * - * // p5 Color object - * background(color(0, 0, 255)); - * describe('canvas with blue background'); + * // A p5.Color object. + * let c = color(0, 0, 255); + * background(c); + * describe('A canvas with a blue background.'); * *
      * @@ -54549,87 +56191,103 @@ * @method background * @param {String} colorstring color string, possible formats include: integer * rgb() or rgba(), percentage rgb() or rgba(), - * 3-digit hex, 6-digit hex + * 3-digit hex, 6-digit hex. * @param {Number} [a] opacity of the background relative to current - * color range (default is 0-255) + * color range (default is 0-255). * @chainable */ /** * @method background - * @param {Number} gray specifies a value between white and black + * @param {Number} gray specifies a value between white and black. * @param {Number} [a] * @chainable */ /** * @method background - * @param {Number} v1 red or hue value (depending on the current color - * mode) - * @param {Number} v2 green or saturation value (depending on the current - * color mode) - * @param {Number} v3 blue or brightness value (depending on the current - * color mode) + * @param {Number} v1 red value if color mode is RGB, or hue value if color mode is HSB. + * @param {Number} v2 green value if color mode is RGB, or saturation value if color mode is HSB. + * @param {Number} v3 blue value if color mode is RGB, or brightness value if color mode is HSB. * @param {Number} [a] * @chainable */ /** * @method background * @param {Number[]} values an array containing the red, green, blue - * and alpha components of the color + * and alpha components of the color. * @chainable */ /** * @method background - * @param {p5.Image} image image created with loadImage() or createImage(), - * to set as background - * (must be same size as the sketch window) + * @param {p5.Image} image image created with loadImage() + * or createImage(), + * to set as background. + * (must be same size as the sketch window). * @param {Number} [a] * @chainable */ - _main.default.prototype.background = function () { var _this$_renderer; (_this$_renderer = this._renderer).background.apply(_this$_renderer, arguments); return this; }; /** - * Clears the pixels within a buffer. This function only clears the canvas. - * It will not clear objects created by createX() methods such as - * createVideo() or createDiv(). - * Unlike the main graphics context, pixels in additional graphics areas created - * with createGraphics() can be entirely - * or partially transparent. This function clears everything to make all of - * the pixels 100% transparent. + * Clears the pixels on the canvas. This function makes every pixel 100% + * transparent. Calling `clear()` doesn't clear objects created by `createX()` + * functions such as createGraphics(), + * createVideo(), and + * createImg(). These objects will remain + * unchanged after calling clear() and can be redrawn. * - * Note: In WebGL mode, this function can be passed normalized RGBA color values in - * order to clear the screen to a specific color. In addition to color, it will also - * clear the depth buffer. If you are not using the webGL renderer - * these color values will have no effect. + * In WebGL mode, this function can clear the screen to a specific color. It + * interprets four numeric parameters as normalized RGBA color values. It also + * clears the depth buffer. If you are not using the WebGL renderer, these + * parameters will have no effect. * * @method clear * @chainable * @example *
      * - * // Clear the screen on mouse press. * function draw() { - * ellipse(mouseX, mouseY, 20, 20); - * describe(`small white ellipses are continually drawn at mouse’s x and y - * coordinates.`); + * circle(mouseX, mouseY, 20); + * describe('A white circle is drawn at the mouse x- and y-coordinates.'); * } + * * function mousePressed() { * clear(); * background(128); - * describe( - * 'canvas is cleared, small white ellipse is drawn at mouse X and mouse Y' - * ); + * describe('The canvas is cleared when the mouse is clicked.'); + * } + * + *
      + * + *
      + * + * let pg; + * + * function setup() { + * createCanvas(100, 100); + * background(200); + * + * pg = createGraphics(60, 60); + * pg.background(200); + * pg.noStroke(); + * pg.circle(pg.width / 2, pg.height / 2, 15); + * image(pg, 20, 20); + * describe('A white circle drawn on a gray square. The square gets smaller when the mouse is pressed.'); + * } + * + * function mousePressed() { + * clear(); + * image(pg, 20, 20); * } * *
      * - * @param {Number} r normalized red val. - * @param {Number} g normalized green val. - * @param {Number} b normalized blue val. - * @param {Number} a normalized alpha val. + * @param {Number} r normalized red value. + * @param {Number} g normalized green value. + * @param {Number} b normalized blue value. + * @param {Number} a normalized alpha value. */ _main.default.prototype.clear = function () { var _r = (arguments.length <= 0 ? undefined : arguments[0]) || 0; @@ -54640,22 +56298,28 @@ return this; }; /** - * colorMode() changes the way p5.js interprets - * color data. By default, the parameters for fill(), - * stroke(), background(), - * and color() are defined by values between 0 and 255 - * using the RGB color model. This is equivalent to setting colorMode(RGB, 255). - * Setting colorMode(HSB) lets you use the HSB system instead. By default, this - * is colorMode(HSB, 360, 100, 100, 1). You can also use HSL. + * Changes the way p5.js interprets color data. By default, the numeric + * parameters for fill(), + * stroke(), + * background(), and + * color() are defined by values between 0 and 255 + * using the RGB color model. This is equivalent to calling + * `colorMode(RGB, 255)`. Pure red is `color(255, 0, 0)` in this model. * - * Note: existing color objects remember the mode that they were created in, - * so you can change modes as you like without affecting their appearance. + * Calling `colorMode(RGB, 100)` sets colors to be interpreted as RGB color + * values between 0 and 100. Pure red is `color(100, 0, 0)` in this model. + * + * Calling `colorMode(HSB)` or `colorMode(HSL)` changes to HSB or HSL system + * instead of RGB. + * + * p5.Color objects remember the mode that they were + * created in. Changing modes doesn't affect their appearance. * * @method colorMode * @param {Constant} mode either RGB, HSB or HSL, corresponding to * Red/Green/Blue and Hue/Saturation/Brightness - * (or Lightness) - * @param {Number} [max] range for all values + * (or Lightness). + * @param {Number} [max] range for all values. * @chainable * * @example @@ -54663,14 +56327,14 @@ * * noStroke(); * colorMode(RGB, 100); - * for (let i = 0; i < 100; i++) { - * for (let j = 0; j < 100; j++) { + * for (let i = 0; i < 100; i += 1) { + * for (let j = 0; j < 100; j += 1) { * stroke(i, j, 0); * point(i, j); * } * } * describe( - * 'Green to red gradient from bottom left to top right with shading from top left' + * 'A diagonal green to red gradient from bottom-left to top-right with shading transitioning to black at top-left corner.' * ); * * @@ -54685,19 +56349,23 @@ * point(i, j); * } * } - * describe(`Rainbow gradient from left to right. - * Brightness increasing to white at top.`); + * describe('A rainbow gradient from left-to-right. Brightness transitions to white at the top.'); * * * *
      * * colorMode(RGB, 255); - * let c = color(127, 255, 0); + * let myColor = color(180, 175, 230); + * background(myColor); * colorMode(RGB, 1); - * let myColor = c._getRed(); - * text(myColor, 10, 10, 80, 80); - * describe('value of color red 0.4980... written on canvas'); + * let redValue = red(myColor); + * let greenValue = green(myColor); + * let blueValue = blue(myColor); + * text(`Red: ${redValue}`, 10, 10, 80, 80); + * text(`Green: ${greenValue}`, 10, 40, 80, 80); + * text(`Blue: ${blueValue}`, 10, 70, 80, 80); + * describe('A purple canvas with the red, green, and blue decimal values of the color written on it.'); * *
      * @@ -54708,9 +56376,9 @@ * background(255); * strokeWeight(4); * stroke(255, 0, 10, 0.3); - * ellipse(40, 40, 50, 50); - * ellipse(50, 50, 40, 40); - * describe('two translucent pink ellipse outlines at middle left and at center'); + * circle(40, 40, 50); + * circle(50, 60, 50); + * describe('Two overlapping translucent pink circle outlines.'); * * * @@ -54719,19 +56387,20 @@ * @method colorMode * @param {Constant} mode * @param {Number} max1 range for the red or hue depending on the - * current color mode + * current color mode. * @param {Number} max2 range for the green or saturation depending - * on the current color mode + * 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 + * 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. + this._colorMode = mode; + // Set color maxes. var maxes = this._colorMaxes[mode]; if (arguments.length === 2) { maxes[0] = max1; // Red @@ -54752,149 +56421,149 @@ return this; }; /** - * Sets the color used to fill shapes. For example, if you run fill(204, 102, 0), - * all shapes drawn after the fill command will be filled with the color orange. - * This color is either specified in terms of the RGB or HSB color depending on - * the current colorMode(). (The default color space - * is RGB, with each value in the range from 0 to 255). The alpha range by default - * is also 0 to 255. + * Sets the color used to fill shapes. Calling `fill(255, 165, 0)` or + * `fill('orange')` means all shapes drawn after the fill command will be + * filled with the color orange. * - * 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. + * The version of `fill()` with one parameter interprets the value one of + * three ways. If the parameter is a number, it's interpreted as a grayscale + * value. If the parameter is a string, it's interpreted as a CSS color + * string. A p5.Color object can also be provided to + * set the fill color. * - * A p5.Color object can also be provided to set the fill color. + * The version of `fill()` with three parameters interprets them as RGB, HSB, + * or HSL colors, depending on the current + * colorMode(). The default color space is RGB, + * with each value in the range from 0 to 255. * * @method fill - * @param {Number} v1 red 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} v1 red value if color mode is RGB or hue value if color mode is HSB. + * @param {Number} v2 green value if color mode is RGB or saturation value if color mode is HSB. + * @param {Number} v3 blue value if color mode is RGB or brightness value if color mode is HSB. * @param {Number} [alpha] * @chainable * @example *
      * - * // Grayscale integer value + * // Grayscale integer value. * fill(51); - * rect(20, 20, 60, 60); - * describe('dark charcoal grey rect with black outline in center of canvas'); + * square(20, 20, 60); + * describe('A dark charcoal gray square with a black outline.'); * *
      * *
      * - * // R, G & B integer values + * // R, G & B integer values. * fill(255, 204, 0); - * rect(20, 20, 60, 60); - * describe('yellow rect with black outline in center of canvas'); + * square(20, 20, 60); + * describe('A yellow square with a black outline.'); * *
      * *
      * - * // H, S & B integer values + * // H, S & B integer values. * colorMode(HSB); * fill(255, 204, 100); - * rect(20, 20, 60, 60); - * describe('royal blue rect with black outline in center of canvas'); + * square(20, 20, 60); + * describe('A royal blue square with a black outline.'); * *
      * *
      * - * // Named SVG/CSS color string + * // A CSS named color. * fill('red'); - * rect(20, 20, 60, 60); - * describe('red rect with black outline in center of canvas'); + * square(20, 20, 60); + * describe('A red square with a black outline.'); * *
      * *
      * - * // three-digit hexadecimal RGB notation + * // Three-digit hex RGB notation. * fill('#fae'); - * rect(20, 20, 60, 60); - * describe('pink rect with black outline in center of canvas'); + * square(20, 20, 60); + * describe('A pink square with a black outline.'); * *
      * *
      * - * // six-digit hexadecimal RGB notation - * fill('#222222'); - * rect(20, 20, 60, 60); - * describe('black rect with black outline in center of canvas'); + * // Six-digit hex RGB notation. + * fill('#A251FA'); + * square(20, 20, 60); + * describe('A purple square with a black outline.'); * *
      * *
      * - * // integer RGB notation + * // Integer RGB notation. * fill('rgb(0,255,0)'); - * rect(20, 20, 60, 60); - * describe('bright green rect with black outline in center of canvas'); + * square(20, 20, 60); + * describe('A bright green square with a black outline.'); * *
      * *
      * - * // integer RGBA notation + * // Integer RGBA notation. * fill('rgba(0,255,0, 0.25)'); - * rect(20, 20, 60, 60); - * describe('soft green rect with black outline in center of canvas'); + * square(20, 20, 60); + * describe('A soft green rectange with a black outline.'); * *
      * *
      * - * // percentage RGB notation + * // Percentage RGB notation. * fill('rgb(100%,0%,10%)'); - * rect(20, 20, 60, 60); - * describe('red rect with black outline in center of canvas'); + * square(20, 20, 60); + * describe('A red square with a black outline.'); * *
      * *
      * - * // percentage RGBA notation + * // Percentage RGBA notation. * fill('rgba(100%,0%,100%,0.5)'); - * rect(20, 20, 60, 60); - * describe('dark fuchsia rect with black outline in center of canvas'); + * square(20, 20, 60); + * describe('A dark fuchsia square with a black outline.'); * *
      * *
      * - * // p5 Color object - * fill(color(0, 0, 255)); - * rect(20, 20, 60, 60); - * describe('blue rect with black outline in center of canvas'); + * // p5.Color object. + * let c = color(0, 0, 255); + * fill(c); + * square(20, 20, 60); + * describe('A blue square with a black outline.'); * *
      */ /** * @method fill - * @param {String} value a color string + * @param {String} value a color string. * @chainable */ /** * @method fill - * @param {Number} gray a gray value + * @param {Number} gray a grayscale value. * @param {Number} [alpha] * @chainable */ /** * @method fill - * @param {Number[]} values an array containing the red,green,blue & - * and alpha components of the color + * @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 + * @param {p5.Color} color the fill color. * @chainable */ _main.default.prototype.fill = function () { @@ -54905,19 +56574,21 @@ return this; }; /** - * Disables filling geometry. If both noStroke() and noFill() are called, - * nothing will be drawn to the screen. + * Disables setting the interior color of shapes. This is the same as making + * the fill completely transparent. If both + * noStroke() and + * noFill() are called, nothing will be drawn to the + * screen. * * @method noFill * @chainable * @example *
      * - * rect(15, 10, 55, 55); + * square(32, 10, 35); * noFill(); - * rect(20, 20, 60, 60); - * describe(`White rect at top middle and noFill rect center, - * both with black outlines.`); + * square(32, 55, 35); + * describe('A white square on top of an empty square. Both squares have black outlines.'); * *
      * @@ -54934,7 +56605,7 @@ * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * box(45, 45, 45); - * describe('black canvas with purple cube wireframe spinning'); + * describe('A purple cube wireframe spinning on a black canvas.'); * } * * @@ -54944,8 +56615,10 @@ return this; }; /** - * Disables drawing the stroke (outline). If both noStroke() and noFill() - * are called, nothing will be drawn to the screen. + * Disables drawing the stroke (outline). If both + * noStroke() and + * noFill() are called, nothing will be drawn to the + * screen. * * @method noStroke * @chainable @@ -54953,8 +56626,8 @@ *
      * * noStroke(); - * rect(20, 20, 60, 60); - * describe('White rect at center; no outline.'); + * square(20, 20, 60); + * describe('A white square with no outline.'); * *
      * @@ -54971,7 +56644,7 @@ * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * box(45, 45, 45); - * describe('black canvas with pink cube spinning'); + * describe('A pink cube with no edge outlines spinning on a black canvas.'); * } * * @@ -54981,161 +56654,167 @@ return this; }; /** - * Sets the color used to draw lines and borders around shapes. This color - * is either specified in terms of the RGB or HSB color depending on the - * current colorMode() (the default color space - * is RGB, with each value in the range from 0 to 255). The alpha range by - * default is also 0 to 255. + * Sets the color used to draw lines and borders around shapes. Calling + * `stroke(255, 165, 0)` or `stroke('orange')` means all shapes drawn after + * the `stroke()` command will be filled with the color orange. The way these + * parameters are interpreted may be changed with the + * colorMode() function. + * + * The version of `stroke()` with one parameter interprets the value one of + * three ways. If the parameter is a number, it's interpreted as a grayscale + * value. If the parameter is a string, it's interpreted as a CSS color + * string. A p5.Color object can also be provided to + * set the stroke color. + * + * The version of `stroke()` with two parameters interprets the first one as a + * grayscale value. The second parameter sets the alpha (transparency) value. * - * 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. + * The version of `stroke()` with three parameters interprets them as RGB, HSB, + * or HSL colors, depending on the current `colorMode()`. * - * A p5.Color object can also be provided to set the stroke color. + * The version of `stroke()` with four parameters interprets them as RGBA, HSBA, + * or HSLA colors, depending on the current `colorMode()`. The last parameter + * sets the alpha (transparency) value. * * @method stroke - * @param {Number} v1 red 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} v1 red value if color mode is RGB or hue value if color mode is HSB. + * @param {Number} v2 green value if color mode is RGB or saturation value if color mode is HSB. + * @param {Number} v3 blue value if color mode is RGB or brightness value if color mode is HSB. * @param {Number} [alpha] * @chainable * * @example *
      * - * // Grayscale integer value + * // Grayscale integer value. * strokeWeight(4); * stroke(51); * rect(20, 20, 60, 60); - * describe('White rect at center with dark charcoal grey outline.'); + * describe('A white rectangle with a dark charcoal gray outline.'); * *
      * *
      * - * // R, G & B integer values + * // R, G & B integer values. * stroke(255, 204, 0); * strokeWeight(4); * rect(20, 20, 60, 60); - * describe('White rect at center with yellow outline.'); + * describe('A white rectangle with a yellow outline.'); * *
      * *
      * - * // H, S & B integer values + * // H, S & B integer values. * colorMode(HSB); * strokeWeight(4); * stroke(255, 204, 100); * rect(20, 20, 60, 60); - * describe('White rect at center with royal blue outline.'); + * describe('A white rectangle with a royal blue outline.'); * *
      * *
      * - * // Named SVG/CSS color string + * // A CSS named color. * stroke('red'); * strokeWeight(4); * rect(20, 20, 60, 60); - * describe('White rect at center with red outline.'); + * describe('A white rectangle with a red outline.'); * *
      * *
      * - * // three-digit hexadecimal RGB notation + * // Three-digit hex RGB notation. * stroke('#fae'); * strokeWeight(4); * rect(20, 20, 60, 60); - * describe('White rect at center with pink outline.'); + * describe('A white rectangle with a pink outline.'); * *
      * *
      * - * // six-digit hexadecimal RGB notation + * // Six-digit hex RGB notation. * stroke('#222222'); * strokeWeight(4); * rect(20, 20, 60, 60); - * describe('White rect at center with black outline.'); + * describe('A white rectangle with a black outline.'); * *
      * *
      * - * // integer RGB notation + * // Integer RGB notation. * stroke('rgb(0,255,0)'); * strokeWeight(4); * rect(20, 20, 60, 60); - * describe('White rect at center with bright green outline.'); + * describe('A whiite rectangle with a bright green outline.'); * *
      * *
      * - * // integer RGBA notation + * // Integer RGBA notation. * stroke('rgba(0,255,0,0.25)'); * strokeWeight(4); * rect(20, 20, 60, 60); - * describe('White rect at center with soft green outline.'); + * describe('A white rectangle with a soft green outline.'); * *
      * *
      * - * // percentage RGB notation + * // Percentage RGB notation. * stroke('rgb(100%,0%,10%)'); * strokeWeight(4); * rect(20, 20, 60, 60); - * describe('White rect at center with red outline.'); + * describe('A white rectangle with a red outline.'); * *
      * *
      * - * // percentage RGBA notation + * // Percentage RGBA notation. * stroke('rgba(100%,0%,100%,0.5)'); * strokeWeight(4); * rect(20, 20, 60, 60); - * describe('White rect at center with dark fuchsia outline.'); + * describe('A white rectangle with a dark fuchsia outline.'); * *
      * *
      * - * // p5 Color object + * // p5.Color object. * stroke(color(0, 0, 255)); * strokeWeight(4); * rect(20, 20, 60, 60); - * describe('White rect at center with blue outline.'); + * describe('A white rectangle with a blue outline.'); * *
      */ /** * @method stroke - * @param {String} value a color string + * @param {String} value a color string. * @chainable */ /** * @method stroke - * @param {Number} gray a gray value + * @param {Number} gray a grayscale value. * @param {Number} [alpha] * @chainable */ /** * @method stroke - * @param {Number[]} values an array containing the red,green,blue & - * and alpha components of the color + * @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 + * @param {p5.Color} color the stroke color. * @chainable */ _main.default.prototype.stroke = function () { @@ -55146,21 +56825,36 @@ return this; }; /** - * All drawing that follows erase() will subtract from - * the canvas. Erased areas will reveal the web page underneath the canvas. Erasing - * can be canceled with noErase(). + * All drawing that follows erase() will subtract + * from the canvas, revealing the web page underneath. The erased areas will + * become transparent, allowing the content behind the canvas to show through. + * The fill(), stroke(), and + * blendMode() have no effect once `erase()` is + * called. + * + * The `erase()` function has two optional parameters. The first parameter + * sets the strength of erasing by the shape's interior. A value of 0 means + * that no erasing will occur. A value of 255 means that the shape's interior + * will fully erase the content underneath. The default value is 255 + * (full strength). + * + * The second parameter sets the strength of erasing by the shape's edge. A + * value of 0 means that no erasing will occur. A value of 255 means that the + * shape's edge will fully erase the content underneath. The default value is + * 255 (full strength). + * + * To cancel the erasing effect, use the noErase() + * function. * - * Drawing done with image() and - * background() in between erase() and - * noErase() will not erase the canvas but works as usual. + * `erase()` has no effect on drawing done with the + * image() and + * background() functions. * * @method erase - * @param {Number} [strengthFill] A number (0-255) for the strength of erasing 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. + * @param {Number} [strengthFill] a number (0-255) for the strength of erasing under a shape's interior. + * Defaults to 255, which is full strength. + * @param {Number} [strengthStroke] a number (0-255) for the strength of erasing under a shape's edge. + * Defaults to 255, which is full strength. * * @chainable * @example @@ -55168,55 +56862,40 @@ * * background(100, 100, 250); * fill(250, 100, 100); - * rect(20, 20, 60, 60); + * square(20, 20, 60); * erase(); - * ellipse(25, 30, 30); + * circle(25, 30, 30); * noErase(); - * describe(`60×60 centered pink rect, purple background. - * Elliptical area in top-left of rect is erased white.`); + * describe('A purple canvas with a pink square in the middle. A circle is erased from the top-left, leaving a white hole.'); * * * *
      * - * 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); + * let p = createP('I am a DOM element'); + * p.style('font-size', '12px'); + * p.style('width', '65px'); + * p.style('text-align', 'center'); + * p.position(18, 26); + * + * background(100, 170, 210); + * erase(200, 100); + * circle(50, 50, 77); * noErase(); - * describe(`60×60 centered purple rect, mint green background. - * Triangle in top-right is partially erased with fully erased outline.`); + * describe('A blue canvas with a circular hole in the center that reveals the message "I am a DOM element".'); * *
      * *
      * - * 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(); - * describe(`60×60 centered teal sphere, yellow background. - * Torus rotating around sphere erases to reveal black text underneath.`); - * } + * background(150, 250, 150); + * fill(100, 100, 250); + * square(20, 20, 60); + * strokeWeight(5); + * erase(150, 255); + * triangle(50, 10, 70, 50, 90, 10); + * noErase(); + * describe('A mint green canvas with a purple square in the center. A triangle in the top-right corner partially erases its interior and a fully erases its outline.'); * *
      */ @@ -55229,8 +56908,8 @@ /** * Ends erasing that was started with erase(). * The fill(), stroke(), and - * blendMode() settings will return to what they were - * prior to calling erase(). + * blendMode() settings will return to what they + * were prior to calling erase(). * * @method noErase * @chainable @@ -55242,11 +56921,10 @@ * fill(30, 45, 220); * rect(30, 10, 10, 80); * erase(); - * ellipse(50, 50, 60); + * circle(50, 50, 60); * noErase(); * rect(70, 10, 10, 80); - * describe(`Orange background, with two tall blue rectangles. - * A centered ellipse erased the first blue rect but not the second.`); + * describe('An orange canvas with two tall blue rectangles. A circular hole in the center erases the rectangle on the left but not the one on the right.'); * * */ @@ -55258,29 +56936,29 @@ exports.default = _default; }, { - '../core/constants': 278, - '../core/main': 290, - './p5.Color': 276, - 'core-js/modules/es.array.fill': 170, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + '../core/constants': 286, + '../core/main': 298, + './p5.Color': 284, + 'core-js/modules/es.array.fill': 172, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 278: [ + 286: [ function (_dereq_, module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); - exports.BEZIER = exports.QUADRATIC = exports.LINEAR = exports._CTX_MIDDLE = exports._DEFAULT_LEADMULT = exports._DEFAULT_TEXT_FILL = exports.WORD = exports.CHAR = exports.BOLDITALIC = exports.BOLD = exports.ITALIC = exports.NORMAL = exports.BLUR = exports.ERODE = exports.DILATE = exports.POSTERIZE = exports.INVERT = exports.OPAQUE = exports.GRAY = exports.THRESHOLD = exports.BURN = exports.DODGE = exports.SOFT_LIGHT = exports.HARD_LIGHT = exports.OVERLAY = exports.REPLACE = exports.SCREEN = exports.MULTIPLY = exports.EXCLUSION = exports.SUBTRACT = exports.DIFFERENCE = exports.LIGHTEST = exports.DARKEST = exports.ADD = exports.REMOVE = exports.BLEND = exports.UP_ARROW = exports.TAB = exports.SHIFT = exports.RIGHT_ARROW = exports.RETURN = exports.OPTION = exports.LEFT_ARROW = exports.ESCAPE = exports.ENTER = exports.DOWN_ARROW = exports.DELETE = exports.CONTROL = exports.BACKSPACE = exports.ALT = exports.AUTO = exports.HSL = exports.HSB = exports.RGB = exports.MITER = exports.BEVEL = exports.ROUND = exports.SQUARE = exports.PROJECT = exports.PIE = exports.CHORD = exports.OPEN = exports.CLOSE = exports.TESS = exports.QUAD_STRIP = exports.QUADS = exports.TRIANGLE_STRIP = exports.TRIANGLE_FAN = exports.TRIANGLES = exports.LINE_LOOP = exports.LINE_STRIP = exports.LINES = exports.POINTS = exports.BASELINE = exports.BOTTOM = exports.TOP = exports.CENTER = exports.LEFT = exports.RIGHT = exports.RADIUS = exports.CORNERS = exports.CORNER = exports.RAD_TO_DEG = exports.DEG_TO_RAD = exports.RADIANS = exports.DEGREES = exports.TWO_PI = exports.TAU = exports.QUARTER_PI = exports.PI = exports.HALF_PI = exports.WAIT = exports.TEXT = exports.MOVE = exports.HAND = exports.CROSS = exports.ARROW = exports.WEBGL = exports.P2D = exports.VERSION = void 0; - exports.COVER = exports.CONTAIN = 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 = exports.FILL = exports.STROKE = exports.CURVE = void 0; + exports.QUADRATIC = exports.LINEAR = exports._CTX_MIDDLE = exports._DEFAULT_LEADMULT = exports._DEFAULT_TEXT_FILL = exports.WORD = exports.CHAR = exports.BOLDITALIC = exports.BOLD = exports.ITALIC = exports.NORMAL = exports.BLUR = exports.ERODE = exports.DILATE = exports.POSTERIZE = exports.INVERT = exports.OPAQUE = exports.GRAY = exports.THRESHOLD = exports.BURN = exports.DODGE = exports.SOFT_LIGHT = exports.HARD_LIGHT = exports.OVERLAY = exports.REPLACE = exports.SCREEN = exports.MULTIPLY = exports.EXCLUSION = exports.SUBTRACT = exports.DIFFERENCE = exports.LIGHTEST = exports.DARKEST = exports.ADD = exports.REMOVE = exports.BLEND = exports.UP_ARROW = exports.TAB = exports.SHIFT = exports.RIGHT_ARROW = exports.RETURN = exports.OPTION = exports.LEFT_ARROW = exports.ESCAPE = exports.ENTER = exports.DOWN_ARROW = exports.DELETE = exports.CONTROL = exports.BACKSPACE = exports.ALT = exports.AUTO = exports.HSL = exports.HSB = exports.RGB = exports.MITER = exports.BEVEL = exports.ROUND = exports.SQUARE = exports.PROJECT = exports.PIE = exports.CHORD = exports.OPEN = exports.CLOSE = exports.TESS = exports.QUAD_STRIP = exports.QUADS = exports.TRIANGLE_STRIP = exports.TRIANGLE_FAN = exports.TRIANGLES = exports.LINE_LOOP = exports.LINE_STRIP = exports.LINES = exports.POINTS = exports.BASELINE = exports.BOTTOM = exports.TOP = exports.CENTER = exports.LEFT = exports.RIGHT = exports.RADIUS = exports.CORNERS = exports.CORNER = exports.RAD_TO_DEG = exports.DEG_TO_RAD = exports.RADIANS = exports.DEGREES = exports.TWO_PI = exports.TAU = exports.QUARTER_PI = exports.PI = exports.HALF_PI = exports.WAIT = exports.TEXT = exports.MOVE = exports.HAND = exports.CROSS = exports.ARROW = exports.WEBGL2 = exports.WEBGL = exports.P2D = exports.VERSION = void 0; + exports.RGBA = exports.HALF_FLOAT = exports.FLOAT = exports.UNSIGNED_INT = exports.UNSIGNED_BYTE = exports.COVER = exports.CONTAIN = exports.FALLBACK = exports.LABEL = exports.AXES = exports.GRID = exports._DEFAULT_FILL = exports._DEFAULT_STROKE = exports.PORTRAIT = exports.LANDSCAPE = exports.SMOOTH = exports.FLAT = exports.MIRROR = exports.CLAMP = exports.REPEAT = exports.NEAREST = exports.IMAGE = exports.IMMEDIATE = exports.TEXTURE = exports.FILL = exports.STROKE = exports.CURVE = exports.BEZIER = void 0; /** * @module Constants * @submodule Constants @@ -55292,7 +56970,8 @@ * @property {String} VERSION * @final */ - var VERSION = '1.6.0'; // GRAPHICS RENDERER + var VERSION = '1.9.0'; + // GRAPHICS RENDERER /** * The default, two-dimensional renderer. * @property {String} P2D @@ -55301,18 +56980,42 @@ exports.VERSION = VERSION; 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 + * One of the two render modes in p5.js, used for computationally intensive tasks like 3D rendering and shaders. + * + * `WEBGL` differs from the default `P2D` renderer in the following ways: + * + * - **Coordinate System** - When drawing in `WEBGL` mode, the origin point (0,0,0) is located at the center of the screen, not the top-left corner. See the learn page about coordinates and transformations. + * - **3D Shapes** - `WEBGL` mode can be used to draw 3-dimensional shapes like box(), sphere(), cone(), and more. See the learn page about custom geometry to make more complex objects. + * - **Shape Detail** - When drawing in `WEBGL` mode, you can specify how smooth curves should be drawn by using a `detail` parameter. See the wiki section about shapes for a more information and an example. + * - **Textures** - A texture is like a skin that wraps onto a shape. See the wiki section about textures for examples of mapping images onto surfaces with textures. + * - **Materials and Lighting** - `WEBGL` offers different types of lights like ambientLight() to place around a scene. Materials like specularMaterial() reflect the lighting to convey shape and depth. See the learn page for styling and appearance to experiment with different combinations. + * - **Camera** - The viewport of a `WEBGL` sketch can be adjusted by changing camera attributes. See the learn page section about cameras for an explanation of camera controls. + * - **Text** - `WEBGL` requires opentype/truetype font files to be preloaded using loadFont(). See the wiki section about text for details, along with a workaround. + * - **Shaders** - Shaders are hardware accelerated programs that can be used for a variety of effects and graphics. See the introduction to shaders to get started with shaders in p5.js. + * - **Graphics Acceleration** - `WEBGL` mode uses the graphics card instead of the CPU, so it may help boost the performance of your sketch (example: drawing more shapes on the screen at once). + * + * To learn more about WEBGL mode, check out all the interactive WEBGL tutorials in the "Learn" section of this website, or read the wiki article "Getting started with WebGL in p5". + * * @property {String} WEBGL * @final */ exports.P2D = P2D; - var WEBGL = 'webgl'; // ENVIRONMENT + var WEBGL = 'webgl'; /** - * @property {String} ARROW + * One of the two possible values of a WebGL canvas (either WEBGL or WEBGL2), + * which can be used to determine what capabilities the rendering environment + * has. + * @property {String} WEBGL2 * @final */ exports.WEBGL = WEBGL; + var WEBGL2 = 'webgl2'; + // ENVIRONMENT + /** + * @property {String} ARROW + * @final + */ + exports.WEBGL2 = WEBGL2; var ARROW = 'default'; /** * @property {String} CROSS @@ -55343,7 +57046,8 @@ * @final */ exports.TEXT = TEXT; - var WAIT = 'wait'; // TRIGONOMETRY + var WAIT = 'wait'; + // TRIGONOMETRY /** * HALF_PI is a mathematical constant with the value * 1.57079632679489661923. It is half the ratio of the @@ -55472,7 +57176,8 @@ exports.RADIANS = RADIANS; var DEG_TO_RAD = _PI / 180; exports.DEG_TO_RAD = DEG_TO_RAD; - var RAD_TO_DEG = 180 / _PI; // SHAPE + var RAD_TO_DEG = 180 / _PI; + // SHAPE /** * @property {String} CORNER * @final @@ -55652,7 +57357,8 @@ * @final */ exports.BEVEL = BEVEL; - var MITER = 'miter'; // COLOR + var MITER = 'miter'; + // COLOR /** * @property {String} RGB * @final @@ -55674,11 +57380,12 @@ * @final */ exports.HSB = HSB; - var HSL = 'hsl'; // DOM EXTENSION + var HSL = 'hsl'; + // DOM EXTENSION /** * AUTO allows us to automatically set the width or height of an element (but not both), * based on the current height and width of the element. Only one parameter can - * be passed to the size function as AUTO, at a time. + * be passed to the size function as AUTO, at a time. * * @property {String} AUTO * @final @@ -55769,7 +57476,8 @@ * @final */ exports.TAB = TAB; - var UP_ARROW = 38; // RENDERING + var UP_ARROW = 38; + // RENDERING /** * @property {String} BLEND * @final @@ -55790,7 +57498,8 @@ * @default lighter */ exports.REMOVE = REMOVE; - var ADD = 'lighter'; //ADD: 'add', // + var ADD = 'lighter'; + //ADD: 'add', // //SUBTRACT: 'subtract', // /** * @property {String} DARKEST @@ -55873,7 +57582,8 @@ * @default color-burn */ exports.DODGE = DODGE; - var BURN = 'color-burn'; // FILTERS + var BURN = 'color-burn'; + // FILTERS /** * @property {String} THRESHOLD * @final @@ -55921,7 +57631,8 @@ * @final */ exports.ERODE = ERODE; - var BLUR = 'blur'; // TYPOGRAPHY + var BLUR = 'blur'; + // TYPOGRAPHY /** * @property {String} NORMAL * @final @@ -55957,13 +57668,15 @@ * @final */ exports.CHAR = CHAR; - var WORD = 'WORD'; // TYPOGRAPHY-INTERNAL + var WORD = 'WORD'; + // TYPOGRAPHY-INTERNAL exports.WORD = WORD; var _DEFAULT_TEXT_FILL = '#000000'; exports._DEFAULT_TEXT_FILL = _DEFAULT_TEXT_FILL; var _DEFAULT_LEADMULT = 1.25; exports._DEFAULT_LEADMULT = _DEFAULT_LEADMULT; - var _CTX_MIDDLE = 'middle'; // VERTICES + var _CTX_MIDDLE = 'middle'; + // VERTICES /** * @property {String} LINEAR * @final @@ -55987,7 +57700,8 @@ * @final */ exports.BEZIER = BEZIER; - var CURVE = 'curve'; // WEBGL DRAWMODES + var CURVE = 'curve'; + // WEBGL DRAWMODES /** * @property {String} STROKE * @final @@ -56011,14 +57725,16 @@ * @final */ exports.TEXTURE = TEXTURE; - var IMMEDIATE = 'immediate'; // WEBGL TEXTURE MODE + 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 + var IMAGE = 'image'; + // WEBGL TEXTURE WRAP AND FILTERING // LINEAR already exists above /** * @property {String} NEAREST @@ -56043,19 +57759,34 @@ * @final */ exports.CLAMP = CLAMP; - var MIRROR = 'mirror'; // DEVICE-ORIENTATION + var MIRROR = 'mirror'; + // WEBGL GEOMETRY SHADING /** - * @property {String} LANDSCAPE + * @property {String} FLAT * @final */ exports.MIRROR = MIRROR; + var FLAT = 'flat'; + /** + * @property {String} SMOOTH + * @final + */ + exports.FLAT = FLAT; + var SMOOTH = 'smooth'; + // DEVICE-ORIENTATION + /** + * @property {String} LANDSCAPE + * @final + */ + exports.SMOOTH = SMOOTH; var LANDSCAPE = 'landscape'; /** * @property {String} PORTRAIT * @final */ exports.LANDSCAPE = LANDSCAPE; - var PORTRAIT = 'portrait'; // DEFAULTS + var PORTRAIT = 'portrait'; + // DEFAULTS exports.PORTRAIT = PORTRAIT; var _DEFAULT_STROKE = '#000000'; exports._DEFAULT_STROKE = _DEFAULT_STROKE; @@ -56096,12 +57827,42 @@ */ exports.CONTAIN = CONTAIN; var COVER = 'cover'; + /** + * @property {String} UNSIGNED_BYTE + * @final + */ exports.COVER = COVER; + var UNSIGNED_BYTE = 'unsigned-byte'; + /** + * @property {String} UNSIGNED_INT + * @final + */ + exports.UNSIGNED_BYTE = UNSIGNED_BYTE; + var UNSIGNED_INT = 'unsigned-int'; + /** + * @property {String} FLOAT + * @final + */ + exports.UNSIGNED_INT = UNSIGNED_INT; + var FLOAT = 'float'; + /** + * @property {String} HALF_FLOAT + * @final + */ + exports.FLOAT = FLOAT; + var HALF_FLOAT = 'half-float'; + /** + * @property {String} RGBA + * @final + */ + exports.HALF_FLOAT = HALF_FLOAT; + var RGBA = 'rgba'; + exports.RGBA = RGBA; }, { } ], - 279: [ + 287: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -56223,165 +57984,218 @@ _main.default.prototype._lastFrameTime = window.performance.now(); _main.default.prototype._targetFrameRate = 60; var _windowPrint = window.print; + var windowPrintDisabled = false; /** - * The print() 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 (+). + * Displays text in the web browser's console. + * + * `print()` is helpful for printing values while debugging. Each call to + * `print()` creates a new line of text. * - * Note 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'). + * Note: Call `print('\n')` to print a blank line. Calling `print()` without + * an argument opens the browser's dialog for printing documents. * * @method print - * @param {Any} contents any combination of Number, String, Object, Boolean, - * Array to print + * @param {Any} contents content to print to the console. * @example - *
      - * let x = 10; - * print('The value of x is ' + x); - * // prints "The value of x is 10" - *
      + *
      + * + * function setup() { + * // Prints "hello, world" to the console. + * print('hello, world'); + * } + * + *
      * - * @alt - * default grey canvas + *
      + * + * function setup() { + * let name = 'ada'; + * // Prints "hello, ada" to the console. + * print(`hello, ${name}`); + * } + * + *
      */ _main.default.prototype.print = function () { if (!arguments.length) { - _windowPrint(); + if (!windowPrintDisabled) { + _windowPrint(); + if (window.confirm('You just tried to print the webpage. Do you want to prevent this from running again?')) { + windowPrintDisabled = true; + } + } } else { var _console; (_console = console).log.apply(_console, arguments); } }; /** - * The system variable frameCount contains the - * number of frames that have been displayed since the program started. Inside - * setup() the value is 0, after the first iteration - * of draw() it is 1, etc. + * Tracks the number of frames drawn since the sketch started. + * + * `frameCount`'s value is 0 inside setup(). It + * increments by 1 each time the code in draw() + * finishes executing. * * @property {Integer} frameCount * @readOnly * @example - *
      + *
      + * + * function setup() { + * background(200); + * + * // Display the value of + * // frameCount. + * textSize(30); + * textAlign(CENTER, CENTER); + * text(frameCount, 50, 50); + * + * describe('The number 0 written in black in the middle of a gray square.'); + * } + * + *
      + * + *
      + * * function setup() { + * // Set the frameRate to 30. * frameRate(30); + * * textSize(30); - * textAlign(CENTER); + * textAlign(CENTER, CENTER); * } * * function draw() { * background(200); - * text(frameCount, width / 2, height / 2); - * } - *
      * - * @alt - * numbers rapidly counting upward with frame count set to 30. + * // Display the value of + * // frameCount. + * text(frameCount, 50, 50); + * + * describe('A number written in black in the middle of a gray square. Its value increases rapidly.'); + * } + *
      + *
      */ _main.default.prototype.frameCount = 0; /** - * The system variable deltaTime contains the time - * difference between the beginning of the previous frame and the beginning - * of the current frame in milliseconds. - * - * This variable is useful for creating time sensitive animation or physics - * calculation that should stay constant regardless of frame rate. + * Tracks the amount of time, in milliseconds, it took for + * draw to draw the previous frame. `deltaTime` is + * useful for simulating physics. * * @property {Integer} deltaTime * @readOnly * @example - *
      - * let rectX = 0; - * let fr = 30; //starting FPS - * let clr; + *
      + * + * let x = 0; + * let speed = 0.05; * - * function setup() { - * background(200); - * frameRate(fr); // Attempt to refresh at starting FPS - * clr = color(255, 0, 0); + * function setup() { + * // Set the frameRate to 30. + * frameRate(30); * } * * 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; + * + * // Use deltaTime to calculate + * // a change in position. + * let deltaX = speed * deltaTime; + * + * // Update the x variable. + * x += deltaX; + * + * // Reset x to 0 if it's + * // greater than 100. + * if (x > 100) { + * x = 0; * } - * fill(clr); - * rect(rectX, 40, 20, 20); - * } - *
      * - * @alt - * red rect moves left to right, followed by blue rect moving at the same speed - * with a lower frame rate. Loops. + * // Use x to set the circle's + * // position. + * circle(x, 50, 20); + * + * describe('A white circle moves from left to right on a gray background. It reappears on the left side when it reaches the right side.'); + * } + *
      + *
      */ _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. + * Tracks whether the browser window is focused and can receive user input. + * `focused` is `true` if the window if focused and `false` if not. * * @property {Boolean} focused * @readOnly * @example - *
      - * // To demonstrate, put two windows side by side. - * // Click on the window that the p5 sketch isn't in! + *
      + * + * // Open this example in two separate browser + * // windows placed side-by-side to demonstrate. + * * 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); + * // Change the background color + * // when the browser window + * // goes in/out of focus. + * if (focused === true) { + * background(0, 255, 0); + * } else { + * background(255, 0, 0); * } - * } - *
      * - * @alt - * green 50×50 ellipse at top left. Red X covers canvas when page focus changes + * describe('A square changes color from green to red when the browser window is out of focus.'); + * } + *
      + *
      */ _main.default.prototype.focused = document.hasFocus(); /** - * Sets the cursor to a predefined symbol or an image, or makes it visible - * if already hidden. If you are trying to set an image as the cursor, the - * recommended size is 16×16 or 32×32 pixels. The values for parameters x and y - * must be less than the dimensions of the image. + * Changes the cursor's appearance. + * + * The first parameter, `type`, sets the type of cursor to display. The + * built-in options are `ARROW`, `CROSS`, `HAND`, `MOVE`, `TEXT`, and `WAIT`. + * `cursor()` also recognizes standard CSS cursor properties passed as + * strings: `'help'`, `'wait'`, `'crosshair'`, `'not-allowed'`, `'zoom-in'`, + * and `'grab'`. If the path to an image is passed, as in + * `cursor('assets/target.png')`, then the image will be used as the cursor. + * Images must be in .cur, .gif, .jpg, .jpeg, or .png format. + * + * The parameters `x` and `y` are optional. If an image is used for the + * cursor, `x` and `y` set the location pointed to within the image. They are + * both 0 by default, so the cursor points to the image's top-left corner. `x` + * and `y` must be less than the image's width and height, respectively. * * @method cursor - * @param {String|Constant} type Built-In: either ARROW, CROSS, HAND, MOVE, TEXT 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) + * @param {String|Constant} type Built-in: either ARROW, CROSS, HAND, MOVE, TEXT, or WAIT. + * Native CSS properties: 'grab', 'progress', and so on. + * Path to cursor image. + * @param {Number} [x] horizontal active spot of the cursor. + * @param {Number} [y] vertical active spot of the cursor. * @example - *
      - * // 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); + * background(200); + * + * // Set the cursor to crosshairs: + + * cursor(CROSS); + * + * describe('A gray square. The cursor appears as crosshairs.'); + * } + * + *
      + * + *
      + * + * function draw() { + * background(200); + * + * // Divide the canvas into quadrants. + * line(50, 0, 50, 100); + * line(0, 50, 100, 50); + * + * // Change cursor based on mouse position. * if (mouseX < 50 && mouseY < 50) { * cursor(CROSS); * } else if (mouseX > 50 && mouseY < 50) { @@ -56391,12 +58205,29 @@ * } else { * cursor('grab'); * } + * + * describe('A gray square divided into quadrants. The cursor image changes when the mouse moves to each quadrant.'); * } - *
      + *
      + *
      * - * @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. + *
      + * + * function draw() { + * background(200); + * + * // Change the cursor's active spot + * // when the mouse is pressed. + * if (mouseIsPressed === true) { + * cursor('https://avatars0.githubusercontent.com/u/1617169?s=16', 8, 8); + * } else { + * cursor('https://avatars0.githubusercontent.com/u/1617169?s=16'); + * } + * + * describe('An image of three purple curves follows the mouse. The image shifts when the mouse is pressed.'); + * } + * + *
      */ _main.default.prototype.cursor = function (type, x, y) { var cursor = 'auto'; @@ -56425,68 +58256,74 @@ canvas.style.cursor = cursor; }; /** - * Specifies the number of frames to be displayed every second. For example, - * the function call frameRate(30) will attempt to refresh 30 times a second. - * If the processor is not fast enough to maintain the specified rate, the - * frame rate will not be achieved. Setting the frame rate within - * setup() is recommended. The default frame rate is - * based on the frame rate of the display (here also called "refresh rate"), - * which is set to 60 frames per second on most computers. A frame rate of 24 - * frames per second (usual for movies) or above will be enough for smooth - * animations. This is the same as setFrameRate(val). + * Sets the number of frames to draw per second. * - * Calling frameRate() with no arguments returns - * the current framerate. The draw function must run at least once before it will - * return a value. This is the same as getFrameRate(). + * Calling `frameRate()` with one numeric argument, as in `frameRate(30)`, + * attempts to draw 30 frames per second (FPS). The target frame rate may not + * be achieved depending on the sketch's processing needs. Most computers + * default to a frame rate of 60 FPS. Frame rates of 24 FPS and above are + * fast enough for smooth animations. * - * Calling frameRate() with arguments that are not - * of the type Number or are non-positive also returns current framerate. + * Calling `frameRate()` without an argument returns the current frame rate. + * The value returned is an approximation. * * @method frameRate - * @param {Number} fps number of frames to be displayed every second + * @param {Number} fps number of frames to draw per second. * @chainable * * @example + *
      + * + * function draw() { + * background(200); * - *
      - * let rectX = 0; - * let fr = 30; //starting FPS - * let clr; + * // Set the x variable based + * // on the current frameCount. + * let x = frameCount % 100; * - * function setup() { - * background(200); - * frameRate(fr); // Attempt to refresh at starting FPS - * clr = color(255, 0, 0); + * // If the mouse is pressed, + * // decrease the frame rate. + * if (mouseIsPressed === true) { + * frameRate(10); + * } else { + * frameRate(60); + * } + * + * // Use x to set the circle's + * // position. + * circle(x, 50, 20); + * + * describe('A white circle on a gray background. The circle moves from left to right in a loop. It slows down when the mouse is pressed.'); * } + * + *
      * + *
      + * * function draw() { * background(200); - * 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 + * + * // If the mouse is pressed, do lots + * // of math to slow down drawing. + * if (mouseIsPressed === true) { + * for (let i = 0; i < 1000000; i += 1) { + * random(); * } - * rectX = 0; * } - * fill(clr); - * rect(rectX, 40, 20, 20); - * } - *
      * - * @alt - * blue rect moves left to right, followed by red rect moving faster. Loops. + * // Get the current frame rate + * // and display it. + * let fps = frameRate(); + * text(fps, 50, 50); + * + * describe('A number written in black written on a gray background. The number decreases when the mouse is pressed.'); + * } + *
      + *
      */ /** * @method frameRate - * @return {Number} current frameRate + * @return {Number} current frame rate. */ _main.default.prototype.frameRate = function (fps) { _main.default._validateParameters('frameRate', arguments); @@ -56516,7 +58353,7 @@ * frame rate will not be achieved. Setting the frame rate within setup() is * recommended. The default rate is 60 frames per second. * - * Calling frameRate() with no arguments returns the current framerate. + * Calling `frameRate()` with no arguments returns the current frame rate. * * @private * @param {Number} [fps] number of frames to be displayed every second @@ -56525,18 +58362,29 @@ return this.frameRate(fps); }; /** - * Returns _targetFrameRate variable. The default _targetFrameRate is set to 60. - * This could be changed by calling frameRate() and setting it to the desired - * value. When getTargetFrameRate() is called, it should return the value that was set. + * Returns the target frame rate. The value is either the system frame rate or + * the last value passed to frameRate(). + * * @method getTargetFrameRate * @return {Number} _targetFrameRate * @example - *
      + *
      + * * function draw() { + * background(200); + * + * // Set the frame rate to 20. * frameRate(20); - * text(getTargetFrameRate(), width / 2, height / 2); + * + * // Get the target frame rate and + * // display it. + * let fps = getTargetFrameRate(); + * text(fps, 43, 54); + * + * describe('The number 20 written in black on a gray background.'); * } - *
      + *
      + *
      */ _main.default.prototype.getTargetFrameRate = function () { return this._targetFrameRate; @@ -56546,108 +58394,271 @@ * * @method noCursor * @example - *
      + *
      + * * function setup() { + * // Hide the cursor. * noCursor(); * } * * function draw() { * background(200); - * ellipse(mouseX, mouseY, 10, 10); - * } - *
      * - * @alt - * cursor becomes 10×10 white ellipse the moves with mouse x and y. + * circle(mouseX, mouseY, 10); + * + * describe('A white circle on a gray background. The circle follows the mouse as it moves. The cursor is hidden.'); + * } + *
      + *
      */ _main.default.prototype.noCursor = function () { this._curElement.elt.style.cursor = 'none'; }; /** - * System variable that stores the width of the screen display according to The - * default pixelDensity. This is used to run a - * full-screen program on any display size. To return actual screen size, - * multiply this by pixelDensity. + * A string variable with the WebGL version in use. Its value equals one of + * the followin string constants: + * + * - `WEBGL2` whose value is `'webgl2'`, + * - `WEBGL` whose value is `'webgl'`, or + * - `P2D` whose value is `'p2d'`. This is the default for 2D sketches. + * + * See setAttributes() for ways to set the + * WebGL version. + * + * @property {String} webglVersion + * @readOnly + * @example + *
      + * + * function setup() { + * background(200); + * + * // Display the current WebGL version. + * text(webglVersion, 42, 54); + * + * describe('The text "p2d" written in black on a gray background.'); + * } + * + *
      + * + *
      + * + * let font; + * + * function preload() { + * // Load a font to use. + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * // Create a canvas using WEBGL mode. + * createCanvas(100, 50, WEBGL); + * background(200); + * + * // Display the current WebGL version. + * fill(0); + * textFont(font); + * text(webglVersion, -15, 5); + * + * describe('The text "webgl2" written in black on a gray background.'); + * } + * + *
      + * + *
      + * + * let font; + * + * function preload() { + * // Load a font to use. + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * // Create a canvas using WEBGL mode. + * createCanvas(100, 50, WEBGL); + * + * // Set WebGL to version 1. + * setAttributes({ version: 1 }); + * + * background(200); + * + * // Display the current WebGL version. + * fill(0); + * textFont(font); + * text(webglVersion, -14, 5); + * + * describe('The text "webgl" written in black on a gray background.'); + * } + * + *
      + */ + _main.default.prototype.webglVersion = C.P2D; + /** + * A numeric variable that stores the width of the screen display. Its value + * depends on the current pixelDensity(). + * `displayWidth` is useful for running full-screen programs. + * + * Note: The actual screen width can be computed as + * `displayWidth * pixelDensity()`. * * @property {Number} displayWidth * @readOnly * @example - *
      - * createCanvas(displayWidth, displayHeight); - *
      + *
      + * + * function setup() { + * // Set the canvas' width and height + * // using the display's dimensions. + * createCanvas(displayWidth, displayHeight); + * + * background(200); + * + * describe('A gray canvas that is the same size as the display.'); + * } + * + *
      * * @alt * This example does not render anything. */ _main.default.prototype.displayWidth = screen.width; /** - * System variable that stores the height of the screen display according to The - * default pixelDensity. This is used to run a - * full-screen program on any display size. To return actual screen size, - * multiply this by pixelDensity. + * A numeric variable that stores the height of the screen display. Its value + * depends on the current pixelDensity(). + * `displayHeight` is useful for running full-screen programs. + * + * Note: The actual screen height can be computed as + * `displayHeight * pixelDensity()`. * * @property {Number} displayHeight * @readOnly * @example - *
      - * createCanvas(displayWidth, displayHeight); - *
      + *
      + * + * function setup() { + * // Set the canvas' width and height + * // using the display's dimensions. + * createCanvas(displayWidth, displayHeight); + * + * background(200); + * + * describe('A gray canvas that is the same size as the display.'); + * } + * + *
      * * @alt * This example does not render anything. */ _main.default.prototype.displayHeight = screen.height; /** - * System variable that stores the width of the inner window, it maps to - * window.innerWidth. + * A numeric variable that stores the width of the browser's + * layout viewport. + * This viewport is the area within the browser that's available for drawing. * * @property {Number} windowWidth * @readOnly * @example - *
      - * createCanvas(windowWidth, windowHeight); - *
      + *
      + * + * function setup() { + * // Set the canvas' width and height + * // using the browser's dimensions. + * createCanvas(windowWidth, windowHeight); + * + * background(200); + * + * describe('A gray canvas that takes up the entire browser window.'); + * } + * + *
      * * @alt * This example does not render anything. */ _main.default.prototype.windowWidth = getWindowWidth(); /** - * System variable that stores the height of the inner window, it maps to - * window.innerHeight. + * A numeric variable that stores the height of the browser's + * layout viewport. + * This viewport is the area within the browser that's available for drawing. * * @property {Number} windowHeight * @readOnly * @example - *
      - * createCanvas(windowWidth, windowHeight); - *
      + *
      + * + * function setup() { + * // Set the canvas' width and height + * // using the browser's dimensions. + * createCanvas(windowWidth, windowHeight); + * + * background(200); + * + * describe('A gray canvas that takes up the entire browser window.'); + * } + * + *
      * * @alt * This example does not render anything. */ _main.default.prototype.windowHeight = getWindowHeight(); /** - * The windowResized() function is called once - * every time the browser window is resized. This is a good place to resize the - * canvas or do any other adjustments to accommodate the new window size. + * The code in `windowResized()` is called once each time the browser window + * is resized. It's a good place to resize the canvas or make other + * adjustments to accommodate the new window size. + * + * The `event` parameter is optional. If added to the function definition, it + * can be used for debugging or other purposes. * * @method windowResized - * @param {Object} [event] optional Event callback argument. + * @param {UIEvent} [event] optional resize Event. * @example - *
      + *
      + * * function setup() { * createCanvas(windowWidth, windowHeight); * } * * function draw() { - * background(0, 100, 200); + * background(200); + * + * describe('A gray canvas that takes up the entire browser window. It changes size to match the browser window.'); * } * + * // Resize the canvas when the + * // browser's size changes. * function windowResized() { * resizeCanvas(windowWidth, windowHeight); * } - *
      + *
      + *
      + * @alt + * This example does not render anything. + * + *
      + * + * function setup() { + * createCanvas(windowWidth, windowHeight); + * } + * + * function draw() { + * background(200); + * + * describe('A gray canvas that takes up the entire browser window. It changes size to match the browser window.'); + * } + * + * function windowResized(event) { + * // Resize the canvas when the + * // browser's size changes. + * resizeCanvas(windowWidth, windowHeight); + * + * // Print the resize event to the console for debugging. + * print(event); + * } + * + *
      * @alt * This example does not render anything. */ @@ -56669,11 +58680,68 @@ function getWindowHeight() { return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body && document.body.clientHeight || 0; } /** - * System variable that stores the width of the drawing canvas. This value - * is set by the first parameter of the createCanvas() function. - * For example, the function call createCanvas(320, 240) sets the width - * variable to the value 320. The value of width defaults to 100 if - * createCanvas() is not used in a program. + * A numeric variable that stores the width of the drawing canvas. Its + * default value is 100. + * + * Calling createCanvas() or + * resizeCanvas() changes the value of + * `width`. Calling noCanvas() sets its value to + * 0. + * + * @example + *
      + * + * function setup() { + * background(200); + * + * // Display the canvas' width. + * text(width, 42, 54); + * + * describe('The number 100 written in black on a gray square.'); + * } + * + *
      + * + *
      + * + * function setup() { + * createCanvas(50, 100); + * + * background(200); + * + * // Display the canvas' width. + * text(width, 21, 54); + * + * describe('The number 50 written in black on a gray rectangle.'); + * } + * + *
      + * + *
      + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Display the canvas' width. + * text(width, 42, 54); + * + * describe('The number 100 written in black on a gray square. When the mouse is pressed, the square becomes a rectangle and the number becomes 50.'); + * } + * + * // If the mouse is pressed, reisze + * // the canvas and display its new + * // width. + * function mousePressed() { + * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { + * resizeCanvas(50, 100); + * background(200); + * text(width, 42, 27); + * } + * } + * + *
      * * @property {Number} width * @readOnly @@ -56681,48 +58749,111 @@ _main.default.prototype.width = 0; /** - * System variable that stores the height of the drawing canvas. This value - * is set by the second parameter of the createCanvas() function. For - * example, the function call createCanvas(320, 240) sets the height - * variable to the value 240. The value of height defaults to 100 if - * createCanvas() is not used in a program. + * A numeric variable that stores the height of the drawing canvas. Its + * default value is 100. + * + * Calling createCanvas() or + * resizeCanvas() changes the value of + * `height`. Calling noCanvas() sets its value to + * 0. + * + * @example + *
      + * + * function setup() { + * background(200); + * + * // Display the canvas' height. + * text(height, 42, 54); + * + * describe('The number 100 written in black on a gray square.'); + * } + * + *
      + * + *
      + * + * function setup() { + * createCanvas(100, 50); + * + * background(200); + * + * // Display the canvas' height. + * text(height, 21, 54); + * + * describe('The number 50 written in black on a gray rectangle.'); + * } + * + *
      + * + *
      + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Display the canvas' height. + * text(height, 42, 54); + * + * describe('The number 100 written in black on a gray square. When the mouse is pressed, the square becomes a rectangle and the number becomes 50.'); + * } + * + * // If the mouse is pressed, reisze + * // the canvas and display its new + * // height. + * function mousePressed() { + * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { + * resizeCanvas(100, 50); + * background(200); + * text(height, 42, 27); + * } + * } + * + *
      * * @property {Number} height * @readOnly */ _main.default.prototype.height = 0; /** - * 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. + * Toggles full-screen mode or returns the current mode. + * + * Calling `fullscreen(true)` makes the sketch full-screen. Calling + * `fullscreen(false)` makes the sketch its original size. + * + * Calling `fullscreen()` without an argument returns `true` if the sketch + * is in full-screen mode and `false` if not. + * + * Note: Due to browser restrictions, `fullscreen()` can only be called with + * user input such as a mouse press. * * @method fullscreen - * @param {Boolean} [val] whether the sketch should be in fullscreen mode - * or not - * @return {Boolean} current fullscreen state + * @param {Boolean} [val] whether the sketch should be in fullscreen mode. + * @return {Boolean} current fullscreen state. * @example *
      * - * // Clicking in the box toggles fullscreen on and off. * function setup() { * background(200); + * + * describe('A gray canvas that switches between default and full-screen display when clicked.'); * } + * + * // If the mouse is pressed, + * // toggle full-screen mode. * function mousePressed() { - * if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { + * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { * let fs = fullscreen(); * fullscreen(!fs); * } * } * *
      - * - * @alt - * This example does not render anything. */ _main.default.prototype.fullscreen = function (val) { - _main.default._validateParameters('fullscreen', arguments); // no arguments, return fullscreen or not + _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 { @@ -56735,22 +58866,31 @@ } }; /** - * Sets the pixel scaling for high pixel density displays. By default - * pixel density is set to match display density, call pixelDensity(1) - * to turn this off. Calling pixelDensity() with no arguments returns - * the current pixel density of the sketch. + * Sets the pixel scaling for high pixel density displays. + * + * By default, the pixel density is set to match display density. Calling + * `pixelDensity(1)` turn this off. + * + * Calling `pixelDensity()` without an argument returns the current pixel + * density. * * @method pixelDensity - * @param {Number} val whether or how much the sketch should scale + * @param {Number} [val] desired pixel density. * @chainable * @example *
      * * function setup() { + * // Set the pixel density to 1. * pixelDensity(1); + * + * // Create a canvas and draw + * // a circle. * createCanvas(100, 100); * background(200); - * ellipse(width / 2, height / 2, 50, 50); + * circle(50, 50, 70); + * + * describe('A fuzzy white circle on a gray canvas.'); * } * *
      @@ -56758,21 +58898,24 @@ *
      * * function setup() { - * pixelDensity(3.0); + * // Set the pixel density to 3. + * pixelDensity(3); + * + * // Create a canvas, paint the + * // background, and draw a + * // circle. * createCanvas(100, 100); * background(200); - * ellipse(width / 2, height / 2, 50, 50); + * circle(50, 50, 70); + * + * describe('A sharp white circle on a gray canvas.'); * } * *
      - * - * @alt - * fuzzy 50×50 white ellipse with black outline in center of canvas. - * sharp 50×50 white ellipse with black outline in center of canvas. */ /** * @method pixelDensity - * @returns {Number} current pixel density of the sketch + * @returns {Number} current pixel density of the sketch. */ _main.default.prototype.pixelDensity = function (val) { _main.default._validateParameters('pixelDensity', arguments); @@ -56789,25 +58932,41 @@ return returnValue; }; /** - * Returns the pixel density of the current display the sketch is running on. + * Returns the display's current pixel density. * * @method displayDensity - * @returns {Number} current pixel density of the display + * @returns {Number} current pixel density of the display. * @example *
      * * function setup() { - * let density = displayDensity(); - * pixelDensity(density); + * // Set the pixel density to 1. + * pixelDensity(1); + * + * // Create a canvas and draw + * // a circle. * createCanvas(100, 100); * background(200); - * ellipse(width / 2, height / 2, 50, 50); + * circle(50, 50, 70); + * + * describe('A fuzzy white circle drawn on a gray background. The circle becomes sharper when the mouse is pressed.'); + * } + * + * function mousePressed() { + * // Get the current display density. + * let d = displayDensity(); + * + * // Use the display density to set + * // the sketch's pixel density. + * pixelDensity(d); + * + * // Paint the background and + * // draw a circle. + * background(200); + * circle(50, 50, 70); * } * *
      - * - * @alt - * 50×50 white ellipse with black outline in center of canvas. */ _main.default.prototype.displayDensity = function () { return window.devicePixelRatio; @@ -56838,58 +58997,62 @@ document.msExitFullscreen(); } } /** - * Gets the current URL. Note: when using the - * p5 Editor, this will return an empty object because the sketch - * is embedded in an iframe. It will work correctly if you view the - * sketch using the editor's present or share URLs. + * Returns the sketch's current + * URL + * as a string. + * * @method getURL * @return {String} url * @example *
      * - * let url; - * let x = 100; - * * function setup() { - * fill(0); - * noStroke(); - * url = getURL(); - * } - * - * function draw() { * background(200); - * text(url, x, height / 2); - * x--; + * + * // Get the sketch's URL + * // and display it. + * let url = getURL(); + * textWrap(CHAR); + * text(url, 0, 40, 100); + * + * describe('The URL "https://p5js.org/reference/#/p5/getURL" written in black on a gray background.'); * } * *
      - * - * @alt - * current url (http://p5js.org/reference/#/p5/getURL) moves right to left. */ _main.default.prototype.getURL = function () { return location.href; }; /** - * Gets the current URL path as an array. Note: when using the - * p5 Editor, this will return an empty object because the sketch - * is embedded in an iframe. It will work correctly if you view the - * sketch using the editor's present or share URLs. + * Returns the current + * URL + * path as an array of strings. + * + * For example, consider a sketch hosted at the URL + * `https://example.com/sketchbook`. Calling `getURLPath()` returns + * `['sketchbook']`. For a sketch hosted at the URL + * `https://example.com/sketchbook/monday`, `getURLPath()` returns + * `['sketchbook', 'monday']`. + * * @method getURLPath - * @return {String[]} path components + * @return {String[]} path components. * @example - *
      + *
      + * * function setup() { - * let urlPath = getURLPath(); - * for (let i = 0; i < urlPath.length; i++) { - * text(urlPath[i], 10, i * 20 + 20); - * } - * } - *
      + * background(200); * - * @alt - * This example does not render anything. + * // Get the sketch's URL path + * // and display the first + * // part. + * let path = getURLPath(); + * text(path[0], 25, 54); + * + * describe('The word "reference" written in black on a gray background.'); + * } + *
      + *
      */ _main.default.prototype.getURLPath = function () { return location.pathname.split('/').filter(function (v) { @@ -56897,22 +59060,34 @@ }); }; /** - * Gets the current URL params as an Object. Note: when using the - * p5 Editor, this will return an empty object because the sketch - * is embedded in an iframe. It will work correctly if you view the - * sketch using the editor's present or share URLs. + * Returns the current + * URL parameters + * in an Object. + * + * For example, calling `getURLParams()` in a sketch hosted at the URL + * `http://p5js.org?year=2014&month=May&day=15` returns + * `{ year: 2014, month: 'May', day: 15 }`. + * * @method getURLParams * @return {Object} URL params * @example *
      * - * // Example: http://p5js.org?year=2014&month=May&day=15 + * // Imagine this sketch is hosted at the following URL: + * // https://p5js.org?year=2014&month=May&day=15 * * function setup() { + * background(200); + * + * // Get the sketch's URL + * // parameters and display + * // them. * let params = getURLParams(); * text(params.day, 10, 20); * text(params.month, 10, 40); * text(params.year, 10, 60); + * + * describe('The text "15", "May", and "2014" written in black on separate lines.'); * } * *
      @@ -56937,33 +59112,34 @@ exports.default = _default; }, { - './constants': 278, - './main': 290, - 'core-js/modules/es.array.concat': 167, - 'core-js/modules/es.array.filter': 171, - 'core-js/modules/es.array.includes': 174, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.exec': 199, - 'core-js/modules/es.string.includes': 203, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.string.search': 208, - 'core-js/modules/es.string.split': 209, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + './constants': 286, + './main': 298, + 'core-js/modules/es.array.concat': 169, + 'core-js/modules/es.array.filter': 173, + 'core-js/modules/es.array.includes': 177, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.string.includes': 209, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.string.search': 215, + 'core-js/modules/es.string.split': 216, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 280: [ + 288: [ function (_dereq_, module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); - exports.default = void 0; // This contains a data table used by ./fes_core.js/fesErrorMonitor(). + exports.default = void 0; + // This contains a data table used by ./fes_core.js/fesErrorMonitor(). // // Note: Different browsers use different error strings for the same error. // Extracting info from the browser error messages is easier and cleaner @@ -57096,7 +59272,7 @@ { } ], - 281: [ + 289: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -57122,8 +59298,8 @@ _dereq_('core-js/modules/es.string.iterator'); _dereq_('core-js/modules/es.string.match'); _dereq_('core-js/modules/es.string.replace'); - _dereq_('core-js/modules/es.string.search'); _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.string.starts-with'); _dereq_('core-js/modules/web.dom-collections.for-each'); _dereq_('core-js/modules/web.dom-collections.iterator'); function _typeof2(obj) { @@ -57161,8 +59337,8 @@ _dereq_('core-js/modules/es.string.iterator'); _dereq_('core-js/modules/es.string.match'); _dereq_('core-js/modules/es.string.replace'); - _dereq_('core-js/modules/es.string.search'); _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.string.starts-with'); _dereq_('core-js/modules/web.dom-collections.for-each'); _dereq_('core-js/modules/web.dom-collections.iterator'); Object.defineProperty(exports, '__esModule', { @@ -57223,7 +59399,31 @@ }; } return _typeof(obj); - } // p5.js blue, p5.js orange, auto dark green; fallback p5.js darkened magenta + } /** + * @for p5 + * @requires core + * + * This is the main file for the Friendly Error System (FES), containing + * the core as well as miscellaneous functionality of the FES. Here is a + * brief outline of the functions called in this system. + * + * The FES may be invoked by a call to either + * (1) _validateParameters, (2) _friendlyFileLoadError, (3) _friendlyError, + * (4) helpForMisusedAtTopLevelCode, or (5) _fesErrorMonitor. + * + * _validateParameters is located in validate_params.js along with other code + * used for parameter validation. + * _friendlyFileLoadError is located in file_errors.js along with other code + * used for dealing with file load errors. + * Apart from this, there's also a file stacktrace.js, which contains the code + * to parse the error stack, borrowed from: + * https://github.com/stacktracejs/stacktrace.js + * + * For more detailed information on the FES functions, including the call + * sequence of each function, please look at the FES Reference + Dev Notes: + * https://github.com/processing/p5.js/blob/main/contributor_docs/fes_reference_dev_notes.md + */ + // p5.js blue, p5.js orange, auto dark green; fallback p5.js darkened magenta // See testColors below for all the color codes and names var typeColors = [ @@ -57233,16 +59433,19 @@ '#C83C00' ]; var misusedAtTopLevelCode = null; - var defineMisusedAtTopLevelCode = null; // the threshold for the maximum allowed levenshtein distance + 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 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 errorTable = _dereq_('./browser_errors').default; + // -- Borrowed from jQuery 1.11.3 -- var class2type = { }; var _toString = class2type.toString; @@ -57265,7 +59468,8 @@ return ''.concat(obj); } return _typeof(obj) === 'object' || typeof obj === 'function' ? class2type[_toString.call(obj)] || 'object' : _typeof(obj); - }; // -- End borrow -- + }; + // -- End borrow -- // entry points into user-defined code var entryPoints = [ 'setup', @@ -57319,7 +59523,8 @@ 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, ')'); + //Whenever func having p5.[Class] is encountered, we need to have the error link as mentioned below else different link + funcName.startsWith('p5.') ? msgWithReference = ''.concat(message, ' (http://p5js.org/reference/#/').concat(referenceSection, '.').concat(funcName, ')') : msgWithReference = ''.concat(message, ' (http://p5js.org/reference/#/').concat(referenceSection, '/').concat(funcName, ')'); } return msgWithReference; }; @@ -57348,7 +59553,7 @@ } 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 + } // Add a link to the reference docs of func at the end of the message message = mapToReference(message, func); var style = [ @@ -57456,19 +59661,22 @@ * "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 + 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 + }; + // 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 + 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') { @@ -57481,7 +59689,7 @@ } }; /** - * Compares the symbol caught in the ReferenceErrror to everything in + * Compares the symbol caught in the ReferenceError to everything in * misusedAtTopLevel ( all public p5 properties ). * * Generates and prints a friendly error message using key: "fes.misspelling". @@ -57499,7 +59707,8 @@ } var distanceMap = { }; - var min = 999999; // compute the levenshtein distance for the symbol against all known + 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); @@ -57508,8 +59717,10 @@ 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 + }); + // 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; @@ -57550,7 +59761,7 @@ location: locationObj ? (0, _internationalization.translator) ('fes.location', locationObj) : '', count: matchedSymbols.length }); - } // If there is only one closest match, tell _friendlyError to also add + } // 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. @@ -57600,12 +59811,12 @@ * Generates and prints a friendly error message using key: * "fes.wrongPreload", "fes.libraryError". * - * The processed stack is used to find whether the error happended internally + * The processed stack is used to find whether the error happened internally * within the library, and if the error was due to a non-loadX() method * being used in preload. * * "Internally" here means that the exact location of the error (the top of - * the stack) is a piece of code write in the p5.js library (which may or + * the stack) is a piece of code written in the p5.js library (which may or * may not have been called from the user's sketch). * * @method processStack @@ -57624,11 +59835,21 @@ null]; stacktrace.forEach(function (frame) { frame.functionName = frame.functionName || ''; - }); // isInternal - Did this error happen inside the library + }); + // isInternal - Did this error happen inside the library var isInternal = false; var p5FileName, friendlyStack, currentEntryPoint; + // Intentionally throw an error that we catch so that we can check the name + // of the current file. Any errors we see from this file, we treat as + // internal errors. + try { + throw new Error(); + } catch (testError) { + var testStacktrace = _main.default._getErrorStackParser().parse(testError); + p5FileName = testStacktrace[0].fileName; + } for (var i = stacktrace.length - 1; i >= 0; i--) { var splitted = stacktrace[i].functionName.split('.'); if (entryPoints.includes(splitted[splitted.length - 1])) { @@ -57636,19 +59857,18 @@ // (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; - } + // We call the error "internal" if the source of the error was a + // function from within the p5.js library file, but called from the + // user's code directly. We only need to check the topmost frame in + // the stack trace since any function internal to p5 should pass this + // check, not just public p5 functions. + if (stacktrace[0].fileName === p5FileName) { + isInternal = true; + break; } break; } - } // in some cases ( errors in promises, callbacks, etc), no entry-point + } // 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 @@ -57663,22 +59883,26 @@ return frame; }).filter(function (frame) { return frame.fileName !== p5FileName; - }); // a weird case, if for some reason we can't identify the function called + }); + // 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. + 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 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 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 + } // 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) { @@ -57694,7 +59918,7 @@ location: locationObj ? (0, _internationalization.translator) ('fes.location', locationObj) : '', error: error.message }), func); - } // Finally, if it's an internal error, print the friendlyStack + } // Finally, if it's an internal error, print the friendlyStack // ( fesErrorMonitor won't handle this error ) if (friendlyStack && friendlyStack.length) { @@ -57718,7 +59942,8 @@ * @param {*} e Event object to extract error details from */ var fesErrorMonitor = function fesErrorMonitor(e) { - if (_main.default.disableFriendlyErrors) return; // Try to get the error object from e + if (_main.default.disableFriendlyErrors) return; + // Try to get the error object from e var error; if (e instanceof Error) { error = e; @@ -57729,7 +59954,8 @@ 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 + 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), @@ -57748,7 +59974,8 @@ 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 + 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_]+)'); @@ -57774,7 +60001,8 @@ } } } - if (!matchedError) return; // Try and get the location from the top element of the stack + 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 = { @@ -57860,7 +60088,7 @@ var _errSym = matchedError.match[1]; if (_errSym && handleMisspelling(_errSym, error)) { break; - } // if the flow gets this far, this is likely not a misspelling + } // if the flow gets this far, this is likely not a misspelling // of a p5 property/function var _url5 = 'https://p5js.org/examples/data-variable-scope.html'; @@ -57899,13 +60127,15 @@ //let a = document.getElementByID('foo'); -> getElementById instead of getElementByID var _errSym3 = matchedError.match[1]; var splitSym = _errSym3.split('.'); - var _url7 = 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Errors/Not_a_function#What_went_wrong'; // if errSym is aa.bb.cc , symbol would be cc and obj would aa.bb + var _url7 = 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Errors/Not_a_function#What_went_wrong'; + // if errSym is aa.bb.cc , symbol would be cc and obj would aa.bb var translationObj = { url: _url7, symbol: splitSym[splitSym.length - 1], obj: splitSym.slice(0, splitSym.length - 1).join('.'), location: locationObj ? (0, _internationalization.translator) ('fes.location', locationObj) : '' - }; // There are two cases to handle here. When the function is called + }; + // 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) { @@ -57968,7 +60198,8 @@ } }; _main.default._fesErrorMonitor = fesErrorMonitor; - _main.default._checkForUserDefinedFunctions = checkForUserDefinedFunctions; // logger for testing purposes. + _main.default._checkForUserDefinedFunctions = checkForUserDefinedFunctions; + // logger for testing purposes. _main.default._fesLogger = null; _main.default._fesLogCache = { }; @@ -57998,7 +60229,7 @@ p5._friendlyError(str, 'print', '#C83C00'); // auto dark orange p5._friendlyError(str, 'print', '#4DB200'); // auto dark green } */ - } // This is a lazily-defined list of p5 symbols that may be + } // 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. @@ -58042,10 +60273,11 @@ }); }; misusedAtTopLevelCode = [ - ].concat(getSymbols(_main.default.prototype), // At present, p5 only adds its constants to p5.prototype during + ].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 + 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) { @@ -58072,7 +60304,7 @@ } if (!misusedAtTopLevelCode) { defineMisusedAtTopLevelCode(); - } // If we find that we're logging lots of false positives, we can + } // 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.) @@ -58108,10 +60340,12 @@ return true; } }); - }; // Exposing this primarily for unit testing. + }; + // 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 + 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. @@ -58123,40 +60357,40 @@ exports.default = _default; }, { - '../constants': 278, - '../internationalization': 288, - '../main': 290, - './browser_errors': 280, - 'core-js/modules/es.array.concat': 167, - 'core-js/modules/es.array.filter': 171, - 'core-js/modules/es.array.for-each': 172, - 'core-js/modules/es.array.includes': 174, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.join': 177, - 'core-js/modules/es.array.map': 179, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.array.some': 181, - 'core-js/modules/es.function.name': 183, - 'core-js/modules/es.object.assign': 190, - 'core-js/modules/es.object.get-own-property-names': 192, - 'core-js/modules/es.object.keys': 194, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.constructor': 198, - 'core-js/modules/es.regexp.exec': 199, - 'core-js/modules/es.regexp.to-string': 200, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.string.match': 205, - 'core-js/modules/es.string.replace': 207, - 'core-js/modules/es.string.search': 208, - 'core-js/modules/es.string.split': 209, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/web.dom-collections.for-each': 247, - 'core-js/modules/web.dom-collections.iterator': 248 + '../constants': 286, + '../internationalization': 296, + '../main': 298, + './browser_errors': 288, + 'core-js/modules/es.array.concat': 169, + 'core-js/modules/es.array.filter': 173, + 'core-js/modules/es.array.for-each': 175, + 'core-js/modules/es.array.includes': 177, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.join': 180, + 'core-js/modules/es.array.map': 182, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.array.some': 184, + 'core-js/modules/es.function.name': 186, + 'core-js/modules/es.object.assign': 194, + 'core-js/modules/es.object.get-own-property-names': 197, + 'core-js/modules/es.object.keys': 199, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.constructor': 204, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.string.match': 211, + 'core-js/modules/es.string.replace': 214, + 'core-js/modules/es.string.split': 216, + 'core-js/modules/es.string.starts-with': 217, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/web.dom-collections.for-each': 255, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 282: [ + 290: [ function (_dereq_, module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { @@ -58269,11 +60503,11 @@ exports.default = _default; }, { - '../internationalization': 288, - '../main': 290 + '../internationalization': 296, + '../main': 298 } ], - 283: [ + 291: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -58326,30 +60560,22 @@ } return _typeof(obj); } - _dereq_('core-js/modules/es.symbol'); - _dereq_('core-js/modules/es.symbol.description'); - _dereq_('core-js/modules/es.symbol.iterator'); _dereq_('core-js/modules/es.array.filter'); _dereq_('core-js/modules/es.array.for-each'); - _dereq_('core-js/modules/es.array.from'); _dereq_('core-js/modules/es.array.includes'); _dereq_('core-js/modules/es.array.index-of'); - _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.join'); _dereq_('core-js/modules/es.array.map'); _dereq_('core-js/modules/es.array.slice'); _dereq_('core-js/modules/es.object.keys'); - _dereq_('core-js/modules/es.object.to-string'); _dereq_('core-js/modules/es.regexp.constructor'); _dereq_('core-js/modules/es.regexp.exec'); _dereq_('core-js/modules/es.regexp.to-string'); _dereq_('core-js/modules/es.string.includes'); - _dereq_('core-js/modules/es.string.iterator'); _dereq_('core-js/modules/es.string.match'); _dereq_('core-js/modules/es.string.split'); _dereq_('core-js/modules/es.string.trim'); _dereq_('core-js/modules/web.dom-collections.for-each'); - _dereq_('core-js/modules/web.dom-collections.iterator'); Object.defineProperty(exports, '__esModule', { value: true }); @@ -58420,7 +60646,11 @@ } return arr2; } - } /** + } /** + * @for p5 + * @requires core + */ + /** * Checks if any p5.js constant/function is declared outside of setup() * and draw() function. Also checks any reserved constant/function is * redeclared. @@ -58481,18 +60711,21 @@ //if the element in variableArray is a p5.js constant then the below condidion //will be true, hence a match is found if (constants[variableArray[i]] !== undefined) { - var url = 'https://p5js.org/reference/#/p5/'.concat(variableArray[i]); //display the FES message if a match is found + var url = 'https://p5js.org/reference/#/p5/'.concat(variableArray[i]); + //display the FES message if a match is found _main.default._friendlyError((0, _internationalization.translator) ('fes.sketchReaderErrors.reservedConst', { url: url, symbol: variableArray[i] })); - return; //if match found then end search + return; + //if match found then end search } } var p5Constructors = { }; for (var _i = 0, _Object$keys = Object.keys(_main.default); _i < _Object$keys.length; _i++) { - var key = _Object$keys[_i]; // Get a list of all constructors in p5. They are functions whose names + 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]; @@ -58502,7 +60735,8 @@ //ignoreFunction contains the list of functions to be ignored if (!ignoreFunction.includes(variableArray[_i2])) { var keyArray = Object.keys(p5Constructors); - var j = 0; //for every function name obtained check if it matches any p5.js function name + var j = 0; + //for every function name obtained check if it matches any p5.js function name for (; j < keyArray.length; j++) { if (p5Constructors[keyArray[j]].prototype[variableArray[_i2]] !== undefined) { //if a p5.js function is used ie it is in the funcs array @@ -58516,9 +60750,11 @@ } } } - }; //these regex are used to perform variable extraction + }; + //these regex are used to perform variable extraction //visit https://regexr.com/ for the detailed view - var optionalVarKeyword = /(?:(?:let|const|var)\s+)?/; // Bracketed expressions start with an opening bracket, some amount of non + var optionalVarKeyword = /(?:(?:let|const|var)\s+)?/; + // Bracketed expressions start with an opening bracket, some amount of non // bracket characters, then a closing bracket. Note that this won't properly // parse nested brackets: `constrain(millis(), 0, 1000)` will match // `constrain(millis()` only, but will still fail gracefully and not try to @@ -58530,7 +60766,8 @@ squareBracketedExpr, curlyBracketedExpr].map(function (regex) { return regex.source; - }).join('|')); // In an a = b expression, `b` can be any character up to a newline or comma, + }).join('|')); + // In an a = b expression, `b` can be any character up to a newline or comma, // unless the comma is inside of a bracketed expression of some kind (to make // sure we parse function calls with multiple arguments properly.) var rightHandSide = new RegExp('(?:' + bracketedExpr.source + '|[^\\n,])+'); @@ -58563,7 +60800,8 @@ matches.push.apply(matches, _toConsumableArray(match.slice(1).filter(function (group) { return group !== undefined; }))); - }); //check if the obtained variables are a part of p5.js or not + }); + //check if the obtained variables are a part of p5.js or not checkForConstsAndFuncs(matches); }; /** @@ -58577,12 +60815,14 @@ */ var extractFuncVariables = function extractFuncVariables(linesArray) { var matches = [ - ]; //RegExp to extract function names from let/const x = function()... + ]; + //RegExp to extract function names from let/const x = function()... //visit https://regexr.com/ for the detailed view. linesArray.forEach(function (ele) { var m = ele.match(letConstName); if (m !== null) matches.push(ele.match(letConstName) [1]); - }); //matches array contains the names of the functions + }); + //matches array contains the names of the functions checkForConstsAndFuncs(matches); }; /** @@ -58600,13 +60840,15 @@ return line.trim(); }).filter(function (line) { return line !== '' && !line.includes('//') && (line.includes('let') || line.includes('const')) && !line.includes('=>') && !line.includes('function'); - } //filter out lines containing variable names - ); //filter out lines containing function names + } //filter out lines containing variable names + ); + //filter out lines containing function names var arrayFunctions = code.split('\n').map(function (line) { return line.trim(); }).filter(function (line) { return line !== '' && !line.includes('//') && (line.includes('let') || line.includes('const')) && (line.includes('=>') || line.includes('function')); - }); //pass the relevant array to a function which will extract all the variables/functions names + }); + //pass the relevant array to a function which will extract all the variables/functions names extractVariables(arrayVariables); extractFuncVariables(arrayFunctions); }; @@ -58620,7 +60862,8 @@ */ var removeMultilineComments = function removeMultilineComments(code) { var start = code.indexOf('/*'); - var end = code.indexOf('*/'); //create a new string which don't have multiline comments + var end = code.indexOf('*/'); + //create a new string which don't have multiline comments while (start !== - 1 && end !== - 1) { if (start === 0) { code = code.slice(end + 2); @@ -58654,7 +60897,7 @@ //is OK so we will skip the current iteration and check for the //next element. continue; - } //if we are not getting an error this means + } //if we are not getting an error this means //user have changed the value. We will check //if the value is changed and if it is changed //then report. @@ -58664,32 +60907,37 @@ _main.default._friendlyError((0, _internationalization.translator) ('fes.sketchReaderErrors.reservedConst', { url: url, symbol: tempArray[i] - })); //if a p5.js constant is already reported then no need to check + })); + //if a p5.js constant is already reported then no need to check //for p5.js functions. return true; } - } //the below code gets a list of p5.js functions + } //the below code gets a list of p5.js functions var p5Constructors = { }; for (var _i3 = 0, _Object$keys2 = Object.keys(_main.default); _i3 < _Object$keys2.length; _i3++) { - var key = _Object$keys2[_i3]; // Get a list of all constructors in p5. They are functions whose names + var key = _Object$keys2[_i3]; + // Get a list of all constructors in p5. They are functions whose names // start with a capital letter if (typeof _main.default[key] === 'function' && key[0] !== key[0].toLowerCase()) { p5Constructors[key] = _main.default[key]; } } var keyArray = Object.keys(p5Constructors); + var classesWithGlobalFns = [ + 'Renderer', + 'Renderer2D', + 'RendererGL' + ]; var functionArray = [ - ]; //get the names of all p5.js functions - for (var _i4 = 0; _i4 < keyArray.length; _i4++) { - var _functionArray; - (_functionArray = functionArray).push.apply(_functionArray, _toConsumableArray(Object.keys(p5Constructors[keyArray[_i4]].prototype))); - } - functionArray = functionArray.filter(function (ele) { - return !ele.includes('_'); - }); //we have p5.js function names with us so we will check + ]; + //get the names of all p5.js functions which are available globally + for (var _i4 = 0; _i4 < classesWithGlobalFns.length; _i4++) { + functionArray.push.apply(functionArray, _toConsumableArray(Object.keys(p5Constructors[classesWithGlobalFns[_i4]].prototype))); + } //we have p5.js function names with us so we will check //if they have been declared or not. + for (var _i5 = 0; _i5 < functionArray.length; _i5++) { //ignoreFunction contains the list of functions to be ignored if (!ignoreFunction.includes(functionArray[_i5])) { @@ -58699,7 +60947,7 @@ } catch (e) { //we will skip the iteration continue; - } //if we are not getting an error this means + } //if we are not getting an error this means //user have used p5.js function. Check if it is //changed and if so then report it. @@ -58757,38 +61005,38 @@ exports.default = _default; }, { - '../constants': 278, - '../internationalization': 288, - '../main': 290, - 'core-js/modules/es.array.filter': 171, - 'core-js/modules/es.array.for-each': 172, - 'core-js/modules/es.array.from': 173, - 'core-js/modules/es.array.includes': 174, - 'core-js/modules/es.array.index-of': 175, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.join': 177, - 'core-js/modules/es.array.map': 179, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.keys': 194, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.constructor': 198, - 'core-js/modules/es.regexp.exec': 199, - 'core-js/modules/es.regexp.to-string': 200, - 'core-js/modules/es.string.includes': 203, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.string.match': 205, - 'core-js/modules/es.string.split': 209, - 'core-js/modules/es.string.trim': 211, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.for-each': 247, - 'core-js/modules/web.dom-collections.iterator': 248 + '../constants': 286, + '../internationalization': 296, + '../main': 298, + 'core-js/modules/es.array.filter': 173, + 'core-js/modules/es.array.for-each': 175, + 'core-js/modules/es.array.from': 176, + 'core-js/modules/es.array.includes': 177, + 'core-js/modules/es.array.index-of': 178, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.join': 180, + 'core-js/modules/es.array.map': 182, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.keys': 199, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.constructor': 204, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.includes': 209, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.string.match': 211, + 'core-js/modules/es.string.split': 216, + 'core-js/modules/es.string.trim': 219, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.for-each': 255, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 284: [ + 292: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.array.filter'); @@ -58843,7 +61091,6 @@ // 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])?$/; @@ -58861,7 +61108,8 @@ return this.parseV8OrIE(error); } else if (error.stack) { return this.parseFFOrSafari(error); - } else { // throw new Error('Cannot parse given Error object'); + } else { + // throw new Error('Cannot parse given Error object'); } }, // Separate line and column numbers from a string of the form: (URI:Line:Column) @@ -58885,11 +61133,14 @@ // 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 + 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 + 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 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 = [ @@ -59004,7 +61255,7 @@ }, this); } }; - } // End borrow + } // End borrow // wrapper exposing ErrorStackParser _main.default._getErrorStackParser = function getErrorStackParser() { @@ -59014,19 +61265,19 @@ exports.default = _default; }, { - '../main': 290, - 'core-js/modules/es.array.filter': 171, - 'core-js/modules/es.array.index-of': 175, - 'core-js/modules/es.array.join': 177, - 'core-js/modules/es.array.map': 179, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.regexp.exec': 199, - 'core-js/modules/es.string.match': 205, - 'core-js/modules/es.string.replace': 207, - 'core-js/modules/es.string.split': 209 + '../main': 298, + 'core-js/modules/es.array.filter': 173, + 'core-js/modules/es.array.index-of': 178, + 'core-js/modules/es.array.join': 180, + 'core-js/modules/es.array.map': 182, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.string.match': 211, + 'core-js/modules/es.string.replace': 214, + 'core-js/modules/es.string.split': 216 } ], - 285: [ + 293: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -59076,19 +61327,15 @@ _dereq_('core-js/modules/es.array.concat'); _dereq_('core-js/modules/es.array.for-each'); _dereq_('core-js/modules/es.array.includes'); - _dereq_('core-js/modules/es.array.index-of'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.join'); _dereq_('core-js/modules/es.array.last-index-of'); _dereq_('core-js/modules/es.array.map'); _dereq_('core-js/modules/es.array.slice'); _dereq_('core-js/modules/es.function.name'); - _dereq_('core-js/modules/es.map'); _dereq_('core-js/modules/es.number.constructor'); - _dereq_('core-js/modules/es.object.get-prototype-of'); _dereq_('core-js/modules/es.object.keys'); _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.reflect.construct'); _dereq_('core-js/modules/es.regexp.exec'); _dereq_('core-js/modules/es.regexp.to-string'); _dereq_('core-js/modules/es.set'); @@ -59290,7 +61537,11 @@ }; } return _typeof(obj); - } + } /** + * @for p5 + * @requires core + */ + if (typeof IS_MINIFIED !== 'undefined') { _main.default._validateParameters = _main.default._clearValidateParamsCache = function () { }; @@ -59314,12 +61565,13 @@ string: true, function : true, undefined: true - }; // reverse map of all constants + }; + // 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 + } // mapping names of p5 types to their constructor function // p5Constructors: // - Color: f() // - Graphics: f() @@ -59327,7 +61579,8 @@ // and so on var p5Constructors = { - }; // For speedup over many runs. funcSpecificConstructors[func] only has the + }; + // For speedup over many runs. funcSpecificConstructors[func] only has the // constructors for types which were seen earlier as args of "func" var funcSpecificConstructors = { }; @@ -59336,7 +61589,8 @@ // 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 + 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]; @@ -59344,7 +61598,8 @@ } }); var argumentTree = { - }; // The following two functions are responsible for querying and inserting + }; + // 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. @@ -59402,12 +61657,13 @@ obj = obj[value.constructor.name] || (obj[value.constructor.name] = { }); return obj; - } // constructors for types defined in p5 do not have a name property. + } // 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 + 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 @@ -59427,11 +61683,12 @@ // 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 + }); + // if found, add to known constructors for this function p5C[_key3] = p5Constructors[_key3]; return obj; } - } // nothing worked, put the type as is + } // nothing worked, put the type as it is obj = obj[type] || (obj[type] = { }); @@ -59484,7 +61741,8 @@ var funcName = func.slice(ichDot + 1); var funcClass = func.slice(0, ichDot !== - 1 ? ichDot : 0) || 'p5'; var classitems = arrDoc; - var queryResult = classitems[funcClass][funcName]; // different JSON structure for funct with multi-format + var queryResult = classitems[funcClass][funcName]; + // different JSON structure for funct with multi-format var overloads = [ ]; if (queryResult.hasOwnProperty('overloads')) { @@ -59500,24 +61758,26 @@ formats: queryResult.params || [ ] }); - } // parse the parameter types for each overload + } // 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 + 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 + } // 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 + 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) { @@ -59528,7 +61788,8 @@ array: ct(type.slice(0, - 2)) }; } - var lowerType = type.toLowerCase(); // contant + var lowerType = type.toLowerCase(); + // constant if (lowerType === 'constant') { var constant; if (mapConstants.hasOwnProperty(format.name)) { @@ -59567,21 +61828,22 @@ names: constant.names, values: constant.values }; - } // function + } // function if (lowerType.slice(0, 'function'.length) === 'function') { lowerType = 'function'; - } // builtin + } // builtin if (builtinTypes.has(lowerType)) { return { name: type, builtin: lowerType }; - } // find type's prototype + } // find type's prototype var t = window; - var typeParts = type.split('.'); // special-case 'p5' since it may be non-global + var typeParts = type.split('.'); + // special-case 'p5' since it may be non-global if (typeParts[0] === 'p5') { t = _main.default; typeParts.shift(); @@ -59613,9 +61875,10 @@ * @method isNumber * @private * - * @returns {String} a string indicating the type + * @returns {Boolean} a boolean indicating whether input type is Number */ var isNumber = function isNumber(param) { + if (isNaN(parseFloat(param))) return false; switch (_typeof(param)) { case 'number': return true; @@ -59656,8 +61919,7 @@ matches = isArray; break; case 'string': - matches = /*typeof param === 'number' ||*/ - typeof param === 'string'; + matches = /*typeof param === 'number' ||*/ typeof param === 'string'; break; case 'constant': matches = type.values.hasOwnProperty(param); @@ -59696,18 +61958,20 @@ 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 + 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. + } // 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' + var format = formats[p]; + // '== null' checks for 'null' and typeof 'undefined' if (arg == null) { // handle undefined args if (!format.optional || p < minParams || p < argCount) { @@ -59726,7 +61990,8 @@ */ var getOverloadErrors = function getOverloadErrors(args, argCount, overload) { var formats = overload.formats; - var minParams = overload.minParams; // check for too few/many args + var minParams = overload.minParams; + // check for too few/many args if (argCount < minParams) { return [{ type: 'TOO_FEW_ARGUMENTS', @@ -59746,7 +62011,8 @@ ]; for (var p = 0; p < formats.length; p++) { var arg = args[p]; - var format = formats[p]; // '== null' checks for 'null' and typeof 'undefined' + var format = formats[p]; + // '== null' checks for 'null' and typeof 'undefined' if (arg == null) { // handle undefined args if (!format.optional || p < minParams || p < argCount) { @@ -59774,8 +62040,7 @@ * @private */ _main.default.ValidationError = function (name) { - var err = /*#__PURE__*/ - function (_Error) { + var err = /*#__PURE__*/ function (_Error) { _inherits(err, _Error); var _super = _createSuper(err); function err(message, func, type) { @@ -59790,8 +62055,7 @@ return _this; } return err; - }( /*#__PURE__*/ - _wrapNativeSuper(Error)); + }( /*#__PURE__*/ _wrapNativeSuper(Error)); err.prototype.name = name; return err; }('ValidationError'); @@ -59830,7 +62094,7 @@ case 'WRONG_TYPE': { var arg = errorObj.arg; - var argType = arg instanceof Array ? 'array' : arg === null ? 'null' : arg.name || _typeof(arg); + var argType = arg instanceof Array ? 'array' : arg === null ? 'null' : arg === undefined ? 'undefined' : typeof arg === 'number' && isNaN(arg) ? 'NaN' : arg.name || _typeof(arg); translationObj = { func: func, formatType: formatType(), @@ -59872,7 +62136,7 @@ } if (_main.default._throwValidationErrors) { throw new _main.default.ValidationError(message, func, errorObj.type); - } // try to extract the location from where the function was called + } // 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); @@ -59881,7 +62145,8 @@ // 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 + }); + // 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; } @@ -59890,7 +62155,8 @@ throw err; } } - translationObj.context = errorObj.type; // i18next-extract-mark-context-next-line ["EMPTY_VAR", "TOO_MANY_ARGUMENTS", "TOO_FEW_ARGUMENTS", "WRONG_TYPE"] + 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); } @@ -59912,7 +62178,8 @@ var _key4 = _Object$keys2[_i2]; delete argumentTree[_key4]; } - }; // allowing access to argumentTree for testing + }; + // allowing access to argumentTree for testing _main.default._getValidateParamsArgTree = function getValidateParamsArgTree() { return argumentTree; }; @@ -59930,7 +62197,7 @@ * @example: * const a; * ellipse(10,10,a,5); - * console ouput: + * console output: * "It looks like ellipse received an empty variable in spot #2." * * @example: @@ -59942,18 +62209,20 @@ _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 + } // 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 + } // mark this sequence as seen - obj.seen = true; // lookup the docs in the 'data.json' file + 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 + 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--; @@ -59969,11 +62238,12 @@ minScore = score; minOverload = i; } - } // this should _always_ be true here... + } // 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 + var errorArray = getOverloadErrors(args, argCount, overloads[minOverload]); + // generate err msg for (var n = 0; n < errorArray.length; n++) { _main.default._friendlyParamError(errorArray[n], func); } @@ -59986,41 +62256,41 @@ }, { '../../../docs/parameterData.json': 1, - '../constants': 278, - '../internationalization': 288, - '../main': 290, - 'core-js/modules/es.array.concat': 167, - 'core-js/modules/es.array.for-each': 172, - 'core-js/modules/es.array.includes': 174, - 'core-js/modules/es.array.index-of': 175, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.join': 177, - 'core-js/modules/es.array.last-index-of': 178, - 'core-js/modules/es.array.map': 179, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.function.name': 183, - 'core-js/modules/es.map': 184, - 'core-js/modules/es.number.constructor': 187, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.get-prototype-of': 193, - 'core-js/modules/es.object.keys': 194, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.reflect.construct': 197, - 'core-js/modules/es.regexp.exec': 199, - 'core-js/modules/es.regexp.to-string': 200, - 'core-js/modules/es.set': 201, - 'core-js/modules/es.string.includes': 203, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.string.split': 209, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.for-each': 247, - 'core-js/modules/web.dom-collections.iterator': 248 + '../constants': 286, + '../internationalization': 296, + '../main': 298, + 'core-js/modules/es.array.concat': 169, + 'core-js/modules/es.array.for-each': 175, + 'core-js/modules/es.array.includes': 177, + 'core-js/modules/es.array.index-of': 178, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.join': 180, + 'core-js/modules/es.array.last-index-of': 181, + 'core-js/modules/es.array.map': 182, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.function.name': 186, + 'core-js/modules/es.map': 187, + 'core-js/modules/es.number.constructor': 191, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.get-prototype-of': 198, + 'core-js/modules/es.object.keys': 199, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.reflect.construct': 202, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.set': 207, + 'core-js/modules/es.string.includes': 209, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.string.split': 216, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.for-each': 255, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 286: [ + 294: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -60142,19 +62412,19 @@ exports.default = _default; }, { - './constants': 278, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + './constants': 286, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 287: [ + 295: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.array.iterator'); @@ -60202,33 +62472,36 @@ new _main.default(); } } - }; // make a promise that resolves when the document is ready + }; + // 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 + 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 + }; + // only load translations if we're using the full, un-minified library var waitingForTranslator = typeof IS_MINIFIED === 'undefined' ? (0, _internationalization.initialize) () : Promise.resolve(); Promise.all([waitForDocumentReady(), waitingForTranslator]).then(_globalInit); }, { - '../core/main': 290, - './internationalization': 288, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.promise': 196, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/web.dom-collections.iterator': 248 + '../core/main': 298, + './internationalization': 296, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.promise': 201, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 288: [ + 296: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.array.includes'); @@ -60299,7 +62572,8 @@ // 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 + 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('-'); @@ -60314,12 +62588,11 @@ * from a CDN. */ - var FetchResources = /*#__PURE__*/ - function () { + var FetchResources = /*#__PURE__*/ function () { function FetchResources(services, options) { _classCallCheck(this, FetchResources); this.init(services, options); - } // run fetch with a timeout. Automatically rejects on timeout + } // run fetch with a timeout. Automatically rejects on timeout // default timeout = 2000 ms _createClass(FetchResources, [ @@ -60403,12 +62676,13 @@ * @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. + 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!) + _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 */ @@ -60447,7 +62721,8 @@ 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 + }); + // 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; @@ -60480,25 +62755,25 @@ exports.setTranslatorLanguage = setTranslatorLanguage; }, { - '../../translations': 349, + '../../translations': 360, '../../translations/dev': undefined, - 'core-js/modules/es.array.includes': 174, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.join': 177, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.object.keys': 194, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.promise': 196, - 'core-js/modules/es.regexp.exec': 199, - 'core-js/modules/es.string.includes': 203, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.string.split': 209, - 'core-js/modules/web.dom-collections.iterator': 248, - 'i18next': 259, - 'i18next-browser-languagedetector': 256 + 'core-js/modules/es.array.includes': 177, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.join': 180, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.object.keys': 199, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.promise': 201, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.string.includes': 209, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.string.split': 216, + 'core-js/modules/web.dom-collections.iterator': 256, + 'i18next': 267, + 'i18next-browser-languagedetector': 264 } ], - 289: [ + 297: [ function (_dereq_, module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { @@ -60537,10 +62812,10 @@ exports.default = _default; }, { - './main': 290 + './main': 298 } ], - 290: [ + 298: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -60549,6 +62824,7 @@ _dereq_('core-js/modules/es.array.for-each'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.splice'); _dereq_('core-js/modules/es.object.get-own-property-descriptor'); _dereq_('core-js/modules/es.object.get-own-property-names'); _dereq_('core-js/modules/es.object.to-string'); @@ -60586,6 +62862,7 @@ _dereq_('core-js/modules/es.array.for-each'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.splice'); _dereq_('core-js/modules/es.object.get-own-property-names'); _dereq_('core-js/modules/es.object.to-string'); _dereq_('core-js/modules/es.string.iterator'); @@ -60656,7 +62933,14 @@ if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; - } /** + } /** + * @module Structure + * @submodule Structure + * @for p5 + * @requires constants + */ + // Core needs the PVariables object + /** * This is the p5 instance constructor. * * A p5 instance holds all the properties and methods related to @@ -60673,18 +62957,18 @@ * * @class p5 * @constructor - * @param {function} sketch a closure that can set optional preload(), + * @param {function(p5)} sketch a closure that can set optional preload(), * setup(), and/or draw() properties on the * given p5 instance * @param {HTMLElement} [node] element to attach canvas to * @return {p5} a p5 instance */ - var p5 = /*#__PURE__*/ - function () { - function p5(sketch, node, sync) { + var p5 = /*#__PURE__*/ function () { + function p5(sketch, node) { var _this = this; - _classCallCheck(this, p5); ////////////////////////////////////////////// + _classCallCheck(this, p5); + ////////////////////////////////////////////// // PUBLIC p5 PROPERTIES AND METHODS ////////////////////////////////////////////// /** @@ -60811,7 +63095,8 @@ // PRIVATE p5 PROPERTIES AND METHODS ////////////////////////////////////////////// this._setupDone = false; - this._preloadDone = false; // for handling hidpi + this._preloadDone = false; + // for handling hidpi this._pixelDensity = Math.ceil(window.devicePixelRatio) || 1; this._userNode = node; this._curElement = null; @@ -60822,6 +63107,7 @@ this._preloadCount = 0; this._isGlobal = false; this._loop = true; + this._startListener = null; this._initializeInstanceVariables(); this._defaultCanvasSize = { width: 100, @@ -60848,11 +63134,13 @@ blur: null }; this._millisStart = - 1; - this._recording = false; // States used in the custom random generators + this._recording = false; + // States used in the custom random generators this._lcg_random_state = null; this._gaussian_previous = false; this._events.wheel = null; - this._loadingScreenId = 'p5_loading'; // Allows methods to be registered on an instance that + this._loadingScreenId = 'p5_loading'; + // Allows methods to be registered on an instance that // are instance-specific. this._registeredMethods = { }; @@ -60884,7 +63172,39 @@ } if (window.DeviceMotionEvent && !window._isNodeWebkit) { this._events.devicemotion = null; - } + } // Function to invoke registered hooks before or after events such as preload, setup, and pre/post draw. + + p5.prototype.callRegisteredHooksFor = function (hookName) { + var target = this || p5.prototype; + var context = this._isGlobal ? window : this; + if (target._registeredMethods.hasOwnProperty(hookName)) { + var _methods = target._registeredMethods[hookName]; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + try { + for (var _iterator2 = _methods[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var method = _step2.value; + if (typeof method === 'function') { + method.call(context); + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + }; this._start = function () { // Find node if id given if (_this._userNode) { @@ -60894,6 +63214,7 @@ } var context = _this._isGlobal ? window : _this; if (context.preload) { + _this.callRegisteredHooksFor('beforePreload'); // Setup loading screen // Set loading screen into dom if not present // Otherwise displays and removes user provided loading screen @@ -60906,11 +63227,12 @@ var _node = _this._userNode || document.body; _node.appendChild(loadingScreen); } - var _methods = _this._preloadMethods; - for (var method in _methods) { + var _methods2 = _this._preloadMethods; + for (var method in _methods2) { // 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 + _methods2[method] = _methods2[method] || p5; + var obj = _methods2[method]; + //it's p5, check if it's global or instance if (obj === p5.prototype || obj === p5) { if (_this._isGlobal) { window[method] = _this._wrapPreload(_this, method); @@ -60936,6 +63258,7 @@ if (loadingScreen) { loadingScreen.parentNode.removeChild(loadingScreen); } + this.callRegisteredHooksFor('afterPreload'); if (!this._setupDone) { this._lastTargetFrameTime = window.performance.now(); this._lastRealFrameTime = window.performance.now(); @@ -60957,7 +63280,8 @@ var _this2 = this; return function () { //increment counter - _this2._incrementPreload(); //call original function + _this2._incrementPreload(); + //call original function for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } @@ -60965,15 +63289,18 @@ }; }; this._incrementPreload = function () { - var context = this._isGlobal ? window : this; // Do nothing if we tried to increment preloads outside of `preload` + var context = this._isGlobal ? window : this; + // Do nothing if we tried to increment preloads outside of `preload` if (context._preloadDone) return; context._setProperty('_preloadCount', context._preloadCount + 1); }; this._setup = function () { + _this.callRegisteredHooksFor('beforeSetup'); // Always create a default canvas. // Later on if the user calls createCanvas, this default one // will be replaced - _this.createCanvas(_this._defaultCanvasSize.width, _this._defaultCanvasSize.height, 'p2d'); // return preload functions to their normal vals if switched by preload + _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) { @@ -60982,38 +63309,39 @@ context[f] = context[f].bind(_this); } } - } // Record the time when sketch starts + } // Record the time when sketch starts _this._millisStart = window.performance.now(); - context._preloadDone = true; // Short-circuit on this, in case someone used the library in "global" + context._preloadDone = true; + // Short-circuit on this, in case someone used the library in "global" // mode earlier if (typeof context.setup === 'function') { context.setup(); - } // unhide any hidden canvases that were created + } // unhide any hidden canvases that were created var canvases = document.getElementsByTagName('canvas'); - var _iteratorNormalCompletion2 = true; - var _didIteratorError2 = false; - var _iteratorError2 = undefined; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; try { - for (var _iterator2 = canvases[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { - var k = _step2.value; + for (var _iterator3 = canvases[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var k = _step3.value; if (k.dataset.hidden === 'true') { k.style.visibility = ''; delete k.dataset.hidden; } } } catch (err) { - _didIteratorError2 = true; - _iteratorError2 = err; + _didIteratorError3 = true; + _iteratorError3 = err; } finally { try { - if (!_iteratorNormalCompletion2 && _iterator2.return != null) { - _iterator2.return(); + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); } } finally { - if (_didIteratorError2) { - throw _iteratorError2; + if (_didIteratorError3) { + throw _iteratorError3; } } } @@ -61023,11 +63351,13 @@ if (_this._accessibleOutputs.grid || _this._accessibleOutputs.text) { _this._updateAccsOutput(); } + _this.callRegisteredHooksFor('afterSetup'); }; this._draw = function () { var now = window.performance.now(); var time_since_last = now - _this._lastTargetFrameTime; - var target_time_between_frames = 1000 / _this._targetFrameRate; // only draw if we really need to; don't overextend the browser. + 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 @@ -61038,22 +63368,24 @@ var epsilon = 5; if (!_this._loop || time_since_last >= target_time_between_frames - epsilon) { //mandatory update values(matrixes and stack) - _this.redraw(); - _this._frameRate = 1000 / (now - _this._lastRealFrameTime); _this.deltaTime = now - _this._lastRealFrameTime; _this._setProperty('deltaTime', _this.deltaTime); + _this._frameRate = 1000 / _this.deltaTime; + _this.redraw(); _this._lastTargetFrameTime = Math.max(_this._lastTargetFrameTime + target_time_between_frames, now); - _this._lastRealFrameTime = now; // If the user is actually using mouse module, then update + _this._lastRealFrameTime = now; + // If the user is actually using mouse module, then update // coordinates, otherwise skip. We can test this by simply // checking if any of the mouse functions are available or not. // NOTE : This reflects only in complete build or modular build. if (typeof _this._updateMouseCoords !== 'undefined') { - _this._updateMouseCoords(); //reset delta values so they reset even if there is no mouse event to set them + _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 + } // get notified the next time the browser gives us // an opportunity to draw. if (_this._loop) { @@ -61092,9 +63424,14 @@ * */ this.remove = function () { + // Remove start listener to prevent orphan canvas being created + if (_this._startListener) { + window.removeEventListener('load', _this._startListener, false); + } var loadingScreen = document.getElementById(_this._loadingScreenId); if (loadingScreen) { - loadingScreen.parentNode.removeChild(loadingScreen); // Add 1 to preload counter to prevent the sketch ever executing setup() + loadingScreen.parentNode.removeChild(loadingScreen); + // Add 1 to preload counter to prevent the sketch ever executing setup() _this._incrementPreload(); } if (_this._curElement) { @@ -61102,37 +63439,37 @@ _this._loop = false; if (_this._requestAnimId) { window.cancelAnimationFrame(_this._requestAnimId); - } // unregister events sketch-wide + } // unregister events sketch-wide for (var ev in _this._events) { window.removeEventListener(ev, _this._events[ev]); - } // remove DOM elements created by p5, and listeners + } // remove DOM elements created by p5, and listeners - var _iteratorNormalCompletion3 = true; - var _didIteratorError3 = false; - var _iteratorError3 = undefined; + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; try { - for (var _iterator3 = _this._elements[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { - var e = _step3.value; + for (var _iterator4 = _this._elements[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var e = _step4.value; if (e.elt && e.elt.parentNode) { e.elt.parentNode.removeChild(e.elt); } for (var elt_ev in e._events) { e.elt.removeEventListener(elt_ev, e._events[elt_ev]); } - } // call any registered remove functions + } // call any registered remove functions } catch (err) { - _didIteratorError3 = true; - _iteratorError3 = err; + _didIteratorError4 = true; + _iteratorError4 = err; } finally { try { - if (!_iteratorNormalCompletion3 && _iterator3.return != null) { - _iterator3.return(); + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); } } finally { - if (_didIteratorError3) { - throw _iteratorError3; + if (_didIteratorError4) { + throw _iteratorError4; } } } @@ -61142,7 +63479,7 @@ f.call(self); } }); - } // remove window bound properties and methods + } // remove window bound properties and methods if (_this._isGlobal) { for (var p in p5.prototype) { @@ -61163,18 +63500,22 @@ } p5.instance = null; } - }; // call any registered init functions + }; + // call any registered init functions this._registeredMethods.init.forEach(function (f) { if (typeof f !== 'undefined') { f.call(this); } - }, this); // Set up promise preloads + }, this); + // Set up promise preloads this._setupPromisePreloads(); - var friendlyBindGlobal = this._createFriendlyGlobalFunctionBinder(); // If the user has created a global setup or draw function, + 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 + 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); @@ -61190,7 +63531,7 @@ } else { friendlyBindGlobal(p, p5.prototype[p]); } - } // Attach its properties to the window + } // Attach its properties to the window for (var p2 in this) { if (this.hasOwnProperty(p2)) { @@ -61200,10 +63541,11 @@ } 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 + 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) + } // 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)]; @@ -61230,7 +63572,8 @@ if (document.readyState === 'complete') { this._start(); } else { - window.addEventListener('load', this._start.bind(this), false); + this._startListener = this._start.bind(this); + window.addEventListener('load', this._startListener, false); } } _createClass(p5, [ @@ -61290,6 +63633,27 @@ ]; } target._registeredMethods[name].push(m); + } + }, + { + key: 'unregisterMethod', + value: function unregisterMethod(name, m) { + var target = this || p5.prototype; + if (target._registeredMethods.hasOwnProperty(name)) { + var methods = target._registeredMethods[name]; + var indexesToRemove = [ + ]; + // Find all indexes of the method `m` in the array of registered methods + for (var i = 0; i < methods.length; i++) { + if (methods[i] === m) { + indexesToRemove.push(i); + } + } // Remove all instances of the method `m` from the array + + for (var _i = indexesToRemove.length - 1; _i >= 0; _i--) { + methods.splice(indexesToRemove[_i], 1); + } + } } // create a function which provides a standardized process for binding // globals; this is implemented as a factory primarily so that there's a // way to redefine what "global" means for the binding function so it @@ -61324,7 +63688,7 @@ // 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 + } // 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 @@ -61385,13 +63749,15 @@ * } * */ - p5.disableFriendlyErrors = false; // attach constants to p5 prototype + p5.disableFriendlyErrors = false; + // attach constants to p5 prototype for (var k in constants) { p5.prototype[k] = constants[k]; - } // makes the `VERSION` constant available on the p5 object - // in instance mode, even if it hasn't been instatiated yet + } // makes the `VERSION` constant available on the p5 object + // in instance mode, even if it hasn't been instantiated yet - p5.VERSION = constants.VERSION; // functions that cause preload to wait + p5.VERSION = constants.VERSION; + // functions that cause preload to wait // more can be added by using registerPreloadMethod(func) p5.prototype._preloadMethods = { loadJSON: p5.prototype, @@ -61420,24 +63786,25 @@ exports.default = _default; }, { - './constants': 278, - './shim': 301, - 'core-js/modules/es.array.for-each': 172, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.get-own-property-names': 192, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.for-each': 247, - 'core-js/modules/web.dom-collections.iterator': 248 + './constants': 286, + './shim': 309, + 'core-js/modules/es.array.for-each': 175, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.array.splice': 185, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.get-own-property-names': 197, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.for-each': 255, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 291: [ + 299: [ function (_dereq_, module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { @@ -61450,819 +63817,1349 @@ 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 p5.Element - * objects are created by calling createCanvas(), createGraphics(), - * createDiv(), createImg(), createInput(), 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 - *
      - * - * function setup() { - * let c = createCanvas(50, 50); - * c.elt.style.border = '5px solid red'; - * } - * - * function draw() { - * background(220); - * } - * - *
      - * - * @property elt - * @readOnly - */ - this.elt = elt; - this._pInst = this._pixelsState = pInst; - this._events = { - }; - this.width = this.elt.offsetWidth; - this.height = this.elt.offsetHeight; - }; - /** - * - * Attaches the element to the parent specified. A way of setting - * the container for the element. Accepts either a string ID, DOM - * node, or p5.Element. If no arguments are given, parent node is returned. - * For more ways to position the canvas, see the - * - * positioning the canvas wiki page. - * - * @method parent - * @param {String|p5.Element|Object} parent the ID, DOM node, or p5.Element - * of desired parent element - * @chainable - * - * @example - *
      - * // Add the following comment to html file. - * // <div id="myContainer"></div> - * - * // The js code - * let cnv = createCanvas(100, 100); - * cnv.parent('myContainer'); - *
      - * - *
      - * let div0 = createDiv('this is the parent'); - * let div1 = createDiv('this is the child'); - * div1.parent(div0); // use p5.Element - *
      - * - *
      - * let div0 = createDiv('this is the parent'); - * div0.id('apples'); - * let div1 = createDiv('this is the child'); - * div1.parent('apples'); // use id - *
      - * - *
      - * let elt = document.getElementById('myParentDiv'); - * let div1 = createDiv('this is the child'); - * div1.parent(elt); // use element from page - *
      - * - * @alt - * no display. - */ - /** - * @method parent - * @return {p5.Element} - */ - _main.default.Element.prototype.parent = function (p) { - if (typeof p === 'undefined') { - return this.elt.parentNode; - } - if (typeof p === 'string') { - if (p[0] === '#') { - p = p.substring(1); - } - p = document.getElementById(p); - } else if (p instanceof _main.default.Element) { - p = p.elt; - } - p.appendChild(this.elt); - return this; - }; - /** - * - * Sets the ID of the element. If no ID argument is passed in, it instead - * returns the current ID of the element. - * Note that only one element can have a particular id in a page. - * The class() method can be used - * to identify multiple elements with the same class name. - * - * @method id - * @param {String} id ID of the element - * @chainable - * - * @example - *
      - * function setup() { - * let cnv = createCanvas(100, 100); - * // Assigns a CSS selector ID to - * // the canvas element. - * cnv.id('mycanvas'); - * } - *
      - * - * @alt - * no display. - */ - /** - * @method id - * @return {String} the id of the element - */ - _main.default.Element.prototype.id = function (id) { - if (typeof id === 'undefined') { - return this.elt.id; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); } - this.elt.id = id; - this.width = this.elt.offsetWidth; - this.height = this.elt.offsetHeight; - return this; - }; - /** - * - * Adds given class to the element. If no class argument is passed in, it - * instead returns a string containing the current class(es) of the element. - * - * @method class - * @param {String} class class to add - * @chainable - * - * @example - *
      - * function setup() { - * let cnv = createCanvas(100, 100); - * // Assigns a CSS selector class 'small' - * // to the canvas element. - * cnv.class('small'); - * } - *
      - * - * @alt - * no display. - */ - /** - * @method class - * @return {String} the class of the element - */ - _main.default.Element.prototype.class = function (c) { - if (typeof c === 'undefined') { - return this.elt.className; + } + 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); } - this.elt.className = c; - return this; - }; - /** - * The mousePressed() method is called - * once after every time a mouse button is pressed over the element. Some mobile - * browsers may also trigger this event on a touch screen, if the user performs - * a quick tap. This can be used to attach element-specific event listeners. - * - * @method mousePressed - * @param {Function|Boolean} fxn function to be fired when mouse is - * pressed over the element. - * if `false` is passed instead, the previously - * firing function will no longer fire. - * @chainable - * @example - *
      - * let cnv, d, g; - * function setup() { - * cnv = createCanvas(100, 100); - * cnv.mousePressed(changeGray); // attach listener for - * // canvas click only - * d = 10; - * g = 100; - * } - * - * function draw() { - * background(g); - * ellipse(width / 2, height / 2, d, d); - * } - * - * // this function fires with any click anywhere - * function mousePressed() { - * d = d + 10; - * } - * - * // this function fires only when cnv is clicked - * function changeGray() { - * g = random(0, 255); - * } - *
      - * - * @alt - * no display. - */ - _main.default.Element.prototype.mousePressed = function (fxn) { - // Prepend the mouse property setters to the event-listener. - // This is required so that mouseButton is set correctly prior to calling the callback (fxn). - // For details, see https://github.com/processing/p5.js/issues/3087. - var eventPrependedFxn = function eventPrependedFxn(event) { - this._pInst._setProperty('mouseIsPressed', true); - this._pInst._setMouseButton(event); // Pass along the return-value of the callback: - return fxn.call(this, event); - }; // Pass along the event-prepended form of the callback. - _main.default.Element._adjustListener('mousedown', eventPrependedFxn, this); - return this; - }; - /** - * The doubleClicked() method is called once after every time a - * mouse button is pressed twice over the element. This can be used to - * attach element and action-specific event listeners. - * - * @method doubleClicked - * @param {Function|Boolean} fxn function to be fired when mouse is - * double clicked over the element. - * if `false` is passed instead, the previously - * firing function will no longer fire. - * @return {p5.Element} - * @example - *
      - * let cnv, d, g; - * function setup() { - * cnv = createCanvas(100, 100); - * cnv.doubleClicked(changeGray); // attach listener for - * // canvas double click only - * d = 10; - * g = 100; - * } - * - * function draw() { - * background(g); - * ellipse(width / 2, height / 2, d, d); - * } - * - * // this function fires with any double click anywhere - * function doubleClicked() { - * d = d + 10; - * } - * - * // this function fires only when cnv is double clicked - * function changeGray() { - * g = random(0, 255); - * } - *
      - * - * @alt - * no display. - */ - _main.default.Element.prototype.doubleClicked = function (fxn) { - _main.default.Element._adjustListener('dblclick', fxn, this); - return this; - }; + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } /** + * @module DOM + * @submodule DOM + * @for p5.Element + */ /** - * The mouseWheel() method is called - * once after every time a mouse wheel is scrolled over the element. This can - * be used to attach element-specific event listeners. - * - * The method accepts a callback function as argument which will be executed - * when the `wheel` event is triggered on the element, the callback function is - * passed one argument `event`. The `event.deltaY` property returns negative - * values if the mouse wheel is rotated up or away from the user and positive - * in the other direction. The `event.deltaX` does the same as `event.deltaY` - * except it reads the horizontal wheel scroll of the mouse wheel. - * - * On macOS with "natural" scrolling enabled, the `event.deltaY` values are - * reversed. - * - * @method mouseWheel - * @param {Function|Boolean} fxn function to be fired when mouse is - * scrolled over the element. - * if `false` is passed instead, the previously - * firing function will no longer fire. - * @chainable - * @example - *
      - * let cnv, d, g; - * function setup() { - * cnv = createCanvas(100, 100); - * cnv.mouseWheel(changeSize); // attach listener for - * // activity on canvas only - * d = 10; - * g = 100; - * } - * - * function draw() { - * background(g); - * ellipse(width / 2, height / 2, d, d); - * } - * - * // this function fires with mousewheel movement - * // anywhere on screen - * function mouseWheel() { - * g = g + 10; - * } + * A class to describe an + * HTML element. + * Sketches can use many elements. Common elements include the drawing canvas, + * buttons, sliders, webcam feeds, and so on. * - * // this function fires with mousewheel movement - * // over canvas only - * function changeSize(event) { - * if (event.deltaY > 0) { - * d = d + 10; - * } else { - * d = d - 10; - * } - * } - *
      + * All elements share the methods of the `p5.Element` class. They're created + * with functions such as createCanvas() and + * createButton(). * - * @alt - * no display. - */ - _main.default.Element.prototype.mouseWheel = function (fxn) { - _main.default.Element._adjustListener('wheel', fxn, this); - return this; - }; - /** - * The mouseReleased() method is - * called once after every time a mouse button is released over the element. - * Some mobile browsers may also trigger this event on a touch screen, if the - * user performs a quick tap. This can be used to attach element-specific event listeners. + * @class p5.Element + * @constructor + * @param {HTMLElement} elt wrapped DOM element. + * @param {p5} [pInst] pointer to p5 instance. * - * @method mouseReleased - * @param {Function|Boolean} fxn function to be fired when mouse is - * released over the element. - * if `false` is passed instead, the previously - * firing function will no longer fire. - * @chainable * @example - *
      - * let cnv, d, g; + *
      + * * function setup() { - * cnv = createCanvas(100, 100); - * cnv.mouseReleased(changeGray); // attach listener for - * // activity on canvas only - * d = 10; - * g = 100; - * } - * - * function draw() { - * background(g); - * ellipse(width / 2, height / 2, d, d); - * } - * - * // this function fires after the mouse has been - * // released - * function mouseReleased() { - * d = d + 10; - * } - * - * // this function fires after the mouse has been - * // released while on canvas - * function changeGray() { - * g = random(0, 255); - * } - *
      + * createCanvas(100, 100); * - * @alt - * no display. - */ - _main.default.Element.prototype.mouseReleased = function (fxn) { - _main.default.Element._adjustListener('mouseup', fxn, this); - return this; - }; - /** - * The mouseClicked() method is - * called once after a mouse button is pressed and released over the element. - * Some mobile browsers may also trigger this event on a touch screen, if the - * user performs a quick tap. This can be used to attach element-specific event listeners. + * background(200); * - * @method mouseClicked - * @param {Function|Boolean} fxn function to be fired when mouse is - * clicked over the element. - * if `false` is passed instead, the previously - * firing function will no longer fire. - * @chainable - * @example - *
      - * - * let cnv, d, g; - * function setup() { - * cnv = createCanvas(100, 100); - * cnv.mouseClicked(changeGray); // attach listener for - * // activity on canvas only - * d = 10; - * g = 100; - * } + * // Create a button element and + * // place it beneath the canvas. + * let btn = createButton('change'); + * btn.position(0, 100); * - * function draw() { - * background(g); - * ellipse(width / 2, height / 2, d, d); - * } + * // Call randomColor() when + * // the button is pressed. + * btn.mousePressed(randomColor); * - * // this function fires after the mouse has been - * // clicked anywhere - * function mouseClicked() { - * d = d + 10; + * describe('A gray square with a button that says "change" beneath it. The square changes color when the user presses the button.'); * } * - * // this function fires after the mouse has been - * // clicked on canvas - * function changeGray() { - * g = random(0, 255); + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); * } * *
      - * - * @alt - * no display. - */ - _main.default.Element.prototype.mouseClicked = function (fxn) { - _main.default.Element._adjustListener('click', fxn, this); - return this; - }; - /** - * The mouseMoved() method is called once every time a - * mouse moves over the element. This can be used to attach an - * element-specific event listener. - * - * @method mouseMoved - * @param {Function|Boolean} fxn function to be fired when a mouse moves - * over the element. - * if `false` is passed instead, the previously - * firing function will no longer fire. - * @chainable - * @example - *
      - * let cnv; - * let d = 30; - * let g; - * function setup() { - * cnv = createCanvas(100, 100); - * cnv.mouseMoved(changeSize); // attach listener for - * // activity on canvas only - * d = 10; - * g = 100; - * } - * - * function draw() { - * background(g); - * fill(200); - * ellipse(width / 2, height / 2, d, d); - * } - * - * // this function fires when mouse moves anywhere on - * // page - * function mouseMoved() { - * g = g + 5; - * if (g > 255) { - * g = 0; - * } - * } - * - * // this function fires when mouse moves over canvas - * function changeSize() { - * d = d + 2; - * if (d > 100) { - * d = 0; - * } - * } - *
      - * - * @alt - * no display. - */ - _main.default.Element.prototype.mouseMoved = function (fxn) { - _main.default.Element._adjustListener('mousemove', fxn, this); - return this; - }; - /** - * The mouseOver() method is called once after every time a - * mouse moves onto the element. This can be used to attach an - * element-specific event listener. - * - * @method mouseOver - * @param {Function|Boolean} fxn function to be fired when a mouse moves - * onto the element. - * if `false` is passed instead, the previously - * firing function will no longer fire. - * @chainable - * @example - *
      - * let cnv; - * let d; - * function setup() { - * cnv = createCanvas(100, 100); - * cnv.mouseOver(changeGray); - * d = 10; - * } - * - * function draw() { - * ellipse(width / 2, height / 2, d, d); - * } - * - * function changeGray() { - * d = d + 10; - * if (d > 100) { - * d = 0; - * } - * } - *
      - * - * @alt - * no display. */ - _main.default.Element.prototype.mouseOver = function (fxn) { - _main.default.Element._adjustListener('mouseover', fxn, this); - return this; - }; - /** - * The mouseOut() method is called once after every time a - * mouse moves off the element. This can be used to attach an - * element-specific event listener. - * - * @method mouseOut - * @param {Function|Boolean} fxn function to be fired when a mouse - * moves off of an element. - * if `false` is passed instead, the previously - * firing function will no longer fire. - * @chainable - * @example - *
      - * let cnv; - * let d; - * function setup() { - * cnv = createCanvas(100, 100); - * cnv.mouseOut(changeGray); - * d = 10; - * } - * - * function draw() { - * ellipse(width / 2, height / 2, d, d); - * } - * - * function changeGray() { - * d = d + 10; - * if (d > 100) { - * d = 0; - * } - * } - *
      - * - * @alt - * no display. - */ - _main.default.Element.prototype.mouseOut = function (fxn) { - _main.default.Element._adjustListener('mouseout', fxn, this); - return this; - }; - /** - * The touchStarted() method is called once after every time a touch is - * registered. This can be used to attach element-specific event listeners. - * - * @method touchStarted - * @param {Function|Boolean} fxn function to be fired when a touch - * starts over the element. - * if `false` is passed instead, the previously - * firing function will no longer fire. - * @chainable - * @example - *
      - * let cnv; - * let d; - * let g; - * function setup() { - * cnv = createCanvas(100, 100); - * cnv.touchStarted(changeGray); // attach listener for - * // canvas click only - * d = 10; - * g = 100; - * } - * - * function draw() { - * background(g); - * ellipse(width / 2, height / 2, d, d); - * } - * - * // this function fires with any touch anywhere - * function touchStarted() { - * d = d + 10; - * } - * - * // this function fires only when cnv is clicked - * function changeGray() { - * g = random(0, 255); - * } - *
      - * - * @alt - * no display. - */ - _main.default.Element.prototype.touchStarted = function (fxn) { - _main.default.Element._adjustListener('touchstart', fxn, this); - return this; - }; - /** - * The touchMoved() method is called once after every time a touch move is - * registered. This can be used to attach element-specific event listeners. - * - * @method touchMoved - * @param {Function|Boolean} fxn function to be fired when a touch moves over - * the element. - * if `false` is passed instead, the previously - * firing function will no longer fire. - * @chainable - * @example - *
      - * let cnv; - * let g; - * function setup() { - * cnv = createCanvas(100, 100); - * cnv.touchMoved(changeGray); // attach listener for - * // canvas click only - * g = 100; - * } - * - * function draw() { - * background(g); - * } - * - * // this function fires only when cnv is clicked - * function changeGray() { - * g = random(0, 255); - * } - *
      - * - * @alt - * no display. - */ - _main.default.Element.prototype.touchMoved = function (fxn) { - _main.default.Element._adjustListener('touchmove', fxn, this); - return this; - }; - /** - * The touchEnded() method is called once after every time a touch is - * registered. This can be used to attach element-specific event listeners. - * - * @method touchEnded - * @param {Function|Boolean} fxn function to be fired when a touch ends - * over the element. - * if `false` is passed instead, the previously - * firing function will no longer fire. - * @chainable - * @example - *
      - * let cnv; - * let d; - * let g; - * function setup() { - * cnv = createCanvas(100, 100); - * cnv.touchEnded(changeGray); // attach listener for - * // canvas click only - * d = 10; - * g = 100; - * } - * - * function draw() { - * background(g); - * ellipse(width / 2, height / 2, d, d); - * } - * - * // this function fires with any touch anywhere - * function touchEnded() { - * d = d + 10; - * } - * - * // this function fires only when cnv is clicked - * function changeGray() { - * g = random(0, 255); - * } - *
      - * - * @alt - * no display. - */ - _main.default.Element.prototype.touchEnded = function (fxn) { - _main.default.Element._adjustListener('touchend', fxn, this); - return this; - }; - /** - * The dragOver() method is called once after every time a - * file is dragged over the element. This can be used to attach an - * element-specific event listener. - * - * @method dragOver - * @param {Function|Boolean} fxn function to be fired when a file is - * dragged over the element. - * if `false` is passed instead, the previously - * firing function will no longer fire. - * @chainable - * @example - *
      - * // To test this sketch, simply drag a - * // file over the canvas - * function setup() { - * let c = createCanvas(100, 100); - * background(200); - * textAlign(CENTER); - * text('Drag file', width / 2, height / 2); - * c.dragOver(dragOverCallback); - * } - * - * // This function will be called whenever - * // a file is dragged over the canvas - * function dragOverCallback() { - * background(240); - * text('Dragged over', width / 2, height / 2); - * } - *
      - * @alt - * nothing displayed - */ - _main.default.Element.prototype.dragOver = function (fxn) { - _main.default.Element._adjustListener('dragover', fxn, this); - return this; - }; - /** - * The dragLeave() method is called once after every time a - * dragged file leaves the element area. This can be used to attach an - * element-specific event listener. - * - * @method dragLeave - * @param {Function|Boolean} fxn function to be fired when a file is - * dragged off the element. - * if `false` is passed instead, the previously - * firing function will no longer fire. - * @chainable - * @example - *
      - * // To test this sketch, simply drag a file - * // over and then out of the canvas area - * function setup() { - * let c = createCanvas(100, 100); - * background(200); - * textAlign(CENTER); - * text('Drag file', width / 2, height / 2); - * c.dragLeave(dragLeaveCallback); - * } - * - * // This function will be called whenever - * // a file is dragged out of the canvas - * function dragLeaveCallback() { - * background(240); - * text('Dragged off', width / 2, height / 2); - * } - *
      - * @alt - * nothing displayed - */ - _main.default.Element.prototype.dragLeave = function (fxn) { - _main.default.Element._adjustListener('dragleave', fxn, this); - return this; - }; // General handler for event attaching and detaching - _main.default.Element._adjustListener = function (ev, fxn, ctx) { - if (fxn === false) { - _main.default.Element._detachListener(ev, ctx); - } else { - _main.default.Element._attachListener(ev, fxn, ctx); - } - return this; - }; - _main.default.Element._attachListener = function (ev, fxn, ctx) { - // detach the old listener if there was one - if (ctx._events[ev]) { - _main.default.Element._detachListener(ev, ctx); - } - var f = fxn.bind(ctx); - ctx.elt.addEventListener(ev, f, false); - ctx._events[ev] = f; - }; - _main.default.Element._detachListener = function (ev, ctx) { - var f = ctx._events[ev]; - ctx.elt.removeEventListener(ev, f, false); - ctx._events[ev] = null; - }; - /** - * Helper fxn for sharing pixel methods - */ - _main.default.Element.prototype._setProperty = function (prop, value) { - this[prop] = value; - }; + + _main.default.Element = /*#__PURE__*/ function () { + function _class(elt, pInst) { + _classCallCheck(this, _class); + /** + * Underlying + * HTMLElement + * object. Its properties and methods can be used directly. + * + * @example + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Set the border style for the + * // canvas. + * cnv.elt.style.border = '5px dashed deeppink'; + * + * describe('A gray square with a pink border drawn with dashed lines.'); + * } + * + *
      + * + * @property elt + * @name elt + * @readOnly + */ + this.elt = elt; + /** + * @private + * @type {p5.Element} + * @name _pInst + */ + this._pInst = this._pixelsState = pInst; + this._events = { + }; + /** + * @type {Number} + * @property width + * @name width + */ + this.width = this.elt.offsetWidth; + /** + * @type {Number} + * @property height + * @name height + */ + this.height = this.elt.offsetHeight; + } /** + * Attaches this element to a parent element. + * + * For example, a `<div></div>` element may be used as a box to + * hold two pieces of text, a header and a paragraph. The + * `<div></div>` is the parent element of both the header and + * paragraph. + * + * The parameter `parent` can have one of three types. `parent` can be a + * string with the parent element's ID, as in + * `myElement.parent('container')`. It can also be another + * p5.Element object, as in + * `myElement.parent(myDiv)`. Finally, `parent` can be an `HTMLElement` + * object, as in `myElement.parent(anotherElement)`. + * + * Calling `myElement.parent()` without an argument returns this element's + * parent. + * + * @method parent + * @param {String|p5.Element|Object} parent ID, p5.Element, + * or HTMLElement of desired parent element. + * @chainable + * + * @example + *
      + * + * function setup() { + * background(200); + * + * // Create a div element. + * let div = createDiv(); + * // Place the div in the top-left corner. + * div.position(10, 20); + * // Set its width and height. + * div.size(80, 60); + * // Set its background color to white + * div.style('background-color', 'white'); + * // Align any text to the center. + * div.style('text-align', 'center'); + * // Set its ID to "container". + * div.id('container'); + * + * // Create a paragraph element. + * let p = createP('p5*js'); + * // Make the div its parent + * // using its ID "container". + * p.parent('container'); + * + * describe('The text "p5*js" written in black at the center of a white rectangle. The rectangle is inside a gray square.'); + * } + * + *
      + * + *
      + * + * function setup() { + * background(200); + * + * // Create rectangular div element. + * let div = createDiv(); + * // Place the div in the top-left corner. + * div.position(10, 20); + * // Set its width and height. + * div.size(80, 60); + * // Set its background color and align + * // any text to the center. + * div.style('background-color', 'white'); + * div.style('text-align', 'center'); + * + * // Create a paragraph element. + * let p = createP('p5*js'); + * // Make the div its parent. + * p.parent(div); + * + * describe('The text "p5*js" written in black at the center of a white rectangle. The rectangle is inside a gray square.'); + * } + * + *
      + * + *
      + * + * function setup() { + * background(200); + * + * // Create rectangular div element. + * let div = createDiv(); + * // Place the div in the top-left corner. + * div.position(10, 20); + * // Set its width and height. + * div.size(80, 60); + * // Set its background color and align + * // any text to the center. + * div.style('background-color', 'white'); + * div.style('text-align', 'center'); + * + * // Create a paragraph element. + * let p = createP('p5*js'); + * // Make the div its parent + * // using the underlying + * // HTMLElement. + * p.parent(div.elt); + * + * describe('The text "p5*js" written in black at the center of a white rectangle. The rectangle is inside a gray square.'); + * } + * + *
      + */ + /** + * @method parent + * @return {p5.Element} + */ + + _createClass(_class, [ + { + key: 'parent', + value: function parent(p) { + if (typeof p === 'undefined') { + return this.elt.parentNode; + } + if (typeof p === 'string') { + if (p[0] === '#') { + p = p.substring(1); + } + p = document.getElementById(p); + } else if (p instanceof _main.default.Element) { + p = p.elt; + } + p.appendChild(this.elt); + return this; + } /** + * Sets this element's ID using a given string. + * + * Calling `myElement.id()` without an argument returns its ID as a string. + * + * @method id + * @param {String} id ID of the element. + * @chainable + * + * @example + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Set the canvas' ID + * // to "mycanvas". + * cnv.id('mycanvas'); + * + * // Get the canvas' ID. + * let id = cnv.id(); + * text(id, 24, 54); + * + * describe('The text "mycanvas" written in black on a gray background.'); + * } + * + *
      + */ + /** + * @method id + * @return {String} ID of the element. + */ + + }, + { + key: 'id', + value: function id(_id) { + if (typeof _id === 'undefined') { + return this.elt.id; + } + this.elt.id = _id; + this.width = this.elt.offsetWidth; + this.height = this.elt.offsetHeight; + return this; + } /** + * Adds a + * class attribute + * to the element. + * + * Calling `myElement.class()` without an argument returns a string with its current classes. + * + * @method class + * @param {String} class class to add. + * @chainable + * + * @example + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Add the class "small" to the + * // canvas element. + * cnv.class('small'); + * + * // Get the canvas element's class + * // and display it. + * let c = cnv.class(); + * text(c, 35, 54); + * + * describe('The word "small" written in black on a gray canvas.'); + * + * } + * + *
      + */ + /** + * @method class + * @return {String} element's classes, if any. + */ + + }, + { + key: 'class', + value: function _class(c) { + if (typeof c === 'undefined') { + return this.elt.className; + } + this.elt.className = c; + return this; + } /** + * Calls a function when the mouse is pressed over the element. + * Calling `myElement.mousePressed(false)` disables the function. + * + * Note: Some mobile browsers may also trigger this event when the element + * receives a quick tap. + * + * @method mousePressed + * @param {Function|Boolean} fxn function to call when the mouse is + * pressed over the element. + * `false` disables the function. + * @chainable + * @example + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when the canvas + * // is pressed. + * cnv.mousePressed(randomColor); + * + * describe('A gray square changes color when the mouse is pressed.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
      + * + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Paint the background either + * // red, yellow, blue, or green + * // when the canvas is pressed. + * cnv.mousePressed(() => { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * }); + * + * describe('A gray square changes color when the mouse is pressed.'); + * } + * + *
      + */ + + }, + { + key: 'mousePressed', + value: function mousePressed(fxn) { + // Prepend the mouse property setters to the event-listener. + // This is required so that mouseButton is set correctly prior to calling the callback (fxn). + // For details, see https://github.com/processing/p5.js/issues/3087. + var eventPrependedFxn = function eventPrependedFxn(event) { + this._pInst._setProperty('mouseIsPressed', true); + this._pInst._setMouseButton(event); + // Pass along the return-value of the callback: + return fxn.call(this, event); + }; + // Pass along the event-prepended form of the callback. + _main.default.Element._adjustListener('mousedown', eventPrependedFxn, this); + return this; + } /** + * Calls a function when the mouse is pressed twice over the element. + * Calling `myElement.doubleClicked(false)` disables the function. + * + * @method doubleClicked + * @param {Function|Boolean} fxn function to call when the mouse is + * double clicked over the element. + * `false` disables the function. + * @chainable + * @example + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when the + * // canvas is double-clicked. + * cnv.doubleClicked(randomColor); + * + * describe('A gray square changes color when the user double-clicks the canvas.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
      + * + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Paint the background either + * // red, yellow, blue, or green + * // when the canvas is double-clicked. + * cnv.doubleClicked(() => { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * }); + * + * describe('A gray square changes color when the user double-clicks the canvas.'); + * } + * + *
      + */ + + }, + { + key: 'doubleClicked', + value: function doubleClicked(fxn) { + _main.default.Element._adjustListener('dblclick', fxn, this); + return this; + } /** + * Calls a function when the mouse wheel scrolls over th element. + * + * The callback function, `fxn`, is passed an `event` object. `event` has + * two numeric properties, `deltaY` and `deltaX`. `event.deltaY` is + * negative if the mouse wheel rotates away from the user. It's positive if + * the mouse wheel rotates toward the user. `event.deltaX` is positive if + * the mouse wheel moves to the right. It's negative if the mouse wheel moves + * to the left. + * + * Calling `myElement.mouseWheel(false)` disables the function. + * + * @method mouseWheel + * @param {Function|Boolean} fxn function to call when the mouse wheel is + * scrolled over the element. + * `false` disables the function. + * @chainable + * @example + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when the + * // mouse wheel moves. + * cnv.mouseWheel(randomColor); + * + * describe('A gray square changes color when the user scrolls the mouse wheel over the canvas.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
      + * + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Paint the background either + * // red, yellow, blue, or green + * // when the mouse wheel moves. + * cnv.mouseWheel(() => { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * }); + * + * describe('A gray square changes color when the user scrolls the mouse wheel over the canvas.'); + * } + * + *
      + * + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call changeBackground() when the + * // mouse wheel moves. + * cnv.mouseWheel(changeBackground); + * + * describe('A gray square. When the mouse wheel scrolls over the square, it changes color and displays shapes.'); + * } + * + * function changeBackground(event) { + * // Change the background color + * // based on deltaY. + * if (event.deltaY > 0) { + * background('deeppink'); + * } else if (event.deltaY < 0) { + * background('cornflowerblue'); + * } else { + * background(200); + * } + * + * // Draw a shape based on deltaX. + * if (event.deltaX > 0) { + * circle(50, 50, 20); + * } else if (event.deltaX < 0) { + * square(40, 40, 20); + * } + * } + * + *
      + */ + + }, + { + key: 'mouseWheel', + value: function mouseWheel(fxn) { + _main.default.Element._adjustListener('wheel', fxn, this); + return this; + } /** + * Calls a function when the mouse is released over the element. Calling + * `myElement.mouseReleased(false)` disables the function. + * + * Note: Some mobile browsers may also trigger this event when the element + * receives a quick tap. + * + * @method mouseReleased + * @param {Function|Boolean} fxn function to call when the mouse is + * pressed over the element. + * `false` disables the function. + * @chainable + * @example + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when a + * // mouse press ends. + * cnv.mouseReleased(randomColor); + * + * describe('A gray square changes color when the user releases a mouse press.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
      + * + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Paint the background either + * // red, yellow, blue, or green + * // when a mouse press ends. + * cnv.mouseReleased(() => { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * }); + * + * describe('A gray square changes color when the user releases a mouse press.'); + * } + * + *
      + */ + + }, + { + key: 'mouseReleased', + value: function mouseReleased(fxn) { + _main.default.Element._adjustListener('mouseup', fxn, this); + return this; + } /** + * Calls a function when the mouse is pressed and released over the element. + * Calling `myElement.mouseReleased(false)` disables the function. + * + * Note: Some mobile browsers may also trigger this event when the element + * receives a quick tap. + * + * @method mouseClicked + * @param {Function|Boolean} fxn function to call when the mouse is + * pressed and released over the element. + * `false` disables the function. + * @chainable + * @example + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when a + * // mouse press ends. + * cnv.mouseClicked(randomColor); + * + * describe('A gray square changes color when the user releases a mouse press.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
      + * + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Paint the background either + * // red, yellow, blue, or green + * // when a mouse press ends. + * cnv.mouseClicked(() => { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * }); + * + * describe('A gray square changes color when the user releases a mouse press.'); + * } + * + *
      + */ + + }, + { + key: 'mouseClicked', + value: function mouseClicked(fxn) { + _main.default.Element._adjustListener('click', fxn, this); + return this; + } /** + * Calls a function when the mouse moves over the element. Calling + * `myElement.mouseMoved(false)` disables the function. + * + * @method mouseMoved + * @param {Function|Boolean} fxn function to call when the mouse + * moves over the element. + * `false` disables the function. + * @chainable + * @example + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when the + * // mouse moves. + * cnv.mouseMoved(randomColor); + * + * describe('A gray square changes color when the mouse moves over the canvas.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
      + * + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Paint the background either + * // red, yellow, blue, or green + * // when the mouse moves. + * cnv.mouseMoved(() => { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * }); + * + * describe('A gray square changes color when the mouse moves over the canvas.'); + * } + * + *
      + */ + + }, + { + key: 'mouseMoved', + value: function mouseMoved(fxn) { + _main.default.Element._adjustListener('mousemove', fxn, this); + return this; + } /** + * Calls a function when the mouse moves onto the element. Calling + * `myElement.mouseOver(false)` disables the function. + * + * @method mouseOver + * @param {Function|Boolean} fxn function to call when the mouse + * moves onto the element. + * `false` disables the function. + * @chainable + * @example + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when the + * // mouse moves onto the canvas. + * cnv.mouseOver(randomColor); + * + * describe('A gray square changes color when the mouse moves onto the canvas.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
      + * + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Paint the background either + * // red, yellow, blue, or green + * // when the mouse moves onto + * // the canvas. + * cnv.mouseOver(() => { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * }); + * + * describe('A gray square changes color when the mouse moves onto the canvas.'); + * } + * + *
      + */ + + }, + { + key: 'mouseOver', + value: function mouseOver(fxn) { + _main.default.Element._adjustListener('mouseover', fxn, this); + return this; + } /** + * Calls a function when the mouse moves off the element. Calling + * `myElement.mouseOut(false)` disables the function. + * + * @method mouseOut + * @param {Function|Boolean} fxn function to call when the mouse + * moves off the element. + * `false` disables the function. + * @chainable + * @example + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when the + * // mouse moves off the canvas. + * cnv.mouseOut(randomColor); + * + * describe('A gray square changes color when the mouse moves off the canvas.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
      + * + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Paint the background either + * // red, yellow, blue, or green + * // when the mouse moves off + * // the canvas. + * cnv.mouseOut(() => { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * }); + * + * describe('A gray square changes color when the mouse moves off the canvas.'); + * } + * + *
      + */ + + }, + { + key: 'mouseOut', + value: function mouseOut(fxn) { + _main.default.Element._adjustListener('mouseout', fxn, this); + return this; + } /** + * Calls a function when the element is touched. Calling + * `myElement.touchStarted(false)` disables the function. + * + * Note: Touch functions only work on mobile devices. + * + * @method touchStarted + * @param {Function|Boolean} fxn function to call when the touch + * starts. + * `false` disables the function. + * @chainable + * @example + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when the + * // user touches the canvas. + * cnv.touchStarted(randomColor); + * + * describe('A gray square changes color when the user touches the canvas.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
      + * + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Paint the background either + * // red, yellow, blue, or green + * // when the user touches the + * // canvas. + * cnv.touchStarted(() => { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * }); + * + * describe('A gray square changes color when the user touches the canvas.'); + * } + * + *
      + */ + + }, + { + key: 'touchStarted', + value: function touchStarted(fxn) { + _main.default.Element._adjustListener('touchstart', fxn, this); + return this; + } /** + * Calls a function when the user touches the element and moves their + * finger. Calling `myElement.touchMoved(false)` disables the + * function. + * + * Note: Touch functions only work on mobile devices. + * + * @method touchMoved + * @param {Function|Boolean} fxn function to call when the touch + * moves over the element. + * `false` disables the function. + * @chainable + * @example + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when the + * // user touches the canvas + * // and moves. + * cnv.touchMoved(randomColor); + * + * describe('A gray square changes color when the user touches the canvas and moves.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
      + * + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Paint the background either + * // red, yellow, blue, or green + * // when the user touches the + * // canvas and moves. + * cnv.touchMoved(() => { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * }); + * + * describe('A gray square changes color when the user touches the canvas and moves.'); + * } + * + *
      + */ + + }, + { + key: 'touchMoved', + value: function touchMoved(fxn) { + _main.default.Element._adjustListener('touchmove', fxn, this); + return this; + } /** + * Calls a function when the user stops touching the element. Calling + * `myElement.touchMoved(false)` disables the function. + * + * Note: Touch functions only work on mobile devices. + * + * @method touchEnded + * @param {Function|Boolean} fxn function to call when the touch + * ends. + * `false` disables the function. + * @chainable + * @example + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when the + * // user touches the canvas, + * // then lifts their finger. + * cnv.touchEnded(randomColor); + * + * describe('A gray square changes color when the user touches the canvas, then lifts their finger.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
      + * + *
      + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Paint the background either + * // red, yellow, blue, or green + * // when the user touches the + * // canvas, then lifts their + * // finger. + * cnv.touchEnded(() => { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * }); + * + * describe('A gray square changes color when the user touches the canvas, then lifts their finger.'); + * } + * + *
      + */ + + }, + { + key: 'touchEnded', + value: function touchEnded(fxn) { + _main.default.Element._adjustListener('touchend', fxn, this); + return this; + } /** + * Calls a function when a file is dragged over the element. Calling + * `myElement.dragOver(false)` disables the function. + * + * @method dragOver + * @param {Function|Boolean} fxn function to call when the file is + * dragged over the element. + * `false` disables the function. + * @chainable + * @example + *
      + * + * // Drag a file over the canvas to test. + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call helloFile() when a + * // file is dragged over + * // the canvas. + * cnv.dragOver(helloFile); + * + * describe('A gray square. The text "hello, file" appears when a file is dragged over the square.'); + * } + * + * function helloFile() { + * text('hello, file', 50, 50); + * } + * + *
      + * + *
      + * + * // Drag a file over the canvas to test. + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Say "hello, file" when a + * // file is dragged over + * // the canvas. + * cnv.dragOver(() => { + * text('hello, file', 50, 50); + * }); + * + * describe('A gray square. The text "hello, file" appears when a file is dragged over the square.'); + * } + * + *
      + */ + + }, + { + key: 'dragOver', + value: function dragOver(fxn) { + _main.default.Element._adjustListener('dragover', fxn, this); + return this; + } /** + * Calls a function when a file is dragged off the element. Calling + * Calling `myElement.dragLeave(false)` disables the function. + * + * @method dragLeave + * @param {Function|Boolean} fxn function to call when the file is + * dragged off the element. + * `false` disables the function. + * @chainable + * @example + *
      + * + * // Drag a file over, then off + * // the canvas to test. + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call byeFile() when a + * // file is dragged over, + * // then off the canvas. + * cnv.dragLeave(byeFile); + * + * describe('A gray square. The text "bye, file" appears when a file is dragged over, then off the square.'); + * } + * + * function byeFile() { + * text('bye, file', 50, 50); + * } + * + *
      + * + *
      + * + * // Drag a file over, then off + * // the canvas to test. + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Say "bye, file" when a + * // file is dragged over, + * // then off the canvas. + * cnv.dragLeave(() => { + * text('bye, file', 50, 50); + * }); + * + * describe('A gray square. The text "bye, file" appears when a file is dragged over, then off the square.'); + * } + * + *
      + */ + + }, + { + key: 'dragLeave', + value: function dragLeave(fxn) { + _main.default.Element._adjustListener('dragleave', fxn, this); + return this; + } /** + * + * @private + * @static + * @param {String} ev + * @param {Boolean|Function} fxn + * @param {Element} ctx + * @chainable + * @alt + * General handler for event attaching and detaching + */ + + }, + { + key: '_setProperty', + /** + * Helper fxn for sharing pixel methods + */ + value: function _setProperty(prop, value) { + this[prop] = value; + } + } + ], [ + { + key: '_adjustListener', + value: function _adjustListener(ev, fxn, ctx) { + if (fxn === false) { + _main.default.Element._detachListener(ev, ctx); + } else { + _main.default.Element._attachListener(ev, fxn, ctx); + } + return this; + } /** + * + * @private + * @static + * @param {String} ev + * @param {Function} fxn + * @param {Element} ctx + */ + + }, + { + key: '_attachListener', + value: function _attachListener(ev, fxn, ctx) { + // detach the old listener if there was one + if (ctx._events[ev]) { + _main.default.Element._detachListener(ev, ctx); + } + var f = fxn.bind(ctx); + ctx.elt.addEventListener(ev, f, false); + ctx._events[ev] = f; + } /** + * + * @private + * @static + * @param {String} ev + * @param {Element} ctx + */ + + }, + { + key: '_detachListener', + value: function _detachListener(ev, ctx) { + var f = ctx._events[ev]; + ctx.elt.removeEventListener(ev, f, false); + ctx._events[ev] = null; + } + } + ]); + return _class; + }(); var _default = _main.default.Element; exports.default = _default; }, { - './main': 290 + './main': 298 } ], - 292: [ + 300: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -62272,7 +65169,10 @@ _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.splice'); _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.get-prototype-of'); _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.reflect.construct'); + _dereq_('core-js/modules/es.regexp.to-string'); _dereq_('core-js/modules/es.string.iterator'); _dereq_('core-js/modules/es.weak-map'); _dereq_('core-js/modules/web.dom-collections.iterator'); @@ -62302,6 +65202,7 @@ } _dereq_('core-js/modules/es.array.index-of'); _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.object.get-prototype-of'); Object.defineProperty(exports, '__esModule', { value: true }); @@ -62354,11 +65255,94 @@ default: obj }; - } /** - * @module Rendering - * @submodule Rendering - * @for p5 - */ + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } + function _inherits(subClass, superClass) { + if (typeof superClass !== 'function' && superClass !== null) { + throw new TypeError('Super expression must either be null or a function'); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + if (superClass) _setPrototypeOf(subClass, superClass); + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + return _setPrototypeOf(o, p); + } + function _createSuper(Derived) { + function isNativeReflectConstruct() { + if (typeof Reflect === 'undefined' || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === 'function') return true; + try { + Date.prototype.toString.call(Reflect.construct(Date, [ + ], function () { + })); + return true; + } catch (e) { + return false; + } + } + return function () { + var Super = _getPrototypeOf(Derived), + result; + if (isNativeReflectConstruct()) { + var NewTarget = _getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return _possibleConstructorReturn(this, result); + }; + } + function _possibleConstructorReturn(self, call) { + if (call && (_typeof(call) === 'object' || typeof call === 'function')) { + return call; + } + return _assertThisInitialized(self); + } + function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called'); + } + return self; + } + function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); + } /** + * @module Rendering + * @submodule Rendering + * @for p5 + */ /** * Thin wrapper around a renderer, to be used for creating a * graphics buffer object. Use this class if you need @@ -62373,180 +65357,222 @@ * @param {Number} h height * @param {Constant} renderer the renderer to use, either P2D or WEBGL * @param {p5} [pInst] pointer to p5 instance + * @param {HTMLCanvasElement} [canvas] existing html canvas element */ - _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.Graphics = /*#__PURE__*/ function (_p5$Element) { + _inherits(_class, _p5$Element); + var _super = _createSuper(_class); + function _class(w, h, renderer, pInst, canvas) { + var _this; + _classCallCheck(this, _class); + var canvasTemp; + if (canvas) { + canvasTemp = canvas; + } else { + canvasTemp = document.createElement('canvas'); + } + _this = _super.call(this, canvasTemp, pInst); + _this.canvas = canvasTemp; + var r = renderer || constants.P2D; + var node = pInst._userNode || document.body; + if (!canvas) { + node.appendChild(_this.canvas); + } // bind methods and props of p5 to the new object + + for (var p in _main.default.prototype) { + if (!_this[p]) { + if (typeof _main.default.prototype[p] === 'function') { + _this[p] = _main.default.prototype[p].bind(_assertThisInitialized(_this)); + } else { + _this[p] = _main.default.prototype[p]; + } } } - } - _main.default.prototype._initializeInstanceVariables.apply(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; + _main.default.prototype._initializeInstanceVariables.apply(_assertThisInitialized(_this)); + _this.width = w; + _this.height = h; + _this._pixelDensity = pInst._pixelDensity; + if (r === constants.WEBGL) { + _this._renderer = new _main.default.RendererGL(_this.canvas, _assertThisInitialized(_this), false); + } else { + _this._renderer = new _main.default.Renderer2D(_this.canvas, _assertThisInitialized(_this), false); } - }); - this._renderer.resize(w, h); - this._renderer._applyDefaults(); - return this; - }; - _main.default.Graphics.prototype = Object.create(_main.default.Element.prototype); - /** - * Resets certain values such as those modified by functions in the Transform category - * and in the Lights category that are not automatically reset - * with graphics buffer objects. Calling this in draw() will copy the behavior - * of the standard canvas. - * - * @method reset - * @example - * - *
      - * let pg; - * function setup() { - * createCanvas(100, 100); - * background(0); - * pg = createGraphics(50, 100); - * pg.fill(0); - * frameRate(5); - * } - * - * function draw() { - * image(pg, width / 2, 0); - * pg.background(255); - * // p5.Graphics object behave a bit differently in some cases - * // The normal canvas on the left resets the translate - * // with every loop through draw() - * // the graphics object on the right doesn't automatically reset - * // so translate() is additive and it moves down the screen - * rect(0, 0, width / 2, 5); - * pg.rect(0, 0, width / 2, 5); - * translate(0, 5, 0); - * pg.translate(0, 5, 0); - * } - * function mouseClicked() { - * // if you click you will see that - * // reset() resets the translate back to the initial state - * // of the Graphics object - * pg.reset(); - * } - *
      - * - * @alt - * A white line on a black background stays still on the top-left half. - * A black line animates from top to bottom on a white background on the right half. - * When clicked, the black line starts back over at the top. - */ - _main.default.Graphics.prototype.reset = function () { - this._renderer.resetMatrix(); - if (this._renderer.isP3D) { - this._renderer._update(); - } - }; - /** - * Removes a Graphics object from the page and frees any resources - * associated with it. - * - * @method remove - * - * @example - *
      - * let bg; - * function setup() { - * bg = createCanvas(100, 100); - * bg.background(0); - * image(bg, 0, 0); - * bg.remove(); - * } - *
      - * - *
      - * 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; - * } - * } - *
      - * - * @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]); - } - }; + pInst._elements.push(_assertThisInitialized(_this)); + Object.defineProperty(_assertThisInitialized(_this), 'deltaTime', { + get: function get() { + return this._pInst.deltaTime; + } + }); + _this._renderer.resize(w, h); + _this._renderer._applyDefaults(); + return _possibleConstructorReturn(_this, _assertThisInitialized(_this)); + } /** + * Resets certain values such as those modified by functions in the Transform category + * and in the Lights category that are not automatically reset + * with graphics buffer objects. Calling this in draw() will copy the behavior + * of the standard canvas. + * + * @method reset + * @example + * + *
      + * let pg; + * function setup() { + * createCanvas(100, 100); + * background(0); + * pg = createGraphics(50, 100); + * pg.fill(0); + * frameRate(5); + * } + * + * function draw() { + * image(pg, width / 2, 0); + * pg.background(255); + * // p5.Graphics object behave a bit differently in some cases + * // The normal canvas on the left resets the translate + * // with every loop through draw() + * // the graphics object on the right doesn't automatically reset + * // so translate() is additive and it moves down the screen + * rect(0, 0, width / 2, 5); + * pg.rect(0, 0, width / 2, 5); + * translate(0, 5, 0); + * pg.translate(0, 5, 0); + * } + * function mouseClicked() { + * // if you click you will see that + * // reset() resets the translate back to the initial state + * // of the Graphics object + * pg.reset(); + * } + *
      + * + * @alt + * A white line on a black background stays still on the top-left half. + * A black line animates from top to bottom on a white background on the right half. + * When clicked, the black line starts back over at the top. + */ + + _createClass(_class, [ + { + key: 'reset', + value: function reset() { + 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 + *
      + * let bg; + * function setup() { + * bg = createCanvas(100, 100); + * bg.background(0); + * image(bg, 0, 0); + * bg.remove(); + * } + *
      + * + *
      + * 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; + * } + * } + *
      + * + * @alt + * no image + * a multi-colored circle moving back and forth over a scrolling background. + */ + + }, + { + key: 'remove', + value: function remove() { + if (this.elt.parentNode) { + this.elt.parentNode.removeChild(this.elt); + } + var idx = this._pInst._elements.indexOf(this); + if (idx !== - 1) { + this._pInst._elements.splice(idx, 1); + } + for (var elt_ev in this._events) { + this.elt.removeEventListener(elt_ev, this._events[elt_ev]); + } + } /** + * Creates and returns a new p5.Framebuffer + * inside a p5.Graphics WebGL context. + * + * This takes the same parameters as the global + * createFramebuffer function. + * + * @method createFramebuffer + */ + + }, + { + key: 'createFramebuffer', + value: function createFramebuffer(options) { + return new _main.default.Framebuffer(this, options); + } + } + ]); + return _class; + }(_main.default.Element); var _default = _main.default.Graphics; exports.default = _default; }, { - './constants': 278, - './main': 290, - 'core-js/modules/es.array.index-of': 175, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.splice': 182, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + './constants': 286, + './main': 298, + 'core-js/modules/es.array.index-of': 178, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.splice': 185, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.get-prototype-of': 198, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.reflect.construct': 202, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 293: [ + 301: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -62556,7 +65582,9 @@ _dereq_('core-js/modules/es.number.constructor'); _dereq_('core-js/modules/es.object.assign'); _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.get-prototype-of'); _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.reflect.construct'); _dereq_('core-js/modules/es.regexp.exec'); _dereq_('core-js/modules/es.regexp.to-string'); _dereq_('core-js/modules/es.string.iterator'); @@ -62577,20 +65605,15 @@ } return _typeof2(obj); } - _dereq_('core-js/modules/es.symbol'); - _dereq_('core-js/modules/es.symbol.description'); - _dereq_('core-js/modules/es.symbol.iterator'); - _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.number.constructor'); _dereq_('core-js/modules/es.object.assign'); + _dereq_('core-js/modules/es.object.get-prototype-of'); _dereq_('core-js/modules/es.object.to-string'); _dereq_('core-js/modules/es.regexp.exec'); _dereq_('core-js/modules/es.regexp.to-string'); - _dereq_('core-js/modules/es.string.iterator'); _dereq_('core-js/modules/es.string.replace'); _dereq_('core-js/modules/es.string.split'); _dereq_('core-js/modules/es.string.trim'); - _dereq_('core-js/modules/web.dom-collections.iterator'); Object.defineProperty(exports, '__esModule', { value: true }); @@ -62655,7 +65678,95 @@ }; } return _typeof(obj); - } /** + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } + function _inherits(subClass, superClass) { + if (typeof superClass !== 'function' && superClass !== null) { + throw new TypeError('Super expression must either be null or a function'); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + if (superClass) _setPrototypeOf(subClass, superClass); + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + return _setPrototypeOf(o, p); + } + function _createSuper(Derived) { + function isNativeReflectConstruct() { + if (typeof Reflect === 'undefined' || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === 'function') return true; + try { + Date.prototype.toString.call(Reflect.construct(Date, [ + ], function () { + })); + return true; + } catch (e) { + return false; + } + } + return function () { + var Super = _getPrototypeOf(Derived), + result; + if (isNativeReflectConstruct()) { + var NewTarget = _getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return _possibleConstructorReturn(this, result); + }; + } + function _possibleConstructorReturn(self, call) { + if (call && (_typeof(call) === 'object' || typeof call === 'function')) { + return call; + } + return _assertThisInitialized(self); + } + function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called'); + } + return self; + } + function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); + } /** + * @module Rendering + * @submodule Rendering + * @for p5 + */ + /** * Main graphics and rendering context, as well as the base API * implementation for p5.js "core". To be used as the superclass for * Renderer2D and Renderer3D classes, respectively. @@ -62663,399 +65774,473 @@ * @class p5.Renderer * @constructor * @extends p5.Element - * @param {String} elt DOM node that is wrapped + * @param {HTMLElement} elt DOM node that is wrapped * @param {p5} [pInst] pointer to p5 instance * @param {Boolean} [isMainCanvas] whether we're using it as main canvas */ - _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._textWrap = constants.WORD; - this._rectMode = constants.CORNER; - this._ellipseMode = constants.CENTER; - this._curveTightness = 0; - this._imageMode = constants.CORNER; - this._tint = null; - this._doStroke = true; - this._doFill = true; - this._strokeSet = false; - this._fillSet = false; - this._leadingSet = false; - }; - _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, - _leadingSet: this._leadingSet, - _textSize: this._textSize, - _textAlign: this._textAlign, - _textBaseline: this._textBaseline, - _textStyle: this._textStyle, - _textWrap: this._textWrap - } - }; - }; // a pop() operation is in progress - // the renderer is passed the 'style' object that it returned - // from its push() method. - _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('_leadingSet', true); - 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); - if (!this._leadingSet) { - // only use a default value if not previously set (#5181) - this._setProperty('_textLeading', s * constants._DEFAULT_LEADMULT); - } - return this._applyTextProperties(); - } - return this._textSize; - }; - _main.default.Renderer.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.textWrap = function (wrapStyle) { - this._setProperty('_textWrap', wrapStyle); - return this._textWrap; - }; - _main.default.Renderer.prototype.text = function (str, x, y, maxWidth, maxHeight) { - var p = this._pInst; - var textWrapStyle = this._textWrap; - var lines; - var line; - var testLine; - var testWidth; - var words; - var chars; - var shiftedY; - var finalMaxHeight = Number.MAX_VALUE; // fix for #5785 (top of bounding box) - var finalMinHeight = y; - if (!(this._doFill || this._doStroke)) { - return; - } - if (typeof str === 'undefined') { - return; - } else if (typeof str !== 'string') { - str = str.toString(); - } // Replaces tabs with double-spaces and splits string on any line - // breaks present in the original string + var Renderer = /*#__PURE__*/ function (_p5$Element) { + _inherits(Renderer, _p5$Element); + var _super = _createSuper(Renderer); + function Renderer(elt, pInst, isMainCanvas) { + var _this; + _classCallCheck(this, Renderer); + _this = _super.call(this, elt, pInst); + _this.canvas = elt; + _this._pixelsState = pInst; + if (isMainCanvas) { + _this._isMainCanvas = true; + // for pixel method sharing with pimage + _this._pInst._setProperty('_curElement', _assertThisInitialized(_this)); + _this._pInst._setProperty('canvas', _this.canvas); + _this._pInst._setProperty('width', _this.width); + _this._pInst._setProperty('height', _this.height); + } else { + // hide if offscreen buffer by default + _this.canvas.style.display = 'none'; + _this._styles = [ + ]; // non-main elt styles stored in p5.Renderer + } + _this._clipping = false; + _this._clipInvert = false; + _this._textSize = 12; + _this._textLeading = 15; + _this._textFont = 'sans-serif'; + _this._textStyle = constants.NORMAL; + _this._textAscent = null; + _this._textDescent = null; + _this._textAlign = constants.LEFT; + _this._textBaseline = constants.BASELINE; + _this._textWrap = constants.WORD; + _this._rectMode = constants.CORNER; + _this._ellipseMode = constants.CENTER; + _this._curveTightness = 0; + _this._imageMode = constants.CORNER; + _this._tint = null; + _this._doStroke = true; + _this._doFill = true; + _this._strokeSet = false; + _this._fillSet = false; + _this._leadingSet = false; + _this._pushPopDepth = 0; + return _this; + } // the renderer should return a 'style' object that it wishes to + // store on the push stack. - str = str.replace(/(\t)/g, ' '); - lines = str.split('\n'); - if (typeof maxWidth !== 'undefined') { - if (this._rectMode === constants.CENTER) { - x -= maxWidth / 2; - } - switch (this._textAlign) { - case constants.CENTER: - x += maxWidth / 2; - break; - case constants.RIGHT: - x += maxWidth; - break; - } - if (typeof maxHeight !== 'undefined') { - if (this._rectMode === constants.CENTER) { - y -= maxHeight / 2; - finalMinHeight -= maxHeight / 2; - } - var originalY = y; - var ascent = p.textAscent(); - switch (this._textBaseline) { - case constants.BOTTOM: - shiftedY = y + maxHeight; - y = Math.max(shiftedY, y); // fix for #5785 (top of bounding box) - finalMinHeight += ascent; - break; - case constants.CENTER: - shiftedY = y + maxHeight / 2; - y = Math.max(shiftedY, y); // fix for #5785 (top of bounding box) - finalMinHeight += ascent / 2; - break; - } // remember the max-allowed y-position for any line (fix to #928) + _createClass(Renderer, [ + { + key: 'push', + value: function push() { + this._pushPopDepth++; + return { + properties: { + _doStroke: this._doStroke, + _strokeSet: this._strokeSet, + _doFill: this._doFill, + _fillSet: this._fillSet, + _tint: this._tint, + _imageMode: this._imageMode, + _rectMode: this._rectMode, + _ellipseMode: this._ellipseMode, + _textFont: this._textFont, + _textLeading: this._textLeading, + _leadingSet: this._leadingSet, + _textSize: this._textSize, + _textAlign: this._textAlign, + _textBaseline: this._textBaseline, + _textStyle: this._textStyle, + _textWrap: this._textWrap + } + }; + } // a pop() operation is in progress + // the renderer is passed the 'style' object that it returned + // from its push() method. - finalMaxHeight = y + maxHeight - ascent; // fix for #5785 (bottom of bounding box) - if (this._textBaseline === constants.CENTER) { - finalMaxHeight = originalY + maxHeight - ascent / 2; + }, + { + key: 'pop', + value: function pop(style) { + this._pushPopDepth--; + if (style.properties) { + // copy the style properties back into the renderer + Object.assign(this, style.properties); + } } - } else { - // no text-height specified, show warning for BOTTOM / CENTER - if (this._textBaseline === constants.BOTTOM) { - return console.warn('textAlign(*, BOTTOM) requires x, y, width and height'); + }, + { + key: 'beginClip', + value: function beginClip() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { + }; + if (this._clipping) { + throw new Error('It looks like you\'re trying to clip while already in the middle of clipping. Did you forget to endClip()?'); + } + this._clipping = true; + this._clipInvert = options.invert; } - if (this._textBaseline === constants.CENTER) { - return console.warn('textAlign(*, CENTER) requires x, y, width and height'); + }, + { + key: 'endClip', + value: function endClip() { + if (!this._clipping) { + throw new Error('It looks like you\'ve called endClip() without beginClip(). Did you forget to call beginClip() first?'); + } + this._clipping = false; + } /** + * Resize our canvas element. + */ + + }, + { + key: 'resize', + value: function resize(w, h) { + this.width = w; + this.height = h; + this.elt.width = w * this._pInst._pixelDensity; + this.elt.height = h * this._pInst._pixelDensity; + this.elt.style.width = ''.concat(w, 'px'); + this.elt.style.height = ''.concat(h, 'px'); + if (this._isMainCanvas) { + this._pInst._setProperty('width', this.width); + this._pInst._setProperty('height', this.height); + } } - } // Render lines of text according to settings of textWrap - // Splits lines at spaces, for loop adds one word + space - // at a time and tests length with next word added + }, + { + key: 'get', + value: function get(x, y, w, h) { + var pixelsState = this._pixelsState; + var pd = pixelsState._pixelDensity; + var canvas = this.canvas; + if (typeof x === 'undefined' && typeof y === 'undefined') { + // get() + x = y = 0; + w = pixelsState.width; + h = pixelsState.height; + } else { + x *= pd; + y *= pd; + if (typeof w === 'undefined' && typeof h === 'undefined') { + // get(x,y) + if (x < 0 || y < 0 || x >= canvas.width || y >= canvas.height) { + return [0, + 0, + 0, + 0]; + } + return this._getPixel(x, y); + } // get(x,y,w,h) - if (textWrapStyle === constants.WORD) { - var nlines = [ - ]; - for (var lineIndex = 0; lineIndex < lines.length; lineIndex++) { - line = ''; - words = lines[lineIndex].split(' '); - for (var wordIndex = 0; wordIndex < words.length; wordIndex++) { - testLine = ''.concat(line + words[wordIndex]) + ' '; - testWidth = this.textWidth(testLine); - if (testWidth > maxWidth && line.length > 0) { - nlines.push(line); - line = ''.concat(words[wordIndex]) + ' '; - } else { - line = testLine; - } } - nlines.push(line); - } - var offset = 0; - if (this._textBaseline === constants.CENTER) { - offset = (nlines.length - 1) * p.textLeading() / 2; - } else if (this._textBaseline === constants.BOTTOM) { - offset = (nlines.length - 1) * p.textLeading(); - } - for (var _lineIndex = 0; _lineIndex < lines.length; _lineIndex++) { - line = ''; - words = lines[_lineIndex].split(' '); - for (var _wordIndex = 0; _wordIndex < words.length; _wordIndex++) { - testLine = ''.concat(line + words[_wordIndex]) + ' '; - testWidth = this.textWidth(testLine); - if (testWidth > maxWidth && line.length > 0) { - this._renderText(p, line.trim(), x, y - offset, finalMaxHeight, finalMinHeight); - line = ''.concat(words[_wordIndex]) + ' '; - y += p.textLeading(); - } else { - line = testLine; + var region = new _main.default.Image(w * pd, h * pd); + region.pixelDensity(pd); + region.canvas.getContext('2d').drawImage(canvas, x, y, w * pd, h * pd, 0, 0, w * pd, h * pd); + return region; + } + }, + { + key: 'textLeading', + value: function textLeading(l) { + if (typeof l === 'number') { + this._setProperty('_leadingSet', true); + this._setProperty('_textLeading', l); + return this._pInst; + } + return this._textLeading; + } + }, + { + key: 'textStyle', + value: function textStyle(s) { + if (s) { + if (s === constants.NORMAL || s === constants.ITALIC || s === constants.BOLD || s === constants.BOLDITALIC) { + this._setProperty('_textStyle', s); } + return this._applyTextProperties(); } - this._renderText(p, line.trim(), x, y - offset, finalMaxHeight, finalMinHeight); - y += p.textLeading(); + return this._textStyle; } - } else { - var _nlines = [ - ]; - for (var _lineIndex2 = 0; _lineIndex2 < lines.length; _lineIndex2++) { - line = ''; - chars = lines[_lineIndex2].split(''); - for (var charIndex = 0; charIndex < chars.length; charIndex++) { - testLine = ''.concat(line + chars[charIndex]); - testWidth = this.textWidth(testLine); - if (testWidth <= maxWidth) { - line += chars[charIndex]; - } else if (testWidth > maxWidth && line.length > 0) { - _nlines.push(line); - line = ''.concat(chars[charIndex]); + }, + { + key: 'textAscent', + value: function textAscent() { + if (this._textAscent === null) { + this._updateTextMetrics(); + } + return this._textAscent; + } + }, + { + key: 'textDescent', + value: function textDescent() { + if (this._textDescent === null) { + this._updateTextMetrics(); + } + return this._textDescent; + } + }, + { + key: 'textAlign', + value: function textAlign(h, v) { + if (typeof h !== 'undefined') { + this._setProperty('_textAlign', h); + if (typeof v !== 'undefined') { + this._setProperty('_textBaseline', v); } + return this._applyTextProperties(); + } else { + return { + horizontal: this._textAlign, + vertical: this._textBaseline + }; } } - _nlines.push(line); - var _offset = 0; - if (this._textBaseline === constants.CENTER) { - _offset = (_nlines.length - 1) * p.textLeading() / 2; - } else if (this._textBaseline === constants.BOTTOM) { - _offset = (_nlines.length - 1) * p.textLeading(); - } // Splits lines at characters, for loop adds one char at a time - // and tests length with next char added - - for (var _lineIndex3 = 0; _lineIndex3 < lines.length; _lineIndex3++) { - line = ''; - chars = lines[_lineIndex3].split(''); - for (var _charIndex = 0; _charIndex < chars.length; _charIndex++) { - testLine = ''.concat(line + chars[_charIndex]); - testWidth = this.textWidth(testLine); - if (testWidth <= maxWidth) { - line += chars[_charIndex]; - } else if (testWidth > maxWidth && line.length > 0) { + }, + { + key: 'textWrap', + value: function textWrap(wrapStyle) { + this._setProperty('_textWrap', wrapStyle); + return this._textWrap; + } + }, + { + key: 'text', + value: function text(str, x, y, maxWidth, maxHeight) { + var p = this._pInst; + var textWrapStyle = this._textWrap; + var lines; + var line; + var testLine; + var testWidth; + var words; + var chars; + var shiftedY; + var finalMaxHeight = Number.MAX_VALUE; + // fix for #5785 (top of bounding box) + var finalMinHeight = y; + if (!(this._doFill || this._doStroke)) { + return; + } + if (typeof str === 'undefined') { + return; + } else if (typeof str !== 'string') { + str = str.toString(); + } // Replaces tabs with double-spaces and splits string on any line + // breaks present in the original string + + str = str.replace(/(\t)/g, ' '); + lines = str.split('\n'); + if (typeof maxWidth !== 'undefined') { + if (this._rectMode === constants.CENTER) { + x -= maxWidth / 2; + } + switch (this._textAlign) { + case constants.CENTER: + x += maxWidth / 2; + break; + case constants.RIGHT: + x += maxWidth; + break; + } + if (typeof maxHeight !== 'undefined') { + if (this._rectMode === constants.CENTER) { + y -= maxHeight / 2; + finalMinHeight -= maxHeight / 2; + } + var originalY = y; + var ascent = p.textAscent(); + switch (this._textBaseline) { + case constants.BOTTOM: + shiftedY = y + maxHeight; + y = Math.max(shiftedY, y); + // fix for #5785 (top of bounding box) + finalMinHeight += ascent; + break; + case constants.CENTER: + shiftedY = y + maxHeight / 2; + y = Math.max(shiftedY, y); + // fix for #5785 (top of bounding box) + finalMinHeight += ascent / 2; + break; + } // remember the max-allowed y-position for any line (fix to #928) + + finalMaxHeight = y + maxHeight - ascent; + // fix for #5785 (bottom of bounding box) + if (this._textBaseline === constants.CENTER) { + finalMaxHeight = originalY + maxHeight - ascent / 2; + } + } else { + // no text-height specified, show warning for BOTTOM / CENTER + if (this._textBaseline === constants.BOTTOM || this._textBaseline === constants.CENTER) { + // use rectHeight as an approximation for text height + var rectHeight = p.textSize() * this._textLeading; + finalMinHeight = y - rectHeight / 2; + finalMaxHeight = y + rectHeight / 2; + } + } // Render lines of text according to settings of textWrap + // Splits lines at spaces, for loop adds one word + space + // at a time and tests length with next word added + + if (textWrapStyle === constants.WORD) { + var nlines = [ + ]; + for (var lineIndex = 0; lineIndex < lines.length; lineIndex++) { + line = ''; + words = lines[lineIndex].split(' '); + for (var wordIndex = 0; wordIndex < words.length; wordIndex++) { + testLine = ''.concat(line + words[wordIndex]) + ' '; + testWidth = this.textWidth(testLine); + if (testWidth > maxWidth && line.length > 0) { + nlines.push(line); + line = ''.concat(words[wordIndex]) + ' '; + } else { + line = testLine; + } + } + nlines.push(line); + } + var offset = 0; + if (this._textBaseline === constants.CENTER) { + offset = (nlines.length - 1) * p.textLeading() / 2; + } else if (this._textBaseline === constants.BOTTOM) { + offset = (nlines.length - 1) * p.textLeading(); + } + for (var _lineIndex = 0; _lineIndex < lines.length; _lineIndex++) { + line = ''; + words = lines[_lineIndex].split(' '); + for (var _wordIndex = 0; _wordIndex < words.length; _wordIndex++) { + testLine = ''.concat(line + words[_wordIndex]) + ' '; + testWidth = this.textWidth(testLine); + if (testWidth > maxWidth && line.length > 0) { + this._renderText(p, line.trim(), x, y - offset, finalMaxHeight, finalMinHeight); + line = ''.concat(words[_wordIndex]) + ' '; + y += p.textLeading(); + } else { + line = testLine; + } + } + this._renderText(p, line.trim(), x, y - offset, finalMaxHeight, finalMinHeight); + y += p.textLeading(); + } + } else { + var _nlines = [ + ]; + for (var _lineIndex2 = 0; _lineIndex2 < lines.length; _lineIndex2++) { + line = ''; + chars = lines[_lineIndex2].split(''); + for (var charIndex = 0; charIndex < chars.length; charIndex++) { + testLine = ''.concat(line + chars[charIndex]); + testWidth = this.textWidth(testLine); + if (testWidth <= maxWidth) { + line += chars[charIndex]; + } else if (testWidth > maxWidth && line.length > 0) { + _nlines.push(line); + line = ''.concat(chars[charIndex]); + } + } + } + _nlines.push(line); + var _offset = 0; + if (this._textBaseline === constants.CENTER) { + _offset = (_nlines.length - 1) * p.textLeading() / 2; + } else if (this._textBaseline === constants.BOTTOM) { + _offset = (_nlines.length - 1) * p.textLeading(); + } // Splits lines at characters, for loop adds one char at a time + // and tests length with next char added + + for (var _lineIndex3 = 0; _lineIndex3 < lines.length; _lineIndex3++) { + line = ''; + chars = lines[_lineIndex3].split(''); + for (var _charIndex = 0; _charIndex < chars.length; _charIndex++) { + testLine = ''.concat(line + chars[_charIndex]); + testWidth = this.textWidth(testLine); + if (testWidth <= maxWidth) { + line += chars[_charIndex]; + } else if (testWidth > maxWidth && line.length > 0) { + this._renderText(p, line.trim(), x, y - _offset, finalMaxHeight, finalMinHeight); + y += p.textLeading(); + line = ''.concat(chars[_charIndex]); + } + } + } this._renderText(p, line.trim(), x, y - _offset, finalMaxHeight, finalMinHeight); y += p.textLeading(); - line = ''.concat(chars[_charIndex]); + } + } else { + // Offset to account for vertically centering multiple lines of text - no + // need to adjust anything for vertical align top or baseline + var _offset2 = 0; + if (this._textBaseline === constants.CENTER) { + _offset2 = (lines.length - 1) * p.textLeading() / 2; + } else if (this._textBaseline === constants.BOTTOM) { + _offset2 = (lines.length - 1) * p.textLeading(); + } // Renders lines of text at any line breaks present in the original string + + for (var i = 0; i < lines.length; i++) { + this._renderText(p, lines[i], x, y - _offset2, finalMaxHeight, finalMinHeight - _offset2); + y += p.textLeading(); } } + return p; } - this._renderText(p, line.trim(), x, y - _offset, finalMaxHeight, finalMinHeight); - y += p.textLeading(); - } - } else { - // Offset to account for vertically centering multiple lines of text - no - // need to adjust anything for vertical align top or baseline - var _offset2 = 0; - if (this._textBaseline === constants.CENTER) { - _offset2 = (lines.length - 1) * p.textLeading() / 2; - } else if (this._textBaseline === constants.BOTTOM) { - _offset2 = (lines.length - 1) * p.textLeading(); - } // Renders lines of text at any line breaks present in the original string + }, + { + key: '_applyDefaults', + value: function _applyDefaults() { + return this; + } /** + * Helper function to check font type (system or otf) + */ - for (var i = 0; i < lines.length; i++) { - this._renderText(p, lines[i], x, y - _offset2, finalMaxHeight, finalMinHeight - _offset2); - y += p.textLeading(); + }, + { + key: '_isOpenType', + value: function _isOpenType() { + var f = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this._textFont; + return _typeof(f) === 'object' && f.font && f.font.supported; + } + }, + { + key: '_updateTextMetrics', + value: function _updateTextMetrics() { + if (this._isOpenType()) { + this._setProperty('_textAscent', this._textFont._textAscent()); + this._setProperty('_textDescent', this._textFont._textDescent()); + return this; + } // Adapted from http://stackoverflow.com/a/25355178 + + var text = document.createElement('span'); + text.style.fontFamily = this._textFont; + text.style.fontSize = ''.concat(this._textSize, 'px'); + text.innerHTML = 'ABCjgq|'; + var block = document.createElement('div'); + block.style.display = 'inline-block'; + block.style.width = '1px'; + block.style.height = '0px'; + var container = document.createElement('div'); + container.appendChild(text); + container.appendChild(block); + container.style.height = '0px'; + container.style.overflow = 'hidden'; + document.body.appendChild(container); + block.style.verticalAlign = 'baseline'; + var blockOffset = calculateOffset(block); + var textOffset = calculateOffset(text); + var ascent = blockOffset[1] - textOffset[1]; + block.style.verticalAlign = 'bottom'; + blockOffset = calculateOffset(block); + textOffset = calculateOffset(text); + var height = blockOffset[1] - textOffset[1]; + var descent = height - ascent; + document.body.removeChild(container); + this._setProperty('_textAscent', ascent); + this._setProperty('_textDescent', descent); + return this; + } } - } - return p; - }; - _main.default.Renderer.prototype._applyDefaults = function () { - return this; - }; - /** - * Helper function 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; - }; + ]); + return Renderer; + }(_main.default.Element); /** * Helper fxn to measure ascent and descent. * Adapted from http://stackoverflow.com/a/25355178 @@ -63074,32 +66259,47 @@ } return [currentLeft, currentTop]; - } + } // This caused the test to failed. + + Renderer.prototype.textSize = function (s) { + if (typeof s === 'number') { + this._setProperty('_textSize', s); + if (!this._leadingSet) { + // only use a default value if not previously set (#5181) + this._setProperty('_textLeading', s * constants._DEFAULT_LEADMULT); + } + return this._applyTextProperties(); + } + return this._textSize; + }; + _main.default.Renderer = Renderer; var _default = _main.default.Renderer; exports.default = _default; }, { - '../core/constants': 278, - './main': 290, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.number.constructor': 187, - 'core-js/modules/es.object.assign': 190, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.exec': 199, - 'core-js/modules/es.regexp.to-string': 200, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.string.replace': 207, - 'core-js/modules/es.string.split': 209, - 'core-js/modules/es.string.trim': 211, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + '../core/constants': 286, + './main': 298, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.number.constructor': 191, + 'core-js/modules/es.object.assign': 194, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.get-prototype-of': 198, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.reflect.construct': 202, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.string.replace': 214, + 'core-js/modules/es.string.split': 216, + 'core-js/modules/es.string.trim': 219, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 294: [ + 302: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -63114,7 +66314,10 @@ _dereq_('core-js/modules/es.function.name'); _dereq_('core-js/modules/es.number.to-fixed'); _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.get-prototype-of'); _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.reflect.construct'); + _dereq_('core-js/modules/es.reflect.get'); _dereq_('core-js/modules/es.regexp.to-string'); _dereq_('core-js/modules/es.string.iterator'); _dereq_('core-js/modules/es.weak-map'); @@ -63150,6 +66353,7 @@ _dereq_('core-js/modules/es.array.slice'); _dereq_('core-js/modules/es.function.name'); _dereq_('core-js/modules/es.number.to-fixed'); + _dereq_('core-js/modules/es.object.get-prototype-of'); _dereq_('core-js/modules/es.object.to-string'); _dereq_('core-js/modules/es.regexp.to-string'); Object.defineProperty(exports, '__esModule', { @@ -63205,956 +66409,1382 @@ 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) { - if ((arguments.length <= 1 ? undefined : arguments[1]) >= 0) { - // set transparency of background - var img = arguments.length <= 0 ? undefined : arguments[0]; - this.drawingContext.globalAlpha = (arguments.length <= 1 ? undefined : arguments[1]) / 255; - this._pInst.image(img, 0, 0, this.width, this.height); - } else { - this._pInst.image(arguments.length <= 0 ? undefined : arguments[0], 0, 0, this.width, this.height); - } - } else { - var _this$_pInst; - var curFill = this._getFill(); // create background rect - var color = (_this$_pInst = this._pInst).color.apply(_this$_pInst, arguments); //accessible Outputs - if (this._pInst._addAccsOutput()) { - this._pInst._accsBackground(color.levels); - } - var newFill = color.toString(); - this._setFill(newFill); - if (this._isErasing) { - this.blendMode(this._cachedBlendMode); - } - this.drawingContext.fillRect(0, 0, this.width, this.height); // reset fill - this._setFill(curFill); - if (this._isErasing) { - this._pInst.erase(); - } - } - this.drawingContext.restore(); - }; - _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; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); } - }; - _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); + } + 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); } - try { - if (_main.default.MediaElement && img instanceof _main.default.MediaElement) { - img._ensureCanvas(); - } - if (this._tint && img.canvas) { - cnv = this._getTintedImageCanvas(img); - } - if (!cnv) { - cnv = img.canvas || img.elt; - } - var s = 1; - if (img.width && img.width > 0) { - s = cnv.width / img.width; - } - if (this._isErasing) { - this.blendMode(this._cachedBlendMode); - } - this.drawingContext.drawImage(cnv, s * sx, s * sy, s * sWidth, s * sHeight, dx, dy, dWidth, dHeight); - if (this._isErasing) { - this._pInst.erase(); - } - } catch (e) { - if (e.name !== 'NS_ERROR_NOT_AVAILABLE') { - throw e; - } - } - }; - _main.default.Renderer2D.prototype._getTintedImageCanvas = function (img) { - if (!img.canvas) { - return img; - } - if (!img.tintCanvas) { - // Once an image has been tinted, keep its tint canvas - // around so we don't need to re-incur the cost of - // creating a new one for each tint - img.tintCanvas = document.createElement('canvas'); - } // Keep the size of the tint canvas up-to-date - - if (img.tintCanvas.width !== img.canvas.width) { - img.tintCanvas.width = img.canvas.width; - } - if (img.tintCanvas.height !== img.canvas.height) { - img.tintCanvas.height = img.canvas.height; - } // Goal: multiply the r,g,b,a values of the source by - // the r,g,b,a values of the tint color - - var ctx = img.tintCanvas.getContext('2d'); - ctx.save(); - ctx.clearRect(0, 0, img.canvas.width, img.canvas.height); - if (this._tint[0] < 255 || this._tint[1] < 255 || this._tint[2] < 255) { - // Color tint: we need to use the multiply blend mode to change the colors. - // However, the canvas implementation of this destroys the alpha channel of - // the image. To accommodate, we first get a version of the image with full - // opacity everywhere, tint using multiply, and then use the destination-in - // blend mode to restore the alpha channel again. - // Start with the original image - ctx.drawImage(img.canvas, 0, 0); // This blend mode makes everything opaque but forces the luma to match - // the original image again - ctx.globalCompositeOperation = 'luminosity'; - ctx.drawImage(img.canvas, 0, 0); // This blend mode forces the hue and chroma to match the original image. - // After this we should have the original again, but with full opacity. - ctx.globalCompositeOperation = 'color'; - ctx.drawImage(img.canvas, 0, 0); // Apply color tint - ctx.globalCompositeOperation = 'multiply'; - ctx.fillStyle = 'rgb('.concat(this._tint.slice(0, 3).join(', '), ')'); - ctx.fillRect(0, 0, img.canvas.width, img.canvas.height); // Replace the alpha channel with the original alpha * the alpha tint - ctx.globalCompositeOperation = 'destination-in'; - ctx.globalAlpha = this._tint[3] / 255; - ctx.drawImage(img.canvas, 0, 0); - } else { - // If we only need to change the alpha, we can skip all the extra work! - ctx.globalAlpha = this._tint[3] / 255; - ctx.drawImage(img.canvas, 0, 0); - } - ctx.restore(); - return img.tintCanvas; - }; ////////////////////////////////////////////// - // IMAGE | Pixels - ////////////////////////////////////////////// - _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; + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } + function _get(target, property, receiver) { + if (typeof Reflect !== 'undefined' && Reflect.get) { + _get = Reflect.get; } else { - throw new Error('Mode '.concat(mode, ' not recognized.')); + _get = function _get(target, property, receiver) { + var base = _superPropBase(target, property); + if (!base) return; + var desc = Object.getOwnPropertyDescriptor(base, property); + if (desc.get) { + return desc.get.call(receiver); + } + return desc.value; + }; } - }; - _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]; + return _get(target, property, receiver || target); + } + function _superPropBase(object, property) { + while (!Object.prototype.hasOwnProperty.call(object, property)) { + object = _getPrototypeOf(object); + if (object === null) break; } - 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 ecridge.com/bezier.pdf for an explanation of the method. - */ - _main.default.Renderer2D.prototype._acuteArcToBezier = function _acuteArcToBezier(start, size) { - // Evaluate constants. - var alpha = size / 2, - cos_alpha = Math.cos(alpha), - sin_alpha = Math.sin(alpha), - cot_alpha = 1 / Math.tan(alpha), - // This is how far the arc needs to be rotated. - phi = start + alpha, - cos_phi = Math.cos(phi), - sin_phi = Math.sin(phi), - lambda = (4 - cos_alpha) / 3, - mu = sin_alpha + (cos_alpha - lambda) * cot_alpha; // Return rotated waypoints. - return { - ax: Math.cos(start).toFixed(7), - ay: Math.sin(start).toFixed(7), - bx: (lambda * cos_phi + mu * sin_phi).toFixed(7), - by: (lambda * sin_phi - mu * cos_phi).toFixed(7), - cx: (lambda * cos_phi - mu * sin_phi).toFixed(7), - cy: (lambda * sin_phi + mu * cos_phi).toFixed(7), - dx: Math.cos(start + size).toFixed(7), - dy: Math.sin(start + size).toFixed(7) - }; - }; - /* - * This function requires that: - * - * 0 <= start < TWO_PI - * - * start <= stop < start + TWO_PI - */ - _main.default.Renderer2D.prototype.arc = function (x, y, w, h, start, stop, mode) { - var ctx = this.drawingContext; - var rx = w / 2; - var ry = h / 2; - var epsilon = 0.00001; // Smallest visible angle on displays up to 4K. - var arcToDraw = 0; - var curves = [ - ]; - x += rx; - y += ry; // Create curves - while (stop - start >= epsilon) { - arcToDraw = Math.min(stop - start, constants.HALF_PI); - curves.push(this._acuteArcToBezier(start, arcToDraw)); - start += arcToDraw; - } // Fill curves - - if (this._doFill) { - ctx.beginPath(); - curves.forEach(function (curve, index) { - if (index === 0) { - ctx.moveTo(x + curve.ax * rx, y + curve.ay * ry); - } /* eslint-disable indent */ - - ctx.bezierCurveTo(x + curve.bx * rx, y + curve.by * ry, x + curve.cx * rx, y + curve.cy * ry, x + curve.dx * rx, y + curve.dy * ry); - /* eslint-enable indent */ - }); - if (mode === constants.PIE || mode == null) { - ctx.lineTo(x, y); - } - ctx.closePath(); - 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); - } /* eslint-disable indent */ - - ctx.bezierCurveTo(x + curve.bx * rx, y + curve.by * ry, x + curve.cx * rx, y + curve.cy * ry, x + curve.dx * rx, y + curve.dy * ry); - /* eslint-enable indent */ - }); - if (mode === constants.PIE) { - ctx.lineTo(x, y); - ctx.closePath(); - } else if (mode === constants.CHORD) { - ctx.closePath(); - } - ctx.stroke(); + return object; + } + function _inherits(subClass, superClass) { + if (typeof superClass !== 'function' && superClass !== null) { + throw new TypeError('Super expression must either be null or a function'); } - 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; + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true } - } else if (!doFill && doStroke) { - if (this._getStroke() === styleEmpty) { - return this; + }); + if (superClass) _setPrototypeOf(subClass, superClass); + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + return _setPrototypeOf(o, p); + } + function _createSuper(Derived) { + function isNativeReflectConstruct() { + if (typeof Reflect === 'undefined' || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === 'function') return true; + try { + Date.prototype.toString.call(Reflect.construct(Date, [ + ], function () { + })); + return true; + } catch (e) { + return false; } } - 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(); // swapping fill color to stroke and back after for correct point rendering - this._setFill(s); - ctx.beginPath(); - ctx.arc(x, y, ctx.lineWidth / 2, 0, constants.TWO_PI, false); - ctx.fill(); - 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; + return function () { + var Super = _getPrototypeOf(Derived), + result; + if (isNativeReflectConstruct()) { + var NewTarget = _getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); } + return _possibleConstructorReturn(this, result); + }; + } + function _possibleConstructorReturn(self, call) { + if (call && (_typeof(call) === 'object' || typeof call === 'function')) { + return call; } - 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; - } + return _assertThisInitialized(self); + } + function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called'); } - 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 + return self; + } + function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); + } /** + * p5.Renderer2D + * The 2D graphics canvas renderer class. + * extends p5.Renderer + */ - 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 styleEmpty = 'rgba(0,0,0,0)'; + // const alphaThreshold = 0.00125; // minimum visible + var Renderer2D = /*#__PURE__*/ function (_p5$Renderer) { + _inherits(Renderer2D, _p5$Renderer); + var _super = _createSuper(Renderer2D); + function Renderer2D(elt, pInst, isMainCanvas) { + var _this; + _classCallCheck(this, Renderer2D); + _this = _super.call(this, elt, pInst, isMainCanvas); + _this.drawingContext = _this.canvas.getContext('2d'); + _this._pInst._setProperty('drawingContext', _this.drawingContext); + return _this; } - 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]); + _createClass(Renderer2D, [ + { + key: 'getFilterGraphicsLayer', + value: function getFilterGraphicsLayer() { + // create hidden webgl renderer if it doesn't exist + if (!this.filterGraphicsLayer) { + // the real _pInst is buried when this is a secondary p5.Graphics + var pInst = this._pInst instanceof _main.default.Graphics ? this._pInst._pInst : this._pInst; + // create secondary layer + this.filterGraphicsLayer = new _main.default.Graphics(this.width, this.height, constants.WEBGL, pInst); + } + if (this.filterGraphicsLayer.width !== this.width || this.filterGraphicsLayer.height !== this.height) { + // Resize the graphics layer + this.filterGraphicsLayer.resizeCanvas(this.width, this.height); + } + if (this.filterGraphicsLayer.pixelDensity() !== this._pInst.pixelDensity()) { + this.filterGraphicsLayer.pixelDensity(this._pInst.pixelDensity()); + } + return this.filterGraphicsLayer; } - if (closeShape) { - this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]); + }, + { + key: '_applyDefaults', + value: function _applyDefaults() { + this._cachedFillStyle = this._cachedStrokeStyle = undefined; + this._cachedBlendMode = constants.BLEND; + this._setFill(constants._DEFAULT_FILL); + this._setStroke(constants._DEFAULT_STROKE); + this.drawingContext.lineCap = constants.ROUND; + this.drawingContext.font = 'normal 12px sans-serif'; } - 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]); + }, + { + key: 'resize', + value: function resize(w, h) { + _get(_getPrototypeOf(Renderer2D.prototype), 'resize', this).call(this, w, h); + this.drawingContext.scale(this._pInst._pixelDensity, this._pInst._pixelDensity); + } ////////////////////////////////////////////// + // COLOR | Setting + ////////////////////////////////////////////// + + }, + { + key: 'background', + value: function background() { + this.drawingContext.save(); + this.resetMatrix(); + if ((arguments.length <= 0 ? undefined : arguments[0]) instanceof _main.default.Image) { + if ((arguments.length <= 1 ? undefined : arguments[1]) >= 0) { + // set transparency of background + var img = arguments.length <= 0 ? undefined : arguments[0]; + this.drawingContext.globalAlpha = (arguments.length <= 1 ? undefined : arguments[1]) / 255; + this._pInst.image(img, 0, 0, this.width, this.height); + } else { + this._pInst.image(arguments.length <= 0 ? undefined : arguments[0], 0, 0, this.width, this.height); + } } else { - this.drawingContext.lineTo(vertices[i][0], vertices[i][1]); + 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(); + } } - } else { - this.drawingContext.bezierCurveTo(vertices[i][0], vertices[i][1], vertices[i][2], vertices[i][3], vertices[i][4], vertices[i][5]); + this.drawingContext.restore(); } - } - 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]); + }, + { + key: 'clear', + value: function clear() { + this.drawingContext.save(); + this.resetMatrix(); + this.drawingContext.clearRect(0, 0, this.width, this.height); + this.drawingContext.restore(); + } + }, + { + key: 'fill', + value: function fill() { + var _this$_pInst2; + var color = (_this$_pInst2 = this._pInst).color.apply(_this$_pInst2, arguments); + this._setFill(color.toString()); + //accessible Outputs + if (this._pInst._addAccsOutput()) { + this._pInst._accsCanvasColors('fill', color.levels); } - } 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]); + }, + { + key: 'stroke', + value: function stroke() { + var _this$_pInst3; + var color = (_this$_pInst3 = this._pInst).color.apply(_this$_pInst3, arguments); + this._setStroke(color.toString()); + //accessible Outputs + if (this._pInst._addAccsOutput()) { + this._pInst._accsCanvasColors('stroke', color.levels); } - 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]); + }, + { + key: 'erase', + value: function erase(opacityFill, opacityStroke) { + if (!this._isErasing) { + // cache the fill style + this._cachedFillStyle = this.drawingContext.fillStyle; + var newFill = this._pInst.color(255, opacityFill).toString(); + this.drawingContext.fillStyle = newFill; + // cache the stroke style + this._cachedStrokeStyle = this.drawingContext.strokeStyle; + var newStroke = this._pInst.color(255, opacityStroke).toString(); + this.drawingContext.strokeStyle = newStroke; + // cache blendMode + var tempBlendMode = this._cachedBlendMode; + this.blendMode(constants.REMOVE); + this._cachedBlendMode = tempBlendMode; + this._isErasing = true; + } + } + }, + { + key: 'noErase', + value: function noErase() { + if (this._isErasing) { + this.drawingContext.fillStyle = this._cachedFillStyle; + this.drawingContext.strokeStyle = this._cachedStrokeStyle; + this.blendMode(this._cachedBlendMode); + this._isErasing = false; } - 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]; + }, + { + key: 'beginClip', + value: function beginClip() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { + }; + _get(_getPrototypeOf(Renderer2D.prototype), 'beginClip', this).call(this, options); + // cache the fill style + this._cachedFillStyle = this.drawingContext.fillStyle; + var newFill = this._pInst.color(255, 0).toString(); + this.drawingContext.fillStyle = newFill; + // cache the stroke style + this._cachedStrokeStyle = this.drawingContext.strokeStyle; + var newStroke = this._pInst.color(255, 0).toString(); + this.drawingContext.strokeStyle = newStroke; + // cache blendMode + var tempBlendMode = this._cachedBlendMode; + this.blendMode(constants.BLEND); + this._cachedBlendMode = tempBlendMode; + // Start a new path. Everything from here on out should become part of this + // one path so that we can clip to the whole thing. this.drawingContext.beginPath(); - 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._clipInvert) { + // Slight hack: draw a big rectangle over everything with reverse winding + // order. This is hopefully large enough to cover most things. + this.drawingContext.moveTo( - 2 * this.width, - 2 * this.height); + this.drawingContext.lineTo( - 2 * this.width, 2 * this.height); + this.drawingContext.lineTo(2 * this.width, 2 * this.height); + this.drawingContext.lineTo(2 * this.width, - 2 * this.height); + this.drawingContext.closePath(); } - if (this._doStroke) { - this._pInst.stroke(vertices[i + 2][6]); - this.drawingContext.stroke(); + } + }, + { + key: 'endClip', + value: function endClip() { + this._doFillStrokeClose(); + this.drawingContext.clip(); + _get(_getPrototypeOf(Renderer2D.prototype), 'endClip', this).call(this); + this.drawingContext.fillStyle = this._cachedFillStyle; + this.drawingContext.strokeStyle = this._cachedStrokeStyle; + this.blendMode(this._cachedBlendMode); + } ////////////////////////////////////////////// + // IMAGE | Loading & Displaying + ////////////////////////////////////////////// + + }, + { + key: 'image', + value: function image(img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) { + var cnv; + if (img.gifProperties) { + img._animateGif(this._pInst); + } + try { + if (_main.default.MediaElement && img instanceof _main.default.MediaElement) { + img._ensureCanvas(); + } + if (this._tint && img.canvas) { + cnv = this._getTintedImageCanvas(img); + } + if (!cnv) { + cnv = img.canvas || img.elt; + } + var s = 1; + if (img.width && img.width > 0) { + s = cnv.width / img.width; + } + if (this._isErasing) { + this.blendMode(this._cachedBlendMode); + } + this.drawingContext.drawImage(cnv, s * sx, s * sy, s * sWidth, s * sHeight, dx, dy, dWidth, dHeight); + if (this._isErasing) { + this._pInst.erase(); + } + } catch (e) { + if (e.name !== 'NS_ERROR_NOT_AVAILABLE') { + throw e; + } } } - } 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]); + }, + { + key: '_getTintedImageCanvas', + value: function _getTintedImageCanvas(img) { + if (!img.canvas) { + return img; + } + if (!img.tintCanvas) { + // Once an image has been tinted, keep its tint canvas + // around so we don't need to re-incur the cost of + // creating a new one for each tint + img.tintCanvas = document.createElement('canvas'); + } // Keep the size of the tint canvas up-to-date + + if (img.tintCanvas.width !== img.canvas.width) { + img.tintCanvas.width = img.canvas.width; + } + if (img.tintCanvas.height !== img.canvas.height) { + img.tintCanvas.height = img.canvas.height; + } // Goal: multiply the r,g,b,a values of the source by + // the r,g,b,a values of the tint color + + var ctx = img.tintCanvas.getContext('2d'); + ctx.save(); + ctx.clearRect(0, 0, img.canvas.width, img.canvas.height); + if (this._tint[0] < 255 || this._tint[1] < 255 || this._tint[2] < 255) { + // Color tint: we need to use the multiply blend mode to change the colors. + // However, the canvas implementation of this destroys the alpha channel of + // the image. To accommodate, we first get a version of the image with full + // opacity everywhere, tint using multiply, and then use the destination-in + // blend mode to restore the alpha channel again. + // Start with the original image + ctx.drawImage(img.canvas, 0, 0); + // This blend mode makes everything opaque but forces the luma to match + // the original image again + ctx.globalCompositeOperation = 'luminosity'; + ctx.drawImage(img.canvas, 0, 0); + // This blend mode forces the hue and chroma to match the original image. + // After this we should have the original again, but with full opacity. + ctx.globalCompositeOperation = 'color'; + ctx.drawImage(img.canvas, 0, 0); + // Apply color tint + ctx.globalCompositeOperation = 'multiply'; + ctx.fillStyle = 'rgb('.concat(this._tint.slice(0, 3).join(', '), ')'); + ctx.fillRect(0, 0, img.canvas.width, img.canvas.height); + // Replace the alpha channel with the original alpha * the alpha tint + ctx.globalCompositeOperation = 'destination-in'; + ctx.globalAlpha = this._tint[3] / 255; + ctx.drawImage(img.canvas, 0, 0); + } else { + // If we only need to change the alpha, we can skip all the extra work! + ctx.globalAlpha = this._tint[3] / 255; + ctx.drawImage(img.canvas, 0, 0); + } + ctx.restore(); + return img.tintCanvas; + } ////////////////////////////////////////////// + // IMAGE | Pixels + ////////////////////////////////////////////// + + }, + { + key: 'blendMode', + value: function blendMode(mode) { + if (mode === constants.SUBTRACT) { + console.warn('blendMode(SUBTRACT) only works in WEBGL mode.'); + } else if (mode === constants.BLEND || mode === constants.REMOVE || mode === constants.DARKEST || mode === constants.LIGHTEST || mode === constants.DIFFERENCE || mode === constants.MULTIPLY || mode === constants.EXCLUSION || mode === constants.SCREEN || mode === constants.REPLACE || mode === constants.OVERLAY || mode === constants.HARD_LIGHT || mode === constants.SOFT_LIGHT || mode === constants.DODGE || mode === constants.BURN || mode === constants.ADD) { + this._cachedBlendMode = mode; + this.drawingContext.globalCompositeOperation = mode; + } else { + throw new Error('Mode '.concat(mode, ' not recognized.')); + } + } + }, + { + key: 'blend', + value: function blend() { + var currBlend = this.drawingContext.globalCompositeOperation; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + var blendMode = args[args.length - 1]; + var copyArgs = Array.prototype.slice.call(args, 0, args.length - 1); + this.drawingContext.globalCompositeOperation = blendMode; + _main.default.prototype.copy.apply(this, copyArgs); + this.drawingContext.globalCompositeOperation = currBlend; + } // p5.Renderer2D.prototype.get = p5.Renderer.prototype.get; + // .get() is not overridden + // x,y are canvas-relative (pre-scaled by _pixelDensity) + + }, + { + key: '_getPixel', + value: function _getPixel(x, y) { + var imageData, + index; + imageData = this.drawingContext.getImageData(x, y, 1, 1).data; + index = 0; + return [imageData[index + 0], + imageData[index + 1], + imageData[index + 2], + imageData[index + 3]]; + } + }, + { + key: 'loadPixels', + value: function loadPixels() { + var pixelsState = this._pixelsState; // if called by p5.Image + var pd = pixelsState._pixelDensity; + var w = this.width * pd; + var h = this.height * pd; + var imageData = this.drawingContext.getImageData(0, 0, w, h); + // @todo this should actually set pixels per object, so diff buffers can + // have diff pixel arrays. + pixelsState._setProperty('imageData', imageData); + pixelsState._setProperty('pixels', imageData.data); + } + }, + { + key: 'set', + value: function set(x, y, imgOrCol) { + // round down to get integer numbers + x = Math.floor(x); + y = Math.floor(y); + var pixelsState = this._pixelsState; + if (imgOrCol instanceof _main.default.Image) { + this.drawingContext.save(); + this.drawingContext.setTransform(1, 0, 0, 1, 0, 0); + this.drawingContext.scale(pixelsState._pixelDensity, pixelsState._pixelDensity); + this.drawingContext.clearRect(x, y, imgOrCol.width, imgOrCol.height); + this.drawingContext.drawImage(imgOrCol.canvas, x, y); + this.drawingContext.restore(); + } else { + var r = 0, + g = 0, + b = 0, + a = 0; + var idx = 4 * (y * pixelsState._pixelDensity * (this.width * pixelsState._pixelDensity) + x * pixelsState._pixelDensity); + if (!pixelsState.imageData) { + pixelsState.loadPixels.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; + } + } } + } + }, + { + key: 'updatePixels', + value: function updatePixels(x, y, w, h) { + var pixelsState = this._pixelsState; + var pd = pixelsState._pixelDensity; + if (x === undefined && y === undefined && w === undefined && h === undefined) { + x = 0; + y = 0; + w = this.width; + h = this.height; + } + x *= pd; + y *= pd; + w *= pd; + h *= pd; + if (this.gifProperties) { + this.gifProperties.frames[this.gifProperties.displayIndex].image = pixelsState.imageData; + } + this.drawingContext.putImageData(pixelsState.imageData, x, y, 0, 0, w, h); + } ////////////////////////////////////////////// + // SHAPE | 2D Primitives + ////////////////////////////////////////////// + /** + * Generate a cubic Bezier representing an arc on the unit circle of total + * angle `size` radians, beginning `start` radians above the x-axis. Up to + * four of these curves are combined to make a full arc. + * + * See ecridge.com/bezier.pdf for an explanation of the method. + */ + + }, + { + key: '_acuteArcToBezier', + value: function _acuteArcToBezier(start, size) { + // Evaluate constants. + var alpha = size / 2, + cos_alpha = Math.cos(alpha), + sin_alpha = Math.sin(alpha), + cot_alpha = 1 / Math.tan(alpha), + // This is how far the arc needs to be rotated. + phi = start + alpha, + cos_phi = Math.cos(phi), + sin_phi = Math.sin(phi), + lambda = (4 - cos_alpha) / 3, + mu = sin_alpha + (cos_alpha - lambda) * cot_alpha; + // Return rotated waypoints. + return { + ax: Math.cos(start).toFixed(7), + ay: Math.sin(start).toFixed(7), + bx: (lambda * cos_phi + mu * sin_phi).toFixed(7), + by: (lambda * sin_phi - mu * cos_phi).toFixed(7), + cx: (lambda * cos_phi - mu * sin_phi).toFixed(7), + cy: (lambda * sin_phi + mu * cos_phi).toFixed(7), + dx: Math.cos(start + size).toFixed(7), + dy: Math.sin(start + size).toFixed(7) + }; + } /* + * This function requires that: + * + * 0 <= start < TWO_PI + * + * start <= stop < start + TWO_PI + */ + + }, + { + key: 'arc', + value: function arc(x, y, w, h, start, stop, mode) { + var ctx = this.drawingContext; + var rx = w / 2; + var ry = h / 2; + var epsilon = 0.00001; // Smallest visible angle on displays up to 4K. + var arcToDraw = 0; + var curves = [ + ]; + x += rx; + y += ry; + // Create curves + while (stop - start >= epsilon) { + arcToDraw = Math.min(stop - start, constants.HALF_PI); + curves.push(this._acuteArcToBezier(start, arcToDraw)); + start += arcToDraw; + } // Fill curves + if (this._doFill) { - this._pInst.fill(vertices[i + 1][5]); + if (!this._clipping) ctx.beginPath(); + curves.forEach(function (curve, index) { + if (index === 0) { + ctx.moveTo(x + curve.ax * rx, y + curve.ay * ry); + } /* eslint-disable indent */ + + ctx.bezierCurveTo(x + curve.bx * rx, y + curve.by * ry, x + curve.cx * rx, y + curve.cy * ry, x + curve.dx * rx, y + curve.dy * ry); + /* eslint-enable indent */ + }); + if (mode === constants.PIE || mode == null) { + ctx.lineTo(x, y); + } + ctx.closePath(); + if (!this._clipping) ctx.fill(); + } // Stroke curves + + if (this._doStroke) { + if (!this._clipping) ctx.beginPath(); + curves.forEach(function (curve, index) { + if (index === 0) { + ctx.moveTo(x + curve.ax * rx, y + curve.ay * ry); + } /* eslint-disable indent */ + + ctx.bezierCurveTo(x + curve.bx * rx, y + curve.by * ry, x + curve.cx * rx, y + curve.cy * ry, x + curve.dx * rx, y + curve.dy * ry); + /* eslint-enable indent */ + }); + if (mode === constants.PIE) { + ctx.lineTo(x, y); + ctx.closePath(); + } else if (mode === constants.CHORD) { + ctx.closePath(); + } + if (!this._clipping) ctx.stroke(); } - 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]); + return this; + } + }, + { + key: 'ellipse', + value: function ellipse(args) { + var ctx = this.drawingContext; + var doFill = this._doFill, + doStroke = this._doStroke; + var x = parseFloat(args[0]), + y = parseFloat(args[1]), + w = parseFloat(args[2]), + h = parseFloat(args[3]); + if (doFill && !doStroke) { + if (this._getFill() === styleEmpty) { + return this; } - if (this._doFill) { - this._pInst.fill(vertices[i + 2][5]); + } else if (!doFill && doStroke) { + if (this._getStroke() === styleEmpty) { + return this; } } - this._doFillStrokeClose(closeShape); + 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 + if (!this._clipping) 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 (!this._clipping && doFill) { + ctx.fill(); + } + if (!this._clipping && doStroke) { + ctx.stroke(); + } } - } 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]); + }, + { + key: 'line', + value: function line(x1, y1, x2, y2) { + var ctx = this.drawingContext; + if (!this._doStroke) { + return this; + } else if (this._getStroke() === styleEmpty) { + return this; + } + if (!this._clipping) ctx.beginPath(); + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + ctx.stroke(); + return this; + } + }, + { + key: 'point', + value: function point(x, y) { + var ctx = this.drawingContext; + if (!this._doStroke) { + return this; + } else if (this._getStroke() === styleEmpty) { + return this; + } + var s = this._getStroke(); + var f = this._getFill(); + if (!this._clipping) { + // swapping fill color to stroke and back after for correct point rendering + this._setFill(s); + } + if (!this._clipping) ctx.beginPath(); + ctx.arc(x, y, ctx.lineWidth / 2, 0, constants.TWO_PI, false); + if (!this._clipping) { + ctx.fill(); + this._setFill(f); + } + } + }, + { + key: 'quad', + value: function quad(x1, y1, x2, y2, x3, y3, x4, y4) { + var ctx = this.drawingContext; + var doFill = this._doFill, + doStroke = this._doStroke; + if (doFill && !doStroke) { + if (this._getFill() === styleEmpty) { + return this; + } + } else if (!doFill && doStroke) { + if (this._getStroke() === styleEmpty) { + return this; + } + } + if (!this._clipping) ctx.beginPath(); + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + ctx.lineTo(x3, y3); + ctx.lineTo(x4, y4); + ctx.closePath(); + if (!this._clipping && doFill) { + ctx.fill(); + } + if (!this._clipping && doStroke) { + ctx.stroke(); + } + return this; + } + }, + { + key: 'rect', + value: function rect(args) { + var x = args[0]; + var y = args[1]; + var w = args[2]; + var h = args[3]; + var tl = args[4]; + var tr = args[5]; + var br = args[6]; + var bl = args[7]; + var ctx = this.drawingContext; + var doFill = this._doFill, + doStroke = this._doStroke; + if (doFill && !doStroke) { + if (this._getFill() === styleEmpty) { + return this; + } + } else if (!doFill && doStroke) { + if (this._getStroke() === styleEmpty) { + return this; + } + } + if (!this._clipping) ctx.beginPath(); + if (typeof tl === 'undefined') { + // No rounded corners + ctx.rect(x, y, w, h); + } else { + // At least one rounded corner + // Set defaults when not specified + if (typeof tr === 'undefined') { + tr = tl; + } + if (typeof br === 'undefined') { + br = tr; + } + if (typeof bl === 'undefined') { + bl = br; + } // corner rounding must always be positive + + var absW = Math.abs(w); + var absH = Math.abs(h); + var hw = absW / 2; + var hh = absH / 2; + // Clip radii + if (absW < 2 * tl) { + tl = hw; + } + if (absH < 2 * tl) { + tl = hh; + } + if (absW < 2 * tr) { + tr = hw; + } + if (absH < 2 * tr) { + tr = hh; + } + if (absW < 2 * br) { + br = hw; + } + if (absH < 2 * br) { + br = hh; + } + if (absW < 2 * bl) { + bl = hw; + } + if (absH < 2 * bl) { + bl = hh; + } // Draw shape + + if (!this._clipping) ctx.beginPath(); + ctx.moveTo(x + tl, y); + ctx.arcTo(x + w, y, x + w, y + h, tr); + ctx.arcTo(x + w, y + h, x, y + h, br); + ctx.arcTo(x, y + h, x, y, bl); + ctx.arcTo(x, y, x + w, y, tl); + ctx.closePath(); + } + if (!this._clipping && this._doFill) { + ctx.fill(); + } + if (!this._clipping && this._doStroke) { + ctx.stroke(); + } + return this; + } + }, + { + key: 'triangle', + value: function triangle(args) { + var ctx = this.drawingContext; + var doFill = this._doFill, + doStroke = this._doStroke; + var x1 = args[0], + y1 = args[1]; + var x2 = args[2], + y2 = args[3]; + var x3 = args[4], + y3 = args[5]; + if (doFill && !doStroke) { + if (this._getFill() === styleEmpty) { + return this; + } + } else if (!doFill && doStroke) { + if (this._getStroke() === styleEmpty) { + return this; + } + } + if (!this._clipping) ctx.beginPath(); + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + ctx.lineTo(x3, y3); + ctx.closePath(); + if (!this._clipping && doFill) { + ctx.fill(); + } + if (!this._clipping && doStroke) { + ctx.stroke(); + } + } + }, + { + key: 'endShape', + value: function endShape(mode, vertices, isCurve, isBezier, isQuadratic, isContour, shapeKind) { + if (vertices.length === 0) { + return this; + } + if (!this._doStroke && !this._doFill) { + return this; + } + var closeShape = mode === constants.CLOSE; + var v; + if (closeShape && !isContour) { + vertices.push(vertices[0]); + } + var i, + j; + var numVerts = vertices.length; + if (isCurve && shapeKind === null) { + if (numVerts > 3) { + var b = [ + ], + s = 1 - this._curveTightness; + if (!this._clipping) this.drawingContext.beginPath(); + this.drawingContext.moveTo(vertices[1][0], vertices[1][1]); + for (i = 1; i + 2 < numVerts; i++) { + v = vertices[i]; + b[0] = [ + v[0], + v[1] + ]; + b[1] = [ + v[0] + (s * vertices[i + 1][0] - s * vertices[i - 1][0]) / 6, + v[1] + (s * vertices[i + 1][1] - s * vertices[i - 1][1]) / 6 + ]; + b[2] = [ + vertices[i + 1][0] + (s * vertices[i][0] - s * vertices[i + 2][0]) / 6, + vertices[i + 1][1] + (s * vertices[i][1] - s * vertices[i + 2][1]) / 6 + ]; + b[3] = [ + vertices[i + 1][0], + vertices[i + 1][1] + ]; + this.drawingContext.bezierCurveTo(b[1][0], b[1][1], b[2][0], b[2][1], b[3][0], b[3][1]); + } + if (closeShape) { + this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]); + } + this._doFillStrokeClose(closeShape); + } + } else if (isBezier && shapeKind === null) { + if (!this._clipping) this.drawingContext.beginPath(); + for (i = 0; i < numVerts; i++) { + if (vertices[i].isVert) { + if (vertices[i].moveTo) { + this.drawingContext.moveTo(vertices[i][0], vertices[i][1]); + } else { + this.drawingContext.lineTo(vertices[i][0], vertices[i][1]); } + } else { + this.drawingContext.bezierCurveTo(vertices[i][0], vertices[i][1], vertices[i][2], vertices[i][3], vertices[i][4], vertices[i][5]); + } + } + this._doFillStrokeClose(closeShape); + } else if (isQuadratic && shapeKind === null) { + if (!this._clipping) this.drawingContext.beginPath(); + for (i = 0; i < numVerts; i++) { + if (vertices[i].isVert) { + if (vertices[i].moveTo) { + this.drawingContext.moveTo(vertices[i][0], vertices[i][1]); + } else { + this.drawingContext.lineTo(vertices[i][0], vertices[i][1]); + } + } else { + this.drawingContext.quadraticCurveTo(vertices[i][0], vertices[i][1], vertices[i][2], vertices[i][3]); + } + } + this._doFillStrokeClose(closeShape); + } else { + if (shapeKind === constants.POINTS) { + for (i = 0; i < numVerts; i++) { + v = vertices[i]; if (this._doStroke) { this._pInst.stroke(v[6]); - this.drawingContext.stroke(); + } + this._pInst.point(v[0], v[1]); + } + } else if (shapeKind === constants.LINES) { + for (i = 0; i + 1 < numVerts; i += 2) { + v = vertices[i]; + if (this._doStroke) { this._pInst.stroke(vertices[i + 1][6]); } + this._pInst.line(v[0], v[1], vertices[i + 1][0], vertices[i + 1][1]); + } + } else if (shapeKind === constants.TRIANGLES) { + for (i = 0; i + 2 < numVerts; i += 3) { + v = vertices[i]; + if (!this._clipping) this.drawingContext.beginPath(); + this.drawingContext.moveTo(v[0], v[1]); + this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]); + this.drawingContext.lineTo(vertices[i + 2][0], vertices[i + 2][1]); this.drawingContext.closePath(); - this.drawingContext.beginPath(); // Begin the next one + if (!this._clipping && this._doFill) { + this._pInst.fill(vertices[i + 2][5]); + this.drawingContext.fill(); + } + if (!this._clipping && this._doStroke) { + this._pInst.stroke(vertices[i + 2][6]); + this.drawingContext.stroke(); + } + } + } else if (shapeKind === constants.TRIANGLE_STRIP) { + for (i = 0; i + 1 < numVerts; i++) { + v = vertices[i]; + if (!this._clipping) this.drawingContext.beginPath(); + this.drawingContext.moveTo(vertices[i + 1][0], vertices[i + 1][1]); + this.drawingContext.lineTo(v[0], v[1]); + if (!this._clipping && this._doStroke) { + this._pInst.stroke(vertices[i + 1][6]); + } + if (!this._clipping && this._doFill) { + this._pInst.fill(vertices[i + 1][5]); + } + if (i + 2 < numVerts) { + this.drawingContext.lineTo(vertices[i + 2][0], vertices[i + 2][1]); + if (!this._clipping && this._doStroke) { + this._pInst.stroke(vertices[i + 2][6]); + } + if (!this._clipping && this._doFill) { + this._pInst.fill(vertices[i + 2][5]); + } + } + this._doFillStrokeClose(closeShape); + } + } else if (shapeKind === constants.TRIANGLE_FAN) { + if (numVerts > 2) { + // For performance reasons, try to batch as many of the + // fill and stroke calls as possible. + if (!this._clipping) this.drawingContext.beginPath(); + for (i = 2; i < numVerts; i++) { + v = vertices[i]; + this.drawingContext.moveTo(vertices[0][0], vertices[0][1]); + this.drawingContext.lineTo(vertices[i - 1][0], vertices[i - 1][1]); + this.drawingContext.lineTo(v[0], v[1]); + this.drawingContext.lineTo(vertices[0][0], vertices[0][1]); + // If the next colour is going to be different, stroke / fill now + if (i < numVerts - 1) { + if (this._doFill && v[5] !== vertices[i + 1][5] || this._doStroke && v[6] !== vertices[i + 1][6]) { + if (!this._clipping && this._doFill) { + this._pInst.fill(v[5]); + this.drawingContext.fill(); + this._pInst.fill(vertices[i + 1][5]); + } + if (!this._clipping && this._doStroke) { + this._pInst.stroke(v[6]); + this.drawingContext.stroke(); + this._pInst.stroke(vertices[i + 1][6]); + } + this.drawingContext.closePath(); + if (!this._clipping) this.drawingContext.beginPath(); // Begin the next one + } + } + } + this._doFillStrokeClose(closeShape); + } + } else if (shapeKind === constants.QUADS) { + for (i = 0; i + 3 < numVerts; i += 4) { + v = vertices[i]; + if (!this._clipping) this.drawingContext.beginPath(); + this.drawingContext.moveTo(v[0], v[1]); + for (j = 1; j < 4; j++) { + this.drawingContext.lineTo(vertices[i + j][0], vertices[i + j][1]); + } + this.drawingContext.lineTo(v[0], v[1]); + if (!this._clipping && this._doFill) { + this._pInst.fill(vertices[i + 3][5]); + } + if (!this._clipping && this._doStroke) { + this._pInst.stroke(vertices[i + 3][6]); + } + this._doFillStrokeClose(closeShape); + } + } else if (shapeKind === constants.QUAD_STRIP) { + if (numVerts > 3) { + for (i = 0; i + 1 < numVerts; i += 2) { + v = vertices[i]; + if (!this._clipping) this.drawingContext.beginPath(); + if (i + 3 < numVerts) { + this.drawingContext.moveTo(vertices[i + 2][0], vertices[i + 2][1]); + this.drawingContext.lineTo(v[0], v[1]); + this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]); + this.drawingContext.lineTo(vertices[i + 3][0], vertices[i + 3][1]); + if (!this._clipping && this._doFill) { + this._pInst.fill(vertices[i + 3][5]); + } + if (!this._clipping && this._doStroke) { + this._pInst.stroke(vertices[i + 3][6]); + } + } else { + this.drawingContext.moveTo(v[0], v[1]); + this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]); + } + this._doFillStrokeClose(closeShape); + } + } + } else { + if (!this._clipping) this.drawingContext.beginPath(); + this.drawingContext.moveTo(vertices[0][0], vertices[0][1]); + for (i = 1; i < numVerts; i++) { + v = vertices[i]; + if (v.isVert) { + if (v.moveTo) { + if (closeShape) this.drawingContext.closePath(); + this.drawingContext.moveTo(v[0], v[1]); + } else { + this.drawingContext.lineTo(v[0], v[1]); + } + } } + this._doFillStrokeClose(closeShape); } } - this._doFillStrokeClose(closeShape); + isCurve = false; + isBezier = false; + isQuadratic = false; + isContour = false; + if (closeShape) { + vertices.pop(); + } + return this; + } ////////////////////////////////////////////// + // SHAPE | Attributes + ////////////////////////////////////////////// + + }, + { + key: 'strokeCap', + value: function strokeCap(cap) { + if (cap === constants.ROUND || cap === constants.SQUARE || cap === constants.PROJECT) { + this.drawingContext.lineCap = cap; + } + return this; } - } 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]); + }, + { + key: 'strokeJoin', + value: function strokeJoin(join) { + if (join === constants.ROUND || join === constants.BEVEL || join === constants.MITER) { + this.drawingContext.lineJoin = join; } - this.drawingContext.lineTo(v[0], v[1]); - if (this._doFill) { - this._pInst.fill(vertices[i + 3][5]); + return this; + } + }, + { + key: 'strokeWeight', + value: function strokeWeight(w) { + if (typeof w === 'undefined' || w === 0) { + // hack because lineWidth 0 doesn't work + this.drawingContext.lineWidth = 0.0001; + } else { + this.drawingContext.lineWidth = w; } - 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]); + return this; + } + }, + { + key: '_getFill', + value: function _getFill() { + if (!this._cachedFillStyle) { + this._cachedFillStyle = this.drawingContext.fillStyle; + } + return this._cachedFillStyle; + } + }, + { + key: '_setFill', + value: function _setFill(fillStyle) { + if (fillStyle !== this._cachedFillStyle) { + this.drawingContext.fillStyle = fillStyle; + this._cachedFillStyle = fillStyle; + } + } + }, + { + key: '_getStroke', + value: function _getStroke() { + if (!this._cachedStrokeStyle) { + this._cachedStrokeStyle = this.drawingContext.strokeStyle; + } + return this._cachedStrokeStyle; + } + }, + { + key: '_setStroke', + value: function _setStroke(strokeStyle) { + if (strokeStyle !== this._cachedStrokeStyle) { + this.drawingContext.strokeStyle = strokeStyle; + this._cachedStrokeStyle = strokeStyle; + } + } ////////////////////////////////////////////// + // SHAPE | Curves + ////////////////////////////////////////////// + + }, + { + key: 'bezier', + value: function bezier(x1, y1, x2, y2, x3, y3, x4, y4) { + this._pInst.beginShape(); + this._pInst.vertex(x1, y1); + this._pInst.bezierVertex(x2, y2, x3, y3, x4, y4); + this._pInst.endShape(); + return this; + } + }, + { + key: 'curve', + value: function curve(x1, y1, x2, y2, x3, y3, x4, y4) { + this._pInst.beginShape(); + this._pInst.curveVertex(x1, y1); + this._pInst.curveVertex(x2, y2); + this._pInst.curveVertex(x3, y3); + this._pInst.curveVertex(x4, y4); + this._pInst.endShape(); + return this; + } ////////////////////////////////////////////// + // SHAPE | Vertex + ////////////////////////////////////////////// + + }, + { + key: '_doFillStrokeClose', + value: function _doFillStrokeClose(closeShape) { + if (closeShape) { + this.drawingContext.closePath(); + } + if (!this._clipping && this._doFill) { + this.drawingContext.fill(); + } + if (!this._clipping && this._doStroke) { + this.drawingContext.stroke(); + } + } ////////////////////////////////////////////// + // TRANSFORM + ////////////////////////////////////////////// + + }, + { + key: 'applyMatrix', + value: function applyMatrix(a, b, c, d, e, f) { + this.drawingContext.transform(a, b, c, d, e, f); + } + }, + { + key: 'resetMatrix', + value: function resetMatrix() { + this.drawingContext.setTransform(1, 0, 0, 1, 0, 0); + this.drawingContext.scale(this._pInst._pixelDensity, this._pInst._pixelDensity); + return this; + } + }, + { + key: 'rotate', + value: function rotate(rad) { + this.drawingContext.rotate(rad); + } + }, + { + key: 'scale', + value: function scale(x, y) { + this.drawingContext.scale(x, y); + return this; + } + }, + { + key: 'translate', + value: function translate(x, y) { + // support passing a vector as the 1st parameter + if (x instanceof _main.default.Vector) { + y = x.y; + x = x.x; + } + this.drawingContext.translate(x, y); + return this; + } ////////////////////////////////////////////// + // TYPOGRAPHY + // + ////////////////////////////////////////////// + + }, + { + key: '_renderText', + value: function _renderText(p, line, x, y, maxY, minY) { + if (y < minY || y >= maxY) { + return; // don't render lines beyond our minY/maxY bounds (see #5785) + } + p.push(); // fix to #803 + if (!this._isOpenType()) { + // a system/browser font + // no stroke unless specified by user + if (this._doStroke && this._strokeSet) { + this.drawingContext.strokeText(line, x, y); + } + if (!this._clipping && this._doFill) { + // if fill hasn't been set by user, use default text fill + if (!this._fillSet) { + this._setFill(constants._DEFAULT_TEXT_FILL); } - } else { - this.drawingContext.moveTo(v[0], v[1]); - this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]); + this.drawingContext.fillText(line, x, y); } - this._doFillStrokeClose(closeShape); + } else { + // an opentype font, let it handle the rendering + this._textFont._renderPath(line, x, y, { + renderer: this + }); } + p.pop(); + return p; } - } 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]); - } + }, + { + key: 'textWidth', + value: function textWidth(s) { + if (this._isOpenType()) { + return this._textFont._textWidth(s, this._textSize); } + return this.drawingContext.measureText(s).width; } - 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) + }, + { + key: '_applyTextProperties', + value: function _applyTextProperties() { + var font; + var p = this._pInst; + this._setProperty('_textAscent', null); + this._setProperty('_textDescent', null); + font = this._textFont; + if (this._isOpenType()) { + font = this._textFont.font.familyName; + this._setProperty('_textStyle', this._textFont.font.styleName); + } + 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. + + }, + { + key: 'push', + value: function push() { + this.drawingContext.save(); + // get the base renderer style + return _get(_getPrototypeOf(Renderer2D.prototype), 'push', this).call(this); + } // a pop() operation is in progress + // the renderer is passed the 'style' object that it returned + // from its push() method. + // derived renderers should pass this object to their base + // class' pop method + + }, + { + key: 'pop', + value: function pop(style) { + this.drawingContext.restore(); + // Re-cache the fill / stroke state + this._cachedFillStyle = this.drawingContext.fillStyle; + this._cachedStrokeStyle = this.drawingContext.strokeStyle; + _get(_getPrototypeOf(Renderer2D.prototype), 'pop', this).call(this, style); + } + } + ]); + return Renderer2D; + }(_main.default.Renderer); // Fix test + Renderer2D.prototype.text = function (str, x, y, maxWidth, maxHeight) { + var baselineHacked; + // baselineHacked: (HACK) // A temporary fix to conform to Processing's implementation // of BASELINE vertical alignment in a bounding box if (typeof maxWidth !== 'undefined') { @@ -64169,106 +67799,37 @@ } return p; }; - _main.default.Renderer2D.prototype._renderText = function (p, line, x, y, maxY, minY) { - if (y < minY || y >= maxY) { - return; // don't render lines beyond our minY/maxY bounds (see #5785) - } - p.push(); // fix to #803 - if (!this._isOpenType()) { - // a system/browser font - // no stroke unless specified by user - if (this._doStroke && this._strokeSet) { - this.drawingContext.strokeText(line, x, y); - } - if (this._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); - }; + _main.default.Renderer2D = Renderer2D; var _default = _main.default.Renderer2D; exports.default = _default; }, { - './constants': 278, - './main': 290, - './p5.Renderer': 293, - 'core-js/modules/es.array.concat': 167, - 'core-js/modules/es.array.fill': 170, - 'core-js/modules/es.array.for-each': 172, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.join': 177, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.function.name': 183, - 'core-js/modules/es.number.to-fixed': 189, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.to-string': 200, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + './constants': 286, + './main': 298, + './p5.Renderer': 301, + 'core-js/modules/es.array.concat': 169, + 'core-js/modules/es.array.fill': 172, + 'core-js/modules/es.array.for-each': 175, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.join': 180, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.function.name': 186, + 'core-js/modules/es.number.to-fixed': 193, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.get-prototype-of': 198, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.reflect.construct': 202, + 'core-js/modules/es.reflect.get': 203, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 295: [ + 303: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -64328,19 +67889,22 @@ 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 + 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 + } // Replace the original method with a wrapped version - target[method] = this._wrapPromisePreload(thisValue, sourceFunction, addCallbacks); // If a legacy preload is required + 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 + var legacyMethod = legacyPreloadSetup.method; + // Wrap the already wrapped Promise-returning method with the legacy setup target[legacyMethod] = this._legacyPreloadGenerator(thisValue, legacyPreloadSetup, target[method]); } } @@ -64362,9 +67926,12 @@ }; _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 _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]; @@ -64379,21 +67946,23 @@ errorCallback = callback; callback = args.pop(); } - } // Call the underlying function and pass it to Promise.resolve, + } // Call the underlying function and pass it to Promise.resolve, // so that even if it didn't return a promise we can still // act on the result as if it did. - var promise = Promise.resolve(fn.apply(this, args)); // Add the optional callbacks + 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 + } // 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 the original promise so that neither callback changes the result. return promise; }; if (thisValue) { @@ -64411,12 +67980,19 @@ // 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) { + var _this2 = this; + // Our then clause needs to run before setup, so we also increment the preload counter + this._incrementPreload(); + // Generate the return value based on the generator. + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + var returnValue = baseValueGenerator.apply(this, args); + // Run the original wrapper + fn.apply(this, args).then(function (data) { // Copy each key from the resolved value into returnValue - Object.assign(returnValue, data); // Decrement the preload counter, to allow setup to continue. + Object.assign(returnValue, data); + // Decrement the preload counter, to allow setup to continue. _this2._decrementPreload(); }); return returnValue; @@ -64428,19 +68004,19 @@ }; }, { - './main': 290, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.object.assign': 190, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.promise': 196, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/web.dom-collections.iterator': 248 + './main': 298, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.object.assign': 194, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.promise': 201, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 296: [ + 304: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -64540,7 +68116,12 @@ }; } return _typeof(obj); - } + } /** + * @module Rendering + * @submodule Rendering + * @for p5 + */ + var defaultId = 'defaultCanvas0'; // this gets set again in createCanvas var defaultClass = 'p5Canvas'; /** @@ -64556,10 +68137,18 @@ * 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. * + * A WebGL canvas will use a WebGL2 context if it is supported by the browser. + * Check the webglVersion property to check what + * version is being used, or call setAttributes({ version: 1 }) + * to create a WebGL1 context. + * * The system variables width and height are set by the parameters passed to this * function. If createCanvas() is not used, the * window will be given a default size of 100×100 pixels. * + * Optionally, an existing canvas can be passed using a selector, ie. `document.getElementById('')`. + * If specified, avoid using `setAttributes()` afterwards, as this will remove and recreate the existing canvas. + * * For more ways to position the canvas, see the * * positioning the canvas wiki page. @@ -64568,6 +68157,7 @@ * @param {Number} w width of the canvas * @param {Number} h height of the canvas * @param {Constant} [renderer] either P2D or WEBGL + * @param {HTMLCanvasElement} [canvas] existing html canvas element * @return {p5.Renderer} pointer to p5.Renderer holding canvas * @example *
      @@ -64583,55 +68173,82 @@ * @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; + /** + * @method createCanvas + * @param {Number} w + * @param {Number} h + * @param {HTMLCanvasElement} [canvas] + * @return {p5.Renderer} pointer to p5.Renderer holding canvas + */ + _main.default.prototype.createCanvas = function (w, h, renderer, canvas) { + _main.default._validateParameters('createCanvas', arguments); + //optional: renderer, otherwise defaults to p2d + var r; + if (arguments[2] instanceof HTMLCanvasElement) { + renderer = constants.P2D; + canvas = arguments[2]; + } else { + r = renderer || constants.P2D; + } var c; - if (r === constants.WEBGL) { + if (canvas) { 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); + c = canvas; + this._defaultGraphicsCreated = false; } else { - if (!this._defaultGraphicsCreated) { - c = document.createElement('canvas'); - var i = 0; - while (document.getElementById('defaultCanvas'.concat(i))) { - i++; + 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; + }); } - defaultId = 'defaultCanvas'.concat(i); + c = document.createElement('canvas'); c.id = defaultId; c.classList.add(defaultClass); } else { - // resize the default canvas if new one is created - c = this.canvas; + if (!this._defaultGraphicsCreated) { + if (canvas) { + c = canvas; + } else { + c = document.createElement('canvas'); + } + var i = 0; + while (document.getElementById('defaultCanvas'.concat(i))) { + i++; + } + defaultId = 'defaultCanvas'.concat(i); + c.id = defaultId; + c.classList.add(defaultClass); + } else { + // resize the default canvas if new one is created + c = this.canvas; + } + } // set to invisible if still in setup (to prevent flashing with manipulate) + + if (!this._setupDone) { + c.dataset.hidden = true; // tag to show later + c.style.visibility = 'hidden'; } - } // set to invisible if still in setup (to prevent flashing with manipulate) + 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 - 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 + document.getElementsByTagName('main') [0].appendChild(c); + } + } // Init our graphics renderer //webgl mode if (r === constants.WEBGL) { @@ -64687,19 +68304,23 @@ props[key] = val; } } - this._renderer.resize(w, h); this.width = w; - this.height = h; // reset canvas properties + this.height = h; + // Make sure width and height are updated before the renderer resizes so + // that framebuffers updated from the resize read the correct size + this._renderer.resize(w, h); + // reset canvas properties for (var savedKey in props) { try { this.drawingContext[savedKey] = props[savedKey]; - } catch (err) { // ignore read-only property errors + } catch (err) { + // ignore read-only property errors } } if (!noRedraw) { this.redraw(); } - } //accessible Outputs + } //accessible Outputs if (this._addAccsOutput()) { this._updateAccsOutput(); @@ -64726,15 +68347,24 @@ } }; /** - * Creates and returns a new p5.Renderer object. Use this class if you need + * Creates and returns a new p5.Graphics 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. * + * A WebGL p5.Graphics will use a WebGL2 context if it is supported by the browser. + * Check the pg.webglVersion property of the renderer + * to check what version is being used, or call pg.setAttributes({ version: 1 }) + * to create a WebGL1 context. + * + * Optionally, an existing canvas can be passed using a selector, ie. document.getElementById(''). + * By default this canvas will be hidden (offscreen buffer), to make visible, set element's style to display:block; + * * @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 + * @param {HTMLCanvasElement} [canvas] existing html canvas element * @return {p5.Graphics} offscreen graphics buffer * @example *
      @@ -64759,9 +68389,102 @@ * @alt * 4 grey squares alternating light and dark grey. White quarter circle mid-left. */ - _main.default.prototype.createGraphics = function (w, h, renderer) { + /** + * @method createGraphics + * @param {Number} w + * @param {Number} h + * @param {HTMLCanvasElement} [canvas] + * @return {p5.Graphics} offscreen graphics buffer + */ + _main.default.prototype.createGraphics = function (w, h) { + for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { + args[_key - 2] = arguments[_key]; + } /** + * args[0] is expected to be renderer + * args[1] is expected to be canvas + */ + + if (args[0] instanceof HTMLCanvasElement) { + args[1] = args[0]; + args[0] = constants.P2D; + } _main.default._validateParameters('createGraphics', arguments); - return new _main.default.Graphics(w, h, renderer, this); + return new _main.default.Graphics(w, h, args[0], this, args[1]); + }; + /** + * Creates and returns a new p5.Framebuffer, a + * high-performance WebGL object that you can draw to and then use as a texture. + * + * Options can include: + * - `format`: The data format of the texture, either `UNSIGNED_BYTE`, `FLOAT`, or `HALF_FLOAT`. The default is `UNSIGNED_BYTE`. + * - `channels`: What color channels to store, either `RGB` or `RGBA`. The default is to match the channels in the main canvas (with alpha unless disabled with `setAttributes`.) + * - `depth`: A boolean, whether or not to include a depth buffer. Defaults to true. + * - `depthFormat`: The data format for depth information, either `UNSIGNED_INT` or `FLOAT`. The default is `FLOAT` if available, or `UNSIGNED_INT` otherwise. + * - `stencil`: A boolean, whether or not to include a stencil buffer, which can be used for masking. This may only be used if also using a depth buffer. Defaults to the value of `depth`, which is true if not provided. + * - `antialias`: Boolean or Number, whether or not to render with antialiased edges, and if so, optionally the number of samples to use. Defaults to whether or not the main canvas is antialiased, using a default of 2 samples if so. Antialiasing is only supported when WebGL 2 is available. + * - `width`: The width of the texture. Defaults to matching the main canvas. + * - `height`: The height of the texture. Defaults to matching the main canvas. + * - `density`: The pixel density of the texture. Defaults to the pixel density of the main canvas. + * - `textureFiltering`: Either `LINEAR` (nearby pixels will be interpolated when reading values from the color texture) or `NEAREST` (no interpolation.) Generally, use `LINEAR` when using the texture as an image, and use `NEAREST` if reading the texture as data. Defaults to `LINEAR`. + * + * If `width`, `height`, or `density` are specified, then the framebuffer will + * keep that size until manually changed. Otherwise, it will be autosized, and + * it will update to match the main canvas's size and density when the main + * canvas changes. + * + * @method createFramebuffer + * @param {Object} [options] An optional object with configuration + * + * @example + *
      + * + * let prev, next, cam; + * function setup() { + * createCanvas(100, 100, WEBGL); + * prev = createFramebuffer({ format: FLOAT }); + * next = createFramebuffer({ format: FLOAT }); + * cam = createCamera(); + * noStroke(); + * } + * + * function draw() { + * // Swap prev and next so that we can use the previous + * // frame as a texture when drawing the current frame + * [prev, next] = [next, prev]; + * + * // Draw to the framebuffer + * next.begin(); + * background(255); + * + * push(); + * // Draw the previous texture farther away, but scaled + * // up to fill the screen, plus a bit extra scale so it grows + * translate(0, 0, -200); + * scale(1.001 * (200 + cam.eyeZ) / cam.eyeZ); + * tint(255, 253); + * image(prev, -width/2, -height/2); + * pop(); + * + * push(); + * normalMaterial(); + * translate(25*sin(frameCount * 0.014), 25*sin(frameCount * 0.02), 0); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * box(12); + * pop(); + * next.end(); + * + * image(next, -width/2, -height/2); + * } + * + *
      + * + * @alt + * A red, green, and blue box (using normalMaterial) moves and rotates around + * the canvas, leaving a trail behind it that slowly grows and fades away. + */ + _main.default.prototype.createFramebuffer = function (options) { + return new _main.default.Framebuffer(this, options); }; /** * Blends the pixels in the display window according to the defined mode. @@ -64875,33 +68598,35 @@ exports.default = _default; }, { - '../webgl/p5.RendererGL': 344, - './constants': 278, - './main': 290, - './p5.Graphics': 292, - './p5.Renderer2D': 294, - 'core-js/modules/es.array.filter': 171, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + '../webgl/p5.RendererGL': 355, + './constants': 286, + './main': 298, + './p5.Graphics': 300, + './p5.Renderer2D': 302, + 'core-js/modules/es.array.filter': 173, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 297: [ + 305: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); _dereq_('core-js/modules/es.symbol.description'); _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.from'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.slice'); _dereq_('core-js/modules/es.object.get-own-property-descriptor'); _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.to-string'); _dereq_('core-js/modules/es.string.iterator'); _dereq_('core-js/modules/es.weak-map'); _dereq_('core-js/modules/web.dom-collections.iterator'); @@ -64986,13 +68711,30 @@ default: obj }; - } /** - * @module Shape - * @submodule 2D Primitives - * @for p5 - * @requires core - * @requires constants - */ + } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + function _nonIterableSpread() { + throw new TypeError('Invalid attempt to spread non-iterable instance'); + } + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === '[object Arguments]') return Array.from(iter); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + return arr2; + } + } /** + * @module Shape + * @submodule 2D Primitives + * @for p5 + * @requires core + * @requires constants + */ /** * This function does 3 things: * @@ -65018,11 +68760,13 @@ _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 + 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. + 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 @@ -65034,7 +68778,8 @@ // (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. + 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)); @@ -65050,7 +68795,7 @@ } else { stop = Math.atan(width / height * Math.tan(stop)) + constants.TWO_PI; } - } // Ensure that start <= stop < start + TWO_PI. + } // Ensure that start <= stop < start + TWO_PI. if (start > stop) { stop += constants.TWO_PI; @@ -65062,28 +68807,24 @@ }; }; /** - * Draw an arc to the screen. If called with only x, y, w, h, start and stop, - * the arc will be drawn and filled as an open pie segment. If a mode parameter - * is provided, the arc will be filled like an open semi-circle (OPEN), a closed - * semi-circle (CHORD), or as a closed pie segment (PIE). The origin may be changed - * with the ellipseMode() function. + * Draws an arc to the canvas. Arcs are drawn along the outer edge of an ellipse + * (oval) defined by the `x`, `y`, `w`, and `h` parameters. Use the `start` and `stop` + * parameters to specify the angles (in radians) at which to draw the arc. Arcs are + * always drawn clockwise from `start` to `stop`. The origin of the arc's ellipse may + * be changed with the ellipseMode() function. * - * The arc is always drawn clockwise from wherever start falls to wherever stop - * falls on the ellipse. Adding or subtracting TWO_PI to either angle does not - * change where they fall. If both start and stop fall at the same place, a full - * ellipse will be drawn. Be aware that the y-axis increases in the downward - * direction, therefore angles are measured clockwise from the positive - * x-direction ("3 o'clock"). + * The optional `mode` parameter determines the arc's fill style. The fill modes are + * a semi-circle (`OPEN`), a closed semi-circle (`CHORD`), or a closed pie segment (`PIE`). * * @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 {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 + * the arc. either CHORD, PIE, or OPEN. * @param {Integer} [detail] optional parameter for WebGL mode only. This is to * specify the number of vertices that makes up the * perimeter of the arc. Default value is 25. Won't @@ -65099,7 +68840,7 @@ * arc(50, 55, 70, 70, PI, PI + QUARTER_PI); * arc(50, 55, 80, 80, PI + QUARTER_PI, TWO_PI); * describe( - * 'shattered outline of ellipse with a quarter of a white circle bottom-right' + * 'A shattered outline of an ellipse with a quarter of a white circle at the bottom-right.' * ); *
      *
      @@ -65107,36 +68848,37 @@ *
      * * arc(50, 50, 80, 80, 0, PI + QUARTER_PI); - * describe('white ellipse with top right quarter missing'); + * describe('A white ellipse with the top-right third missing. The bottom is outlined in black.'); * *
      * *
      * * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, OPEN); - * describe('white ellipse with black outline with top right missing'); + * describe( + * 'A white ellipse missing a section from the top-right. The bottom is outlined in black.' + * ); * *
      * *
      * * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, CHORD); - * describe('white open arc with black outline with top right missing'); + * describe('A white ellipse with a black outline missing a section from the top-right.'); * *
      * *
      * * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, PIE); - * describe( - * 'white ellipse with top right quarter missing with black outline around the shape' - * ); + * describe('A white ellipse with a black outline. The top-right third is missing.'); * *
      * */ _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 + _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; @@ -65145,7 +68887,8 @@ return this; } start = this._toRadians(start); - stop = this._toRadians(stop); // p5 supports negative width and heights for ellipses + 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); @@ -65162,9 +68905,10 @@ 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 + 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, @@ -65180,14 +68924,15 @@ 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. + * Draws an ellipse (oval) to the canvas. An ellipse with equal width and height + * is a circle. By default, the first two parameters set the location of the + * center of the ellipse. The third and fourth parameters set the shape's width + * and height, respectively. The origin may be changed with the + * ellipseMode() function. * - * An ellipse with equal width and height is a circle. The origin may be changed - * with the ellipseMode() function. + * 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. * * @method ellipse * @param {Number} x x-coordinate of the center of the ellipse. @@ -65199,7 +68944,7 @@ *
      * * ellipse(56, 46, 55, 55); - * describe('white ellipse with black outline in middle of a gray canvas'); + * describe('A white ellipse with black outline in middle of a gray canvas.'); * *
      * @@ -65210,7 +68955,7 @@ * @param {Number} y * @param {Number} w * @param {Number} h - * @param {Integer} [detail] optional parameter for WEBGL mode only. This is to + * @param {Integer} [detail] optional parameter for WebGL mode only. This is to * specify the number of vertices that makes up the * perimeter of the ellipse. Default value is 25. Won't * draw a stroke for a detail of more than 50. @@ -65220,14 +68965,11 @@ return this._renderEllipse.apply(this, arguments); }; /** - * Draws a circle to the screen. A circle is a simple closed shape. It is the set - * of all points in a plane that are at a given distance from a given point, - * the center. This function is a special case of the - * ellipse() function, where the width and height - * of the ellipse are the same. Height and width of the ellipse correspond to - * the diameter of the circle. By default, the first two parameters set the - * location of the center of the circle, the third sets the diameter of the - * circle. + * Draws a circle to the canvas. A circle is a round shape. Every point on the + * edge of a circle is the same distance from its center. By default, the first + * two parameters set the location of the center of the circle. The third + * parameter sets the shape's width and height (diameter). The origin may be + * changed with the ellipseMode() function. * * @method circle * @param {Number} x x-coordinate of the center of the circle. @@ -65237,9 +68979,8 @@ * @example *
      * - * // Draw a circle at location (30, 30) with a diameter of 20. * circle(30, 30, 20); - * describe('white circle with black outline in mid of gray canvas'); + * describe('A white circle with black outline in the middle of a gray canvas.'); * *
      * @@ -65249,14 +68990,15 @@ 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) + return this._renderEllipse.apply(this, _toConsumableArray(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 + } // p5 supports negative width and heights for rects if (w < 0) { w = Math.abs(w); @@ -65272,7 +69014,8 @@ vals.y, vals.w, vals.h, - detailX]); //accessible Outputs + detailX]); + //accessible Outputs if (this._accessibleOutputs.grid || this._accessibleOutputs.text) { this._accsOutput('ellipse', [ vals.x, @@ -65284,25 +69027,29 @@ return this; }; /** - * Draws a line (a direct path between two points) to the screen. If called with - * only 4 parameters, it will draw a line in 2D with a default width of 1 pixel. - * This width can be modified by using the - * strokeWeight() function. A line cannot be filled, therefore the fill() function will not affect the color of a line. So to - * color a line, use the stroke() function. + * Draws a line, a straight path between two points. Its default width is one pixel. + * The version of `line()` with four parameters draws the line in 2D. To color a line, + * use the stroke() function. To change its width, use the + * strokeWeight() function. A line + * can't be filled, so the fill() function won't affect + * the color of a line. + * + * The version of `line()` with six parameters allows the line to be drawn in 3D + * space. Doing so requires adding the `WEBGL` argument to + * createCanvas(). * * @method line - * @param {Number} x1 the x-coordinate of the first point - * @param {Number} y1 the y-coordinate of the first point - * @param {Number} x2 the x-coordinate of the second point - * @param {Number} y2 the y-coordinate of the second point + * @param {Number} x1 the x-coordinate of the first point. + * @param {Number} y1 the y-coordinate of the first point. + * @param {Number} x2 the x-coordinate of the second point. + * @param {Number} y2 the y-coordinate of the second point. * @chainable * @example *
      * * line(30, 20, 85, 75); * describe( - * 'a 78 pixels long line running from mid-top to bottom-right of canvas' + * 'A black line on a gray canvas running from top-center to bottom-right.' * ); * *
      @@ -65315,20 +69062,34 @@ * stroke(255); * line(85, 75, 30, 75); * describe( - * '3 lines of various stroke colors. Form top, bottom and right sides of a square' + * 'Three lines drawn in grayscale on a gray canvas. They form the top, right, and bottom sides of a square.' * ); * *
      * + *
      + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * describe('A black line drawn on a gray canvas.'); + * } + * + * function draw() { + * background(220); + * line(0, 0, 0, 10, 10, 0); + * } + * + *
      + * */ /** * @method line * @param {Number} x1 * @param {Number} y1 - * @param {Number} z1 the z-coordinate of the first point + * @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} z2 the z-coordinate of the second point. * @chainable */ _main.default.prototype.line = function () { @@ -65339,7 +69100,7 @@ if (this._renderer._doStroke) { var _this$_renderer; (_this$_renderer = this._renderer).line.apply(_this$_renderer, args); - } //accessible Outputs + } //accessible Outputs if (this._accessibleOutputs.grid || this._accessibleOutputs.text) { this._accsOutput('line', args); @@ -65347,16 +69108,22 @@ return this; }; /** - * Draws a point, a coordinate in space at the dimension of one pixel. - * The first parameter is the horizontal value for the point, the second - * param is the vertical value for the point. The color of the point is - * changed with the stroke() function. The size of the point - * can be changed with the strokeWeight() function. + * Draws a point, a single coordinate in space. Its default size is one pixel. The first two + * parameters are the point's x- and y-coordinates, respectively. To color a point, use + * the stroke() function. To change its size, use the + * strokeWeight() function. + * + * The version of `point()` with three parameters allows the point to be drawn in 3D + * space. Doing so requires adding the `WEBGL` argument to + * createCanvas(). + * + * The version of point() with one parameter allows the point's location to be set with + * a p5.Vector object. * * @method point - * @param {Number} x the x-coordinate - * @param {Number} y the y-coordinate - * @param {Number} [z] the z-coordinate (for WebGL mode) + * @param {Number} x the x-coordinate. + * @param {Number} y the y-coordinate. + * @param {Number} [z] the z-coordinate (for WebGL mode). * @chainable * @example *
      @@ -65365,7 +69132,9 @@ * point(85, 20); * point(85, 75); * point(30, 75); - * describe('4 points create the corners of a square'); + * describe( + * 'Four small, black points drawn on a gray canvas. The points form the corners of a square.' + * ); * *
      * @@ -65373,11 +69142,13 @@ * * point(30, 20); * point(85, 20); - * stroke('purple'); // Change the color - * strokeWeight(10); // Make the points 10 pixels in size + * stroke('purple'); + * strokeWeight(10); * point(85, 75); * point(30, 75); - * describe('2 points and 2 large purple points in middle-right of canvas'); + * describe( + * 'Four points drawn on a gray canvas. Two are black and two are purple. The points form the corners of a square.' + * ); * *
      * @@ -65387,10 +69158,12 @@ * point(a); * let b = createVector(10, 20); * point(b); - * point(createVector(20, 10)); - * point(createVector(20, 20)); + * let c = createVector(20, 10); + * point(c); + * let d = createVector(20, 20); + * point(d); * describe( - * 'four points create vertices of 10x10 pixel square on top-left of canvas' + * 'Four small, black points drawn on a gray canvas. The points form the corners of a square.' * ); * * @@ -65398,7 +69171,7 @@ */ /** * @method point - * @param {p5.Vector} coordinate_vector the coordinate vector + * @param {p5.Vector} coordinateVector the coordinate vector. * @chainable */ _main.default.prototype.point = function () { @@ -65411,7 +69184,8 @@ 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 + (_this$_renderer2 = this._renderer).point.apply(_this$_renderer2, args); + //accessible Outputs if (this._accessibleOutputs.grid || this._accessibleOutputs.text) { this._accsOutput('point', args); } @@ -65420,48 +69194,72 @@ 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. + * Draws a quad to the canvas. A quad is a quadrilateral, a four-sided + * polygon. Some examples of quads include rectangles, squares, rhombuses, + * and trapezoids. The first pair of parameters (`x1`,`y1`) sets the quad's + * first point. The following pairs of parameters set the coordinates for + * its next three points. Parameters should proceed clockwise or + * counter-clockwise around the shape. + * + * The version of `quad()` with twelve parameters allows the quad to be drawn + * in 3D space. Doing so requires adding the `WEBGL` argument to + * createCanvas(). * * @method quad - * @param {Number} x1 the x-coordinate of the first point - * @param {Number} y1 the y-coordinate of the first point - * @param {Number} x2 the x-coordinate of the second point - * @param {Number} y2 the y-coordinate of the second point - * @param {Number} x3 the x-coordinate of the third point - * @param {Number} y3 the y-coordinate of the third point - * @param {Number} x4 the x-coordinate of the fourth point - * @param {Number} y4 the y-coordinate of the fourth point - * @param {Integer} [detailX] number of segments in the x-direction - * @param {Integer} [detailY] number of segments in the y-direction + * @param {Number} x1 the x-coordinate of the first point. + * @param {Number} y1 the y-coordinate of the first point. + * @param {Number} x2 the x-coordinate of the second point. + * @param {Number} y2 the y-coordinate of the second point. + * @param {Number} x3 the x-coordinate of the third point. + * @param {Number} y3 the y-coordinate of the third point. + * @param {Number} x4 the x-coordinate of the fourth point. + * @param {Number} y4 the y-coordinate of the fourth point. + * @param {Integer} [detailX] number of segments in the x-direction. + * @param {Integer} [detailY] number of segments in the y-direction. * @chainable * @example *
      * - * quad(38, 31, 86, 20, 69, 63, 30, 76); - * describe('irregular white quadrilateral with black outline'); + * quad(20, 20, 80, 20, 80, 80, 20, 80); + * describe('A white square with a black outline drawn on a gray canvas.'); + * + *
      + * + *
      + * + * quad(20, 30, 80, 30, 80, 70, 20, 70); + * describe('A white rectangle with a black outline drawn on a gray canvas.'); + * + *
      + * + *
      + * + * quad(50, 62, 86, 50, 50, 38, 14, 50); + * describe('A white rhombus with a black outline drawn on a gray canvas.'); * *
      * + *
      + * + * quad(20, 50, 80, 30, 80, 70, 20, 70); + * describe('A white trapezoid with a black outline drawn on a gray canvas.'); + * + *
      */ /** * @method quad * @param {Number} x1 * @param {Number} y1 - * @param {Number} z1 the z-coordinate of the first point + * @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} 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} z3 the z-coordinate of the third point. * @param {Number} x4 * @param {Number} y4 - * @param {Number} z4 the z-coordinate of the fourth point + * @param {Number} z4 the z-coordinate of the fourth point. * @param {Integer} [detailX] * @param {Integer} [detailY] * @chainable @@ -65477,7 +69275,8 @@ this._renderer.quad.call(this._renderer, args[0], args[1], 0, args[2], args[3], 0, args[4], args[5], 0, args[6], args[7], 0, args[8], args[9]); } else { var _this$_renderer3; - (_this$_renderer3 = this._renderer).quad.apply(_this$_renderer3, args); //accessibile outputs + (_this$_renderer3 = this._renderer).quad.apply(_this$_renderer3, args); + //accessibile outputs if (this._accessibleOutputs.grid || this._accessibleOutputs.text) { this._accsOutput('quadrilateral', args); } @@ -65486,16 +69285,21 @@ return this; }; /** - * Draws a rectangle on the canvas. A rectangle is a four-sided closed shape with - * every angle at ninety degrees. By default, the first two parameters set - * the location of the upper-left corner, the third sets the width, and the - * fourth sets the height. The way these parameters are interpreted may be - * changed with the rectMode() function. + * Draws a rectangle to the canvas. A rectangle is a four-sided polygon with + * every angle at ninety degrees. By default, the first two parameters set the + * location of the rectangle's upper-left corner. The third and fourth set the + * shape's the width and height, respectively. The way these parameters are + * interpreted may be changed with the rectMode() + * function. * - * The fifth, sixth, seventh and eighth parameters, if specified, - * determine corner radius for the top-left, top-right, lower-right and - * lower-left corners, respectively. An omitted corner radius parameter is set - * to the value of the previously specified radius value in the parameter list. + * The version of `rect()` with five parameters creates a rounded rectangle. The + * fifth parameter is used as the radius value for all four corners. + * + * The version of `rect()` with eight parameters also creates a rounded rectangle. + * When using eight parameters, the latter four set the radius of the arc at + * each corner separately. The radii start with the top-left corner and move + * clockwise around the rectangle. If any of these parameters are omitted, they + * are set to the value of the last specified corner radius. * * @method rect * @param {Number} x x-coordinate of the rectangle. @@ -65510,28 +69314,24 @@ * @example *
      * - * // Draw a rectangle at location (30, 20) with a width and height of 55. * rect(30, 20, 55, 55); - * describe('white rect with black outline in mid-right of canvas'); + * describe('A white rectangle with a black outline on a gray canvas.'); * *
      * *
      * - * // Draw a rectangle with rounded corners, each having a radius of 20. * rect(30, 20, 55, 55, 20); * describe( - * 'white rect with black outline and round edges in mid-right of canvas' + * 'A white rectangle with a black outline and round edges on a gray canvas.' * ); * *
      * *
      * - * // Draw a rectangle with rounded corners having the following radii: - * // top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5. * rect(30, 20, 55, 55, 20, 15, 10, 5); - * describe('white rect with black outline and round edges of different radii'); + * describe('A white rectangle with a black outline and round edges of different radii.'); * *
      * @@ -65542,27 +69342,32 @@ * @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) + * @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); + for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + _main.default._validateParameters('rect', args); + return this._renderRect.apply(this, args); }; /** - * Draws a square to the screen. A square is a four-sided shape with every angle - * at ninety degrees, and equal side size. This function is a special case of the - * rect() function, where the width and height are the same, and the parameter - * is called "s" for side size. By default, the first two parameters set the - * location of the upper-left corner, the third sets the side size of the square. - * The way these parameters are interpreted, may be changed with the rectMode() function. + * Draws a square to the canvas. A square is a four-sided polygon with every + * angle at ninety degrees and equal side lengths. By default, the first two + * parameters set the location of the square's upper-left corner. The third + * parameter sets its side size. The way these parameters are interpreted may + * be changed with the rectMode() function. * - * The fourth, fifth, sixth and seventh parameters, if specified, - * determine corner radius for the top-left, top-right, lower-right and - * lower-left corners, respectively. An omitted corner radius parameter is set - * to the value of the previously specified radius value in the parameter list. + * The version of `square()` with four parameters creates a rounded square. The + * fourth parameter is used as the radius value for all four corners. + * + * The version of `square()` with seven parameters also creates a rounded square. + * When using seven parameters, the latter four set the radius of the arc at + * each corner separately. The radii start with the top-left corner and move + * clockwise around the square. If any of these parameters are omitted, they + * are set to the value of the last specified corner radius. * * @method square * @param {Number} x x-coordinate of the square. @@ -65576,36 +69381,34 @@ * @example *
      * - * // Draw a square at location (30, 20) with a side size of 55. * square(30, 20, 55); - * describe('white square with black outline in mid-right of canvas'); + * describe('A white square with a black outline in on a gray canvas.'); * *
      * *
      * - * // Draw a square with rounded corners, each having a radius of 20. * square(30, 20, 55, 20); * describe( - * 'white square with black outline and round edges in mid-right of canvas' + * 'A white square with a black outline and round edges on a gray canvas.' * ); * *
      * *
      * - * // Draw a square with rounded corners having the following radii: - * // top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5. * square(30, 20, 55, 20, 15, 10, 5); - * describe('white square with black outline and round edges of different radii'); + * describe('A white square with a black outline and round edges of different radii.'); * *
      * */ _main.default.prototype.square = function (x, y, s, tl, tr, br, bl) { - _main.default._validateParameters('square', arguments); // duplicate width for height in case of square + _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 + }; + // 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 @@ -65618,12 +69421,14 @@ vals.y, vals.w, vals.h - ]; // append the additional arguments (either cornder radii, or + ]; + // 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 + this._renderer.rect(args); + //accessible outputs if (this._accessibleOutputs.grid || this._accessibleOutputs.text) { this._accsOutput('rectangle', [ vals.x, @@ -65636,36 +69441,36 @@ 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. + * Draws a triangle to the canvas. A triangle is a three-sided polygon. The + * first two parameters specify the triangle's first point `(x1,y1)`. The middle + * two parameters specify its second point `(x2,y2)`. And the last two parameters + * specify its third point `(x3, y3)`. * * @method triangle - * @param {Number} x1 x-coordinate of the first point - * @param {Number} y1 y-coordinate of the first point - * @param {Number} x2 x-coordinate of the second point - * @param {Number} y2 y-coordinate of the second point - * @param {Number} x3 x-coordinate of the third point - * @param {Number} y3 y-coordinate of the third point + * @param {Number} x1 x-coordinate of the first point. + * @param {Number} y1 y-coordinate of the first point. + * @param {Number} x2 x-coordinate of the second point. + * @param {Number} y2 y-coordinate of the second point. + * @param {Number} x3 x-coordinate of the third point. + * @param {Number} y3 y-coordinate of the third point. * @chainable * @example *
      * * triangle(30, 75, 58, 20, 86, 75); - * describe('white triangle with black outline in mid-right of canvas'); + * describe('A white triangle with a black outline on a gray canvas.'); * *
      * */ _main.default.prototype.triangle = function () { - for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { - args[_key4] = arguments[_key4]; + for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + args[_key5] = arguments[_key5]; } _main.default._validateParameters('triangle', args); if (this._renderer._doStroke || this._renderer._doFill) { this._renderer.triangle(args); - } //accessible outputs + } //accessible outputs if (this._accessibleOutputs.grid || this._accessibleOutputs.text) { this._accsOutput('triangle', args); @@ -65676,25 +69481,27 @@ exports.default = _default; }, { - '../constants': 278, - '../friendly_errors/fes_core': 281, - '../friendly_errors/file_errors': 282, - '../friendly_errors/validate_params': 285, - '../helpers': 286, - '../main': 290, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + '../constants': 286, + '../friendly_errors/fes_core': 289, + '../friendly_errors/file_errors': 290, + '../friendly_errors/validate_params': 293, + '../helpers': 294, + '../main': 298, + 'core-js/modules/es.array.from': 176, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 298: [ + 306: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -65790,28 +69597,24 @@ * @requires constants */ /** - * Modifies the location from which ellipses are drawn by changing the way in - * which parameters given to ellipse(), - * circle() and arc() are interpreted. - * - * The default mode is `CENTER`, in which the first two parameters are interpreted - * as the shape's center point's x and y coordinates respectively, while the third - * and fourth parameters are its width and height. + * Modifies the location from which ellipses, circles, and arcs are drawn. By default, the + * first two parameters are the x- and y-coordinates of the shape's center. The next + * parameters are its width and height. This is equivalent to calling `ellipseMode(CENTER)`. * - * `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(RADIUS)` also uses the first two parameters to set the x- and y-coordinates + * of the shape's center. The next parameters are half of the shapes's width and height. + * Calling `ellipse(0, 0, 10, 15)` draws a shape with a width of 20 and height of 30. * - * `ellipseMode(CORNER)` 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(CORNER)` uses the first two parameters as the upper-left corner of the + * shape. The next 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. + * `ellipseMode(CORNERS)` uses the first two parameters as the location of one corner + * of the ellipse's bounding box. The third and fourth parameters are 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. + * The argument passed to `ellipseMode()` must be written in ALL CAPS because the constants + * `CENTER`, `RADIUS`, `CORNER`, and `CORNERS` are defined this way. JavaScript is a + * case-sensitive language. * * @method ellipseMode * @param {Constant} mode either CENTER, RADIUS, CORNER, or CORNERS @@ -65819,31 +69622,27 @@ * @example *
      * - * // Example showing RADIUS and CENTER ellipsemode with 2 overlaying ellipses * ellipseMode(RADIUS); * fill(255); - * ellipse(50, 50, 30, 30); // Outer white ellipse + * ellipse(50, 50, 30, 30); * ellipseMode(CENTER); * fill(100); - * ellipse(50, 50, 30, 30); // Inner gray ellipse + * ellipse(50, 50, 30, 30); + * describe('A white circle with a gray circle at its center. Both circles have black outlines.'); * *
      * *
      * - * // Example showing CORNER and CORNERS ellipseMode with 2 overlaying ellipses * ellipseMode(CORNER); * fill(255); - * ellipse(25, 25, 50, 50); // Outer white ellipse + * ellipse(25, 25, 50, 50); * ellipseMode(CORNERS); * fill(100); - * ellipse(25, 25, 50, 50); // Inner gray ellipse + * ellipse(25, 25, 50, 50); + * describe('A white circle with a gray circle at its top-left corner. Both circles have black outlines.'); * *
      - * - * @alt - * 60×60 white ellipse and 30×30 grey ellipse with black outlines at center. - * 60×60 white ellipse and 30×30 grey ellipse top-right with black outlines. */ _main.default.prototype.ellipseMode = function (m) { @@ -65856,13 +69655,11 @@ /** * Draws all geometry with jagged (aliased) edges. * - * Note that smooth() is active by default in 2D mode, so it is - * necessary to call noSmooth() to disable smoothing of geometry, - * images, and fonts. + * smooth() is active by default in 2D mode. It's necessary to call + * noSmooth() to disable smoothing of geometry, images, and fonts. * - * In 3D mode, noSmooth() is enabled by default, so it is necessary - * to call smooth() if you would like smooth (antialiased) edges on your - * geometry. + * In WebGL mode, noSmooth() is active by default. It's necessary + * to call smooth() to draw smooth (antialiased) edges. * * @method noSmooth * @chainable @@ -65875,11 +69672,9 @@ * ellipse(30, 48, 36, 36); * noSmooth(); * ellipse(70, 48, 36, 36); + * describe('Two pixelated white circles on a black background.'); * * - * - * @alt - * 2 pixelated 36×36 white ellipses to left & right of center, black background */ _main.default.prototype.noSmooth = function () { if (!this._renderer.isP3D) { @@ -65892,28 +69687,25 @@ return this; }; /** - * Modifies the location from which rectangles are drawn by changing the way - * in which parameters given to rect() are interpreted. - * - * The default mode is `CORNER`, which interprets the first two parameters as the - * upper-left corner of the shape, while the third and fourth parameters are its - * width and height. + * Modifies the location from which rectangles and squares are drawn. By default, + * the first two parameters are the x- and y-coordinates of the shape's upper-left + * corner. The next parameters are its width and height. This is equivalent to + * calling `rectMode(CORNER)`. * - * `rectMode(CORNERS)` interprets the first two parameters as the location of - * one of the corners, and the third and fourth parameters as the location of - * the diagonally opposite corner. Note, the rectangle is drawn between the - * coordinates, so it is not necessary that the first corner be the upper left + * `rectMode(CORNERS)` also uses the first two parameters as the location of one of + * the corners. The third and fourth parameters are the location of the opposite * 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(CENTER)` uses the first two parameters as the x- and y-coordinates of + * the shape's center. The next parameters are its width and height. * - * `rectMode(RADIUS)` also uses the first two parameters as the shape's center - * point, but uses the third and fourth parameters to specify half of the shape's - * width and height respectively. + * `rectMode(RADIUS)` also uses the first two parameters as the x- and y-coordinates + * of the shape's center. The next parameters are half of the shape's width and + * height. * - * The 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. + * The argument passed to `rectMode()` must be written in ALL CAPS because the + * constants `CENTER`, `RADIUS`, `CORNER`, and `CORNERS` are defined this way. + * JavaScript is a case-sensitive language. * * @method rectMode * @param {Constant} mode either CORNER, CORNERS, CENTER, or RADIUS @@ -65923,11 +69715,13 @@ * * rectMode(CORNER); * fill(255); - * rect(25, 25, 50, 50); // Draw white rectangle using CORNER mode + * rect(25, 25, 50, 50); * * rectMode(CORNERS); * fill(100); - * rect(25, 25, 50, 50); // Draw gray rectangle using CORNERS mode + * rect(25, 25, 50, 50); + * + * describe('A small gray square drawn at the top-left corner of a white square.'); * * * @@ -65935,17 +69729,15 @@ * * rectMode(RADIUS); * fill(255); - * rect(50, 50, 30, 30); // Draw white rectangle using RADIUS mode + * rect(50, 50, 30, 30); * * rectMode(CENTER); * fill(100); - * rect(50, 50, 30, 30); // Draw gray rectangle using CENTER mode + * rect(50, 50, 30, 30); + * + * describe('A small gray square drawn at the center of a white square.'); * * - * - * @alt - * 50×50 white rect at center and 25×25 grey rect in the top left of the other. - * 50×50 white rect at center and 25×25 grey rect in the center of the other. */ _main.default.prototype.rectMode = function (m) { _main.default._validateParameters('rectMode', arguments); @@ -65958,13 +69750,11 @@ * Draws all geometry with smooth (anti-aliased) edges. smooth() will also * improve image quality of resized images. * - * Note that smooth() is active by default in 2D mode; - * noSmooth() can be used to disable smoothing of geometry, - * images, and fonts. + * smooth() is active by default in 2D mode. It's necessary to call + * noSmooth() to disable smoothing of geometry, images, and fonts. * - * In 3D mode, noSmooth() is enabled by default, so it is - * necessary to call smooth() if you would like smooth (antialiased) - * edges on your geometry. + * In WebGL mode, noSmooth() is active by default. It's necessary + * to call smooth() to draw smooth (antialiased) edges. * * @method smooth * @chainable @@ -65977,11 +69767,9 @@ * ellipse(30, 48, 36, 36); * noSmooth(); * ellipse(70, 48, 36, 36); + * describe('Two pixelated white circles on a black background.'); * * - * - * @alt - * 2 pixelated 36×36 white ellipses one left one right of center. On black. */ _main.default.prototype.smooth = function () { this.setAttributes('antialias', true); @@ -65993,12 +69781,13 @@ return this; }; /** - * Sets the style for rendering line endings. These ends are either rounded, - * squared, or extended, each of which specified with the corresponding - * parameters: `ROUND`, `SQUARE`, or `PROJECT`. The default cap is `ROUND`. + * Sets the style for rendering line endings. These ends are either rounded + * (`ROUND`), squared (`SQUARE`), or extended (`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. + * The argument passed to `strokeCap()` must be written in ALL CAPS because + * the constants `ROUND`, `SQUARE`, and `PROJECT` are defined this way. + * JavaScript is a case-sensitive language. * * @method strokeCap * @param {Constant} cap either ROUND, SQUARE, or PROJECT @@ -66006,7 +69795,6 @@ * @example *
      * - * // Example of different strokeCaps * strokeWeight(12.0); * strokeCap(ROUND); * line(20, 30, 80, 30); @@ -66014,11 +69802,9 @@ * line(20, 50, 80, 50); * strokeCap(PROJECT); * line(20, 70, 80, 70); + * describe('Three horizontal lines. The top line has rounded ends, the middle line has squared ends, and the bottom line has longer, squared ends.'); * *
      - * - * @alt - * 3 lines. Top line: rounded ends, mid: squared, bottom:longer squared ends. */ _main.default.prototype.strokeCap = function (cap) { _main.default._validateParameters('strokeCap', arguments); @@ -66028,13 +69814,13 @@ return this; }; /** - * Sets the style of the joints which connect line segments. These joints - * are either mitered, beveled, or rounded and specified with the - * corresponding parameters: `MITER`, `BEVEL`, or `ROUND`. The default joint is - * `MITER` in 2D mode and `ROUND` in WebGL mode. + * Sets the style of the joints which connect line segments. These joints are + * either mitered (`MITER`), beveled (`BEVEL`), or rounded (`ROUND`). The default + * joint is `MITER` in 2D mode and `ROUND` in WebGL mode. * - * The parameter to this method must be written in ALL CAPS because they are - * predefined as constants in ALL CAPS and Javascript is a case-sensitive language. + * The argument passed to `strokeJoin()` must be written in ALL CAPS because + * the constants `MITER`, `BEVEL`, and `ROUND` are defined this way. + * JavaScript is a case-sensitive language. * * @method strokeJoin * @param {Constant} join either MITER, BEVEL, or ROUND @@ -66042,7 +69828,6 @@ * @example *
      * - * // Example of MITER type of joints * noFill(); * strokeWeight(10.0); * strokeJoin(MITER); @@ -66051,12 +69836,12 @@ * vertex(65, 50); * vertex(35, 80); * endShape(); + * describe('A right-facing arrowhead shape with a pointed tip in center of canvas.'); * *
      * *
      * - * // Example of BEVEL type of joints * noFill(); * strokeWeight(10.0); * strokeJoin(BEVEL); @@ -66065,12 +69850,12 @@ * vertex(65, 50); * vertex(35, 80); * endShape(); + * describe('A right-facing arrowhead shape with a flat tip in center of canvas.'); * *
      * *
      * - * // Example of ROUND type of joints * noFill(); * strokeWeight(10.0); * strokeJoin(ROUND); @@ -66079,13 +69864,9 @@ * vertex(65, 50); * vertex(35, 80); * endShape(); + * describe('A right-facing arrowhead shape with a rounded tip in center of canvas.'); * *
      - * - * @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); @@ -66098,40 +69879,38 @@ * Sets the width of the stroke used for lines, points, and the border around * shapes. All widths are set in units of pixels. * - * Note that it is affected by any transformation or scaling that has - * been applied previously. + * Note that `strokeWeight()` is affected by any transformation or scaling that + * has been applied previously. * * @method strokeWeight - * @param {Number} weight the weight of the stroke (in pixels) + * @param {Number} weight the weight of the stroke (in pixels). * @chainable * @example *
      * - * // Example of different stroke weights - * strokeWeight(1); // Default + * // Default. * line(20, 20, 80, 20); - * strokeWeight(4); // Thicker + * // Thicker. + * strokeWeight(4); * line(20, 40, 80, 40); - * strokeWeight(10); // Beastly + * // Beastly. + * strokeWeight(10); * line(20, 70, 80, 70); + * describe('Three horizontal black lines. The top line is thin, the middle is medium, and the bottom is thick.'); * *
      * *
      * - * //Example of stroke weights - * //after transformations - * strokeWeight(1); // Default + * // Default. * line(20, 20, 80, 20); - * scale(5); // Adding scale transformation - * strokeWeight(1); // Resulting strokeweight is 5 - * line(4, 8, 16, 8); // Coordinates adjusted for scaling + * // Adding scale transformation. + * scale(5); + * // Coordinates adjusted for scaling. + * line(4, 8, 16, 8); + * describe('Two horizontal black lines. The top line is thin and the bottom is five times thicker than the top.'); * *
      - * - * @alt - * 3 horizontal black lines. Top line: thin, mid: medium, bottom:thick. - * 2 horizontal black line. Top line: thin, botton line: 5 times thicker than top */ _main.default.prototype.strokeWeight = function (w) { _main.default._validateParameters('strokeWeight', arguments); @@ -66142,20 +69921,20 @@ exports.default = _default; }, { - '../constants': 278, - '../main': 290, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + '../constants': 286, + '../main': 298, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 299: [ + 307: [ function (_dereq_, module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { @@ -66247,7 +70026,8 @@ 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 + _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; @@ -66686,13 +70466,13 @@ exports.default = _default; }, { - '../friendly_errors/fes_core': 281, - '../friendly_errors/file_errors': 282, - '../friendly_errors/validate_params': 285, - '../main': 290 + '../friendly_errors/fes_core': 289, + '../friendly_errors/file_errors': 290, + '../friendly_errors/validate_params': 293, + '../main': 298 } ], - 300: [ + 308: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -66842,9 +70622,13 @@ * white rect and smaller grey rect with red outlines in center of canvas. */ _main.default.prototype.beginContour = function () { - contourVertices = [ - ]; - isContour = true; + if (this._renderer.isP3D) { + this._renderer.beginContour(); + } else { + contourVertices = [ + ]; + isContour = true; + } return this; }; /** @@ -67341,10 +71125,14 @@ * white rect and smaller grey rect with red outlines in center of canvas. */ _main.default.prototype.endContour = function () { + if (this._renderer.isP3D) { + return this; + } var vert = contourVertices[0].slice(); // copy all data vert.isVert = contourVertices[0].isVert; vert.moveTo = false; - contourVertices.push(vert); // prevent stray lines with multiple contours + contourVertices.push(vert); + // prevent stray lines with multiple contours if (isFirstContour) { vertices.push(vertices[0]); isFirstContour = false; @@ -67358,11 +71146,19 @@ * The endShape() function is the companion to beginShape() and may only be * called after beginShape(). When endShape() is called, all of the image * data defined since the previous call to beginShape() is written into the image - * buffer. The constant CLOSE as the value for the `mode` parameter to close + * buffer. The constant CLOSE is the value for the `mode` parameter to close * the shape (to connect the beginning and the end). + * When using instancing with endShape() the instancing will not apply to the strokes. + * When the count parameter is used with a value greater than 1, it enables instancing for shapes built when in WEBGL mode. Instancing + * is a feature that allows the GPU to efficiently draw multiples of the same shape. It's often used for particle effects or other + * times when you need a lot of repetition. In order to take advantage of instancing, you will also need to write your own custom + * shader using the gl_InstanceID keyword. You can read more about instancing + * here or by working from the example on this + * page. * * @method endShape * @param {Constant} [mode] use CLOSE to close the shape + * @param {Integer} [count] number of times you want to draw/instance the shape (for WebGL mode). * @chainable * @example *
      @@ -67383,30 +71179,120 @@ * *
      * + * @example + *
      + * + * let fx; + * let vs = `#version 300 es + * + * precision mediump float; + * + * in vec3 aPosition; + * flat out int instanceID; + * + * uniform mat4 uModelViewMatrix; + * uniform mat4 uProjectionMatrix; + * + * void main() { + * + * // copy the instance ID to the fragment shader + * instanceID = gl_InstanceID; + * vec4 positionVec4 = vec4(aPosition, 1.0); + * + * // gl_InstanceID represents a numeric value for each instance + * // using gl_InstanceID allows us to move each instance separately + * // here we move each instance horizontally by id * 40 + * float xOffset = float(gl_InstanceID) * 40.0; + * + * // apply the offset to the final position + * gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4 - + * vec4(xOffset, 0.0, 0.0, 0.0); + * } + * `; + * let fs = `#version 300 es + * + * precision mediump float; + * + * out vec4 outColor; + * flat in int instanceID; + * uniform float numInstances; + * + * void main() { + * vec4 red = vec4(1.0, 0.0, 0.0, 1.0); + * vec4 blue = vec4(0.0, 0.0, 1.0, 1.0); + * + * // Normalize the instance id + * float normId = float(instanceID) / numInstances; + * + * // Mix between two colors using the normalized instance id + * outColor = mix(red, blue, normId); + * } + * `; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * fx = createShader(vs, fs); + * } + * + * function draw() { + * background(220); + * + * // strokes aren't instanced, and are rather used for debug purposes + * shader(fx); + * fx.setUniform('numInstances', 4); + * + * // this doesn't have to do with instancing, this is just for centering the squares + * translate(25, -10); + * + * // here we draw the squares we want to instance + * beginShape(); + * vertex(0, 0); + * vertex(0, 20); + * vertex(20, 20); + * vertex(20, 0); + * vertex(0, 0); + * endShape(CLOSE, 4); + * + * resetShader(); + * } + * + *
      + * * @alt * Triangle line shape with smallest interior angle on bottom and upside-down L. */ _main.default.prototype.endShape = function (mode) { + var count = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; _main.default._validateParameters('endShape', arguments); + if (count < 1) { + console.log('🌸 p5.js says: You can not have less than one instance'); + count = 1; + } if (this._renderer.isP3D) { - this._renderer.endShape(mode, isCurve, isBezier, isQuadratic, isContour, shapeKind); + this._renderer.endShape(mode, isCurve, isBezier, isQuadratic, isContour, shapeKind, count); } else { + if (count !== 1) { + console.log('🌸 p5.js says: Instancing is only supported in WebGL2 mode'); + } if (vertices.length === 0) { return this; } if (!this._renderer._doStroke && !this._renderer._doFill) { return this; } - var closeShape = mode === constants.CLOSE; // if the shape is closed, the first element is also the last element + 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 + 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. + 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) { @@ -67804,32 +71690,34 @@ exports.default = _default; }, { - '../constants': 278, - '../main': 290, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + '../constants': 286, + '../main': 298, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 301: [ + 309: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); _dereq_('core-js/modules/es.symbol.description'); _dereq_('core-js/modules/es.symbol.iterator'); _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.from'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.slice'); _dereq_('core-js/modules/es.object.assign'); _dereq_('core-js/modules/es.object.keys'); _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.to-string'); _dereq_('core-js/modules/es.string.iterator'); _dereq_('core-js/modules/es.typed-array.uint8-clamped-array'); _dereq_('core-js/modules/es.typed-array.copy-within'); @@ -67903,6 +71791,23 @@ _dereq_('core-js/modules/es.typed-array.to-locale-string'); _dereq_('core-js/modules/es.typed-array.to-string'); _dereq_('core-js/modules/web.dom-collections.iterator'); + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + function _nonIterableSpread() { + throw new TypeError('Invalid attempt to spread non-iterable instance'); + } + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === '[object Arguments]') return Array.from(iter); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + return arr2; + } + } function _typeof(obj) { if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { _typeof = function _typeof(obj) { @@ -67914,7 +71819,7 @@ }; } return _typeof(obj); - } // requestAnim shim layer by Paul Irish + } // 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 @@ -67965,7 +71870,8 @@ return function isEnumerable(prop) { return propIsEnumerable.call(obj, prop); }; - }; // per ES6 spec, this function has to have a length of 2 + }; + // 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'); @@ -67979,7 +71885,8 @@ source = Object(arguments[s]); props = keys(source); if (hasSymbols && Object.getOwnPropertySymbols) { - props.push.apply(props, Object.getOwnPropertySymbols(source).filter(isEnumerableOn(source))); + var _props; + (_props = props).push.apply(_props, _toConsumableArray(Object.getOwnPropertySymbols(source).filter(isEnumerableOn(source)))); } for (i = 0; i < props.length; ++i) { objTarget[props[i]] = source[props[i]]; @@ -67997,52 +71904,50 @@ }) (); }, { - 'core-js/modules/es.array.filter': 171, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.object.assign': 190, - 'core-js/modules/es.object.keys': 194, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.typed-array.copy-within': 215, - 'core-js/modules/es.typed-array.every': 216, - 'core-js/modules/es.typed-array.fill': 217, - 'core-js/modules/es.typed-array.filter': 218, - 'core-js/modules/es.typed-array.find': 220, - 'core-js/modules/es.typed-array.find-index': 219, - 'core-js/modules/es.typed-array.for-each': 223, - 'core-js/modules/es.typed-array.includes': 224, - 'core-js/modules/es.typed-array.index-of': 225, - 'core-js/modules/es.typed-array.iterator': 228, - 'core-js/modules/es.typed-array.join': 229, - 'core-js/modules/es.typed-array.last-index-of': 230, - 'core-js/modules/es.typed-array.map': 231, - 'core-js/modules/es.typed-array.reduce': 233, - 'core-js/modules/es.typed-array.reduce-right': 232, - 'core-js/modules/es.typed-array.reverse': 234, - 'core-js/modules/es.typed-array.set': 235, - 'core-js/modules/es.typed-array.slice': 236, - 'core-js/modules/es.typed-array.some': 237, - 'core-js/modules/es.typed-array.sort': 238, - 'core-js/modules/es.typed-array.subarray': 239, - 'core-js/modules/es.typed-array.to-locale-string': 240, - 'core-js/modules/es.typed-array.to-string': 241, - 'core-js/modules/es.typed-array.uint8-clamped-array': 245, - 'core-js/modules/web.dom-collections.iterator': 248 + 'core-js/modules/es.array.filter': 173, + 'core-js/modules/es.array.from': 176, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.object.assign': 194, + 'core-js/modules/es.object.keys': 199, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.typed-array.copy-within': 223, + 'core-js/modules/es.typed-array.every': 224, + 'core-js/modules/es.typed-array.fill': 225, + 'core-js/modules/es.typed-array.filter': 226, + 'core-js/modules/es.typed-array.find': 228, + 'core-js/modules/es.typed-array.find-index': 227, + 'core-js/modules/es.typed-array.for-each': 231, + 'core-js/modules/es.typed-array.includes': 232, + 'core-js/modules/es.typed-array.index-of': 233, + 'core-js/modules/es.typed-array.iterator': 236, + 'core-js/modules/es.typed-array.join': 237, + 'core-js/modules/es.typed-array.last-index-of': 238, + 'core-js/modules/es.typed-array.map': 239, + 'core-js/modules/es.typed-array.reduce': 241, + 'core-js/modules/es.typed-array.reduce-right': 240, + 'core-js/modules/es.typed-array.reverse': 242, + 'core-js/modules/es.typed-array.set': 243, + 'core-js/modules/es.typed-array.slice': 244, + 'core-js/modules/es.typed-array.some': 245, + 'core-js/modules/es.typed-array.sort': 246, + 'core-js/modules/es.typed-array.subarray': 247, + 'core-js/modules/es.typed-array.to-locale-string': 248, + 'core-js/modules/es.typed-array.to-string': 249, + 'core-js/modules/es.typed-array.uint8-clamped-array': 253, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 302: [ + 310: [ function (_dereq_, module, exports) { 'use strict'; - _dereq_('core-js/modules/es.array.for-each'); _dereq_('core-js/modules/es.object.assign'); - _dereq_('core-js/modules/web.dom-collections.for-each'); - _dereq_('core-js/modules/es.array.for-each'); _dereq_('core-js/modules/es.object.assign'); - _dereq_('core-js/modules/web.dom-collections.for-each'); Object.defineProperty(exports, '__esModule', { value: true }); @@ -68517,9 +72422,6 @@ 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) { @@ -68529,14 +72431,14 @@ context._renderer._update(); } context._setProperty('frameCount', context.frameCount + 1); - context._registeredMethods.pre.forEach(callMethod); + this.callRegisteredHooksFor('pre'); this._inUserDraw = true; try { context.draw(); } finally { this._inUserDraw = false; } - context._registeredMethods.post.forEach(callMethod); + this.callRegisteredHooksFor('post'); } } }; @@ -68594,13 +72496,11 @@ exports.default = _default; }, { - './main': 290, - 'core-js/modules/es.array.for-each': 172, - 'core-js/modules/es.object.assign': 190, - 'core-js/modules/web.dom-collections.for-each': 247 + './main': 298, + 'core-js/modules/es.object.assign': 194 } ], - 303: [ + 311: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -68637,15 +72537,9 @@ _dereq_('core-js/modules/es.typed-array.to-locale-string'); _dereq_('core-js/modules/es.typed-array.to-string'); _dereq_('core-js/modules/web.dom-collections.iterator'); - _dereq_('core-js/modules/es.symbol'); - _dereq_('core-js/modules/es.symbol.description'); - _dereq_('core-js/modules/es.symbol.iterator'); - _dereq_('core-js/modules/es.array.from'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.object.get-prototype-of'); _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.regexp.to-string'); - _dereq_('core-js/modules/es.string.iterator'); _dereq_('core-js/modules/es.typed-array.uint8-array'); _dereq_('core-js/modules/es.typed-array.copy-within'); _dereq_('core-js/modules/es.typed-array.every'); @@ -68670,7 +72564,6 @@ _dereq_('core-js/modules/es.typed-array.subarray'); _dereq_('core-js/modules/es.typed-array.to-locale-string'); _dereq_('core-js/modules/es.typed-array.to-string'); - _dereq_('core-js/modules/web.dom-collections.iterator'); Object.defineProperty(exports, '__esModule', { value: true }); @@ -68698,7 +72591,14 @@ } return arr2; } - } /** + } /** + * @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 @@ -68718,7 +72618,7 @@ * alt="The transformation matrix used when applyMatrix is called with 4x4 matrix"/> * * @method applyMatrix - * @param {Array} arr an array of numbers - should be 6 or 16 length (2*3 or 4*4 matrix values) + * @param {Array} arr an array of numbers - should be 6 or 16 length (2×3 or 4×4 matrix values) * @chainable * @example *
      @@ -68846,12 +72746,12 @@ */ /** * @method applyMatrix - * @param {Number} a numbers which define the 2×3 or 4x4 matrix to be multiplied - * @param {Number} b numbers which define the 2×3 or 4x4 matrix to be multiplied - * @param {Number} c numbers which define the 2×3 or 4x4 matrix to be multiplied - * @param {Number} d numbers which define the 2×3 or 4x4 matrix to be multiplied - * @param {Number} e numbers which define the 2×3 or 4x4 matrix to be multiplied - * @param {Number} f numbers which define the 2×3 or 4x4 matrix to be multiplied + * @param {Number} a numbers which define the 2×3 or 4×4 matrix to be multiplied + * @param {Number} b numbers which define the 2×3 or 4×4 matrix to be multiplied + * @param {Number} c numbers which define the 2×3 or 4×4 matrix to be multiplied + * @param {Number} d numbers which define the 2×3 or 4×4 matrix to be multiplied + * @param {Number} e numbers which define the 2×3 or 4×4 matrix to be multiplied + * @param {Number} f numbers which define the 2×3 or 4×4 matrix to be multiplied * @chainable */ /** @@ -68862,24 +72762,24 @@ * @param {Number} d * @param {Number} e * @param {Number} f - * @param {Number} g numbers which define the 4x4 matrix to be multiplied - * @param {Number} h numbers which define the 4x4 matrix to be multiplied - * @param {Number} i numbers which define the 4x4 matrix to be multiplied - * @param {Number} j numbers which define the 4x4 matrix to be multiplied - * @param {Number} k numbers which define the 4x4 matrix to be multiplied - * @param {Number} l numbers which define the 4x4 matrix to be multiplied - * @param {Number} m numbers which define the 4x4 matrix to be multiplied - * @param {Number} n numbers which define the 4x4 matrix to be multiplied - * @param {Number} o numbers which define the 4x4 matrix to be multiplied - * @param {Number} p numbers which define the 4x4 matrix to be multiplied + * @param {Number} g numbers which define the 4×4 matrix to be multiplied + * @param {Number} h numbers which define the 4×4 matrix to be multiplied + * @param {Number} i numbers which define the 4×4 matrix to be multiplied + * @param {Number} j numbers which define the 4×4 matrix to be multiplied + * @param {Number} k numbers which define the 4×4 matrix to be multiplied + * @param {Number} l numbers which define the 4×4 matrix to be multiplied + * @param {Number} m numbers which define the 4×4 matrix to be multiplied + * @param {Number} n numbers which define the 4×4 matrix to be multiplied + * @param {Number} o numbers which define the 4×4 matrix to be multiplied + * @param {Number} p numbers which define the 4×4 matrix to be multiplied * @chainable */ _main.default.prototype.applyMatrix = function () { - var isTypedArray = arguments[0] instanceof Object.getPrototypeOf(Uint8Array); - if (Array.isArray(arguments[0]) || isTypedArray) { + var isTypedArray = (arguments.length <= 0 ? undefined : arguments[0]) instanceof Object.getPrototypeOf(Uint8Array); + if (Array.isArray(arguments.length <= 0 ? undefined : arguments[0]) || isTypedArray) { var _this$_renderer; - (_this$_renderer = this._renderer).applyMatrix.apply(_this$_renderer, _toConsumableArray(arguments[0])); + (_this$_renderer = this._renderer).applyMatrix.apply(_this$_renderer, _toConsumableArray(arguments.length <= 0 ? undefined : arguments[0])); } else { var _this$_renderer2; (_this$_renderer2 = this._renderer).applyMatrix.apply(_this$_renderer2, arguments); @@ -69105,7 +73005,8 @@ * @chainable */ _main.default.prototype.scale = function (x, y, z) { - _main.default._validateParameters('scale', arguments); // Only check for Vector argument type if Vector is available + _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; @@ -69272,44 +73173,44 @@ exports.default = _default; }, { - './main': 290, - 'core-js/modules/es.array.from': 173, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.object.get-prototype-of': 193, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.to-string': 200, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.typed-array.copy-within': 215, - 'core-js/modules/es.typed-array.every': 216, - 'core-js/modules/es.typed-array.fill': 217, - 'core-js/modules/es.typed-array.filter': 218, - 'core-js/modules/es.typed-array.find': 220, - 'core-js/modules/es.typed-array.find-index': 219, - 'core-js/modules/es.typed-array.for-each': 223, - 'core-js/modules/es.typed-array.includes': 224, - 'core-js/modules/es.typed-array.index-of': 225, - 'core-js/modules/es.typed-array.iterator': 228, - 'core-js/modules/es.typed-array.join': 229, - 'core-js/modules/es.typed-array.last-index-of': 230, - 'core-js/modules/es.typed-array.map': 231, - 'core-js/modules/es.typed-array.reduce': 233, - 'core-js/modules/es.typed-array.reduce-right': 232, - 'core-js/modules/es.typed-array.reverse': 234, - 'core-js/modules/es.typed-array.set': 235, - 'core-js/modules/es.typed-array.slice': 236, - 'core-js/modules/es.typed-array.some': 237, - 'core-js/modules/es.typed-array.sort': 238, - 'core-js/modules/es.typed-array.subarray': 239, - 'core-js/modules/es.typed-array.to-locale-string': 240, - 'core-js/modules/es.typed-array.to-string': 241, - 'core-js/modules/es.typed-array.uint8-array': 244, - 'core-js/modules/web.dom-collections.iterator': 248 + './main': 298, + 'core-js/modules/es.array.from': 176, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.object.get-prototype-of': 198, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.typed-array.copy-within': 223, + 'core-js/modules/es.typed-array.every': 224, + 'core-js/modules/es.typed-array.fill': 225, + 'core-js/modules/es.typed-array.filter': 226, + 'core-js/modules/es.typed-array.find': 228, + 'core-js/modules/es.typed-array.find-index': 227, + 'core-js/modules/es.typed-array.for-each': 231, + 'core-js/modules/es.typed-array.includes': 232, + 'core-js/modules/es.typed-array.index-of': 233, + 'core-js/modules/es.typed-array.iterator': 236, + 'core-js/modules/es.typed-array.join': 237, + 'core-js/modules/es.typed-array.last-index-of': 238, + 'core-js/modules/es.typed-array.map': 239, + 'core-js/modules/es.typed-array.reduce': 241, + 'core-js/modules/es.typed-array.reduce-right': 240, + 'core-js/modules/es.typed-array.reverse': 242, + 'core-js/modules/es.typed-array.set': 243, + 'core-js/modules/es.typed-array.slice': 244, + 'core-js/modules/es.typed-array.some': 245, + 'core-js/modules/es.typed-array.sort': 246, + 'core-js/modules/es.typed-array.subarray': 247, + 'core-js/modules/es.typed-array.to-locale-string': 248, + 'core-js/modules/es.typed-array.to-string': 249, + 'core-js/modules/es.typed-array.uint8-array': 252, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 304: [ + 312: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -69337,7 +73238,6 @@ _dereq_('core-js/modules/es.symbol'); _dereq_('core-js/modules/es.symbol.description'); _dereq_('core-js/modules/es.symbol.iterator'); - _dereq_('core-js/modules/es.array.from'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.object.to-string'); _dereq_('core-js/modules/es.regexp.to-string'); @@ -69379,7 +73279,14 @@ }; } return _typeof(obj); - } /** + } /** + * @module Data + * @submodule LocalStorage + * @requires core + * + * This module defines the p5 methods for working with local storage + */ + /** * * Stores a value in local storage under the key name. * Local storage is saved in the browser and persists @@ -69593,28 +73500,60 @@ }; }, { - '../core/main': 290, - 'core-js/modules/es.array.from': 173, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.to-string': 200, - 'core-js/modules/es.string.ends-with': 202, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/web.dom-collections.iterator': 248 + '../core/main': 298, + 'core-js/modules/es.array.from': 176, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.ends-with': 208, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 305: [ + 313: [ function (_dereq_, module, exports) { 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.get-prototype-of'); _dereq_('core-js/modules/es.object.keys'); - _dereq_('core-js/modules/es.string.sub'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.reflect.construct'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } _dereq_('core-js/modules/es.array.concat'); _dereq_('core-js/modules/es.object.keys'); - _dereq_('core-js/modules/es.string.sub'); Object.defineProperty(exports, '__esModule', { value: true }); @@ -69625,16 +73564,99 @@ 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. - */ + } + function _inherits(subClass, superClass) { + if (typeof superClass !== 'function' && superClass !== null) { + throw new TypeError('Super expression must either be null or a function'); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + if (superClass) _setPrototypeOf(subClass, superClass); + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + return _setPrototypeOf(o, p); + } + function _createSuper(Derived) { + function isNativeReflectConstruct() { + if (typeof Reflect === 'undefined' || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === 'function') return true; + try { + Date.prototype.toString.call(Reflect.construct(Date, [ + ], function () { + })); + return true; + } catch (e) { + return false; + } + } + return function () { + var Super = _getPrototypeOf(Derived), + result; + if (isNativeReflectConstruct()) { + var NewTarget = _getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return _possibleConstructorReturn(this, result); + }; + } + function _possibleConstructorReturn(self, call) { + if (call && (_typeof(call) === 'object' || typeof call === 'function')) { + return call; + } + return _assertThisInitialized(self); + } + function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called'); + } + return self; + } + function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } /** + * @module Data + * @submodule Dictionary + * @for p5.TypedDict + * @requires core + * + * This module defines the p5 methods for the p5 Dictionary classes. + * The classes StringDict and NumberDict are for storing and working + * with key-value pairs. + */ /** * * Creates a new instance of p5.StringDict using the key-value pair @@ -69708,544 +73730,649 @@ * @class p5.TypedDict * @constructor */ - _main.default.TypedDict = function (key, value) { - if (key instanceof Object) { - this.data = key; - } else { - this.data = { - }; - this.data[key] = value; - } - return this; - }; - /** - * Returns the number of key-value pairs currently stored in the Dictionary. - * - * @method size - * @return {Integer} the number of key-value pairs in the Dictionary - * - * @example - *
      - * - * function setup() { - * let myDictionary = createNumberDict(1, 10); - * myDictionary.create(2, 20); - * myDictionary.create(3, 30); - * print(myDictionary.size()); // logs 3 to the console - * } - *
      - */ - _main.default.TypedDict.prototype.size = function () { - return Object.keys(this.data).length; - }; - /** - * Returns true if the given key exists in the Dictionary, - * otherwise returns false. - * - * @method hasKey - * @param {Number|String} key that you want to look up - * @return {Boolean} whether that key exists in Dictionary - * - * @example - *
      - * - * function setup() { - * let myDictionary = createStringDict('p5', 'js'); - * print(myDictionary.hasKey('p5')); // logs true to console - * } - *
      - */ - _main.default.TypedDict.prototype.hasKey = function (key) { - return this.data.hasOwnProperty(key); - }; - /** - * Returns the value stored at the given key. - * - * @method get - * @param {Number|String} the key you want to access - * @return {Number|String} the value stored at that key - * - * @example - *
      - * - * function setup() { - * let myDictionary = createStringDict('p5', 'js'); - * let myValue = myDictionary.get('p5'); - * print(myValue === 'js'); // logs true to console - * } - *
      - */ - _main.default.TypedDict.prototype.get = function (key) { - if (this.data.hasOwnProperty(key)) { - return this.data[key]; - } else { - console.log(''.concat(key, ' does not exist in this Dictionary')); - } - }; - /** - * Updates the value associated with the given key in case it already exists - * in the Dictionary. Otherwise a new key-value pair is added. - * - * @method set - * @param {Number|String} key - * @param {Number|String} value - * - * @example - *
      - * - * function setup() { - * let myDictionary = createStringDict('p5', 'js'); - * myDictionary.set('p5', 'JS'); - * myDictionary.print(); // logs "key: p5 - value: JS" to console - * } - *
      - */ - _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 - *
      - * - * function setup() { - * let myDictionary = createStringDict('p5', 'js'); - * myDictionary.create('happy', 'coding'); - * myDictionary.print(); - * // above logs "key: p5 - value: js, key: happy - value: coding" to console - * } - *
      - */ - /** - * @method create - * @param {Object} obj key/value pair - */ - _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 - *
      - * - * function setup() { - * let myDictionary = createStringDict('p5', 'js'); - * print(myDictionary.hasKey('p5')); // prints 'true' - * myDictionary.clear(); - * print(myDictionary.hasKey('p5')); // prints 'false' - * } - * - *
      - */ - _main.default.TypedDict.prototype.clear = function () { - this.data = { - }; - }; + _main.default.TypedDict = /*#__PURE__*/ function () { + function TypedDict(key, value) { + _classCallCheck(this, TypedDict); + if (key instanceof Object) { + this.data = key; + } else { + this.data = { + }; + this.data[key] = value; + } + return this; + } /** + * Returns the number of key-value pairs currently stored in the Dictionary. + * + * @method size + * @return {Integer} the number of key-value pairs in the Dictionary + * + * @example + *
      + * + * function setup() { + * let myDictionary = createNumberDict(1, 10); + * myDictionary.create(2, 20); + * myDictionary.create(3, 30); + * print(myDictionary.size()); // logs 3 to the console + * } + *
      + */ + + _createClass(TypedDict, [ + { + key: 'size', + value: function size() { + return Object.keys(this.data).length; + } /** + * Returns true if the given key exists in the Dictionary, + * otherwise returns false. + * + * @method hasKey + * @param {Number|String} key that you want to look up + * @return {Boolean} whether that key exists in Dictionary + * + * @example + *
      + * + * function setup() { + * let myDictionary = createStringDict('p5', 'js'); + * print(myDictionary.hasKey('p5')); // logs true to console + * } + *
      + */ + + }, + { + key: 'hasKey', + value: function hasKey(key) { + return this.data.hasOwnProperty(key); + } /** + * Returns the value stored at the given key. + * + * @method get + * @param {Number|String} the key you want to access + * @return {Number|String} the value stored at that key + * + * @example + *
      + * + * function setup() { + * let myDictionary = createStringDict('p5', 'js'); + * let myValue = myDictionary.get('p5'); + * print(myValue === 'js'); // logs true to console + * } + *
      + */ + + }, + { + key: 'get', + value: function get(key) { + if (this.data.hasOwnProperty(key)) { + return this.data[key]; + } else { + console.log(''.concat(key, ' does not exist in this Dictionary')); + } + } /** + * Updates the value associated with the given key in case it already exists + * in the Dictionary. Otherwise a new key-value pair is added. + * + * @method set + * @param {Number|String} key + * @param {Number|String} value + * + * @example + *
      + * + * function setup() { + * let myDictionary = createStringDict('p5', 'js'); + * myDictionary.set('p5', 'JS'); + * myDictionary.print(); // logs "key: p5 - value: JS" to console + * } + *
      + */ + + }, + { + key: 'set', + value: function set(key, value) { + if (this._validate(value)) { + this.data[key] = value; + } else { + console.log('Those values dont work for this dictionary type.'); + } + } /** + * private helper function to handle the user passing in objects + * during construction or calls to create() + */ + + }, + { + key: '_addObj', + value: function _addObj(obj) { + for (var key in obj) { + this.set(key, obj[key]); + } + } /** + * Creates a new key-value pair in the Dictionary. + * + * @method create + * @param {Number|String} key + * @param {Number|String} value + * + * @example + *
      + * + * function setup() { + * let myDictionary = createStringDict('p5', 'js'); + * myDictionary.create('happy', 'coding'); + * myDictionary.print(); + * // above logs "key: p5 - value: js, key: happy - value: coding" to console + * } + *
      + */ + /** + * @method create + * @param {Object} obj key/value pair + */ + + }, + { + key: 'create', + value: function create(key, value) { + if (key instanceof Object && typeof value === 'undefined') { + this._addObj(key); + } else if (typeof key !== 'undefined') { + this.set(key, value); + } else { + console.log('In order to create a new Dictionary entry you must pass ' + 'an object or a key, value pair'); + } + } /** + * Removes all previously stored key-value pairs from the Dictionary. + * + * @method clear + * @example + *
      + * + * function setup() { + * let myDictionary = createStringDict('p5', 'js'); + * print(myDictionary.hasKey('p5')); // prints 'true' + * myDictionary.clear(); + * print(myDictionary.hasKey('p5')); // prints 'false' + * } + * + *
      + */ + + }, + { + key: 'clear', + value: function clear() { + this.data = { + }; + } /** + * Removes the key-value pair stored at the given key from the Dictionary. + * + * @method remove + * @param {Number|String} key for the pair to remove + * + * @example + *
      + * + * function setup() { + * let myDictionary = createStringDict('p5', 'js'); + * myDictionary.create('happy', 'coding'); + * myDictionary.print(); + * // above logs "key: p5 - value: js, key: happy - value: coding" to console + * myDictionary.remove('p5'); + * myDictionary.print(); + * // above logs "key: happy value: coding" to console + * } + *
      + */ + + }, + { + key: 'remove', + value: function remove(key) { + if (this.data.hasOwnProperty(key)) { + delete this.data[key]; + } else { + throw new Error(''.concat(key, ' does not exist in this Dictionary')); + } + } /** + * Logs the set of items currently stored in the Dictionary to the console. + * + * @method print + * + * @example + *
      + * + * function setup() { + * let myDictionary = createStringDict('p5', 'js'); + * myDictionary.create('happy', 'coding'); + * myDictionary.print(); + * // above logs "key: p5 - value: js, key: happy - value: coding" to console + * } + * + *
      + */ + + }, + { + key: 'print', + value: function print() { + for (var item in this.data) { + console.log('key:'.concat(item, ' value:').concat(this.data[item])); + } + } /** + * Converts the Dictionary into a CSV file for local download. + * + * @method saveTable + * @example + *
      + * + * function setup() { + * createCanvas(100, 100); + * background(200); + * text('click here to save', 10, 10, 70, 80); + * } + * + * function mousePressed() { + * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { + * createStringDict({ + * john: 1940, + * paul: 1942, + * george: 1943, + * ringo: 1940 + * }).saveTable('beatles'); + * } + * } + * + *
      + */ + + }, + { + key: 'saveTable', + value: function saveTable(filename) { + var output = ''; + for (var key in this.data) { + output += ''.concat(key, ',').concat(this.data[key], '\n'); + } + var blob = new Blob([output], { + type: 'text/csv' + }); + _main.default.prototype.downloadFile(blob, filename || 'mycsv', 'csv'); + } /** + * Converts the Dictionary into a JSON file for local download. + * + * @method saveJSON + * @example + *
      + * + * function setup() { + * createCanvas(100, 100); + * background(200); + * text('click here to save', 10, 10, 70, 80); + * } + * + * function mousePressed() { + * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { + * createStringDict({ + * john: 1940, + * paul: 1942, + * george: 1943, + * ringo: 1940 + * }).saveJSON('beatles'); + * } + * } + * + *
      + */ + + }, + { + key: 'saveJSON', + value: function saveJSON(filename, opt) { + _main.default.prototype.saveJSON(this.data, filename, opt); + } /** + * private helper function to ensure that the user passed in valid + * values for the Dictionary type + */ + + }, + { + key: '_validate', + value: function _validate(value) { + return true; + } + } + ]); + return TypedDict; + }(); /** - * Removes the key-value pair stored at the given key from the Dictionary. * - * @method remove - * @param {Number|String} key for the pair to remove + * A simple Dictionary class for Strings. * - * @example - *
      - * - * function setup() { - * let myDictionary = createStringDict('p5', 'js'); - * myDictionary.create('happy', 'coding'); - * myDictionary.print(); - * // above logs "key: p5 - value: js, key: happy - value: coding" to console - * myDictionary.remove('p5'); - * myDictionary.print(); - * // above logs "key: happy value: coding" to console - * } - *
      + * @class p5.StringDict + * @extends p5.TypedDict */ - _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')); + _main.default.StringDict = /*#__PURE__*/ function (_p5$TypedDict) { + _inherits(StringDict, _p5$TypedDict); + var _super = _createSuper(StringDict); + function StringDict() { + _classCallCheck(this, StringDict); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _super.call.apply(_super, [ + this + ].concat(args)); } - }; + _createClass(StringDict, [ + { + key: '_validate', + value: function _validate(value) { + return typeof value === 'string'; + } + } + ]); + return StringDict; + }(_main.default.TypedDict); /** - * Logs the set of items currently stored in the Dictionary to the console. * - * @method print + * A simple Dictionary class for Numbers. * - * @example - *
      - * - * function setup() { - * let myDictionary = createStringDict('p5', 'js'); - * myDictionary.create('happy', 'coding'); - * myDictionary.print(); - * // above logs "key: p5 - value: js, key: happy - value: coding" to console - * } - * - *
      + * @class p5.NumberDict + * @constructor + * @extends p5.TypedDict */ - _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 - *
      - * - * 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'); - * } - * } - * - *
      - */ - _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 - *
      - * - * 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'); - * } - * } - * - *
      - */ - _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 - *
      - * - * function setup() { - * let myDictionary = createNumberDict(2, 5); - * myDictionary.add(2, 2); - * print(myDictionary.get(2)); // logs 7 to console. - * } - *
      - * - */ - _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 - *
      - * - * function setup() { - * let myDictionary = createNumberDict(2, 5); - * myDictionary.sub(2, 2); - * print(myDictionary.get(2)); // logs 3 to console. - * } - *
      - * - */ - _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 - *
      - * - * function setup() { - * let myDictionary = createNumberDict(2, 4); - * myDictionary.mult(2, 2); - * print(myDictionary.get(2)); // logs 8 to console. - * } - *
      - * - */ - _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 - *
      - * - * function setup() { - * let myDictionary = createNumberDict(2, 8); - * myDictionary.div(2, 2); - * print(myDictionary.get(2)); // logs 4 to console. - * } - *
      - * - */ - _main.default.NumberDict.prototype.div = function (key, amount) { - if (this.data.hasOwnProperty(key)) { - this.data[key] /= amount; - } else { - console.log('The key - '.concat(key, ' does not exist in this dictionary.')); - } - }; - /** - * private helper function for finding lowest or highest value - * the argument 'flip' is used to flip the comparison arrow - * from 'less than' to 'greater than' - */ - _main.default.NumberDict.prototype._valueTest = function (flip) { - if (Object.keys(this.data).length === 0) { - throw new Error('Unable to search for a minimum or maximum value on an empty NumberDict'); - } else if (Object.keys(this.data).length === 1) { - return this.data[Object.keys(this.data) [0]]; - } else { - var result = this.data[Object.keys(this.data) [0]]; - for (var key in this.data) { - if (this.data[key] * flip < result * flip) { - result = this.data[key]; - } - } - return result; - } - }; - /** - * Return the lowest number currently stored in the Dictionary. - * - * @method minValue - * @return {Number} - * @example - *
      - * - * function setup() { - * let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 }); - * let lowestValue = myDictionary.minValue(); // value is -10 - * print(lowestValue); - * } - *
      - */ - _main.default.NumberDict.prototype.minValue = function () { - return this._valueTest(1); - }; - /** - * Return the highest number currently stored in the Dictionary. - * - * @method maxValue - * @return {Number} - * @example - *
      - * - * function setup() { - * let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 }); - * let highestValue = myDictionary.maxValue(); // value is 3 - * print(highestValue); - * } - *
      - */ - _main.default.NumberDict.prototype.maxValue = function () { - return this._valueTest( - 1); - }; - /** - * private helper function for finding lowest or highest key - * the argument 'flip' is used to flip the comparison arrow - * from 'less than' to 'greater than' - */ - _main.default.NumberDict.prototype._keyTest = function (flip) { - if (Object.keys(this.data).length === 0) { - throw new Error('Unable to use minValue on an empty NumberDict'); - } else if (Object.keys(this.data).length === 1) { - return Object.keys(this.data) [0]; - } else { - var result = Object.keys(this.data) [0]; - for (var i = 1; i < Object.keys(this.data).length; i++) { - if (Object.keys(this.data) [i] * flip < result * flip) { - result = Object.keys(this.data) [i]; + _main.default.NumberDict = /*#__PURE__*/ function (_p5$TypedDict2) { + _inherits(NumberDict, _p5$TypedDict2); + var _super2 = _createSuper(NumberDict); + function NumberDict() { + _classCallCheck(this, NumberDict); + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + return _super2.call.apply(_super2, [ + this + ].concat(args)); + } /** + * private helper function to ensure that the user passed in valid + * values for the Dictionary type + */ + + _createClass(NumberDict, [ + { + key: '_validate', + value: function _validate(value) { + return typeof value === 'number'; + } /** + * Add the given number to the value currently stored at the given key. + * The sum then replaces the value previously stored in the Dictionary. + * + * @method add + * @param {Number} Key for the value you wish to add to + * @param {Number} Number to add to the value + * @example + *
      + * + * function setup() { + * let myDictionary = createNumberDict(2, 5); + * myDictionary.add(2, 2); + * print(myDictionary.get(2)); // logs 7 to console. + * } + *
      + * + */ + + }, + { + key: 'add', + value: function add(key, amount) { + if (this.data.hasOwnProperty(key)) { + this.data[key] += amount; + } else { + console.log('The key - '.concat(key, ' does not exist in this dictionary.')); + } + } /** + * Subtract the given number from the value currently stored at the given key. + * The difference then replaces the value previously stored in the Dictionary. + * + * @method sub + * @param {Number} Key for the value you wish to subtract from + * @param {Number} Number to subtract from the value + * @example + *
      + * + * function setup() { + * let myDictionary = createNumberDict(2, 5); + * myDictionary.sub(2, 2); + * print(myDictionary.get(2)); // logs 3 to console. + * } + *
      + * + */ + + }, + { + key: 'sub', + value: function sub(key, amount) { + this.add(key, - amount); + } /** + * Multiply the given number with the value currently stored at the given key. + * The product then replaces the value previously stored in the Dictionary. + * + * @method mult + * @param {Number} Key for value you wish to multiply + * @param {Number} Amount to multiply the value by + * @example + *
      + * + * function setup() { + * let myDictionary = createNumberDict(2, 4); + * myDictionary.mult(2, 2); + * print(myDictionary.get(2)); // logs 8 to console. + * } + *
      + * + */ + + }, + { + key: 'mult', + value: function mult(key, amount) { + if (this.data.hasOwnProperty(key)) { + this.data[key] *= amount; + } else { + console.log('The key - '.concat(key, ' does not exist in this dictionary.')); + } + } /** + * Divide the given number with the value currently stored at the given key. + * The quotient then replaces the value previously stored in the Dictionary. + * + * @method div + * @param {Number} Key for value you wish to divide + * @param {Number} Amount to divide the value by + * @example + *
      + * + * function setup() { + * let myDictionary = createNumberDict(2, 8); + * myDictionary.div(2, 2); + * print(myDictionary.get(2)); // logs 4 to console. + * } + *
      + * + */ + + }, + { + key: 'div', + value: function div(key, amount) { + if (this.data.hasOwnProperty(key)) { + this.data[key] /= amount; + } else { + console.log('The key - '.concat(key, ' does not exist in this dictionary.')); + } + } /** + * private helper function for finding lowest or highest value + * the argument 'flip' is used to flip the comparison arrow + * from 'less than' to 'greater than' + */ + + }, + { + key: '_valueTest', + value: function _valueTest(flip) { + if (Object.keys(this.data).length === 0) { + throw new Error('Unable to search for a minimum or maximum value on an empty NumberDict'); + } else if (Object.keys(this.data).length === 1) { + return this.data[Object.keys(this.data) [0]]; + } else { + var result = this.data[Object.keys(this.data) [0]]; + for (var key in this.data) { + if (this.data[key] * flip < result * flip) { + result = this.data[key]; + } + } + return result; + } + } /** + * Return the lowest number currently stored in the Dictionary. + * + * @method minValue + * @return {Number} + * @example + *
      + * + * function setup() { + * let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 }); + * let lowestValue = myDictionary.minValue(); // value is -10 + * print(lowestValue); + * } + *
      + */ + + }, + { + key: 'minValue', + value: function minValue() { + return this._valueTest(1); + } /** + * Return the highest number currently stored in the Dictionary. + * + * @method maxValue + * @return {Number} + * @example + *
      + * + * function setup() { + * let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 }); + * let highestValue = myDictionary.maxValue(); // value is 3 + * print(highestValue); + * } + *
      + */ + + }, + { + key: 'maxValue', + value: function maxValue() { + return this._valueTest( - 1); + } /** + * private helper function for finding lowest or highest key + * the argument 'flip' is used to flip the comparison arrow + * from 'less than' to 'greater than' + */ + + }, + { + key: '_keyTest', + value: function _keyTest(flip) { + if (Object.keys(this.data).length === 0) { + throw new Error('Unable to use minValue on an empty NumberDict'); + } else if (Object.keys(this.data).length === 1) { + return Object.keys(this.data) [0]; + } else { + var result = Object.keys(this.data) [0]; + for (var i = 1; i < Object.keys(this.data).length; i++) { + if (Object.keys(this.data) [i] * flip < result * flip) { + result = Object.keys(this.data) [i]; + } + } + return result; + } + } /** + * Return the lowest key currently used in the Dictionary. + * + * @method minKey + * @return {Number} + * @example + *
      + * + * function setup() { + * let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 }); + * let lowestKey = myDictionary.minKey(); // value is 1.2 + * print(lowestKey); + * } + *
      + */ + + }, + { + key: 'minKey', + value: function minKey() { + return this._keyTest(1); + } /** + * Return the highest key currently used in the Dictionary. + * + * @method maxKey + * @return {Number} + * @example + *
      + * + * function setup() { + * let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 }); + * let highestKey = myDictionary.maxKey(); // value is 4 + * print(highestKey); + * } + *
      + */ + + }, + { + key: 'maxKey', + value: function maxKey() { + return this._keyTest( - 1); } } - return result; - } - }; - /** - * Return the lowest key currently used in the Dictionary. - * - * @method minKey - * @return {Number} - * @example - *
      - * - * function setup() { - * let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 }); - * let lowestKey = myDictionary.minKey(); // value is 1.2 - * print(lowestKey); - * } - *
      - */ - _main.default.NumberDict.prototype.minKey = function () { - return this._keyTest(1); - }; - /** - * Return the highest key currently used in the Dictionary. - * - * @method maxKey - * @return {Number} - * @example - *
      - * - * function setup() { - * let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 }); - * let highestKey = myDictionary.maxKey(); // value is 4 - * print(highestKey); - * } - *
      - */ - _main.default.NumberDict.prototype.maxKey = function () { - return this._keyTest( - 1); - }; + ]); + return NumberDict; + }(_main.default.TypedDict); var _default = _main.default.TypedDict; exports.default = _default; }, { - '../core/main': 290, - 'core-js/modules/es.array.concat': 167, - 'core-js/modules/es.object.keys': 194, - 'core-js/modules/es.string.sub': 210 + '../core/main': 298, + 'core-js/modules/es.array.concat': 169, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.object.get-prototype-of': 198, + 'core-js/modules/es.object.keys': 199, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.reflect.construct': 202, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 306: [ + 314: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -70261,8 +74388,10 @@ _dereq_('core-js/modules/es.array.slice'); _dereq_('core-js/modules/es.array.splice'); _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.object.get-prototype-of'); _dereq_('core-js/modules/es.object.to-string'); _dereq_('core-js/modules/es.promise'); + _dereq_('core-js/modules/es.reflect.construct'); _dereq_('core-js/modules/es.regexp.exec'); _dereq_('core-js/modules/es.regexp.to-string'); _dereq_('core-js/modules/es.string.iterator'); @@ -70319,6 +74448,89 @@ obj }; } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } + function _inherits(subClass, superClass) { + if (typeof superClass !== 'function' && superClass !== null) { + throw new TypeError('Super expression must either be null or a function'); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + if (superClass) _setPrototypeOf(subClass, superClass); + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + return _setPrototypeOf(o, p); + } + function _createSuper(Derived) { + function isNativeReflectConstruct() { + if (typeof Reflect === 'undefined' || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === 'function') return true; + try { + Date.prototype.toString.call(Reflect.construct(Date, [ + ], function () { + })); + return true; + } catch (e) { + return false; + } + } + return function () { + var Super = _getPrototypeOf(Derived), + result; + if (isNativeReflectConstruct()) { + var NewTarget = _getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return _possibleConstructorReturn(this, result); + }; + } + function _possibleConstructorReturn(self, call) { + if (call && (_typeof(call) === 'object' || typeof call === 'function')) { + return call; + } + return _assertThisInitialized(self); + } + function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called'); + } + return self; + } + function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } function _typeof(obj) { if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { _typeof = function _typeof(obj) { @@ -70330,41 +74542,93 @@ }; } return _typeof(obj); - } /** - * Searches the page for the first element that matches the given CSS selector string (can be an - * ID, class, tag name or a combination) and returns it as a p5.Element. - * The DOM node itself can be accessed with .elt. - * Returns null if none found. You can also specify a container to search within. + } /** + * The web is much more than just canvas and the DOM functionality makes it easy to interact + * with other HTML5 objects, including text, hyperlink, image, input, video, + * audio, and webcam. + * There is a set of creation methods, DOM manipulation methods, and + * an extended p5.Element that supports a range of HTML elements. See the + * + * beyond the canvas tutorial for a full overview of how this addon works. + * + * See tutorial: beyond the canvas + * for more info on how to use this library. + * + * @module DOM + * @submodule DOM + * @for p5 + * @requires p5 + */ + /** + * Searches the page for the first element that matches the given + * CSS selector string. + * The string can be an ID, class, tag name, or a combination. `select()` + * returns a p5.Element object if it finds a match + * and `null` otherwise. + * + * The second parameter, `container`, is optional. It specifies a container to + * search within. container can be CSS selector string, a + * p5.Element object, or an + * HTMLElement object. * * @method select - * @param {String} selectors CSS selector string of element to search for + * @param {String} selectors CSS selector string of element to search for. * @param {String|p5.Element|HTMLElement} [container] CSS selector string, p5.Element, or - * HTML element to search within - * @return {p5.Element|null} p5.Element containing node found + * HTMLElement to search within. + * @return {p5.Element|null} p5.Element containing the element. * @example - *
      + *
      + * * function setup() { - * createCanvas(50, 50); - * background(30); - * // move canvas down and right - * select('canvas').position(10, 30); + * createCanvas(100, 100); + * background(200); + * + * // Select the canvas by its tag. + * let cnv = select('canvas'); + * cnv.style('border', '5px deeppink dashed'); + * + * describe('A gray square with a dashed pink border.'); * } - *
      + *
      + *
      * - *
      - * // 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 - *
      + *
      + * + * function setup() { + * let cnv = createCanvas(100, 100); + * // Add a class attribute to the canvas. + * cnv.class('pinkborder'); + * + * background(200); + * + * // Select the canvas by its class. + * cnv = select('.pinkborder'); + * // Style its border. + * cnv.style('border', '5px deeppink dashed'); + * + * describe('A gray square with a dashed pink border.'); + * } + * + *
      + * + *
      + * + * function setup() { + * let cnv = createCanvas(100, 100); + * // Set the canvas ID. + * cnv.id('mycanvas'); + * + * background(200); + * + * // Select the canvas by its ID. + * cnv = select('#mycanvas'); + * // Style its border. + * cnv.style('border', '5px deeppink dashed'); + * + * describe('A gray square with a dashed pink border.'); + * } + * + *
      */ _main.default.prototype.select = function (e, p) { @@ -70378,49 +74642,78 @@ } }; /** - * Searches the page for elements that match the given CSS selector string (can be an ID a class, - * tag name or a combination) and returns them as p5.Elements in - * an array. - * The DOM node itself can be accessed with .elt. - * Returns an empty array if none found. - * You can also specify a container to search within. + * Searches the page for all elements that matches the given + * CSS selector string. + * The string can be an ID, class, tag name, or a combination. `selectAll()` + * returns an array of p5.Element objects if it + * finds any matches and an empty array otherwise. + * + * The second parameter, `container`, is optional. It specifies a container to + * search within. container can be CSS selector string, a + * p5.Element object, or an + * HTMLElement object. * * @method selectAll - * @param {String} selectors CSS selector string of elements to search for - * @param {String|p5.Element|HTMLElement} [container] CSS selector string, p5.Element - * , or HTML element to search within - * @return {p5.Element[]} Array of p5.Elements containing nodes found + * @param {String} selectors CSS selector string of element to search for. + * @param {String|p5.Element|HTMLElement} [container] CSS selector string, p5.Element, or + * HTMLElement to search within. + * @return {p5.Element[]} array of p5.Elements containing any elements found. * @example - *
      + *
      + * * function setup() { - * createButton('btn'); - * createButton('2nd btn'); - * createButton('3rd btn'); + * // Create three buttons. + * createButton('1'); + * createButton('2'); + * createButton('3'); + * + * // Select the buttons by their tag. * let buttons = selectAll('button'); * - * for (let i = 0; i < 3; i++) { - * buttons[i].size(100); + * // Position the buttons. + * for (let i = 0; i < 3; i += 1) { * buttons[i].position(0, i * 30); * } + * + * describe('Three buttons stacked vertically. The buttons are labeled, "1", "2", and "3".'); * } - *
      - *
      - * // 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); - *
      + *
      + *
      + * + *
      + * + * function setup() { + * // Create three buttons and position them. + * let b1 = createButton('1'); + * b1.position(0, 0); + * let b2 = createButton('2'); + * b2.position(0, 30); + * let b3 = createButton('3'); + * b3.position(0, 60); + * + * // Add a class attribute to each button. + * b1.class('btn'); + * b2.class('btn btn-pink'); + * b3.class('btn'); + * + * // Select the buttons by their class. + * let buttons = selectAll('.btn'); + * let pinkButtons = selectAll('.btn-pink'); + * + * // Style the selected buttons. + * buttons.forEach(btn => { + * btn.style('font-family', 'Comic Sans MS'); + * }); + * + * pinkButtons.forEach(btn => { + * btn.style('background', 'deeppink'); + * btn.style('color', 'white'); + * }); + * + * describe('Three buttons stacked vertically. The buttons are labeled, "1", "2", and "3". Buttons "1" and "3" are gray. Button "2" is pink.'); + * } + * + *
      */ _main.default.prototype.selectAll = function (e, p) { _main.default._validateParameters('selectAll', arguments); @@ -70460,7 +74753,7 @@ converted.checked = function () { if (arguments.length === 0) { return this.elt.checked; - } else if (arguments[0]) { + } else if (arguments.length <= 0 ? undefined : arguments[0]) { this.elt.checked = true; } else { this.elt.checked = false; @@ -70481,27 +74774,69 @@ } }; /** - * Removes all elements created by p5, except any canvas / graphics - * elements created by createCanvas or createGraphics. - * Event handlers are removed, and element is removed from the DOM. + * Removes all elements created by p5.js, including any event handlers. + * There are two exceptions: + * canvas elements created by createCanvas + * and p5.Render objects created by + * createGraphics. + * * @method removeElements * @example - *
      + *
      + * * function setup() { * createCanvas(100, 100); - * background('grey'); - * let div = createDiv('this is some text'); - * let p = createP('this is a paragraph'); - * div.style('font-size', '16px'); - * p.style('font-size', '16px'); + * background(200); + * + * // Create a paragraph element and place + * // it in the middle of the canvas. + * let p = createP('p5*js'); + * p.position(25, 25); + * + * describe('A gray square with the text "p5*js" written in its center. The text disappears when the mouse is pressed.'); * } + * * function mousePressed() { - * removeElements(); // this will remove the div and p, not canvas + * removeElements(); * } - *
      + *
      + *
      + * + *
      + * + * let slider; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a paragraph element and place + * // it at the top of the canvas. + * let p = createP('p5*js'); + * p.position(25, 25); + * + * // Create a slider element and place it + * // beneath the canvas. + * slider = createSlider(0, 255, 200); + * slider.position(0, 100); + * + * describe('A gray square with the text "p5*js" written in its center and a range slider beneath it. The square changes color when the slider is moved. The text and slider disappear when the square is double-clicked.'); + * } + * + * function draw() { + * // Use the slider value to change the background color. + * let g = slider.value(); + * background(g); + * } + * + * function doubleClicked() { + * removeElements(); + * } + * + *
      */ _main.default.prototype.removeElements = function (e) { - _main.default._validateParameters('removeElements', arguments); // el.remove splices from this._elements, so don't mix iteration with it + _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); }; @@ -70511,103 +74846,120 @@ }); }; /** - * The .changed() function is called when the value of an - * element changes. - * This can be used to attach an element specific event listener. + * `myElement.changed()` sets a function to call when the value of the + * p5.Element object changes. Calling + * `myElement.changed(false)` disables the function. * * @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. + * @param {Function|Boolean} fxn function to call when the element changes. + * `false` disables the function. * @chainable * @example - *
      - * 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); - * } - *
      * - *
      - * let checkbox; - * let cnv; + * // Create a dropdown menu and add a few color options. + * let drop = createSelect(); + * drop.position(0, 0); + * drop.option('red'); + * drop.option('green'); + * drop.option('blue'); + * + * // When the color option changes, paint the background with + * // that color. + * drop.changed(() => { + * let c = drop.value(); + * background(c); + * }); * - * function setup() { - * checkbox = createCheckbox(' fill'); - * checkbox.changed(changeFill); - * cnv = createCanvas(100, 100); - * cnv.position(0, 30); - * noFill(); + * describe('A gray square with a dropdown menu at the top. The square changes color when an option is selected.'); * } + * + *
      * - * function draw() { + *
      + * + * function setup() { * background(200); - * ellipse(50, 50, 50, 50); - * } * - * function changeFill() { - * if (checkbox.checked()) { - * fill(0); - * } else { - * noFill(); - * } - * } - *
      + * // Create a checkbox and place it beneath the canvas. + * let checkbox = createCheckbox(' circle'); + * checkbox.position(0, 100); * - * @alt - * dropdown: pear, kiwi, grape. When selected text "it's a" + selection shown. + * // When the checkbox changes, paint the background gray + * // and determine whether to draw a circle. + * checkbox.changed(() => { + * background(200); + * if (checkbox.checked() === true) { + * circle(50, 50, 30); + * } + * }); + * + * describe('A gray square with a checkbox underneath it that says "circle". A white circle appears when the box is checked and disappears otherwise.'); + * } + *
      + *
      */ _main.default.Element.prototype.changed = function (fxn) { _main.default.Element._adjustListener('change', fxn, this); return this; }; /** - * The .input() function is called when any user input is - * detected with an element. The input event is often used - * to detect keystrokes in a input element, or changes on a - * slider element. This can be used to attach an element specific - * event listener. + * `myElement.input()` sets a function to call when input is detected within + * the p5.Element object. It's often used to with + * text inputs and sliders. Calling `myElement.input(false)` disables the + * function. * * @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. + * @param {Function|Boolean} fxn function to call when input is detected within + * the element. + * `false` disables the function. * @chainable * @example - *
      - * // Open your console to see the output + *
      + * * function setup() { - * createCanvas(100, 100); - * background('grey'); - * let inp = createInput(''); - * inp.position(0, 0); - * inp.size(100); - * inp.input(myInputEvent); - * } + * background(200); * - * function myInputEvent() { - * console.log('you are typing: ', this.value()); + * // Create a slider and place it beneath the canvas. + * let slider = createSlider(0, 255, 200); + * slider.position(0, 100); + * + * // When the slider changes, use its value to paint + * // the background. + * slider.input(() => { + * let g = slider.value(); + * background(g); + * }); + * + * describe('A gray square with a range slider underneath it. The background changes shades of gray when the slider is moved.'); * } - *
      + *
      + *
      * - * @alt - * no display. + *
      + * + * function setup() { + * background(200); + * + * // Create an input and place it beneath the canvas. + * let inp = createInput(''); + * inp.position(0, 100); + * + * // When input is detected, paint the background gray + * // and display the text. + * inp.input(() => { + * background(200); + * let msg = inp.value(); + * text(msg, 5, 50); + * }); + * + * describe('A gray square with a text input bar beneath it. Any text written in the input appears in the middle of the square.'); + * } + * + *
      */ _main.default.Element.prototype.input = function (fxn) { _main.default.Element._adjustListener('input', fxn, this); @@ -70623,17 +74975,42 @@ pInst._elements.push(c); return c; } /** - * Creates a `<div></div>` element in the DOM with given inner HTML. + * Creates a `<div></div>` element. It's commonly used as a + * container for other elements. + * + * The parameter `html` is optional. It accepts a string that sets the + * inner HTML of the new `<div></div>`. * * @method createDiv - * @param {String} [html] inner HTML for element created - * @return {p5.Element} pointer to p5.Element holding created node + * @param {String} [html] inner HTML for the new `<div></div>` element. + * @return {p5.Element} new p5.Element object. * @example - *
      - * let div = createDiv('this is some text'); - * div.style('font-size', '16px'); - * div.position(10, 0); - *
      + *
      + * + * function setup() { + * background(200); + * + * let div = createDiv('p5*js'); + * div.position(25, 35); + * + * describe('A gray square with the text "p5*js" written in its center.'); + * } + * + *
      + * + *
      + * + * function setup() { + * background(200); + * + * // Create an h3 element within the div. + * let div = createDiv('

      p5*js

      '); + * div.position(20, 5); + * + * describe('A gray square with the text "p5*js" written in its center.'); + * } + *
      + *
      */ _main.default.prototype.createDiv = function () { @@ -70643,18 +75020,28 @@ return addElement(elt, this); }; /** - * Creates a `<p></p>` element in the DOM with given inner HTML. Used - * for paragraph length text. + * Creates a `<p></p>` element. It's commonly used for + * paragraph-length text. + * + * The parameter `html` is optional. It accepts a string that sets the + * inner HTML of the new `<p></p>`. * * @method createP - * @param {String} [html] inner HTML for element created - * @return {p5.Element} pointer to p5.Element holding created node + * @param {String} [html] inner HTML for the new `<p></p>` element. + * @return {p5.Element} new p5.Element object. * @example - *
      - * let p = createP('this is some text'); - * p.style('font-size', '16px'); - * p.position(10, 0); - *
      + *
      + * + * function setup() { + * background(200); + * + * let p = createP('Tell me a story.'); + * p.position(5, 0); + * + * describe('A gray square displaying the text "Tell me a story." written in black.'); + * } + * + *
      */ _main.default.prototype.createP = function () { var html = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; @@ -70663,16 +75050,63 @@ return addElement(elt, this); }; /** - * Creates a `<span></span>` element in the DOM with given inner HTML. + * Creates a `<span></span>` element. It's commonly used as a + * container for inline elements. For example, a `<span></span>` + * can hold part of a sentence that's a + * different style. + * + * The parameter `html` is optional. It accepts a string that sets the + * inner HTML of the new `<span></span>`. * * @method createSpan - * @param {String} [html] inner HTML for element created - * @return {p5.Element} pointer to p5.Element holding created node + * @param {String} [html] inner HTML for the new `<span></span>` element. + * @return {p5.Element} new p5.Element object. * @example - *
      - * let span = createSpan('this is some text'); - * span.position(0, 0); - *
      + *
      + * + * function setup() { + * background(200); + * + * // Create a span element. + * let span = createSpan('p5*js'); + * span.position(25, 35); + * + * describe('A gray square with the text "p5*js" written in its center.'); + * } + * + *
      + * + *
      + * + * function setup() { + * background(200); + * + * // Create a div element as + * // a container. + * let div = createDiv(); + * // Place the div at the + * // center. + * div.position(25, 35); + * + * // Create a span element. + * let s1 = createSpan('p5'); + * // Create a second span element. + * let s2 = createSpan('*'); + * // Set the span's font color. + * s2.style('color', 'deeppink'); + * // Create a third span element. + * let s3 = createSpan('js'); + * + * // Add all the spans to the + * // container div. + * s1.parent(div); + * s2.parent(div); + * s3.parent(div); + * + * describe('A gray square with the text "p5*js" written in black at its center. The asterisk is pink.'); + * } + * + *
      */ _main.default.prototype.createSpan = function () { var html = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; @@ -70681,29 +75115,54 @@ return addElement(elt, this); }; /** - * Creates an `<img>` element in the DOM with given src and - * alternate text. + * Creates an `<img>` element that can appear outside of the canvas. + * + * The first parameter, `src`, is a string with the path to the image file. + * `src` should be a relative path, as in `'assets/image.png'`, or a URL, as + * in `'https://example.com/image.png'`. + * + * The second parameter, `alt`, is a string with the + * alternate text + * for the image. An empty string `''` can be used for images that aren't displayed. + * + * The third parameter, `crossOrigin`, is optional. It's a string that sets the + * crossOrigin property + * of the image. Use `'anonymous'` or `'use-credentials'` to fetch the image + * with cross-origin access. + * + * The fourth parameter, `callback`, is also optional. It sets a function to + * call after the image loads. The new image is passed to the callback + * function as a p5.Element object. * * @method createImg - * @param {String} src src path or url for image - * @param {String} alt alternate text to be used if image does not load. You can use also an empty string (`""`) if that an image is not intended to be viewed. - * @return {p5.Element} pointer to p5.Element holding created node + * @param {String} src relative path or URL for the image. + * @param {String} alt alternate text for the image. + * @return {p5.Element} new p5.Element object. * @example - *
      - * let img = createImg( - * 'https://p5js.org/assets/img/asterisk-01.png', - * 'the p5 magenta asterisk' - * ); - * img.position(0, -10); - *
      + *
      + * + * function setup() { + * background(200); + * + * let img = createImg( + * 'https://p5js.org/assets/img/asterisk-01.png', + * 'The p5.js magenta asterisk.' + * ); + * img.position(0, -10); + * + * describe('A gray square with a magenta asterisk in its center.'); + * } + * + *
      */ /** * @method createImg * @param {String} src * @param {String} alt - * @param {String} crossOrigin crossOrigin property of the `img` element; use either 'anonymous' or 'use-credentials' to retrieve the image with cross-origin access (for later use with `canvas`. if an empty string(`""`) is passed, CORS is not used - * @param {Function} [successCallback] callback to be called once image data is loaded with the p5.Element as argument - * @return {p5.Element} pointer to p5.Element holding created node + * @param {String} [crossOrigin] crossOrigin property to use when fetching the image. + * @param {Function} [successCallback] function to call once the image loads. The new image will be passed + * to the function as a p5.Element object. + * @return {p5.Element} new p5.Element object. */ _main.default.prototype.createImg = function () { _main.default._validateParameters('createImg', arguments); @@ -70727,19 +75186,55 @@ return self; }; /** - * Creates an `<a></a>` element in the DOM for including a hyperlink. + * Creates an `<a></a>` element that links to another web page. + * + * The first parmeter, `href`, is a string that sets the URL of the linked + * page. + * + * The second parameter, `html`, is a string that sets the inner HTML of the + * link. It's common to use text, images, or buttons as links. + * + * The third parameter, `target`, is optional. It's a string that tells the + * web browser where to open the link. By default, links open in the current + * browser tab. Passing `'_blank'` will cause the link to open in a new + * browser tab. MDN describes a few + * other options. * * @method createA - * @param {String} href url of page to link to - * @param {String} html inner html of link element to display - * @param {String} [target] target where new link should open, - * could be _blank, _self, _parent, _top. - * @return {p5.Element} pointer to p5.Element holding created node + * @param {String} href URL of linked page. + * @param {String} html inner HTML of link element to display. + * @param {String} [target] target where the new link should open, + * either `'_blank'`, `'_self'`, `'_parent'`, or `'_top'`. + * @return {p5.Element} new p5.Element object. * @example - *
      - * let a = createA('http://p5js.org/', 'this is a link'); - * a.position(0, 0); - *
      + *
      + * + * function setup() { + * background(200); + * + * // Create an anchor element that links to p5js.org. + * let a = createA('http://p5js.org/', 'p5*js'); + * a.position(25, 35); + * + * describe('The text "p5*js" written at the center of a gray square.'); + * } + * + *
      + * + *
      + * + * function setup() { + * background(200); + * + * // Create an anchor element that links to p5js.org. + * // Open the link in a new tab. + * let a = createA('http://p5js.org/', 'p5*js', '_blank'); + * a.position(25, 35); + * + * describe('The text "p5*js" written at the center of a gray square.'); + * } + * + *
      */ _main.default.prototype.createA = function (href, html, target) { _main.default._validateParameters('createA', arguments); @@ -70751,44 +75246,114 @@ }; /** INPUT **/ /** - * Creates a slider `<input></input>` element in the DOM. - * Use .size() to set the display length of the slider. + * Creates a slider `<input></input>` element. Range sliders are + * useful for quickly selecting numbers from a given range. + * + * The first two parameters, `min` and `max`, are numbers that set the + * slider's minimum and maximum. + * + * The third parameter, `value`, is optional. It's a number that sets the + * slider's default value. + * + * The fourth parameter, `step`, is also optional. It's a number that sets the + * spacing between each value in the slider's range. Setting `step` to 0 + * allows the slider to move smoothly from `min` to `max`. * * @method createSlider - * @param {Number} min minimum value of the slider - * @param {Number} max maximum value of the slider - * @param {Number} [value] default value of the slider - * @param {Number} [step] step size for each tick of the slider (if step is set to 0, the slider will move continuously from the minimum to the maximum value) - * @return {p5.Element} pointer to p5.Element holding the created node + * @param {Number} min minimum value of the slider. + * @param {Number} max maximum value of the slider. + * @param {Number} [value] default value of the slider. + * @param {Number} [step] size for each step in the slider's range. + * @return {p5.Element} new p5.Element object. * @example - *
      + *
      + * * let slider; + * * function setup() { - * slider = createSlider(0, 255, 100); + * // Create a slider and place it at the top of the canvas. + * slider = createSlider(0, 255); * slider.position(10, 10); - * slider.style('width', '80px'); + * slider.size(80); + * + * describe('A dark gray square with a range slider at the top. The square changes color when the slider is moved.'); * } * * function draw() { - * let val = slider.value(); - * background(val); + * // Use the slider as a grayscale value. + * let g = slider.value(); + * background(g); * } - *
      + *
      + *
      * - *
      + *
      + * * let slider; + * * function setup() { - * colorMode(HSB); - * slider = createSlider(0, 360, 60, 40); + * // Create a slider and place it at the top of the canvas. + * // Set its default value to 0. + * slider = createSlider(0, 255, 0); * slider.position(10, 10); - * slider.style('width', '80px'); + * slider.size(80); + * + * describe('A black square with a range slider at the top. The square changes color when the slider is moved.'); * } * * function draw() { - * let val = slider.value(); - * background(val, 100, 100, 1); + * // Use the slider as a grayscale value. + * let g = slider.value(); + * background(g); * } - *
      + *
      + *
      + * + *
      + * + * let slider; + * + * function setup() { + * // Create a slider and place it at the top of the canvas. + * // Set its default value to 0. + * // Set its step size to 50. + * slider = createSlider(0, 255, 0, 50); + * slider.position(10, 10); + * slider.size(80); + * + * describe('A black square with a range slider at the top. The square changes color when the slider is moved.'); + * } + * + * function draw() { + * // Use the slider as a grayscale value. + * let g = slider.value(); + * background(g); + * } + * + *
      + * + *
      + * + * let slider; + * + * function setup() { + * // Create a slider and place it at the top of the canvas. + * // Set its default value to 0. + * // Set its step size to 0 so that it moves smoothly. + * slider = createSlider(0, 255, 0, 0); + * slider.position(10, 10); + * slider.size(80); + * + * describe('A black square with a range slider at the top. The square changes color when the slider is moved.'); + * } + * + * function draw() { + * // Use the slider as a grayscale value. + * let g = slider.value(); + * background(g); + * } + * + *
      */ _main.default.prototype.createSlider = function (min, max, value, step) { _main.default._validateParameters('createSlider', arguments); @@ -70805,30 +75370,68 @@ 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. + * Creates a `<button></button>` element. + * + * The first parameter, `label`, is a string that sets the label displayed on + * the button. + * + * The second parameter, `value`, is optional. It's a string that sets the + * button's value. See + * MDN + * for more details. * * @method createButton - * @param {String} label label displayed on the button - * @param {String} [value] value of the button - * @return {p5.Element} pointer to p5.Element holding created node + * @param {String} label label displayed on the button. + * @param {String} [value] value of the button. + * @return {p5.Element} new p5.Element object. * @example - *
      + *
      + * + * function setup() { + * background(200); + * + * // Create a button and place it beneath the canvas. + * let button = createButton('click me'); + * button.position(0, 100); + * + * // Use the button to change the background color. + * button.mousePressed(() => { + * let g = random(255); + * background(g); + * }); + * + * describe('A gray square with a button that says "click me" beneath it. The square changes color when the button is clicked.'); + * } + * + *
      + * + *
      + * * let button; + * * function setup() { - * createCanvas(100, 100); - * background(0); - * button = createButton('click me'); - * button.position(0, 0); - * button.mousePressed(changeBG); + * // Create a button and set its value to 0. + * // Place the button beneath the canvas. + * button = createButton('click me', 'red'); + * button.position(0, 100); + * + * // Change the button's value when the mouse + * // is pressed. + * button.mousePressed(() => { + * let c = random(['red', 'green', 'blue', 'yellow']); + * button.value(c); + * }); + * + * describe('A red square with a button that says "click me" beneath it. The square changes color when the button is clicked.'); * } * - * function changeBG() { - * let val = random(255); - * background(val); + * function draw() { + * // Use the button's value to set the background color. + * let c = button.value(); + * background(c); * } - *
      + *
      + *
      */ _main.default.prototype.createButton = function (label, value) { _main.default._validateParameters('createButton', arguments); @@ -70838,47 +75441,116 @@ return addElement(elt, this); }; /** - * Creates a checkbox `<input></input>` element in the DOM. - * Calling .checked() on a checkbox returns a boolean indicating whether - * it is checked or not. + * Creates a checkbox `<input></input>` element. Checkboxes extend + * the p5.Element class with a `checked()` method. + * Calling `myBox.checked()` returns `true` if it the box is checked and + * `false` otherwise. + * + * The first parameter, `label`, is optional. It's a string that sets the label + * to display next to the checkbox. + * + * The second parameter, `value`, is also optional. It's a boolean that sets the + * checkbox's value. * * @method createCheckbox - * @param {String} [label] label displayed after checkbox - * @param {boolean} [value] value of the checkbox; checked is true, unchecked is false - * @return {p5.Element} pointer to p5.Element holding created node + * @param {String} [label] label displayed after the checkbox. + * @param {boolean} [value] value of the checkbox. Checked is `true` and unchecked is `false`. + * @return {p5.Element} new p5.Element object. * @example - *
      + *
      + * * let checkbox; * * function setup() { - * checkbox = createCheckbox('label', false); - * checkbox.changed(myCheckedEvent); + * // Create a checkbox and place it beneath the canvas. + * checkbox = createCheckbox(); + * checkbox.position(0, 100); + * + * describe('A black square with a checkbox beneath it. The square turns white when the box is checked.'); * } * - * function myCheckedEvent() { + * function draw() { + * // Use the checkbox to set the background color. * if (checkbox.checked()) { - * console.log('Checking!'); + * background(255); * } else { - * console.log('Unchecking!'); + * background(0); * } * } - *
      + *
      + *
      + * + *
      + * + * let checkbox; + * + * function setup() { + * // Create a checkbox and place it beneath the canvas. + * // Label the checkbox "white". + * checkbox = createCheckbox(' white'); + * checkbox.position(0, 100); + * + * describe('A black square with a checkbox labeled "white" beneath it. The square turns white when the box is checked.'); + * } + * + * function draw() { + * // Use the checkbox to set the background color. + * if (checkbox.checked()) { + * background(255); + * } else { + * background(0); + * } + * } + * + *
      + * + *
      + * + * let checkbox; + * + * function setup() { + * // Create a checkbox and place it beneath the canvas. + * // Label the checkbox "white" and set its value to true. + * checkbox = createCheckbox(' white', true); + * checkbox.position(0, 100); + * + * describe('A white square with a checkbox labeled "white" beneath it. The square turns black when the box is unchecked.'); + * } + * + * function draw() { + * // Use the checkbox to set the background color. + * if (checkbox.checked()) { + * background(255); + * } else { + * background(0); + * } + * } + * + *
      */ _main.default.prototype.createCheckbox = function () { - _main.default._validateParameters('createCheckbox', arguments); // Create a container element - var elt = document.createElement('div'); // Create checkbox type input element + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _main.default._validateParameters('createCheckbox', args); + // Create a container element + var elt = document.createElement('div'); + // Create checkbox type input element var checkbox = document.createElement('input'); - checkbox.type = 'checkbox'; // Create label element and wrap it around checkbox + checkbox.type = 'checkbox'; + // Create label element and wrap it around checkbox var label = document.createElement('label'); - label.appendChild(checkbox); // Append label element inside the container - elt.appendChild(label); //checkbox must be wrapped in p5.Element before label so that label appears after + label.appendChild(checkbox); + // Append label element inside the container + elt.appendChild(label); + //checkbox must be wrapped in p5.Element before label so that label appears after var self = addElement(elt, this); self.checked = function () { var cb = self.elt.firstElementChild.getElementsByTagName('input') [0]; if (cb) { if (arguments.length === 0) { return cb.checked; - } else if (arguments[0]) { + } else if (arguments.length <= 0 ? undefined : arguments[0]) { cb.checked = true; } else { cb.checked = false; @@ -70889,79 +75561,183 @@ this.value = function (val) { self.value = val; return this; - }; // Set the span element innerHTML as the label value if passed - if (arguments[0]) { - self.value(arguments[0]); + }; + // Set the span element innerHTML as the label value if passed + if (args[0]) { + self.value(args[0]); var span = document.createElement('span'); - span.innerHTML = arguments[0]; + span.innerHTML = args[0]; label.appendChild(span); - } // Set the checked value of checkbox if passed + } // Set the checked value of checkbox if passed - if (arguments[1]) { + if (args[1]) { checkbox.checked = true; } return self; }; /** - * Creates a dropdown menu `<select></select>` element in the DOM. - * It also assigns select-related methods to p5.Element when selecting an existing select box. Options in the menu are unique by `name` (the display text). - * - `.option(name, [value])` can be used to add an option with `name` (the display text) and `value` to the select element. If an option with `name` already exists within the select element, this method will change its value to `value`. - * - `.value()` will return the currently selected option. - * - `.selected()` will return the current dropdown element which is an instance of p5.Element. - * - `.selected(value)` can be used to make given option selected by default when the page first loads. - * - `.disable()` marks the whole dropdown element as disabled. - * - `.disable(value)` marks a given option as disabled. + * Creates a dropdown menu `<select></select>` element. + * + * The parameter is optional. If `true` is passed, as in + * `let mySelect = createSelect(true)`, then the dropdown will support + * multiple selections. If an existing `<select></select>` element + * is passed, as in `let mySelect = createSelect(otherSelect)`, the existing + * element will be wrapped in a new p5.Element + * object. + * + * Dropdowns extend the p5.Element class with a few + * helpful methods for managing options: + * - `mySelect.option(name, [value])` adds an option to the menu. The first paremeter, `name`, is a string that sets the option's name and value. The second parameter, `value`, is optional. If provided, it sets the value that corresponds to the key `name`. If an option with `name` already exists, its value is changed to `value`. + * - `mySelect.value()` returns the currently-selected option's value. + * - `mySelect.selected()` returns the currently-selected option. + * - `mySelect.selected(option)` selects the given option by default. + * - `mySelect.disable()` marks the whole dropdown element as disabled. + * - `mySelect.disable(option)` marks a given option as disabled. + * - `mySelect.enable()` marks the whole dropdown element as enabled. + * - `mySelect.enable(option)` marks a given option as enabled. * * @method createSelect - * @param {boolean} [multiple] true if dropdown should support multiple selections - * @return {p5.Element} pointer to p5.Element holding created node + * @param {boolean} [multiple] support multiple selections. + * @return {p5.Element} new p5.Element object. * @example - *
      - * let sel; + *
      + * + * let mySelect; * * 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); + * // Create a dropdown and place it beneath the canvas. + * mySelect = createSelect(); + * mySelect.position(0, 100); + * + * // Add color options. + * mySelect.option('red'); + * mySelect.option('green'); + * mySelect.option('blue'); + * mySelect.option('yellow'); + * + * // Set the selected option to "red". + * mySelect.selected('red'); + * + * describe('A red square with a dropdown menu beneath it. The square changes color when a new color is selected.'); * } * - * function mySelectEvent() { - * let item = sel.value(); - * background(200); - * text('It is a ' + item + '!', 50, 50); + * function draw() { + * // Use the selected value to paint the background. + * let c = mySelect.selected(); + * background(c); * } - *
      + *
      + *
      * - *
      - * let sel; + *
      + * + * let mySelect; * * function setup() { - * textAlign(CENTER); + * // Create a dropdown and place it beneath the canvas. + * mySelect = createSelect(); + * mySelect.position(0, 100); + * + * // Add color options. + * mySelect.option('red'); + * mySelect.option('green'); + * mySelect.option('blue'); + * mySelect.option('yellow'); + * + * // Set the selected option to "red". + * mySelect.selected('red'); + * + * // Disable the "yellow" option. + * mySelect.disable('yellow'); + * + * describe('A red square with a dropdown menu beneath it. The square changes color when a new color is selected.'); + * } + * + * function draw() { + * // Use the selected value to paint the background. + * let c = mySelect.selected(); + * background(c); + * } + * + *
      + * + *
      + * + * let mySelect; + * + * function setup() { + * // Create a dropdown and place it beneath the canvas. + * mySelect = createSelect(); + * mySelect.position(0, 100); + * + * // Add color options with names and values. + * mySelect.option('one', 'red'); + * mySelect.option('two', 'green'); + * mySelect.option('three', 'blue'); + * mySelect.option('four', 'yellow'); + * + * // Set the selected option to "one". + * mySelect.selected('one'); + * + * describe('A red square with a dropdown menu beneath it. The square changes color when a new color is selected.'); + * } + * + * function draw() { + * // Use the selected value to paint the background. + * let c = mySelect.selected(); + * background(c); + * } + * + *
      + * + *
      + * + * // Hold CTRL to select multiple options on Windows and Linux. + * // Hold CMD to select multiple options on macOS. + * let mySelect; + * + * function setup() { + * // Create a dropdown and allow multiple selections. + * // Place it beneath the canvas. + * mySelect = createSelect(true); + * mySelect.position(0, 100); + * + * // Add color options. + * mySelect.option('red'); + * mySelect.option('green'); + * mySelect.option('blue'); + * mySelect.option('yellow'); + * + * describe('A gray square with a dropdown menu beneath it. Colorful circles appear when their color is selected.'); + * } + * + * function draw() { * background(200); - * sel = createSelect(); - * sel.position(10, 10); - * sel.option('oil'); - * sel.option('milk'); - * sel.option('bread'); - * sel.disable('milk'); + * + * // Use the selected value(s) to draw circles. + * let colors = mySelect.selected(); + * colors.forEach((c, index) => { + * let x = 10 + index * 20; + * fill(c); + * circle(x, 50, 20); + * }); * } - *
      + *
      + *
      */ /** * @method createSelect - * @param {Object} existing DOM select element + * @param {Object} existing select element to wrap, either as a p5.Element or + * a HTMLSelectElement. * @return {p5.Element} */ _main.default.prototype.createSelect = function () { - _main.default._validateParameters('createSelect', arguments); + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + _main.default._validateParameters('createSelect', args); var self; - var arg = arguments[0]; + var arg = args[0]; if (arg instanceof _main.default.Element && arg.elt instanceof HTMLSelectElement) { // If given argument is p5.Element of select type self = arg; @@ -70978,17 +75754,18 @@ this.elt = elt; } self.option = function (name, value) { - var index; // if no name is passed, return + var index; + // if no name is passed, return if (name === undefined) { return; - } //see if there is already an option with this name + } //see if there is already an option with this name for (var i = 0; i < this.elt.length; i += 1) { if (this.elt[i].textContent === name) { index = i; break; } - } //if there is an option with this name we will modify it + } //if there is an option with this name we will modify it if (index !== undefined) { //if the user passed in false then delete that option @@ -71061,78 +75838,157 @@ } return this; }; + self.enable = function (value) { + if (typeof value === 'string') { + for (var i = 0; i < this.elt.length; i++) { + if (this.elt[i].value.toString() === value) { + this.elt[i].disabled = false; + this.elt[i].selected = false; + } + } + } else { + this.elt.disabled = false; + for (var _i = 0; _i < this.elt.length; _i++) { + this.elt[_i].disabled = false; + this.elt[_i].selected = false; + } + } + return this; + }; return self; }; /** - * Creates a radio button element in the DOM. It also helps existing radio buttons - * assign methods of p5.Element. - * - `.option(value, [label])` can be used to create a new option for the - * element. If an option with a value already exists, it will be returned. - * It is recommended to use string values as input for `value`. - * Optionally, a label can be provided as second argument for the option. - * - `.remove(value)` can be used to remove an option for the element. String - * values recommended as input for `value`. - * - `.value()` method will return the currently selected value. - * - `.selected()` method will return the currently selected input element. - * - `.selected(value)` method will select the option and return it. String - * values recommended as input for `value`. - * - `.disable(Boolean)` method will enable/disable the whole radio button element. + * Creates a radio button element. + * + * The parameter is optional. If a string is passed, as in + * `let myRadio = createSelect('food')`, then each radio option will + * have `"food"` as its `name` parameter: `<input name="food"></input>`. + * If an existing `<div></div>` or `<span></span>` + * element is passed, as in `let myRadio = createSelect(container)`, it will + * become the radio button's parent element. + * + * Radio buttons extend the p5.Element class with a few + * helpful methods for managing options: + * - `myRadio.option(value, [label])` adds an option to the menu. The first paremeter, `value`, is a string that sets the option's value and label. The second parameter, `label`, is optional. If provided, it sets the label displayed for the `value`. If an option with `value` already exists, its label is changed and its value is returned. + * - `myRadio.value()` returns the currently-selected option's value. + * - `myRadio.selected()` returns the currently-selected option. + * - `myRadio.selected(value)` selects the given option and returns it as an `HTMLInputElement`. + * - `myRadio.disable(shouldDisable)` enables the entire radio button if `true` is passed and disables it if `false` is passed. * * @method createRadio - * @param {Object} containerElement A container HTML Element, either a div - * or span, inside which all existing radio inputs will be considered as options. - * @param {string} [name] A name parameter for each Input Element. - * @return {p5.Element} pointer to p5.Element holding created node + * @param {Object} [containerElement] container HTML Element, either a `<div></div>` + * or `<span></span>`. + * @return {p5.Element} new p5.Element object. * @example - *
      - * let radio; + *
      + * + * let myRadio; * * function setup() { - * radio = createRadio(); - * radio.option('black'); - * radio.option('white'); - * radio.option('gray'); - * radio.style('width', '60px'); - * textAlign(CENTER); - * fill(255, 0, 0); + * // Create a radio button element and place it + * // in the top-left corner. + * myRadio = createRadio(); + * myRadio.position(0, 0); + * myRadio.size(60); + * + * // Add a few color options. + * myRadio.option('red'); + * myRadio.option('yellow'); + * myRadio.option('blue'); + * + * // Choose a default option. + * myRadio.selected('yellow'); + * + * describe('A yellow square with three color options listed, "red", "yellow", and "blue". The square changes color when the user selects a new option.'); * } * * function draw() { - * let val = radio.value(); - * background(val); - * text(val, width / 2, height / 2); + * // Set the background color using the radio button. + * let g = myRadio.value(); + * background(g); * } - *
      - *
      - * let radio; + * + *
      + * + *
      + * + * let myRadio; * * function setup() { - * radio = createRadio(); - * radio.option('1', 'apple'); - * radio.option('2', 'bread'); - * radio.option('3', 'juice'); - * radio.style('width', '30px'); - * radio.selected('2'); - * textAlign(CENTER); + * // Create a radio button element and place it + * // in the top-left corner. + * myRadio = createRadio(); + * myRadio.position(0, 0); + * myRadio.size(50); + * + * // Add a few color options. + * // Color values are labeled with + * // emotions they evoke. + * myRadio.option('red', 'love'); + * myRadio.option('yellow', 'joy'); + * myRadio.option('blue', 'trust'); + * + * // Choose a default option. + * myRadio.selected('yellow'); + * + * describe('A yellow square with three options listed, "love", "joy", and "trust". The square changes color when the user selects a new option.'); * } * * function draw() { - * background(200); - * let val = radio.value(); - * if (val) { - * text('item cost is $' + val, width / 2, height / 2); - * } + * // Set the background color using the radio button. + * let c = myRadio.value(); + * background(c); * } - *
      + *
      + *
      + * + *
      + * + * let myRadio; + * + * function setup() { + * // Create a radio button element and place it + * // in the top-left corner. + * myRadio = createRadio(); + * myRadio.position(0, 0); + * myRadio.size(50); + * + * // Add a few color options. + * myRadio.option('red'); + * myRadio.option('yellow'); + * myRadio.option('blue'); + * + * // Choose a default option. + * myRadio.selected('yellow'); + * + * // Create a button and place it beneath the canvas. + * let btn = createButton('disable'); + * btn.position(0, 100); + * + * // Use the button to disable the radio button. + * btn.mousePressed(() => { + * myRadio.disable(true); + * }); + * + * describe('A yellow square with three options listed, "red", "yellow", and "blue". The square changes color when the user selects a new option. A "disable" button beneath the canvas disables the color options when pressed.'); + * } + * + * function draw() { + * // Set the background color using the radio button. + * let c = myRadio.value(); + * background(c); + * } + * + *
      */ /** * @method createRadio - * @param {String} name - * @return {p5.Element} pointer to p5.Element holding created node + * @param {String} [name] name parameter assigned to each option's `<input></input>` element. + * @return {p5.Element} new p5.Element object. */ /** * @method createRadio - * @return {p5.Element} pointer to p5.Element holding created node + * @return {p5.Element} new p5.Element object. */ _main.default.prototype.createRadio = function () { // Creates a div, adds each option as an individual input inside it. @@ -71141,24 +75997,25 @@ var self; var radioElement; var name; - var arg0 = arguments[0]; + var arg0 = arguments.length <= 0 ? undefined : arguments[0]; if (arg0 instanceof _main.default.Element && (arg0.elt instanceof HTMLDivElement || arg0.elt instanceof HTMLSpanElement)) { // If given argument is p5.Element of div/span type self = arg0; this.elt = arg0.elt; - } else if ( // If existing radio Element is provided as argument 0 + } else if ( // If existing radio Element is provided as argument 0 arg0 instanceof HTMLDivElement || arg0 instanceof HTMLSpanElement) { self = addElement(arg0, this); this.elt = arg0; radioElement = arg0; - if (typeof arguments[1] === 'string') name = arguments[1]; + if (typeof (arguments.length <= 1 ? undefined : arguments[1]) === 'string') name = arguments.length <= 1 ? undefined : arguments[1]; } else { if (typeof arg0 === 'string') name = arg0; radioElement = document.createElement('div'); self = addElement(radioElement, this); this.elt = radioElement; } - self._name = name || 'radioOption'; // setup member functions + self._name = name || 'radioOption'; + // setup member functions var isRadioInput = function isRadioInput(el) { return el instanceof HTMLInputElement && el.type === 'radio'; }; @@ -71188,7 +76045,7 @@ optionEl = option; break; } - } // Create a new option, add it to radioElement and return it. + } // Create a new option, add it to radioElement and return it. } catch (err) { _didIteratorError2 = true; @@ -71209,14 +76066,15 @@ optionEl.setAttribute('type', 'radio'); optionEl.setAttribute('value', value); } - optionEl.setAttribute('name', self._name); // Check if label element exists, else create it + optionEl.setAttribute('name', self._name); + // Check if label element exists, else create it var labelElement; if (!isLabelElement(optionEl.parentElement)) { labelElement = document.createElement('label'); labelElement.insertAdjacentElement('afterbegin', optionEl); } else { labelElement = optionEl.parentElement; - } // Check if span element exists, else create it + } // Check if span element exists, else create it var spanElement; if (!isSpanElement(labelElement.lastElementChild)) { @@ -71224,9 +76082,10 @@ optionEl.insertAdjacentElement('afterend', spanElement); } else { spanElement = labelElement.lastElementChild; - } // Set the innerHTML of span element as the label text + } // Set the innerHTML of span element as the label text - spanElement.innerHTML = label === undefined ? value : label; // Append the label element, which includes option element and + spanElement.innerHTML = label === undefined ? value : label; + // Append the label element, which includes option element and // span element to the radio container element this.elt.appendChild(labelElement); return optionEl; @@ -71385,57 +76244,62 @@ 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. + * Creates a color picker element. + * + * The parameter, `value`, is optional. If a color string or + * p5.Color object is passed, it will set the default + * color. + * + * Color pickers extend the p5.Element class with a + * couple of helpful methods for managing colors: + * - `myPicker.value()` returns the current color as a hex string in the format `'#rrggbb'`. + * - `myPicker.color()` returns the current color as a p5.Color object. + * * * @method createColorPicker - * @param {String|p5.Color} [value] default color of element - * @return {p5.Element} pointer to p5.Element holding created node + * @param {String|p5.Color} [value] default color as a CSS color string. + * @return {p5.Element} new p5.Element object. * @example - *
      - * let colorPicker; + *
      + * + * let myPicker; + * * function setup() { - * createCanvas(100, 100); - * colorPicker = createColorPicker('#ed225d'); - * colorPicker.position(0, height + 5); + * myPicker = createColorPicker('deeppink'); + * myPicker.position(0, 100); + * + * describe('A pink square with a color picker beneath it. The square changes color when the user picks a new color.'); * } * * function draw() { - * background(colorPicker.color()); + * // Use the color picker to paint the background. + * let c = myPicker.color(); + * background(c); * } - *
      - *
      - * let inp1, inp2; + * + *
      + * + *
      + * + * let myPicker; + * * 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(); - * } + * myPicker = createColorPicker('deeppink'); + * myPicker.position(0, 100); * - * function setMidShade() { - * // Finding a shade between the two - * let commonShade = lerpColor(inp1.color(), inp2.color(), 0.5); - * fill(commonShade); - * rect(20, 20, 60, 60); + * describe('A number with the format "#rrggbb" is displayed on a pink canvas. The background color and number change when the user picks a new color.'); * } * - * function 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()); + * function draw() { + * // Use the color picker to paint the background. + * let c = myPicker.value(); + * background(c); + * + * // Display the current color as a hex string. + * text(c, 25, 55); * } - *
      + *
      + *
      */ _main.default.prototype.createColorPicker = function (value) { _main.default._validateParameters('createColorPicker', arguments); @@ -71472,7 +76336,8 @@ } else { elt.value = '#000000'; } - self = addElement(elt, this); // Method to return a p5.Color object for the given color. + self = addElement(elt, this); + // Method to return a p5.Color object for the given color. self.color = function () { if (value) { if (value.mode) { @@ -71487,29 +76352,68 @@ return self; }; /** - * Creates an `<input></input>` element in the DOM for text input. - * Use .size() to set the display length of the box. + * Creates a text `<input></input>` element. Call `myInput.size()` + * to set the length of the text box. + * + * The first parameter, `value`, is optional. It's a string that sets the + * input's default value. The input is blank by default. + * + * The second parameter, `type`, is also optional. It's a string that + * specifies the type of text being input. See MDN for a full + * list of options. + * The default is `'text'`. * * @method createInput - * @param {String} value default value of the input box - * @param {String} [type] type of text, ie text, password etc. Defaults to text. - * Needs a value to be specified first. - * @return {p5.Element} pointer to p5.Element holding created node + * @param {String} [value] default value of the input box. Defaults to an empty string `''`. + * @param {String} [type] type of input. Defaults to `'text'`. + * @return {p5.Element} new p5.Element object. * @example - *
      + *
      + * + * let myInput; + * * function setup() { - * createCanvas(100, 100); - * background('grey'); - * let inp = createInput(''); - * inp.position(0, 0); - * inp.size(100); - * inp.input(myInputEvent); + * // Create an input element and place it + * // beneath the canvas. + * myInput = createInput(); + * myInput.position(0, 100); + * + * describe('A gray square with a text box beneath it. The text in the square changes when the user types something new in the input bar.'); * } * - * function myInputEvent() { - * console.log('you are typing: ', this.value()); + * function draw() { + * background(200); + * + * // Use the input to display a message. + * let msg = myInput.value(); + * text(msg, 25, 55); * } - *
      + *
      + *
      + * + *
      + * + * let myInput; + * + * function setup() { + * // Create an input element and place it + * // beneath the canvas. Set its default + * // text to "hello!". + * myInput = createInput('hello!'); + * myInput.position(0, 100); + * + * describe('The text "hello!" written at the center of a gray square. A text box beneath the square also says "hello!". The text in the square changes when the user types something new in the input bar.'); + * } + * + * function draw() { + * background(200); + * + * // Use the input to display a message. + * let msg = myInput.value(); + * text(msg, 25, 55); + * } + * + *
      */ /** * @method createInput @@ -71526,32 +76430,49 @@ return addElement(elt, this); }; /** - * Creates an `<input></input>` element in the DOM of type 'file'. + * Creates an `<input></input>` element of type `'file'`. * This allows users to select local files for use in a sketch. * + * The first parameter, `callback`, is a function that's called when the file + * loads. The callback function should have one parameter, `file`, that's a + * p5.File object. + * + * The second parameter, `multiple`, is optional. It's a boolean value that + * allows loading multiple files if set to `true`. If `true`, `callback` + * will be called once per file. + * * @method createFileInput - * @param {Function} callback callback function for when a file is loaded - * @param {Boolean} [multiple] optional, to allow multiple files to be selected - * @return {p5.Element} pointer to p5.Element holding created DOM element + * @param {Function} callback function to call once the file loads. + * @param {Boolean} [multiple] allow multiple files to be selected. + * @return {p5.Element} new p5.Element object. * @example - *
      + *
      + * + * // Use the file input to select an image to + * // load and display. * let input; * let img; * * function setup() { - * input = createFileInput(handleFile); - * input.position(0, 0); + * // Create a file input and place it beneath + * // the canvas. + * input = createFileInput(handleImage); + * input.position(0, 100); + * + * describe('A gray square with a file input beneath it. If the user selects an image file to load, it is displayed on the square.'); * } * * function draw() { - * background(255); + * background(200); + * + * // Draw the image if loaded. * if (img) { * image(img, 0, 0, width, height); * } * } * - * function handleFile(file) { - * print(file); + * // Create an image if the file is an image. + * function handleImage(file) { * if (file.type === 'image') { * img = createImg(file.data, ''); * img.hide(); @@ -71559,7 +76480,48 @@ * img = null; * } * } - *
      + *
      + *
      + * + *
      + * + * // Use the file input to select multiple images + * // to load and display. + * let input; + * let images = []; + * + * function setup() { + * // Create a file input and place it beneath + * // the canvas. Allow it to load multiple files. + * input = createFileInput(handleImage, true); + * input.position(0, 100); + * } + * + * function draw() { + * background(200); + * + * // Draw the images if loaded. Each image + * // is drawn 20 pixels lower than the + * // previous image. + * images.forEach((img, index) => { + * let y = index * 20; + * image(img, 0, y, width, height); + * }); + * + * describe('A gray square with a file input beneath it. If the user selects multiple image files to load, they are displayed on the square.'); + * } + * + * // Create an image if the file is an image, + * // then add it to the images array. + * function handleImage(file) { + * if (file.type === 'image') { + * let img = createImg(file.data, ''); + * img.hide(); + * images.push(img); + * } + * } + * + *
      */ _main.default.prototype.createFileInput = function (callback) { var multiple = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; @@ -71587,7 +76549,8 @@ } } } - }; // If File API's are not supported, throw Error + }; + // 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; @@ -71601,7 +76564,8 @@ /** 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 + var elt = document.createElement(type); + // Create source elements from given sources src = src || ''; if (typeof src === 'string') { src = [ @@ -71617,7 +76581,7 @@ var sourceEl = document.createElement('source'); sourceEl.setAttribute('src', mediaSource); elt.appendChild(sourceEl); - } // If callback is provided, attach to element + } // If callback is provided, attach to element } catch (err) { _didIteratorError9 = true; @@ -71641,10 +76605,12 @@ elt.addEventListener('canplaythrough', callbackHandler); } var mediaEl = addElement(elt, pInst, true); - mediaEl.loadedmetadata = false; // set width and height onload metadata + 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 + 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) { @@ -71655,45 +76621,90 @@ }); return mediaEl; } /** - * Creates an HTML5 `<video>` element in the DOM for simple playback - * of audio/video. Shown by default, can be hidden with .hide() - * and drawn into canvas using image(). The first parameter - * can be either a single string path to a video file, or an array of string - * paths to different formats of the same video. This is useful for ensuring - * that your video can play across different browsers, as each supports - * different formats. See this - * page for further information about supported formats. + * Creates a `<video>` element for simple audio/video playback. + * Returns a new p5.MediaElement object. + * + * Videos are shown by default. They can be hidden by calling `video.hide()` + * and drawn to the canvas using image(). + * + * The first parameter, `src`, is the path the video. If a single string is + * passed, as in `'assets/topsecret.mp4'`, a single video is loaded. An array + * of strings can be used to load the same video in different formats. For + * example, `['assets/topsecret.mp4', 'assets/topsecret.ogv', 'assets/topsecret.webm']`. + * This is useful for ensuring that the video can play across different browsers with + * different capabilities. See + * MDN + * for more information about supported formats. + * + * The second parameter, `callback`, is optional. It's a function to call once + * the video is ready to play. * * @method createVideo - * @param {String|String[]} src path to a video file, or array of paths for - * supporting different browsers - * @param {Function} [callback] callback function to be called upon - * 'canplaythrough' event fire, that is, when the - * browser can play the media, and estimates that - * enough data has been loaded to play the media - * up to its end without having to stop for - * further buffering of content - * @return {p5.MediaElement} pointer to video p5.MediaElement + * @param {String|String[]} src path to a video file, or an array of paths for + * supporting different browsers. + * @param {Function} [callback] function to call once the video is ready to play. + * @return {p5.MediaElement} new p5.MediaElement object. * @example - *
      - * let vid; + *
      + * + * function setup() { + * noCanvas(); + * + * // Load a video and add it to the page. + * // Note: this may not work in some browsers. + * let video = createVideo('assets/small.mp4'); + * // Show the default video controls. + * video.showControls(); + * + * describe('A video of a toy robot with playback controls beneath it.'); + * } + * + *
      + * + *
      + * + * function setup() { + * noCanvas(); + * + * // Load a video and add it to the page. + * // Provide an array options for different file formats. + * let video = createVideo( + * ['assets/small.mp4', 'assets/small.ogv', 'assets/small.webm'] + * ); + * // Show the default video controls. + * video.showControls(); + * + * describe('A video of a toy robot with playback controls beneath it.'); + * } + * + *
      + * + *
      + * + * let video; + * * function setup() { * noCanvas(); * - * vid = createVideo( + * // Load a video and add it to the page. + * // Provide an array options for different file formats. + * // Call mute() once the video loads. + * video = createVideo( * ['assets/small.mp4', 'assets/small.ogv', 'assets/small.webm'], - * vidLoad + * muteVideo * ); + * // Show the default video controls. + * video.showControls(); * - * vid.size(100, 100); + * describe('A video of a toy robot with playback controls beneath it.'); * } * - * // This function is called when the video loads - * function vidLoad() { - * vid.loop(); - * vid.volume(0); + * // Mute the video once it loads. + * function muteVideo() { + * video.volume(0); * } - *
      + *
      + *
      */ _main.default.prototype.createVideo = function (src, callback) { @@ -71702,36 +76713,41 @@ }; /** AUDIO STUFF **/ /** - * Creates a hidden HTML5 `<audio>` element in the DOM for simple audio - * playback. The first parameter can be either a single string path to a - * audio file, or an array of string paths to different formats of the same - * audio. This is useful for ensuring that your audio can play across - * different browsers, as each supports different formats. - * See this - * page for further information about supported formats. + * Creates a hidden `<audio>` element for simple audio playback. + * Returns a new p5.MediaElement object. + * + * The first parameter, `src`, is the path the video. If a single string is + * passed, as in `'assets/video.mp4'`, a single video is loaded. An array + * of strings can be used to load the same video in different formats. For + * example, `['assets/video.mp4', 'assets/video.ogv', 'assets/video.webm']`. + * This is useful for ensuring that the video can play across different + * browsers with different capabilities. See + * MDN + * for more information about supported formats. + * + * The second parameter, `callback`, is optional. It's a function to call once + * the audio is ready to play. * * @method createAudio - * @param {String|String[]} [src] path to an audio file, or array of paths - * for supporting different browsers - * @param {Function} [callback] callback function to be called upon - * 'canplaythrough' event fire, that is, when the - * browser can play the media, and estimates that - * enough data has been loaded to play the media - * up to its end without having to stop for - * further buffering of content - * @return {p5.MediaElement} pointer to audio p5.MediaElement + * @param {String|String[]} [src] path to an audio file, or an array of paths + * for supporting different browsers. + * @param {Function} [callback] function to call once the audio is ready to play. + * @return {p5.MediaElement} new p5.MediaElement object. * @example - *
      - * let ele; + *
      + * * function setup() { - * ele = createAudio('assets/beat.mp3'); + * noCanvas(); + * + * // Load the audio. + * let beat = createAudio('assets/beat.mp3'); + * // Show the default audio controls. + * beat.showControls(); * - * // here we set the element to autoplay - * // The element will play as soon - * // as it is able to do so. - * ele.autoplay(true); + * describe('An audio beat plays when the user double-clicks the square.'); * } - *
      + *
      + *
      */ _main.default.prototype.createAudio = function (src, callback) { _main.default._validateParameters('createAudio', arguments); @@ -71739,67 +76755,91 @@ }; /** CAMERA STUFF **/ _main.default.prototype.VIDEO = 'video'; - _main.default.prototype.AUDIO = 'audio'; // from: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia + _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 + } // 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 + 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 + } // Otherwise, wrap the call to the old navigator.getUserMedia with a Promise return new Promise(function (resolve, reject) { getUserMedia.call(navigator, constraints, resolve, reject); }); }; } /** - * Creates a new HTML5 `<video>` element that contains the audio/video feed - * from a webcam. The element is separate from the canvas and is displayed by - * default. The element can be hidden using .hide(). - * The feed can be drawn onto the canvas using image(). - * The loadedmetadata property can be used to detect when the element has fully - * loaded (see second example). - * - * More specific properties of the feed can be passing in a Constraints object. - * See the - * W3C spec for possible properties. Note that not all of these are supported - * by all browsers. - * - * Security note: A new browser security specification requires that - * getUserMedia, which is behind createCapture(), - * only works when you're running the code locally, or on HTTPS. Learn more - * here - * and here. + * Creates a `<video>` element that "captures" the audio/video stream from + * the webcam and microphone. Returns a new + * p5.Element object. + * + * Videos are shown by default. They can be hidden by calling `capture.hide()` + * and drawn to the canvas using image(). + * + * The first parameter, `type`, is optional. It sets the type of capture to + * use. By default, `createCapture()` captures both audio and video. If `VIDEO` + * is passed, as in `createCapture(VIDEO)`, only video will be captured. + * If `AUDIO` is passed, as in `createCapture(AUDIO)`, only audio will be + * captured. A constraints object can also be passed to customize the stream. + * See the + * W3C documentation for possible properties. Different browsers support different + * properties. + * + * The second parameter, `callback`, is optional. It's a function to call once + * the capture is ready for use. The callback function should have one + * parameter, `stream`, that's a + * MediaStream object. + * + * Note: `createCapture()` only works when running a sketch locally or using HTTPS. Learn more + * here + * and here. * * @method createCapture - * @param {String|Constant|Object} type type of capture, either VIDEO or - * AUDIO if none specified, default both, - * or a Constraints object - * @param {Function} [callback] function to be called once - * stream has loaded - * @return {p5.Element} capture video p5.Element + * @param {String|Constant|Object} [type] type of capture, either AUDIO or VIDEO, + * or a constraints object. Both video and audio + * audio streams are captured by default. + * @param {Function} [callback] function to call once the stream + * has loaded. + * @return {p5.Element} new p5.Element object. * @example *
      * + * function setup() { + * noCanvas(); + * createCapture(VIDEO); + * + * describe('A video stream from the webcam.'); + * } + * + *
      + * + *
      + * * let capture; * * function setup() { - * createCanvas(100, 100); + * // Create the video capture and hide the element. * capture = createCapture(VIDEO); * capture.hide(); + * + * describe('A video stream from the webcam with inverted colors.'); * } * * function draw() { + * // Draw the video capture within the canvas. * image(capture, 0, 0, width, width * capture.height / capture.width); + * // Invert the colors in the stream. * filter(INVERT); * } * @@ -71809,6 +76849,8 @@ * * function setup() { * createCanvas(480, 120); + * + * // Create a constraints object. * let constraints = { * video: { * mandatory: { @@ -71817,35 +76859,24 @@ * }, * optional: [{ maxFrameRate: 10 }] * }, - * audio: true + * audio: false * }; - * createCapture(constraints, function(stream) { - * console.log(stream); - * }); - * } - * - *
      - *
      - * - * 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); - * } + * // Create the video capture. + * createCapture(constraints); + * + * describe('A video stream from the webcam.'); * } * *
      */ _main.default.prototype.createCapture = function () { - _main.default._validateParameters('createCapture', arguments); // return if getUserMedia is not supported by browser + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + _main.default._validateParameters('createCapture', args); + // return if getUserMedia is not supported by browser if (!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia)) { throw new DOMException('getUserMedia not supported in this browser'); } @@ -71853,36 +76884,19 @@ 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; - } - } + for (var _i2 = 0, _args = args; _i2 < _args.length; _i2++) { + var arg = _args[_i2]; + if (arg === _main.default.prototype.VIDEO) useAudio = false; + else if (arg === _main.default.prototype.AUDIO) useVideo = false; + else if (_typeof(arg) === 'object') constraints = arg; + else if (typeof arg === 'function') callback = arg; } if (!constraints) constraints = { video: useVideo, audio: useAudio }; - var domElement = document.createElement('video'); // required to work in iOS 11 & up: + var domElement = document.createElement('video'); + // required to work in iOS 11 & up: domElement.setAttribute('playsinline', ''); navigator.mediaDevices.getUserMedia(constraints).then(function (stream) { try { @@ -71896,7 +76910,8 @@ } }, console.log); var videoEl = addElement(domElement, this, true); - videoEl.loadedmetadata = false; // set width and height onload metadata + videoEl.loadedmetadata = false; + // set width and height onload metadata domElement.addEventListener('loadedmetadata', function () { domElement.play(); if (domElement.width) { @@ -71912,18 +76927,48 @@ return videoEl; }; /** - * Creates element with given tag in the DOM with given content. + * Creates a new p5.Element object. + * + * The first parameter, `tag`, is a string an HTML tag such as `'h5'`. + * + * The second parameter, `content`, is optional. It's a string that sets the + * HTML content to insert into the new element. New elements have no content + * by default. * * @method createElement - * @param {String} tag tag for the new element - * @param {String} [content] html content to be inserted into the element - * @return {p5.Element} pointer to p5.Element holding created node + * @param {String} tag tag for the new element. + * @param {String} [content] HTML content to insert into the element. + * @return {p5.Element} new p5.Element object. * @example - *
      - * let h5 = createElement('h5', 'im an h5 p5.element!'); - * h5.style('color', '#00a1d3'); - * h5.position(0, 0); - *
      + *
      + * + * function setup() { + * background(200); + * + * // Create an h5 element with nothing in it. + * createElement('h5'); + * + * describe('A gray square.'); + * } + * + *
      + * + *
      + * + * function setup() { + * background(200); + * + * // Create an h5 element with the content + * // "p5*js". + * let h5 = createElement('h5', 'p5*js'); + * // Set the element's style and position. + * h5.style('color', 'deeppink'); + * h5.position(30, 15); + * + * describe('The text "p5*js" written in pink in the middle of a gray square.'); + * } + * + *
      */ _main.default.prototype.createElement = function (tag, content) { _main.default._validateParameters('createElement', arguments); @@ -71932,7 +76977,8 @@ elt.innerHTML = content; } return addElement(elt, this); - }; // ============================================================================= + }; + // ============================================================================= // p5.Element additions // ============================================================================= /** @@ -72175,11 +77221,11 @@ _main.default.Element.prototype.html = function () { if (arguments.length === 0) { return this.elt.innerHTML; - } else if (arguments[1]) { - this.elt.insertAdjacentHTML('beforeend', arguments[0]); + } else if (arguments.length <= 1 ? undefined : arguments[1]) { + this.elt.insertAdjacentHTML('beforeend', arguments.length <= 0 ? undefined : arguments[0]); return this; } else { - this.elt.innerHTML = arguments[0]; + this.elt.innerHTML = arguments.length <= 0 ? undefined : arguments[0]; return this; } }; @@ -72231,35 +77277,36 @@ }; } 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]; + if ((arguments.length <= 2 ? undefined : arguments[2]) === 'static' || (arguments.length <= 2 ? undefined : arguments[2]) === 'fixed' || (arguments.length <= 2 ? undefined : arguments[2]) === 'relative' || (arguments.length <= 2 ? undefined : arguments[2]) === 'sticky' || (arguments.length <= 2 ? undefined : arguments[2]) === 'initial' || (arguments.length <= 2 ? undefined : arguments[2]) === 'inherit') { + positionType = arguments.length <= 2 ? undefined : arguments[2]; } this.elt.style.position = positionType; - this.elt.style.left = arguments[0] + 'px'; - this.elt.style.top = arguments[1] + 'px'; - this.x = arguments[0]; - this.y = arguments[1]; + this.elt.style.left = (arguments.length <= 0 ? undefined : arguments[0]) + 'px'; + this.elt.style.top = (arguments.length <= 1 ? undefined : arguments[1]) + 'px'; + this.x = arguments.length <= 0 ? undefined : arguments[0]; + this.y = arguments.length <= 1 ? undefined : arguments[1]; return this; } }; /* Helper method called by p5.Element.style() */ _main.default.Element.prototype._translate = function () { - this.elt.style.position = 'absolute'; // save out initial non-translate transform styling + 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)'; + this.elt.style.transform = 'translate(' + (arguments.length <= 0 ? undefined : arguments[0]) + 'px, ' + (arguments.length <= 1 ? undefined : arguments[1]) + 'px)'; } else if (arguments.length > 2) { - this.elt.style.transform = 'translate3d(' + arguments[0] + 'px,' + arguments[1] + 'px,' + arguments[2] + 'px)'; + this.elt.style.transform = 'translate3d(' + (arguments.length <= 0 ? undefined : arguments[0]) + 'px,' + (arguments.length <= 1 ? undefined : arguments[1]) + 'px,' + (arguments.length <= 2 ? undefined : arguments[2]) + 'px)'; if (arguments.length === 3) { this.elt.parentElement.style.perspective = '1000px'; } else { - this.elt.parentElement.style.perspective = arguments[3] + 'px'; + this.elt.parentElement.style.perspective = (arguments.length <= 3 ? undefined : arguments[3]) + 'px'; } - } // add any extra transform styling back on end + } // add any extra transform styling back on end this.elt.style.transform += transform; return this; @@ -72273,61 +77320,121 @@ transform = transform.replace(/rotate[X-Z]?\(.*\)/g, ''); } if (arguments.length === 1) { - this.elt.style.transform = 'rotate(' + arguments[0] + 'deg)'; + this.elt.style.transform = 'rotate(' + (arguments.length <= 0 ? undefined : arguments[0]) + 'deg)'; } else if (arguments.length === 2) { - this.elt.style.transform = 'rotate(' + arguments[0] + 'deg, ' + arguments[1] + 'deg)'; + this.elt.style.transform = 'rotate(' + (arguments.length <= 0 ? undefined : arguments[0]) + 'deg, ' + (arguments.length <= 1 ? undefined : arguments[1]) + 'deg)'; } else if (arguments.length === 3) { - this.elt.style.transform = 'rotateX(' + arguments[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 = 'rotateX(' + (arguments.length <= 0 ? undefined : arguments[0]) + 'deg)'; + this.elt.style.transform += 'rotateY(' + (arguments.length <= 1 ? undefined : arguments[1]) + 'deg)'; + this.elt.style.transform += 'rotateZ(' + (arguments.length <= 2 ? undefined : arguments[2]) + 'deg)'; + } // add remaining transform back on this.elt.style.transform += transform; return this; }; /** - * Sets the given style (CSS) property (1st arg) of the element with the - * given value (2nd arg). If a single argument is given, .style() - * returns the value of the given property; however, if a single argument - * is given in CSS syntax ('text-align:center'), .style() sets the CSS - * appropriately. + * Applies a style to an element by adding a + * CSS declaration. + * + * The first parameter, `property`, is a string. If the name of a style + * property is passed, as in `myElement.style('color')`, the method returns + * the current value as a string or `null` if it hasn't been set. If a + * `property:style` string is passed, as in + * `myElement.style('color:deeppink')`, the method sets `property` to + * `value`. + * + * The second parameter, `value`, is optional. It sets the property's value. + * `value` can be a string, as in + * `myElement.style('color', 'deeppink')`, or a + * p5.Color object, as in + * `myElement.style('color', myColor)`. * * @method style - * @param {String} property property to be set - * @returns {String} value of property + * @param {String} property style property to set. + * @returns {String} value of the property. * @example - *
      - * let myDiv = createDiv('I like pandas.'); - * myDiv.style('font-size', '18px'); - * myDiv.style('color', '#ff0000'); - * myDiv.position(0, 0); - *
      - *
      - * let col = color(25, 23, 200, 50); - * let button = createButton('button'); - * button.style('background-color', col); - * button.position(0, 0); - *
      - *
      - * let myDiv, fontSize; + *
      + * + * function setup() { + * background(200); + * + * // Create a paragraph element and + * // set its font color to "deeppink". + * let p = createP('p5*js'); + * p.position(25, 20); + * p.style('color', 'deeppink'); + * + * describe('The text p5*js written in pink on a gray background.'); + * } + * + *
      + * + *
      + * * function setup() { * background(200); - * myDiv = createDiv('I like gray.'); - * myDiv.position(0, 0); - * myDiv.style('z-index', 10); + * + * // Create a p5.Color object. + * let c = color('deeppink'); + * + * // Create a paragraph element and + * // set its font color using a + * // p5.Color object. + * let p = createP('p5*js'); + * p.position(25, 20); + * p.style('color', c); + * + * describe('The text p5*js written in pink on a gray background.'); * } + * + *
      * - * function draw() { - * fontSize = min(mouseX, 90); - * myDiv.style('font-size', fontSize + 'px'); + *
      + * + * function setup() { + * background(200); + * + * // Create a paragraph element and + * // set its font color to "deeppink" + * // using property:value syntax. + * let p = createP('p5*js'); + * p.position(25, 20); + * p.style('color:deeppink'); + * + * describe('The text p5*js written in pink on a gray background.'); * } - *
      + *
      + *
      + * + *
      + * + * function setup() { + * background(200); + * + * // Create an empty paragraph element + * // and set its font color to "deeppink". + * let p = createP(); + * p.position(5, 5); + * p.style('color', 'deeppink'); + * + * // Get the element's color as an + * // RGB color string. + * let c = p.style('color'); + * + * // Set the element's inner HTML + * // using the RGB color string. + * p.html(c); + * + * describe('The text "rgb(255, 20, 147)" written in pink on a gray background.'); + * } + * + *
      */ /** * @method style * @param {String} property - * @param {String|p5.Color} value value to assign to property - * @return {String} current value of property, if no value is given as second argument + * @param {String|p5.Color} value value to assign to the property. + * @return {String} value of the property. * @chainable */ _main.default.Element.prototype.style = function (prop, val) { @@ -72364,24 +77471,69 @@ return this; }; /** + * Adds an + * attribute + * to the element. This method is useful for advanced tasks. + * + * Most commonly-used attributes, such as `id`, can be set with their + * dedicated methods. For example, `nextButton.id('next')` sets an element's + * `id` attribute. * - * Adds a new attribute or changes the value of an existing attribute - * on the specified element. If no value is specified, returns the - * value of the given attribute, or null if the attribute is not set. + * The first parameter, `attr`, is the attribute's name as a string. Calling + * `myElement.attribute('align')` returns the attribute's current value as a + * string or `null` if it hasn't been set. + * + * The second parameter, `value`, is optional. It's a string used to set the + * attribute's value. For example, calling + * `myElement.attribute('align', 'center')` sets the element's horizontal + * alignment to `center`. * * @method attribute - * @return {String} value of attribute + * @return {String} value of the attribute. * * @example - *
      - * let myDiv = createDiv('I like pandas.'); - * myDiv.attribute('align', 'center'); - *
      + *
      + * + * function setup() { + * // Create a container div and + * // place it at the top-left + * // corner. + * let container = createDiv(); + * container.position(0, 0); + * + * // Create a paragraph element + * // and place it within the container. + * // Set its horizontal alignment to + * // "left". + * let p1 = createP('hi'); + * p1.parent(container); + * p1.attribute('align', 'left'); + * + * // Create a paragraph element + * // and place it within the container. + * // Set its horizontal alignment to + * // "center". + * let p2 = createP('hi'); + * p2.parent(container); + * p2.attribute('align', 'center'); + * + * // Create a paragraph element + * // and place it within the container. + * // Set its horizontal alignment to + * // "right". + * let p3 = createP('hi'); + * p3.parent(container); + * p3.attribute('align', 'right'); + * + * describe('A gray square with the text "hi" written on three separate lines, each placed further to the right.'); + * } + * + *
      */ /** * @method attribute - * @param {String} attr attribute to set - * @param {String} value value to assign to attribute + * @param {String} attr attribute to set. + * @param {String} value value to assign to the attribute. * @chainable */ _main.default.Element.prototype.attribute = function (attr, value) { @@ -72403,35 +77555,39 @@ } }; /** + * Removes an attribute from the element. * - * Removes an attribute on the specified element. + * The parameter `attr` is the attribute's name as a string. For example, + * calling `myElement.removeAttribute('align')` removes its `align` + * attribute if it's been set. * * @method removeAttribute - * @param {String} attr attribute to remove + * @param {String} attr attribute to remove. * @chainable * * @example - *
      - * let button; - * let checkbox; + *
      + * + * let p; * * function setup() { - * checkbox = createCheckbox('enable', true); - * checkbox.changed(enableButton); - * button = createButton('button'); - * button.position(10, 10); + * background(200); + * + * // Create a paragraph element and place it + * // in the center of the canvas. + * // Set its "align" attribute to "center". + * p = createP('hi'); + * p.position(0, 20); + * p.attribute('align', 'center'); + * + * describe('The text "hi" written in black at the center of a gray square. The text moves to the left edge when double-clicked.'); * } * - * function enableButton() { - * if (this.checked()) { - * // Re-enable the button - * button.removeAttribute('disabled'); - * } else { - * // Disable the button - * button.attribute('disabled', ''); - * } + * function doubleClicked() { + * p.removeAttribute('align'); * } - *
      + *
      + *
      */ _main.default.Element.prototype.removeAttribute = function (attr) { if (this.elt.firstChild != null && (this.elt.firstChild.type === 'checkbox' || this.elt.firstChild.type === 'radio')) { @@ -72443,34 +77599,68 @@ return this; }; /** - * Either returns the value of the element if no arguments - * given, or sets the value of the element. + * Returns or sets the element's value. + * + * Calling `myElement.value()` returns the element's current value. + * + * The parameter, `value`, is an optional number or string. If provided, + * as in `myElement.value(123)`, it's used to set the element's value. * * @method value - * @return {String|Number} value of the element + * @return {String|Number} value of the element. * @example - *
      - * // gets the value + *
      + * * let inp; + * * function setup() { - * inp = createInput(''); + * // Create a text input and place it + * // beneath the canvas. Set its default + * // value to "hello". + * inp = createInput('hello'); + * inp.position(0, 100); + * + * describe('The text from an input box is displayed on a gray square.'); * } * - * function mousePressed() { - * print(inp.value()); + * function draw() { + * background(200); + * + * // Use the input's value to display a message. + * let msg = inp.value(); + * text(msg, 0, 55); * } - *
      - *
      - * // sets the value + * + *
      + * + *
      + * * let inp; + * * function setup() { - * inp = createInput('myValue'); + * // Create a text input and place it + * // beneath the canvas. Set its default + * // value to "hello". + * inp = createInput('hello'); + * inp.position(0, 100); + * + * describe('The text from an input box is displayed on a gray square. The text resets to "hello" when the user double-clicks the square.'); * } * - * function mousePressed() { - * inp.value('myValue'); + * function draw() { + * background(200); + * + * // Use the input's value to display a message. + * let msg = inp.value(); + * text(msg, 0, 55); * } - *
      + * + * // Reset the input's value. + * function doubleClicked() { + * inp.value('hello'); + * } + *
      + *
      */ /** * @method value @@ -72479,7 +77669,7 @@ */ _main.default.Element.prototype.value = function () { if (arguments.length > 0) { - this.elt.value = arguments[0]; + this.elt.value = arguments.length <= 0 ? undefined : arguments[0]; return this; } else { if (this.elt.type === 'range') { @@ -72488,65 +77678,174 @@ } }; /** - * - * Shows the current element. Essentially, setting display:block for the style. + * Shows the current element. * * @method show * @chainable * @example - *
      - * let div = createDiv('div'); - * div.style('display', 'none'); - * div.show(); // turns display to block - *
      + *
      + * + * let p; + * + * function setup() { + * background(200); + * + * // Create a paragraph element and hide it. + * p = createP('p5*js'); + * p.position(10, 10); + * p.hide(); + * + * describe('A gray square. The text "p5*js" appears when the user double-clicks the square.'); + * } + * + * // Show the paragraph when double-clicked. + * function doubleClicked() { + * p.show(); + * } + * + *
      */ _main.default.Element.prototype.show = function () { this.elt.style.display = 'block'; return this; }; /** - * Hides the current element. Essentially, setting display:none for the style. + * Hides the current element. * * @method hide * @chainable * @example - *
      - * let div = createDiv('this is a div'); - * div.hide(); - *
      + * let p; + * + * function setup() { + * background(200); + * + * // Create a paragraph element. + * p = createP('p5*js'); + * p.position(10, 10); + * + * describe('The text "p5*js" at the center of a gray square. The text disappears when the user double-clicks the square.'); + * } + * + * // Hide the paragraph when double-clicked. + * function doubleClicked() { + * p.hide(); + * } + * + *
      */ _main.default.Element.prototype.hide = function () { this.elt.style.display = 'none'; return this; }; /** + * Sets the element's width and height. + * + * Calling `myElement.size()` without an argument returns the element's size + * as an object with the properties `width` and `height`. For example, + * `{ width: 20, height: 10 }`. + * + * The first parameter, `width`, is optional. It's a number used to set the + * element's width. Calling `myElement.size(10)` * - * Sets the width and height of the element. AUTO can be used to - * only adjust one dimension at a time. If no arguments are given, it - * returns the width and height of the element in an Object. In the case of - * elements that need to be loaded, such as images, it is recommended - * to call the function after the element has finished loading. + * The second parameter, 'height`, is also optional. It's a + * number used to set the element's height. For example, calling + * `myElement.size(20, 10)` sets the element's width to 20 pixels and height + * to 10 pixels. + * + * The constant `AUTO` can be used to adjust one dimension at a time while + * maintaining the aspect ratio, which is `width / height`. For example, + * consider an element that's 200 pixels wide and 100 pixels tall. Calling + * `myElement.size(20, AUTO)` sets the width to 20 pixels and height to 10 + * pixels. + * + * Note: In the case of elements that need to load data, such as images, wait + * to call `myElement.size()` until after the data loads. * * @method size - * @return {Object} the width and height of the element in an object + * @return {Object} width and height of the element in an object. * @example - *
      - * let div = createDiv('this is a div'); - * div.size(100, 100); - * let img = createImg( - * 'assets/rockies.jpg', - * 'A tall mountain with a small forest and field in front of it on a sunny day', - * '', - * () => { - * img.size(10, AUTO); - * } - * ); - *
      + *
      + * + * function setup() { + * background(200); + * + * // Create a pink div element and place it at + * // the top-left corner. + * let div = createDiv(); + * div.position(10, 10); + * div.style('background-color', 'deeppink'); + * + * // Set the div's width to 80 pixels and + * // height to 20 pixels. + * div.size(80, 20); + * + * describe('A gray square with a pink rectangle near its top.'); + * } + * + *
      + * + *
      + * + * function setup() { + * background(200); + * + * // Create a pink div element and place it at + * // the top-left corner. + * let div = createDiv(); + * div.position(10, 10); + * div.style('background-color', 'deeppink'); + * + * // Set the div's width to 80 pixels and + * // height to 40 pixels. + * div.size(80, 40); + * + * // Get the div's size as an object. + * let s = div.size(); + * // Write the div's dimensions. + * div.html(`${s.width} x ${s.height}`); + * + * describe('A gray square with a pink rectangle near its top. The text "80 x 40" is written within the rectangle.'); + * } + * + *
      + * + *
      + * + * function setup() { + * background(200); + * + * // Load an image of an astronaut on the moon + * // and place it at the top-left of the canvas. + * let img1 = createImg( + * 'assets/moonwalk.jpg', + * 'An astronaut walking on the moon', + * '' + * ); + * img1.position(0, 0); + * + * // Load an image of an astronaut on the moon + * // and place it at the top-left of the canvas. + * // Resize the image once it's loaded. + * let img2 = createImg( + * 'assets/moonwalk.jpg', + * 'An astronaut walking on the moon', + * '', + * () => { + * img2.size(50, AUTO); + * } + * ); + * img2.position(0, 0); + * + * describe('A gray square two copies of a space image at the top-left. The copy in front is smaller.'); + * } + * + *
      */ /** * @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 + * @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) { @@ -72564,7 +77863,7 @@ aW = h * this.width / this.height; } else if (aH === AUTO) { aH = w * this.height / this.width; - } // set diff for cnv vs normal div + } // set diff for cnv vs normal div if (this.elt instanceof HTMLCanvasElement) { var j = { @@ -72602,13 +77901,31 @@ } }; /** - * Removes the element, stops all media streams, and deregisters all listeners. + * Removes the element, stops all audio/video streams, and removes all + * callback functions. + * * @method remove * @example - *
      - * let myDiv = createDiv('this is some text'); - * myDiv.remove(); - *
      + *
      + * + * let p; + * + * function setup() { + * background(200); + * + * // Create a paragraph element. + * p = createP('p5*js'); + * p.position(10, 10); + * + * describe('The text "p5*js" written at the center of a gray square. '); + * } + * + * // Remove the paragraph when double-clicked. + * function doubleClicked() { + * p.remove(); + * } + * + *
      */ _main.default.Element.prototype.remove = function () { // stop all audios/videos and detach all devices like microphone/camera etc @@ -72622,12 +77939,12 @@ track.stop(); }); } - } // delete the reference in this._pInst._elements + } // 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 + } // deregister events for (var ev in this._events) { this.elt.removeEventListener(ev, this._events[ev]); @@ -72637,63 +77954,115 @@ } }; /** - * 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. + * Sets a function to call when the user drops a file on the element. + * + * The first parameter, `callback`, is a function to call once the file loads. + * The callback function should have one parameter, `file`, that's a + * p5.File object. If the user drops multiple files on + * the element, `callback`, is called once for each file. * - * You can optionally pass a second callback which will be registered to the raw - * drop event. - * The callback will thus be provided the original + * The second parameter, `fxn`, is a function to call when the browser detects + * one or more dropped files. The callback function should have one + * parameter, `event`, that's a * DragEvent. - * 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. + * @param {Function} callback called when a file loads. Called once for each file dropped. + * @param {Function} [fxn] called once when any files are dropped. * @chainable * @example - *
      + *
      + * + * // Drop an image on the canvas to view + * // this example. + * let img; + * * function setup() { * let c = createCanvas(100, 100); - * background(200); - * 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); + * + * // Call a function when a file + * // dropped on the canvas has + * // loaded. + * c.drop(file => { + * // Remove the current image, if any. + * if (img) { + * img.remove(); + * } + * + * // Create an element with the + * // dropped file. + * img = createImg(file.data, ''); + * img.hide(); + * + * // Draw the image. + * image(img, 0, 0, width, height); + * }); + * + * describe('A gray square. When the user drops an image on the square, it is displayed.'); * } - *
      + *
      + *
      * - *
      + *
      + * + * // Drop an image on the canvas to view + * // this example. * let img; + * let msg; * * function setup() { * let c = createCanvas(100, 100); + * * background(200); - * textAlign(CENTER); - * text('drop image', width / 2, height / 2); - * c.drop(gotFile); + * + * // Call functions when the user + * // drops a file on the canvas + * // and when the file loads. + * c.drop(handleFile, handleDrop); + * + * describe('A gray square. When the user drops an image on the square, it is displayed. The id attribute of canvas element is also displayed.'); * } * - * function draw() { + * function handleFile(file) { + * // Remove the current image, if any. * if (img) { - * image(img, 0, 0, width, height); + * img.remove(); * } - * } * - * function gotFile(file) { - * img = createImg(file.data, '').hide(); + * // Create an element with the + * // dropped file. + * img = createImg(file.data, ''); + * img.hide(); + * + * // Draw the image. + * image(img, 0, 0, width, height); * } - *
      * - * @alt - * Canvas turns into whatever image is dragged/dropped onto it. + * function handleDrop(event) { + * // Remove current paragraph, if any. + * if (msg) { + * msg.remove(); + * } + * + * // Use event to get the drop + * // target's id. + * let id = event.target.id; + * + * // Write the canvas' id + * // beneath it. + * msg = createP(id); + * msg.position(0, 100); + * + * // Set the font color + * // randomly for each drop. + * let c = random(['red', 'green', 'blue']); + * msg.style('color', c); + * msg.style('font-size', '12px'); + * } + *
      + *
      */ _main.default.Element.prototype.drop = function (callback, fxn) { // Is the file stuff supported? @@ -72702,1268 +78071,1878 @@ this._dragDisabled = true; var preventDefault = function preventDefault(evt) { evt.preventDefault(); - }; // If you want to be able to drop you've got to turn off + }; + // 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('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 + } // 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 + 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 + } // 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); + var files = evt.dataTransfer.files; + // Load each one and trigger the callback + var _iteratorNormalCompletion10 = true; + var _didIteratorError10 = false; + var _iteratorError10 = undefined; + try { + for (var _iterator10 = files[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) { + var f = _step10.value; + _main.default.File._load(f, callback); + } + } catch (err) { + _didIteratorError10 = true; + _iteratorError10 = err; + } finally { + try { + if (!_iteratorNormalCompletion10 && _iterator10.return != null) { + _iterator10.return(); + } + } finally { + if (_didIteratorError10) { + throw _iteratorError10; + } + } } }, this); } else { console.log('The File APIs are not fully supported in this browser.'); } return this; - }; // ============================================================================= - // p5.MediaElement additions - // ============================================================================= - /** - * Extends p5.Element to handle audio and video. In addition to the methods - * of p5.Element, it also contains methods for controlling media. It is not - * called directly, but p5.MediaElements are created by calling createVideo, - * createAudio, and createCapture. - * - * @class p5.MediaElement - * @constructor - * @param {String} elt DOM node that is wrapped - */ - _main.default.MediaElement = function (elt, pInst) { - _main.default.Element.call(this, elt, pInst); - var self = this; - this.elt.crossOrigin = 'anonymous'; - this._prevTime = 0; - this._cueIDCounter = 0; - this._cues = [ - ]; - this._pixelsState = this; - this._pixelDensity = 1; - this._modified = false; - /** - * Path to the media element source. - * - * @property src - * @return {String} src - * @example - *
      - * let ele; - * - * function setup() { - * background(250); - * - * //p5.MediaElement objects are usually created - * //by calling the createAudio(), createVideo(), - * //and createCapture() functions. - * - * //In this example we create - * //a new p5.MediaElement via createAudio(). - * ele = createAudio('assets/beat.mp3'); - * - * //We'll set up our example so that - * //when you click on the text, - * //an alert box displays the MediaElement's - * //src field. - * textAlign(CENTER); - * text('Click Me!', width / 2, height / 2); - * } - * - * function mouseClicked() { - * //here we test if the mouse is over the - * //canvas element when it's clicked - * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) { - * //Show our p5.MediaElement's src field - * alert(ele.src); - * } - * } - *
      - */ - Object.defineProperty(self, 'src', { - get: function get() { - var firstChildSrc = self.elt.children[0].src; - var srcVal = self.elt.src === window.location.href ? '' : self.elt.src; - var ret = firstChildSrc === window.location.href ? srcVal : firstChildSrc; - return ret; - }, - set: function set(newValue) { - for (var i = 0; i < self.elt.children.length; i++) { - self.elt.removeChild(self.elt.children[i]); - } - var source = document.createElement('source'); - source.src = newValue; - elt.appendChild(source); - self.elt.src = newValue; - self.modified = true; - } - }); // private _onended callback, set by the method: onended(callback) - self._onended = function () { - }; - self.elt.onended = function () { - self._onended(self); - }; }; - _main.default.MediaElement.prototype = Object.create(_main.default.Element.prototype); /** - * Play an HTML5 media element. + * Turns p5.Element into a draggable item. If an argument is given, it will drag that p5.Element instead, ie. drag a entire GUI panel (parent container) with the panel's title bar. * - * @method play + * @method draggable + * @param {p5.Element} [elmnt] pass another p5.Element * @chainable - * @example - *
      - * let ele; - * - * function setup() { - * //p5.MediaElement objects are usually created - * //by calling the createAudio(), createVideo(), - * //and createCapture() functions. - * - * //In this example we create - * //a new p5.MediaElement via createAudio(). - * ele = createAudio('assets/beat.mp3'); - * - * background(250); - * textAlign(CENTER); - * text('Click to Play!', width / 2, height / 2); - * } - * - * function mouseClicked() { - * //here we test if the mouse is over the - * //canvas element when it's clicked - * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) { - * //Here we call the play() function on - * //the p5.MediaElement we created above. - * //This will start the audio sample. - * ele.play(); - * - * background(200); - * text('You clicked Play!', width / 2, height / 2); - * } - * } - *
      - */ - _main.default.MediaElement.prototype.play = function () { - var _this = this; - if (this.elt.currentTime === this.elt.duration) { - this.elt.currentTime = 0; - } - var promise; - if (this.elt.readyState > 1) { - promise = this.elt.play(); - } else { - // in Chrome, playback cannot resume after being stopped and must reload - this.elt.load(); - promise = this.elt.play(); - } - if (promise && promise.catch) { - promise.catch(function (e) { - // if it's an autoplay failure error - if (e.name === 'NotAllowedError') { - if (typeof IS_MINIFIED === 'undefined') { - _main.default._friendlyAutoplayError(_this.src); - } else { - console.error(e); - } - } else { - // any other kind of error - console.error('Media play method encountered an unexpected error', e); - } - }); - } - return this; - }; - /** - * Stops an HTML5 media element (sets current time to zero). * - * @method stop - * @chainable * @example *
      - * //This example both starts - * //and stops a sound sample - * //when the user clicks the canvas - * - * //We will store the p5.MediaElement - * //object in here - * let ele; - * - * //while our audio is playing, - * //this will be set to true - * let sampleIsPlaying = false; - * * function setup() { - * //Here we create a p5.MediaElement object - * //using the createAudio() function. - * ele = createAudio('assets/beat.mp3'); + * createCanvas(100, 100); * 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); - * } - * } + * createDiv('Post-It') + * .position(5, 5) + * .size(75, 20) + * .style('font-size', '16px') + * .style('background', 'yellow') + * .style('color', '#000') + * .style('border', '1px solid #aaaa00') + * .style('padding', '5px') + * .draggable(); + * // .style('cursor', 'help') // override cursor + * + * let gui = createDiv('') + * .position(5, 40) + * .size(85, 50) + * .style('font-size', '16px') + * .style('background', 'yellow') + * .style('z-index', '100') + * .style('border', '1px solid #00aaaa'); + * + * createDiv('= PANEL =') + * .parent(gui) + * .style('background', 'cyan') + * .style('padding', '2px') + * .style('text-align', 'center') + * .draggable(gui); + * + * createSlider(0, 100, random(100)) + * .style('cursor', 'pointer') + * .size(80, 5) + * .parent(gui); * } *
      */ - _main.default.MediaElement.prototype.stop = function () { - this.elt.pause(); - this.elt.currentTime = 0; + _main.default.Element.prototype.draggable = function (elmMove) { + var isTouch = ('ontouchstart' in window); + var x = 0, + y = 0, + px = 0, + py = 0, + elmDrag, + dragMouseDownEvt = isTouch ? 'touchstart' : 'mousedown', + closeDragElementEvt = isTouch ? 'touchend' : 'mouseup', + elementDragEvt = isTouch ? 'touchmove' : 'mousemove'; + if (elmMove === undefined) { + elmMove = this.elt; + elmDrag = elmMove; + } else if (elmMove !== this.elt && elmMove.elt !== this.elt) { + elmMove = elmMove.elt; + elmDrag = this.elt; + } + elmDrag.addEventListener(dragMouseDownEvt, dragMouseDown, false); + elmDrag.style.cursor = 'move'; + function dragMouseDown(e) { + e = e || window.event; + if (isTouch) { + var touches = e.changedTouches; + px = parseInt(touches[0].clientX); + py = parseInt(touches[0].clientY); + } else { + px = parseInt(e.clientX); + py = parseInt(e.clientY); + } + document.addEventListener(closeDragElementEvt, closeDragElement, false); + document.addEventListener(elementDragEvt, elementDrag, false); + return false; + } + function elementDrag(e) { + e = e || window.event; + if (isTouch) { + var touches = e.changedTouches; + x = px - parseInt(touches[0].clientX); + y = py - parseInt(touches[0].clientY); + px = parseInt(touches[0].clientX); + py = parseInt(touches[0].clientY); + } else { + x = px - parseInt(e.clientX); + y = py - parseInt(e.clientY); + px = parseInt(e.clientX); + py = parseInt(e.clientY); + } + elmMove.style.left = elmMove.offsetLeft - x + 'px'; + elmMove.style.top = elmMove.offsetTop - y + 'px'; + } + function closeDragElement() { + document.removeEventListener(closeDragElementEvt, closeDragElement, false); + document.removeEventListener(elementDragEvt, elementDrag, false); + } return this; }; + /*** SCHEDULE EVENTS ***/ + // Cue inspired by JavaScript setTimeout, and the + // Tone.js Transport Timeline Event, MIT License Yotam Mann 2015 tonejs.org + // eslint-disable-next-line no-unused-vars + var Cue = function Cue(callback, time, id, val) { + _classCallCheck(this, Cue); + this.callback = callback; + this.time = time; + this.id = id; + this.val = val; + }; // ============================================================================= + // p5.MediaElement additions + // ============================================================================= /** - * Pauses an HTML5 media element. - * - * @method pause - * @chainable - * @example - *
      - * //This example both starts - * //and pauses a sound sample - * //when the user clicks the canvas + * A class to handle audio and video. * - * //We will store the p5.MediaElement - * //object in here - * let ele; - * - * //while our audio is playing, - * //this will be set to true - * let sampleIsPlaying = false; - * - * function setup() { - * //Here we create a p5.MediaElement object - * //using the createAudio() function. - * ele = createAudio('assets/lucky_dragons.mp3'); - * background(200); - * textAlign(CENTER); - * text('Click to play!', width / 2, height / 2); - * } - * - * function mouseClicked() { - * //here we test if the mouse is over the - * //canvas element when it's clicked - * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) { - * background(200); - * - * if (sampleIsPlaying) { - * //Calling pause() on our - * //p5.MediaElement will stop it - * //playing, but when we call the - * //loop() or play() functions - * //the sample will start from - * //where we paused it. - * ele.pause(); - * - * sampleIsPlaying = false; - * text('Click to resume!', width / 2, height / 2); - * } else { - * //loop our sound element until we - * //call ele.pause() on it. - * ele.loop(); - * - * sampleIsPlaying = true; - * text('Click to pause!', width / 2, height / 2); - * } - * } - * } - *
      - */ - _main.default.MediaElement.prototype.pause = function () { - this.elt.pause(); - return this; - }; - /** - * Set 'loop' to true for an HTML5 media element, and starts playing. + * `p5.MediaElement` extends p5.Element with + * methods to handle audio and video. `p5.MediaElement` objects are created by + * calling createVideo, + * createAudio, and + * createCapture. * - * @method loop - * @chainable + * @class p5.MediaElement + * @constructor + * @param {String} elt DOM node that is wrapped + * @extends p5.Element * @example - *
      - * //Clicking the canvas will loop - * //the audio sample until the user - * //clicks again to stop it - * - * //We will store the p5.MediaElement - * //object in here - * let ele; - * - * //while our audio is playing, - * //this will be set to true - * let sampleIsLooping = false; + *
      + * + * let capture; * * function setup() { - * //Here we create a p5.MediaElement object - * //using the createAudio() function. - * ele = createAudio('assets/lucky_dragons.mp3'); - * background(200); - * textAlign(CENTER); - * text('Click to loop!', width / 2, height / 2); - * } - * - * function mouseClicked() { - * //here we test if the mouse is over the - * //canvas element when it's clicked - * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) { - * background(200); - * - * if (!sampleIsLooping) { - * //loop our sound element until we - * //call ele.stop() on it. - * ele.loop(); - * - * sampleIsLooping = true; - * text('Click to stop!', width / 2, height / 2); - * } else { - * ele.stop(); - * - * sampleIsLooping = false; - * text('Click to loop!', width / 2, height / 2); - * } - * } - * } - *
      - */ - _main.default.MediaElement.prototype.loop = function () { - this.elt.setAttribute('loop', true); - this.play(); - return this; - }; - /** - * Set 'loop' to false for an HTML5 media element. Element will stop - * when it reaches the end. - * - * @method noLoop - * @chainable - * @example - *
      - * //This example both starts - * //and stops loop of sound sample - * //when the user clicks the canvas - * - * //We will store the p5.MediaElement - * //object in here - * let ele; - * //while our audio is playing, - * //this will be set to true - * let sampleIsPlaying = false; + * createCanvas(100, 100); * - * 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); + * // Create a p5.MediaElement using createCapture(). + * capture = createCapture(VIDEO); + * capture.hide(); * } * - * 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); - * } - * } + * function draw() { + * // Display the video stream and invert the colors. + * image(capture, 0, 0, width, width * capture.height / capture.width); + * filter(INVERT); * } - *
      - */ - _main.default.MediaElement.prototype.noLoop = function () { - this.elt.removeAttribute('loop'); - return this; - }; - /** - * Sets up logic to check that autoplay succeeded. - * - * @method setupAutoplayFailDetection - * @private + *
      + *
      */ - _main.default.MediaElement.prototype._setupAutoplayFailDetection = function () { - var _this2 = this; - var timeout = setTimeout(function () { - if (typeof IS_MINIFIED === 'undefined') { - _main.default._friendlyAutoplayError(_this2.src); - } else { - console.error(e); - } - }, 500); - this.elt.addEventListener('play', function () { - return clearTimeout(timeout); - }, { - passive: true, - once: true - }); - }; - /** - * Set HTML5 media element to autoplay or not. If no argument is specified, by - * default it will autoplay. - * - * @method autoplay - * @param {Boolean} shouldAutoplay whether the element should autoplay - * @chainable - * @example - *
      - * let videoElement; - * function setup() { - * noCanvas(); - * videoElement = createVideo(['assets/small.mp4'], onVideoLoad); - * } - * function onVideoLoad() { - * // The media will play as soon as it is loaded. - * videoElement.autoplay(); - * videoElement.volume(0); - * videoElement.size(100, 100); - * } - *
      - * - *
      - * let videoElement; - * function setup() { - * noCanvas(); - * videoElement = createVideo(['assets/small.mp4'], onVideoLoad); - * } - * function onVideoLoad() { - * // The media will not play until some explicitly triggered. - * videoElement.autoplay(false); - * videoElement.volume(0); - * videoElement.size(100, 100); - * } - * - * function mouseClicked() { - * videoElement.play(); - * } - *
      - * - * @alt - * An example of a video element which autoplays after it is loaded. - * An example of a video element which waits for a trigger for playing. - */ - _main.default.MediaElement.prototype.autoplay = function (val) { - var _this3 = this; - var oldVal = this.elt.getAttribute('autoplay'); - this.elt.setAttribute('autoplay', val); // if we turned on autoplay - if (val && !oldVal) { - // bind method to this scope - var setupAutoplayFailDetection = function setupAutoplayFailDetection() { - return _this3._setupAutoplayFailDetection(); - }; // if media is ready to play, schedule check now - if (this.elt.readyState === 4) { - setupAutoplayFailDetection(); - } else { - // otherwise, schedule check whenever it is ready - this.elt.addEventListener('canplay', setupAutoplayFailDetection, { - passive: true, - once: true - }); - } - } - return this; - }; + var MediaElement = /*#__PURE__*/ function (_p5$Element) { + _inherits(MediaElement, _p5$Element); + var _super = _createSuper(MediaElement); + function MediaElement(elt, pInst) { + var _this; + _classCallCheck(this, MediaElement); + _this = _super.call(this, elt, pInst); + var self = _assertThisInitialized(_this); + _this.elt.crossOrigin = 'anonymous'; + _this._prevTime = 0; + _this._cueIDCounter = 0; + _this._cues = [ + ]; + _this.pixels = [ + ]; + _this._pixelsState = _assertThisInitialized(_this); + _this._pixelDensity = 1; + _this._modified = false; + // Media has an internal canvas that is used when drawing it to the main + // canvas. It will need to be updated each frame as the video itself plays. + // We don't want to update it every time we draw, however, in case the user + // has used load/updatePixels. To handle this, we record the frame drawn to + // the internal canvas so we only update it if the frame has changed. + _this._frameOnCanvas = - 1; + /** + * Path to the media element's source as a string. + * + * @property src + * @return {String} src + * @example + *
      + * + * let beat; + * + * function setup() { + * // Create a p5.MediaElement using createAudio(). + * beat = createAudio('assets/beat.mp3'); + * + * describe('The text "https://p5js.org/reference/assets/beat.mp3" written in black on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * textWrap(CHAR); + * text(beat.src, 10, 10, 80, 80); + * } + * + *
      + */ + Object.defineProperty(self, 'src', { + get: function get() { + var firstChildSrc = self.elt.children[0].src; + var srcVal = self.elt.src === window.location.href ? '' : self.elt.src; + var ret = firstChildSrc === window.location.href ? srcVal : firstChildSrc; + return ret; + }, + set: function set(newValue) { + for (var i = 0; i < self.elt.children.length; i++) { + self.elt.removeChild(self.elt.children[i]); + } + var source = document.createElement('source'); + source.src = newValue; + elt.appendChild(source); + self.elt.src = newValue; + self.modified = true; + } + }); + // private _onended callback, set by the method: onended(callback) + self._onended = function () { + }; + self.elt.onended = function () { + self._onended(self); + }; + return _this; + } /** + * Play audio or video from a media element. + * + * @method play + * @chainable + * @example + *
      + * + * let beat; + * + * function setup() { + * background(200); + * + * textAlign(CENTER); + * text('Click to play', 50, 50); + * + * // Create a p5.MediaElement using createAudio(). + * beat = createAudio('assets/beat.mp3'); + * + * describe('The text "Click to play" written in black on a gray background. A beat plays when the user clicks the square.'); + * } + * + * // Play the beat when the user + * // presses the mouse. + * function mousePressed() { + * beat.play(); + * } + * + *
      + */ + + _createClass(MediaElement, [ + { + key: 'play', + value: function play() { + var _this2 = this; + if (this.elt.currentTime === this.elt.duration) { + this.elt.currentTime = 0; + } + var promise; + if (this.elt.readyState > 1) { + promise = this.elt.play(); + } else { + // in Chrome, playback cannot resume after being stopped and must reload + this.elt.load(); + promise = this.elt.play(); + } + if (promise && promise.catch) { + promise.catch(function (e) { + // if it's an autoplay failure error + if (e.name === 'NotAllowedError') { + if (typeof IS_MINIFIED === 'undefined') { + _main.default._friendlyAutoplayError(_this2.src); + } else { + console.error(e); + } + } else { + // any other kind of error + console.error('Media play method encountered an unexpected error', e); + } + }); + } + return this; + } /** + * Stops a media element and sets its current time to zero. Calling + * `media.play()` will restart playing audio/video from the beginning. + * + * @method stop + * @chainable + * @example + *
      + * + * let beat; + * let isStopped = true; + * + * function setup() { + * // Create a p5.MediaElement using createAudio(). + * beat = createAudio('assets/beat.mp3'); + * + * describe('The text "Click to start" written in black on a gray background. The beat starts or stops when the user presses the mouse.'); + * } + * + * function draw() { + * background(200); + * + * textAlign(CENTER); + * if (isStopped === true) { + * text('Click to start', 50, 50); + * } else { + * text('Click to stop', 50, 50); + * } + * } + * + * // Adjust playback when the user + * // presses the mouse. + * function mousePressed() { + * if (isStopped === true) { + * // If the beat is stopped, + * // play it. + * beat.play(); + * isStopped = false; + * } else { + * // If the beat is playing, + * // stop it. + * beat.stop(); + * isStopped = true; + * } + * } + * + *
      + */ + + }, + { + key: 'stop', + value: function stop() { + this.elt.pause(); + this.elt.currentTime = 0; + return this; + } /** + * Pauses a media element. Calling `media.play()` will resume playing + * audio/video from the moment it paused. + * + * @method pause + * @chainable + * @example + *
      + * + * let beat; + * let isPaused = true; + * + * function setup() { + * // Create a p5.MediaElement using createAudio(). + * beat = createAudio('assets/beat.mp3'); + * + * describe('The text "Click to play" written in black on a gray background. The beat plays or pauses when the user clicks the square.'); + * } + * + * function draw() { + * background(200); + * + * // Display different instructions + * // based on playback. + * textAlign(CENTER); + * if (isPaused === true) { + * text('Click to play', 50, 50); + * } else { + * text('Click to pause', 50, 50); + * } + * } + * + * // Adjust playback when the user + * // presses the mouse. + * function mousePressed() { + * if (isPaused === true) { + * // If the beat is paused, + * // play it. + * beat.play(); + * isPaused = false; + * } else { + * // If the beat is playing, + * // pause it. + * beat.pause(); + * isPaused = true; + * } + * } + * + *
      + */ + + }, + { + key: 'pause', + value: function pause() { + this.elt.pause(); + return this; + } /** + * Play the audio/video repeatedly in a loop. + * + * @method loop + * @chainable + * @example + *
      + * + * let beat; + * let isLooping = false; + * + * function setup() { + * background(200); + * + * // Create a p5.MediaElement using createAudio(). + * beat = createAudio('assets/beat.mp3'); + * + * describe('The text "Click to loop" written in black on a gray background. A beat plays repeatedly in a loop when the user clicks. The beat stops when the user clicks again.'); + * } + * + * function draw() { + * background(200); + * + * // Display different instructions + * // based on playback. + * textAlign(CENTER); + * if (isLooping === true) { + * text('Click to stop', 50, 50); + * } else { + * text('Click to loop', 50, 50); + * } + * } + * + * // Adjust playback when the user + * // presses the mouse. + * function mousePressed() { + * if (isLooping === true) { + * // If the beat is looping, + * // stop it. + * beat.stop(); + * isLooping = false; + * } else { + * // If the beat is stopped, + * // loop it. + * beat.loop(); + * isLooping = true; + * } + * } + * + *
      + */ + + }, + { + key: 'loop', + value: function loop() { + this.elt.setAttribute('loop', true); + this.play(); + return this; + } /** + * Stops the audio/video from playing in a loop. It will stop when it + * reaches the end. + * + * @method noLoop + * @chainable + * @example + *
      + * + * let beat; + * let isPlaying = false; + * + * function setup() { + * background(200); + * + * // Create a p5.MediaElement using createAudio(). + * beat = createAudio('assets/beat.mp3'); + * + * describe('The text "Click to play" written in black on a gray background. A beat plays when the user clicks. The beat stops when the user clicks again.'); + * } + * + * function draw() { + * background(200); + * + * // Display different instructions + * // based on playback. + * textAlign(CENTER); + * if (isPlaying === true) { + * text('Click to stop', 50, 50); + * } else { + * text('Click to play', 50, 50); + * } + * } + * + * // Adjust playback when the user + * // presses the mouse. + * function mousePressed() { + * if (isPlaying === true) { + * // If the beat is playing, + * // stop it. + * beat.stop(); + * isPlaying = false; + * } else { + * // If the beat is stopped, + * // play it. + * beat.play(); + * isPlaying = true; + * } + * } + * + *
      + */ + + }, + { + key: 'noLoop', + value: function noLoop() { + this.elt.removeAttribute('loop'); + return this; + } /** + * Sets up logic to check that autoplay succeeded. + * + * @method setupAutoplayFailDetection + * @private + */ + + }, + { + key: '_setupAutoplayFailDetection', + value: function _setupAutoplayFailDetection() { + var _this3 = this; + var timeout = setTimeout(function () { + if (typeof IS_MINIFIED === 'undefined') { + _main.default._friendlyAutoplayError(_this3.src); + } else { + console.error(e); + } + }, 500); + this.elt.addEventListener('play', function () { + return clearTimeout(timeout); + }, { + passive: true, + once: true + }); + } /** + * Sets the audio/video to play once it's loaded. + * + * The parameter, `shouldAutoplay`, is optional. Calling + * `media.autoplay()` without an argument causes the media to play + * automatically. If `true` is passed, as in `media.autoplay(true)`, the + * media will automatically play. If `false` is passed, as in + * `media.autoPlay(false)`, it won't play automatically. + * + * @method autoplay + * @param {Boolean} [shouldAutoplay] whether the element should autoplay. + * @chainable + * @example + *
      + * + * function setup() { + * noCanvas(); + * + * // Load a video and play it automatically. + * let video = createVideo('assets/fingers.mov', () => { + * video.autoplay(); + * video.size(100, 100); + * }); + * + * describe('A video of fingers walking on a treadmill.'); + * } + * + *
      + * + *
      + * + * function setup() { + * noCanvas(); + * + * // Load a video, but don't play it automatically. + * let video = createVideo('assets/fingers.mov', () => { + * video.autoplay(false); + * video.size(100, 100); + * }); + * + * // Play the video when the user clicks on it. + * video.mousePressed(() => { + * video.play(); + * }); + * + * describe('An image of fingers on a treadmill. They start walking when the user double-clicks on them.'); + * } + * + *
      + */ + + }, + { + key: 'autoplay', + value: function autoplay(val) { + var _this4 = this; + var oldVal = this.elt.getAttribute('autoplay'); + this.elt.setAttribute('autoplay', val); + // if we turned on autoplay + if (val && !oldVal) { + // bind method to this scope + var setupAutoplayFailDetection = function setupAutoplayFailDetection() { + return _this4._setupAutoplayFailDetection(); + }; + // if media is ready to play, schedule check now + if (this.elt.readyState === 4) { + setupAutoplayFailDetection(); + } else { + // otherwise, schedule check whenever it is ready + this.elt.addEventListener('canplay', setupAutoplayFailDetection, { + passive: true, + once: true + }); + } + } + return this; + } /** + * Manages the audio/video volume. + * + * Calling `media.volume()` without an argument returns the current volume + * as a number in the range 0 (off) to 1 (maximum). + * + * The parameter, `val`, is optional. It's a number that sets the volume + * from 0 (off) to 1 (maximum). For example, calling `media.volume(0.5)` + * sets the volume to half of its maximum. + * + * @method volume + * @return {Number} current volume. + * + * @example + *
      + * + * let dragon; + * + * function setup() { + * // Create a p5.MediaElement using createAudio(). + * dragon = createAudio('assets/lucky_dragons.mp3'); + * // Show the default media controls. + * dragon.showControls(); + * + * describe('The text "Volume: V" on a gray square with media controls beneath it. The number "V" oscillates between 0 and 1 as the music plays.'); + * } + * + * function draw() { + * background(200); + * + * // Produce a number between 0 and 1. + * let n = 0.5 * sin(frameCount * 0.01) + 0.5; + * // Use n to set the volume. + * dragon.volume(n); + * + * // Get the current volume + * // and display it. + * let v = dragon.volume(); + * // Round v to 1 decimal place + * // for display. + * v = round(v, 1); + * textAlign(CENTER); + * text(`Volume: ${v}`, 50, 50); + * } + * + *
      + */ + /** + * @method volume + * @param {Number} val volume between 0.0 and 1.0. + * @chainable + */ + + }, + { + key: 'volume', + value: function volume(val) { + if (typeof val === 'undefined') { + return this.elt.volume; + } else { + this.elt.volume = val; + } + } /** + * Manages the audio/video playback speed. Calling `media.speed()` returns + * the current speed as a number. + * + * The parameter, `val`, is optional. It's a number that sets the playback + * speed. 1 plays the media at normal speed, 0.5 plays it at half speed, 2 + * plays it at double speed, and so on. -1 plays the media at normal speed + * in reverse. + * + * Note: Not all browsers support backward playback. Even if they do, + * playback might not be smooth. + * + * @method speed + * @return {Number} current playback speed. + * + * @example + *
      + * + * let dragon; + * + * function setup() { + * // Create a p5.MediaElement using createAudio(). + * dragon = createAudio('assets/lucky_dragons.mp3'); + * + * // Show the default media controls. + * dragon.showControls(); + * + * describe('The text "Speed: S" on a gray square with media controls beneath it. The number "S" oscillates between 0 and 1 as the music plays.'); + * } + * + * function draw() { + * background(200); + * + * // Produce a number between 0 and 2. + * let n = sin(frameCount * 0.01) + 1; + * // Use n to set the playback speed. + * dragon.speed(n); + * + * // Get the current speed + * // and display it. + * let s = dragon.speed(); + * // Round s to 1 decimal place + * // for display. + * s = round(s, 1); + * textAlign(CENTER); + * text(`Speed: ${s}`, 50, 50); + * } + * + */ + /** + * @method speed + * @param {Number} speed speed multiplier for playback. + * @chainable + */ + + }, + { + key: 'speed', + value: function speed(val) { + if (typeof val === 'undefined') { + return this.presetPlaybackRate || this.elt.playbackRate; + } else { + if (this.loadedmetadata) { + this.elt.playbackRate = val; + } else { + this.presetPlaybackRate = val; + } + } + } /** + * Manages the media element's playback time. Calling `media.time()` + * returns the number of seconds the audio/video has played. Time resets to + * 0 when the looping media restarts. + * + * The parameter, `time`, is optional. It's a number that specifies the + * time, in seconds, to jump to when playback begins. + * + * @method time + * @return {Number} current time (in seconds). + * + * @example + *
      + * + * let dragon; + * + * function setup() { + * // Create a p5.MediaElement using createAudio(). + * dragon = createAudio('assets/lucky_dragons.mp3'); + * // Show the default media controls. + * dragon.showControls(); + * + * describe('The text "S seconds" on a gray square with media controls beneath it. The number "S" increases as the song plays.'); + * } + * + * function draw() { + * background(200); + * + * // Display the current time. + * let s = dragon.time(); + * // Round s to 1 decimal place + * // for display. + * s = round(s, 1); + * textAlign(CENTER); + * text(`${s} seconds`, 50, 50); + * } + * + *
      + * + *
      + * + * let dragon; + * + * function setup() { + * // Create a p5.MediaElement using createAudio(). + * dragon = createAudio('assets/lucky_dragons.mp3'); + * // Show the default media controls. + * dragon.showControls(); + * + * // Jump to 2 seconds + * // to start. + * dragon.time(2); + * + * describe('The text "S seconds" on a gray square with media controls beneath it. The number "S" increases as the song plays.'); + * } + * + * function draw() { + * background(200); + * + * // Display the current time. + * let s = dragon.time(); + * // Round s to 1 decimal place + * // for display. + * s = round(s, 1); + * textAlign(CENTER); + * text(`${s} seconds`, 50, 50); + * } + * + *
      + */ + /** + * @method time + * @param {Number} time time to jump to (in seconds). + * @chainable + */ + + }, + { + key: 'time', + value: function time(val) { + if (typeof val === 'undefined') { + return this.elt.currentTime; + } else { + this.elt.currentTime = val; + return this; + } + } /** + * Returns the audio/video's duration in seconds. + * + * @method duration + * @return {Number} duration (in seconds). + * + * @example + *
      + * + * let dragon; + * + * function setup() { + * background(200); + * + * // Create a p5.MediaElement using createAudio(). + * dragon = createAudio('assets/lucky_dragons.mp3'); + * // Show the default media controls. + * dragon.showControls(); + * + * describe('The text "S seconds left" on a gray square with media controls beneath it. The number "S" decreases as the song plays.'); + * } + * + * function draw() { + * background(200); + * + * // Calculate the time remaining. + * let s = dragon.duration() - dragon.time(); + * // Round s to 1 decimal place + * // for display. + * s = round(s, 1); + * + * // Display the time remaining. + * textAlign(CENTER); + * text(`${s} seconds left`, 50, 50); + * } + * + *
      + */ + + }, + { + key: 'duration', + value: function duration() { + return this.elt.duration; + } + }, + { + key: '_ensureCanvas', + value: function _ensureCanvas() { + if (!this.canvas) { + this.canvas = document.createElement('canvas'); + this.drawingContext = this.canvas.getContext('2d'); + this.setModified(true); + } // Don't update the canvas again if we have already updated the canvas with + // the current frame + + var needsRedraw = this._frameOnCanvas !== this._pInst.frameCount; + if (this.loadedmetadata && needsRedraw) { + // wait for metadata for w/h + if (this.canvas.width !== this.elt.width) { + this.canvas.width = this.elt.width; + this.canvas.height = this.elt.height; + this.width = this.canvas.width; + this.height = this.canvas.height; + } + this.drawingContext.clearRect(0, 0, this.canvas.width, this.canvas.height); + this.drawingContext.drawImage(this.elt, 0, 0, this.canvas.width, this.canvas.height); + this.setModified(true); + this._frameOnCanvas = this._pInst.frameCount; + } + } + }, + { + key: 'loadPixels', + value: function loadPixels() { + this._ensureCanvas(); + for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + return _main.default.Renderer2D.prototype.loadPixels.apply(this, args); + } + }, + { + key: 'updatePixels', + value: function updatePixels(x, y, w, h) { + if (this.loadedmetadata) { + // wait for metadata + this._ensureCanvas(); + _main.default.Renderer2D.prototype.updatePixels.call(this, x, y, w, h); + } + this.setModified(true); + return this; + } + }, + { + key: 'get', + value: function get() { + this._ensureCanvas(); + for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + args[_key5] = arguments[_key5]; + } + return _main.default.Renderer2D.prototype.get.apply(this, args); + } + }, + { + key: '_getPixel', + value: function _getPixel() { + this.loadPixels(); + for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { + args[_key6] = arguments[_key6]; + } + return _main.default.Renderer2D.prototype._getPixel.apply(this, args); + } + }, + { + key: 'set', + value: function set(x, y, imgOrCol) { + if (this.loadedmetadata) { + // wait for metadata + this._ensureCanvas(); + _main.default.Renderer2D.prototype.set.call(this, x, y, imgOrCol); + this.setModified(true); + } + } + }, + { + key: 'copy', + value: function copy() { + this._ensureCanvas(); + for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { + args[_key7] = arguments[_key7]; + } + _main.default.prototype.copy.apply(this, args); + } + }, + { + key: 'mask', + value: function mask() { + this.loadPixels(); + this.setModified(true); + for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { + args[_key8] = arguments[_key8]; + } + _main.default.Image.prototype.mask.apply(this, args); + } /** + * helper method for web GL mode to figure out if the element + * has been modified and might need to be re-uploaded to texture + * memory between frames. + * @method isModified + * @private + * @return {boolean} a boolean indicating whether or not the + * image has been updated or modified since last texture upload. + */ + + }, + { + key: 'isModified', + value: function isModified() { + return this._modified; + } /** + * helper method for web GL mode to indicate that an element has been + * changed or unchanged since last upload. gl texture upload will + * set this value to false after uploading the texture; or might set + * it to true if metadata has become available but there is no actual + * texture data available yet.. + * @method setModified + * @param {boolean} val sets whether or not the element has been + * modified. + * @private + */ + + }, + { + key: 'setModified', + value: function setModified(value) { + this._modified = value; + } /** + * Calls a function when the audio/video reaches the end of its playback + * The function won't be called if the media is looping. + * + * The `p5.MediaElement` is passed as an argument to the callback function. + * + * @method onended + * @param {Function} callback function to call when playback ends. + * The `p5.MediaElement` is passed as + * the argument. + * @chainable + * @example + *
      + * + * let beat; + * let isPlaying = false; + * let isDone = false; + * + * function setup() { + * + * // Create a p5.MediaElement using createAudio(). + * beat = createAudio('assets/beat.mp3'); + * + * // Set isDone to false when + * // the beat finishes. + * beat.onended(() => { + * isDone = true; + * }); + * + * describe('The text "Click to play" written in black on a gray square. A beat plays when the user clicks. The text "Done!" appears when the beat finishes playing.'); + * } + * + * function draw() { + * background(200); + * + * // Display different messages + * // based on playback. + * textAlign(CENTER); + * if (isDone === true) { + * text('Done!', 50, 50); + * } else if (isPlaying === false) { + * text('Click to play', 50, 50); + * } else { + * text('Playing...', 50, 50); + * } + * } + * + * // Play the beat when the + * // user presses the mouse. + * function mousePressed() { + * if (isPlaying === false) { + * isPlaying = true; + * beat.play(); + * } + * } + * + *
      + */ + + }, + { + key: 'onended', + value: function onended(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 + */ + + }, + { + key: 'connect', + value: function connect(obj) { + var audioContext, + mainOutput; + // if p5.sound exists, same audio context + if (typeof _main.default.prototype.getAudioContext === 'function') { + audioContext = _main.default.prototype.getAudioContext(); + mainOutput = _main.default.soundOut.input; + } else { + try { + audioContext = obj.context; + mainOutput = audioContext.destination; + } catch (e) { + throw 'connect() is meant to be used with Web Audio API or p5.sound.js'; + } + } // create a Web Audio MediaElementAudioSourceNode if none already exists + + if (!this.audioSourceNode) { + this.audioSourceNode = audioContext.createMediaElementSource(this.elt); + // connect to main output when this method is first called + this.audioSourceNode.connect(mainOutput); + } // connect to object if provided + + if (obj) { + if (obj.input) { + this.audioSourceNode.connect(obj.input); + } else { + this.audioSourceNode.connect(obj); + } + } else { + // otherwise connect to main output of p5.sound / AudioContext + this.audioSourceNode.connect(mainOutput); + } + } /** + * Disconnect all Web Audio routing, including to main output. + * This is useful if you want to re-route the output through + * audio effects, for example. + * + * @method disconnect + */ + + }, + { + key: 'disconnect', + value: function disconnect() { + if (this.audioSourceNode) { + this.audioSourceNode.disconnect(); + } else { + throw 'nothing to disconnect'; + } + } /*** SHOW / HIDE CONTROLS ***/ + /** + * Show the default + * HTMLMediaElement + * controls. These vary between web browser. + * + * @method showControls + * @example + *
      + * + * function setup() { + * background('cornflowerblue'); + * + * textAlign(CENTER); + * textSize(50); + * text('🐉', 50, 50); + * + * // Create a p5.MediaElement using createAudio(). + * let dragon = createAudio('assets/lucky_dragons.mp3'); + * // Show the default media controls. + * dragon.showControls(); + * + * describe('A dragon emoji, 🐉, drawn in the center of a blue square. A song plays in the background. Audio controls are displayed beneath the canvas.'); + * } + * + *
      + */ + + }, + { + key: 'showControls', + value: function showControls() { + // must set style for the element to show on the page + this.elt.style['text-align'] = 'inherit'; + this.elt.controls = true; + } /** + * Hide the default + * HTMLMediaElement + * controls. + * + * @method hideControls + * @example + *
      + * + * let dragon; + * let isHidden = false; + * + * function setup() { + * // Create a p5.MediaElement using createAudio(). + * dragon = createAudio('assets/lucky_dragons.mp3'); + * // Show the default media controls. + * dragon.showControls(); + * + * describe('The text "Double-click to hide controls" written in the middle of a gray square. A song plays in the background. Audio controls are displayed beneath the canvas. The controls appear/disappear when the user double-clicks the square.'); + * } + * + * function draw() { + * background(200); + * + * // Display a different message when + * // controls are hidden or shown. + * textAlign(CENTER); + * if (isHidden === true) { + * text('Double-click to show controls', 10, 20, 80, 80); + * } else { + * text('Double-click to hide controls', 10, 20, 80, 80); + * } + * } + * + * // Show/hide controls based on a double-click. + * function doubleClicked() { + * if (isHidden === true) { + * dragon.showControls(); + * isHidden = false; + * } else { + * dragon.hideControls(); + * isHidden = true; + * } + * } + * + *
      + */ + + }, + { + key: 'hideControls', + value: function hideControls() { + this.elt.controls = false; + } /** + * Schedules a function to call when the audio/video reaches a specific time + * during its playback. + * + * The first parameter, `time`, is the time, in seconds, when the function + * should run. This value is passed to `callback` as its first argument. + * + * The second parameter, `callback`, is the function to call at the specified + * cue time. + * + * The third parameter, `value`, is optional and can be any type of value. + * `value` is passed to `callback`. + * + * Calling `media.addCue()` returns an ID as a string. This is useful for + * removing the cue later. + * + * @method addCue + * @param {Number} time cue time to run the callback function. + * @param {Function} callback function to call at the cue time. + * @param {Object} [value] object to pass as the argument to + * `callback`. + * @return {Number} id ID of this cue, + * useful for `media.removeCue(id)`. + * @example + *
      + * + * function setup() { + * // Create a p5.MediaElement using createAudio(). + * let beat = createAudio('assets/beat.mp3'); + * // Play the beat in a loop. + * beat.loop(); + * + * // Schedule a few events. + * beat.addCue(0, changeBackground, 'red'); + * beat.addCue(2, changeBackground, 'deeppink'); + * beat.addCue(4, changeBackground, 'orchid'); + * beat.addCue(6, changeBackground, 'lavender'); + * + * describe('A red square with a beat playing in the background. Its color changes every 2 seconds while the audio plays.'); + * } + * + * function changeBackground(c) { + * background(c); + * } + * + *
      + */ + + }, + { + key: 'addCue', + value: function addCue(time, callback, val) { + var id = this._cueIDCounter++; + var cue = new Cue(callback, time, id, val); + this._cues.push(cue); + if (!this.elt.ontimeupdate) { + this.elt.ontimeupdate = this._onTimeUpdate.bind(this); + } + return id; + } /** + * Remove a callback based on its ID. + * + * @method removeCue + * @param {Number} id ID of the cue, created by `media.addCue()`. + * @example + *
      + * + * let lavenderID; + * let isRemoved = false; + * + * function setup() { + * // Create a p5.MediaElement using createAudio(). + * let beat = createAudio('assets/beat.mp3'); + * // Play the beat in a loop. + * beat.loop(); + * + * // Schedule a few events. + * beat.addCue(0, changeBackground, 'red'); + * beat.addCue(2, changeBackground, 'deeppink'); + * beat.addCue(4, changeBackground, 'orchid'); + * + * // Record the ID of the "lavender" callback. + * lavenderID = beat.addCue(6, changeBackground, 'lavender'); + * + * describe('The text "Double-click to remove lavender." written on a red square. The color changes every 2 seconds while the audio plays. The lavender option is removed when the user double-clicks the square.'); + * } + * + * function draw() { + * if (isRemoved === false) { + * text('Double-click to remove lavender.', 10, 10, 80, 80); + * } else { + * text('No more lavender.', 10, 10, 80, 80); + * } + * } + * + * function changeBackground(c) { + * background(c); + * } + * + * // Remove the lavender color-change cue + * // when the user double-clicks. + * function doubleClicked() { + * if (isRemoved === false) { + * beat.removeCue(lavenderID); + * isRemoved = true; + * } + * } + * + *
      + */ + + }, + { + key: 'removeCue', + value: function removeCue(id) { + for (var i = 0; i < this._cues.length; i++) { + if (this._cues[i].id === id) { + console.log(id); + this._cues.splice(i, 1); + } + } + if (this._cues.length === 0) { + this.elt.ontimeupdate = null; + } + } /** + * Removes all functions scheduled with `media.addCue()`. + * + * @method clearCues + * @example + *
      + * + * let isChanging = true; + * + * function setup() { + * background(200); + * + * // Create a p5.MediaElement using createAudio(). + * let beat = createAudio('assets/beat.mp3'); + * // Play the beat in a loop. + * beat.loop(); + * + * // Schedule a few events. + * beat.addCue(0, changeBackground, 'red'); + * beat.addCue(2, changeBackground, 'deeppink'); + * beat.addCue(4, changeBackground, 'orchid'); + * beat.addCue(6, changeBackground, 'lavender'); + * + * describe('The text "Double-click to stop changing." written on a square. The color changes every 2 seconds while the audio plays. The color stops changing when the user double-clicks the square.'); + * } + * + * function draw() { + * if (isChanging === true) { + * text('Double-click to stop changing.', 10, 10, 80, 80); + * } else { + * text('No more changes.', 10, 10, 80, 80); + * } + * } + * + * function changeBackground(c) { + * background(c); + * } + * + * // Remove cued functions and stop + * // changing colors when the user + * // double-clicks. + * function doubleClicked() { + * if (isChanging === true) { + * beat.clearCues(); + * isChanging = false; + * } + * } + * + *
      + */ + + }, + { + key: 'clearCues', + value: function clearCues() { + this._cues = [ + ]; + this.elt.ontimeupdate = null; + } // private method that checks for cues to be fired if events + // have been scheduled using addCue(callback, time). + + }, + { + key: '_onTimeUpdate', + value: function _onTimeUpdate() { + var playbackTime = this.time(); + for (var i = 0; i < this._cues.length; i++) { + var callbackTime = this._cues[i].time; + var val = this._cues[i].val; + if (this._prevTime < callbackTime && callbackTime <= playbackTime) { + // pass the scheduled callbackTime as parameter to the callback + this._cues[i].callback(val); + } + } + this._prevTime = playbackTime; + } + } + ]); + return MediaElement; + }(_main.default.Element); + _main.default.MediaElement = MediaElement; /** - * Sets volume for this HTML5 media element. If no argument is given, - * returns the current volume. + * A class to describe a file. * - * @method volume - * @return {Number} current volume + * `p5.File` objects are used by + * myElement.drop() and + * created by + * createFileInput. * + * @class p5.File + * @constructor + * @param {File} file wrapped file. * @example - *
      - * let ele; + *
      + * + * // Use the file input to load a + * // file and display its info. + * * 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); - * } - *
      - *
      - * let audio; - * let counter = 0; * - * function loaded() { - * audio.play(); - * } + * // Create a file input and place it beneath + * // the canvas. Call displayInfo() when + * // the file loads. + * let input = createFileInput(displayInfo); + * input.position(0, 100); * - * function setup() { - * audio = createAudio('assets/lucky_dragons.mp3', loaded); - * textAlign(CENTER); + * describe('A gray square with a file input beneath it. If the user loads a file, its info is written in black.'); * } * - * 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); - * } - * } + * // Display the p5.File's info + * // once it loads. + * function displayInfo(file) { + * background(200); * - * 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); - * } + * // Display the p5.File's name. + * text(file.name, 10, 10, 80, 40); + * // Display the p5.File's type and subtype. + * text(`${file.type}/${file.subtype}`, 10, 70); + * // Display the p5.File's size in bytes. + * text(file.size, 10, 90); * } * *
      - */ - /** - * @method volume - * @param {Number} val volume between 0.0 and 1.0 - * @chainable - */ - _main.default.MediaElement.prototype.volume = function (val) { - if (typeof val === 'undefined') { - return this.elt.volume; - } else { - this.elt.volume = val; - } - }; - /** - * If no arguments are given, returns the current playback speed of the - * element. The speed parameter sets the speed where 2.0 will play the - * element twice as fast, 0.5 will play at half the speed, and -1 will play - * the element in normal speed in reverse.(Note that not all browsers support - * backward playback and even if they do, playback might not be smooth.) - * - * @method speed - * @return {Number} current playback speed of the element - * - * @example - *
      - * //Clicking the canvas will loop - * //the audio sample until the user - * //clicks again to stop it * - * //We will store the p5.MediaElement - * //object in here - * let ele; - * let button; + *
      + * + * // Use the file input to select an image to + * // load and display. + * let img; * * 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); - * } + * // Create a file input and place it beneath + * // the canvas. Call handleImage() when + * // the file image loads. + * let input = createFileInput(handleImage); + * input.position(0, 100); * - * function twice_speed() { - * ele.speed(2); + * describe('A gray square with a file input beneath it. If the user selects an image file to load, it is displayed on the square.'); * } * - * function half_speed() { - * ele.speed(0.5); - * } + * function draw() { + * background(200); * - * function reverse_speed() { - * ele.speed(-1); + * // Draw the image if it's ready. + * if (img) { + * image(img, 0, 0, width, height); + * } * } * - * function stop_song() { - * ele.stop(); - * } + * // Use the p5.File's data once + * // it loads. + * function handleImage(file) { + * // Check the p5.File's type. + * if (file.type === 'image') { + * // Create an image using using + * // the p5.File's data. + * img = createImg(file.data, ''); * - * function play_speed() { - * ele.play(); + * // Hide the image element so it + * // doesn't appear twice. + * img.hide(); + * } else { + * img = null; + * } * } - *
      - */ - /** - * @method speed - * @param {Number} speed speed multiplier for element playback - * @chainable + *
      + *
      */ - _main.default.MediaElement.prototype.speed = function (val) { - if (typeof val === 'undefined') { - return this.presetPlaybackRate || this.elt.playbackRate; - } else { - if (this.loadedmetadata) { - this.elt.playbackRate = val; - } else { - this.presetPlaybackRate = val; - } - } - }; - /** - * If no arguments are given, returns the current time of the element. - * If an argument is given the current time of the element is set to it. - * - * @method time - * @return {Number} current time (in seconds) - * - * @example - *
      - * let ele; - * let beginning = true; - * function setup() { - * //p5.MediaElement objects are usually created - * //by calling the createAudio(), createVideo(), - * //and createCapture() functions. - * - * //In this example we create - * //a new p5.MediaElement via createAudio(). - * ele = createAudio('assets/lucky_dragons.mp3'); - * background(250); - * textAlign(CENTER); - * text('start at beginning', width / 2, height / 2); - * } - * - * // this function fires with click anywhere - * function mousePressed() { - * if (beginning === true) { - * // here we start the sound at the beginning - * // time(0) is not necessary here - * // as this produces the same result as - * // play() - * ele.play().time(0); - * background(200); - * text('jump 2 sec in', width / 2, height / 2); - * beginning = false; - * } else { - * // here we jump 2 seconds into the sound - * ele.play().time(2); - * background(250); - * text('start at beginning', width / 2, height / 2); - * beginning = true; - * } - * } - *
      - */ - /** - * @method time - * @param {Number} time time to jump to (in seconds) - * @chainable - */ - _main.default.MediaElement.prototype.time = function (val) { - if (typeof val === 'undefined') { - return this.elt.currentTime; - } else { - this.elt.currentTime = val; - return this; - } - }; - /** - * Returns the duration of the HTML5 media element. - * - * @method duration - * @return {Number} duration - * - * @example - *
      - * let ele; - * function setup() { - * //p5.MediaElement objects are usually created - * //by calling the createAudio(), createVideo(), - * //and createCapture() functions. - * //In this example we create - * //a new p5.MediaElement via createAudio(). - * ele = createAudio('assets/doorbell.mp3'); - * background(250); - * textAlign(CENTER); - * text('Click to know the duration!', 10, 25, 70, 80); - * } - * function mouseClicked() { - * ele.play(); - * background(200); - * //ele.duration dislpays the duration - * text(ele.duration() + ' seconds', width / 2, height / 2); - * } - *
      - */ - _main.default.MediaElement.prototype.duration = function () { - return this.elt.duration; - }; - _main.default.MediaElement.prototype.pixels = [ - ]; - _main.default.MediaElement.prototype._ensureCanvas = function () { - if (!this.canvas) { - this.canvas = document.createElement('canvas'); - this.drawingContext = this.canvas.getContext('2d'); - this.setModified(true); - } - if (this.loadedmetadata) { - // wait for metadata for w/h - if (this.canvas.width !== this.elt.width) { - this.canvas.width = this.elt.width; - this.canvas.height = this.elt.height; - this.width = this.canvas.width; - this.height = this.canvas.height; - } - this.drawingContext.drawImage(this.elt, 0, 0, this.canvas.width, this.canvas.height); - this.setModified(true); - } - }; - _main.default.MediaElement.prototype.loadPixels = function () { - this._ensureCanvas(); - return _main.default.Renderer2D.prototype.loadPixels.apply(this, arguments); - }; - _main.default.MediaElement.prototype.updatePixels = function (x, y, w, h) { - if (this.loadedmetadata) { - // wait for metadata - this._ensureCanvas(); - _main.default.Renderer2D.prototype.updatePixels.call(this, x, y, w, h); - } - this.setModified(true); - return this; - }; - _main.default.MediaElement.prototype.get = function () { - this._ensureCanvas(); - return _main.default.Renderer2D.prototype.get.apply(this, arguments); - }; - _main.default.MediaElement.prototype._getPixel = function () { - this.loadPixels(); - return _main.default.Renderer2D.prototype._getPixel.apply(this, arguments); - }; - _main.default.MediaElement.prototype.set = function (x, y, imgOrCol) { - if (this.loadedmetadata) { - // wait for metadata - this._ensureCanvas(); - _main.default.Renderer2D.prototype.set.call(this, x, y, imgOrCol); - this.setModified(true); - } - }; - _main.default.MediaElement.prototype.copy = function () { - this._ensureCanvas(); - _main.default.prototype.copy.apply(this, arguments); - }; - _main.default.MediaElement.prototype.mask = function () { - this.loadPixels(); - this.setModified(true); - _main.default.Image.prototype.mask.apply(this, arguments); - }; - /** - * helper method for web GL mode to figure out if the element - * has been modified and might need to be re-uploaded to texture - * memory between frames. - * @method isModified - * @private - * @return {boolean} a boolean indicating whether or not the - * image has been updated or modified since last texture upload. - */ - _main.default.MediaElement.prototype.isModified = function () { - return this._modified; - }; - /** - * helper method for web GL mode to indicate that an element has been - * changed or unchanged since last upload. gl texture upload will - * set this value to false after uploading the texture; or might set - * it to true if metadata has become available but there is no actual - * texture data available yet.. - * @method setModified - * @param {boolean} val sets whether or not the element has been - * modified. - * @private - */ - _main.default.MediaElement.prototype.setModified = function (value) { - this._modified = value; - }; - /** - * Schedule an event to be called when the audio or video - * element reaches the end. If the element is looping, - * this will not be called. The element is passed in - * as the argument to the onended callback. - * - * @method onended - * @param {Function} callback function to call when the - * soundfile has ended. The - * media element will be passed - * in as the argument to the - * callback. - * @chainable - * @example - *
      - * function setup() { - * let audioEl = createAudio('assets/beat.mp3'); - * audioEl.showControls(); - * audioEl.onended(sayDone); - * } - * - * function sayDone(elt) { - * alert('done playing ' + elt.src); - * } - *
      - */ - _main.default.MediaElement.prototype.onended = function (callback) { - this._onended = callback; - return this; - }; - /*** CONNECT TO WEB AUDIO API / p5.sound.js ***/ - /** - * Send the audio output of this element to a specified audioNode or - * p5.sound object. If no element is provided, connects to p5's main - * output. That connection is established when this method is first called. - * All connections are removed by the .disconnect() method. - * - * This method is meant to be used with the p5.sound.js addon library. - * - * @method connect - * @param {AudioNode|Object} audioNode AudioNode from the Web Audio API, - * or an object from the p5.sound library - */ - _main.default.MediaElement.prototype.connect = function (obj) { - var audioContext, - mainOutput; // if p5.sound exists, same audio context - if (typeof _main.default.prototype.getAudioContext === 'function') { - audioContext = _main.default.prototype.getAudioContext(); - mainOutput = _main.default.soundOut.input; - } else { - try { - audioContext = obj.context; - mainOutput = audioContext.destination; - } catch (e) { - throw 'connect() is meant to be used with Web Audio API or p5.sound.js'; - } - } // create a Web Audio MediaElementAudioSourceNode if none already exists - - if (!this.audioSourceNode) { - this.audioSourceNode = audioContext.createMediaElementSource(this.elt); // connect to main output when this method is first called - this.audioSourceNode.connect(mainOutput); - } // connect to object if provided - - if (obj) { - if (obj.input) { - this.audioSourceNode.connect(obj.input); - } else { - this.audioSourceNode.connect(obj); - } - } else { - // otherwise connect to main output of p5.sound / AudioContext - this.audioSourceNode.connect(mainOutput); - } - }; - /** - * Disconnect all Web Audio routing, including to main output. - * This is useful if you want to re-route the output through - * audio effects, for example. - * - * @method disconnect - */ - _main.default.MediaElement.prototype.disconnect = function () { - if (this.audioSourceNode) { - this.audioSourceNode.disconnect(); - } else { - throw 'nothing to disconnect'; - } - }; - /*** SHOW / HIDE CONTROLS ***/ - /** - * Show the default MediaElement controls, as determined by the web browser. - * - * @method showControls - * @example - *
      - * let ele; - * function setup() { - * //p5.MediaElement objects are usually created - * //by calling the createAudio(), createVideo(), - * //and createCapture() functions. - * //In this example we create - * //a new p5.MediaElement via createAudio() - * ele = createAudio('assets/lucky_dragons.mp3'); - * background(200); - * textAlign(CENTER); - * text('Click to Show Controls!', 10, 25, 70, 80); - * } - * function mousePressed() { - * ele.showControls(); - * background(200); - * text('Controls Shown', width / 2, height / 2); - * } - *
      - */ - _main.default.MediaElement.prototype.showControls = function () { - // must set style for the element to show on the page - this.elt.style['text-align'] = 'inherit'; - this.elt.controls = true; - }; - /** - * Hide the default mediaElement controls. - * @method hideControls - * @example - *
      - * let ele; - * function setup() { - * //p5.MediaElement objects are usually created - * //by calling the createAudio(), createVideo(), - * //and createCapture() functions. - * //In this example we create - * //a new p5.MediaElement via createAudio() - * ele = createAudio('assets/lucky_dragons.mp3'); - * ele.showControls(); - * background(200); - * textAlign(CENTER); - * text('Click to hide Controls!', 10, 25, 70, 80); - * } - * function mousePressed() { - * ele.hideControls(); - * background(200); - * text('Controls hidden', width / 2, height / 2); - * } - *
      - */ - _main.default.MediaElement.prototype.hideControls = function () { - this.elt.controls = false; - }; - /*** SCHEDULE EVENTS ***/ - // Cue inspired by JavaScript setTimeout, and the - // Tone.js Transport Timeline Event, MIT License Yotam Mann 2015 tonejs.org - var Cue = function Cue(callback, time, id, val) { - this.callback = callback; - this.time = time; - this.id = id; - this.val = val; - }; - /** - * Schedule events to trigger every time a MediaElement - * (audio/video) reaches a playback cue point. - * - * Accepts a callback function, a time (in seconds) at which to trigger - * the callback, and an optional parameter for the callback. - * - * Time will be passed as the first parameter to the callback function, - * and param will be the second parameter. - * - * @method addCue - * @param {Number} time Time in seconds, relative to this media - * element's playback. For example, to trigger - * an event every time playback reaches two - * seconds, pass in the number 2. This will be - * passed as the first parameter to - * the callback function. - * @param {Function} callback Name of a function that will be - * called at the given time. The callback will - * receive time and (optionally) param as its - * two parameters. - * @param {Object} [value] An object to be passed as the - * second parameter to the - * callback function. - * @return {Number} id ID of this cue, - * useful for removeCue(id) - * @example - *
      - * // - * // - * 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); - * } - *
      - */ - _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 - *
      - * 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); - * } - *
      - */ - _main.default.MediaElement.prototype.removeCue = function (id) { - for (var i = 0; i < this._cues.length; i++) { - if (this._cues[i].id === id) { - console.log(id); - this._cues.splice(i, 1); - } - } - if (this._cues.length === 0) { - this.elt.ontimeupdate = null; - } - }; - /** - * Remove all of the callbacks that had originally been scheduled - * via the addCue method. - * @method clearCues - * @param {Number} id ID of the cue, as returned by addCue - * @example - *
      - * let audioEl; - * function setup() { - * background(255, 255, 255); - * audioEl = createAudio('assets/beat.mp3'); - * //Show the default MediaElement controls, as determined by the web browser - * audioEl.showControls(); - * // schedule calls to changeBackground - * background(200); - * text('Click to change Cue!', 10, 25, 70, 80); - * audioEl.addCue(0.5, changeBackground, color(255, 0, 0)); - * audioEl.addCue(1.0, changeBackground, color(0, 255, 0)); - * audioEl.addCue(2.5, changeBackground, color(0, 0, 255)); - * audioEl.addCue(3.0, changeBackground, color(0, 255, 255)); - * audioEl.addCue(4.2, changeBackground, color(255, 255, 0)); - * } - * function mousePressed() { - * // here we clear the scheduled callbacks - * audioEl.clearCues(); - * // then we add some more callbacks - * audioEl.addCue(1, changeBackground, color(2, 2, 2)); - * audioEl.addCue(3, changeBackground, color(255, 255, 0)); - * } - * function changeBackground(val) { - * background(val); - * } - *
      - */ - _main.default.MediaElement.prototype.clearCues = function () { - this._cues = [ - ]; - this.elt.ontimeupdate = null; - }; // private method that checks for cues to be fired if events - // have been scheduled using addCue(callback, time). - _main.default.MediaElement.prototype._onTimeUpdate = function () { - var playbackTime = this.time(); - for (var i = 0; i < this._cues.length; i++) { - var callbackTime = this._cues[i].time; - var val = this._cues[i].val; - if (this._prevTime < callbackTime && callbackTime <= playbackTime) { - // pass the scheduled callbackTime as parameter to the callback - this._cues[i].callback(val); - } + var File = /*#__PURE__*/ function () { + function File(file, pInst) { + _classCallCheck(this, File); + /** + * Underlying + * File + * object. All `File` properties and methods are accessible. + * + * @property file + * @example + *
      + * + * // Use the file input to load a + * // file and display its info. + * + * function setup() { + * background(200); + * + * // Create a file input and place it beneath + * // the canvas. Call displayInfo() when + * // the file loads. + * let input = createFileInput(displayInfo); + * input.position(0, 100); + * + * describe('A gray square with a file input beneath it. If the user loads a file, its info is written in black.'); + * } + * + * // Use the p5.File once + * // it loads. + * function displayInfo(file) { + * background(200); + * + * // Display the p5.File's name. + * text(file.name, 10, 10, 80, 40); + * // Display the p5.File's type and subtype. + * text(`${file.type}/${file.subtype}`, 10, 70); + * // Display the p5.File's size in bytes. + * text(file.size, 10, 90); + * } + * + *
      + */ + this.file = file; + this._pInst = pInst; + // Splitting out the file type into two components + // This makes determining if image or text etc simpler + var typeList = file.type.split('/'); + /** + * The file + * MIME type + * as a string. For example, `'image'`, `'text'`, and so on. + * + * @property type + * @example + *
      + * + * // Use the file input to load a + * // file and display its info. + * + * function setup() { + * background(200); + * + * // Create a file input and place it beneath + * // the canvas. Call displayType() when + * // the file loads. + * let input = createFileInput(displayType); + * input.position(0, 100); + * + * describe('A gray square with a file input beneath it. If the user loads a file, its type is written in black.'); + * } + * + * // Display the p5.File's type + * // once it loads. + * function displayType(file) { + * background(200); + * + * // Display the p5.File's type. + * text(`This is file's type is: ${file.type}`, 10, 10, 80, 80); + * } + * + *
      + */ + this.type = typeList[0]; + /** + * The file subtype as a string. For example, a file with an `'image'` + * MIME type + * may have a subtype such as ``png`` or ``jpeg``. + * + * @property subtype + * @example + *
      + * + * // Use the file input to load a + * // file and display its info. + * + * function setup() { + * background(200); + * + * // Create a file input and place it beneath + * // the canvas. Call displaySubtype() when + * // the file loads. + * let input = createFileInput(displaySubtype); + * input.position(0, 100); + * + * describe('A gray square with a file input beneath it. If the user loads a file, its subtype is written in black.'); + * } + * + * // Display the p5.File's type + * // once it loads. + * function displaySubtype(file) { + * background(200); + * + * // Display the p5.File's subtype. + * text(`This is file's subtype is: ${file.subtype}`, 10, 10, 80, 80); + * } + * + *
      + */ + this.subtype = typeList[1]; + /** + * The file name as a string. + * + * @property name + * @example + *
      + * + * // Use the file input to load a + * // file and display its info. + * + * function setup() { + * background(200); + * + * // Create a file input and place it beneath + * // the canvas. Call displayName() when + * // the file loads. + * let input = createFileInput(displayName); + * input.position(0, 100); + * + * describe('A gray square with a file input beneath it. If the user loads a file, its name is written in black.'); + * } + * + * // Display the p5.File's name + * // once it loads. + * function displayName(file) { + * background(200); + * + * // Display the p5.File's name. + * text(`This is file's name is: ${file.name}`, 10, 10, 80, 80); + * } + * + *
      + */ + this.name = file.name; + /** + * The number of bytes in the file. + * + * @property size + * @example + *
      + * + * // Use the file input to load a + * // file and display its info. + * + * function setup() { + * background(200); + * + * // Create a file input and place it beneath + * // the canvas. Call displaySize() when + * // the file loads. + * let input = createFileInput(displaySize); + * input.position(0, 100); + * + * describe('A gray square with a file input beneath it. If the user loads a file, its size in bytes is written in black.'); + * } + * + * // Display the p5.File's size + * // in bytes once it loads. + * function displaySize(file) { + * background(200); + * + * // Display the p5.File's size. + * text(`This is file has ${file.size} bytes.`, 10, 10, 80, 80); + * } + * + *
      + */ + this.size = file.size; + /** + * A string containing either the file's image data, text contents, or + * a parsed object in the case of JSON and + * p5.XML objects. + * + * @property data + * @example + *
      + * + * // Use the file input to load a + * // file and display its info. + * + * function setup() { + * background(200); + * + * // Create a file input and place it beneath + * // the canvas. Call displayData() when + * // the file loads. + * let input = createFileInput(displayData); + * input.position(0, 100); + * + * describe('A gray square with a file input beneath it. If the user loads a file, its data is written in black.'); + * } + * + * // Display the p5.File's data + * // once it loads. + * function displayData(file) { + * background(200); + * + * // Display the p5.File's data, + * // which looks like a random + * // string of characters. + * text(file.data, 10, 10, 80, 80); + * } + * + *
      + */ + this.data = undefined; } - 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; + _createClass(File, null, [ + { + key: '_createLoader', + value: function _createLoader(theFile, callback) { + var reader = new FileReader(); + reader.onload = function (e) { + var p5file = new _main.default.File(theFile); + if (p5file.file.type === 'application/json') { + // Parse JSON and store the result in data + p5file.data = JSON.parse(e.target.result); + } else if (p5file.file.type === 'text/xml') { + // Parse XML, wrap it in p5.XML and store the result in data + var parser = new DOMParser(); + var xml = parser.parseFromString(e.target.result, 'text/xml'); + p5file.data = new _main.default.XML(xml.documentElement); + } else { + p5file.data = e.target.result; + } + callback(p5file); + }; + return reader; + } + }, + { + key: '_load', + value: function _load(f, callback) { + // Text or data? + // This should likely be improved + if (/^text\//.test(f.type) || f.type === 'application/json') { + _main.default.File._createLoader(f, callback).readAsText(f); + } else if (!/^(video|audio)\//.test(f.type)) { + _main.default.File._createLoader(f, callback).readAsDataURL(f); + } else { + var file = new _main.default.File(f); + file.data = URL.createObjectURL(f); + callback(file); + } + } } - 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); - } - }; + ]); + return File; + }(); + _main.default.File = File; var _default = _main.default; exports.default = _default; }, { - '../core/main': 290, - 'core-js/modules/es.array.every': 169, - 'core-js/modules/es.array.filter': 171, - 'core-js/modules/es.array.for-each': 172, - 'core-js/modules/es.array.from': 173, - 'core-js/modules/es.array.index-of': 175, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.map': 179, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.array.splice': 182, - 'core-js/modules/es.function.name': 183, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.promise': 196, - 'core-js/modules/es.regexp.exec': 199, - 'core-js/modules/es.regexp.to-string': 200, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.string.replace': 207, - 'core-js/modules/es.string.split': 209, - 'core-js/modules/es.string.trim': 211, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/web.dom-collections.for-each': 247, - 'core-js/modules/web.dom-collections.iterator': 248, - 'core-js/modules/web.url': 250 + '../core/main': 298, + 'core-js/modules/es.array.every': 171, + 'core-js/modules/es.array.filter': 173, + 'core-js/modules/es.array.for-each': 175, + 'core-js/modules/es.array.from': 176, + 'core-js/modules/es.array.index-of': 178, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.map': 182, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.array.splice': 185, + 'core-js/modules/es.function.name': 186, + 'core-js/modules/es.object.get-prototype-of': 198, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.promise': 201, + 'core-js/modules/es.reflect.construct': 202, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.string.replace': 214, + 'core-js/modules/es.string.split': 216, + 'core-js/modules/es.string.trim': 219, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/web.dom-collections.for-each': 255, + 'core-js/modules/web.dom-collections.iterator': 256, + 'core-js/modules/web.url': 258 } ], - 307: [ + 315: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -74056,6 +80035,7 @@ * @submodule Acceleration * @for p5 * @requires core + * @main Events */ /** * The system variable deviceOrientation always contains the orientation of @@ -74693,7 +80673,8 @@ context.deviceTurned(); } this.pRotateDirectionX = rotateDirectionX; - startAngleX = wSAX - 180; // Y-axis is identical to X-axis except for changing some names. + 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; @@ -74711,7 +80692,8 @@ context.deviceTurned(); } this.pRotateDirectionY = rotateDirectionY; - startAngleY = wSAY - 180; // Z-axis is already in the range 0 to 360 + 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'; @@ -74731,7 +80713,8 @@ } if (typeof context.deviceShaken === 'function') { var accelerationChangeX; - var accelerationChangeY; // Add accelerationChangeZ if acceleration change on Z is needed + 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); @@ -74745,20 +80728,20 @@ exports.default = _default; }, { - '../core/constants': 278, - '../core/main': 290, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + '../core/constants': 286, + '../core/main': 298, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 308: [ + 316: [ function (_dereq_, module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { @@ -74885,7 +80868,7 @@ * behavior for this event, add "return false" to the end of the method. * * @method keyPressed - * @param {Object} [event] optional KeyboardEvent callback argument. + * @param {KeyboardEvent} [event] optional KeyboardEvent callback argument. * @example *
      * @@ -74958,7 +80941,7 @@ * behavior for this event, add "return false" to the end of the function. * * @method keyReleased - * @param {Object} [event] optional KeyboardEvent callback argument. + * @param {KeyboardEvent} [event] optional KeyboardEvent callback argument. * @example *
      * @@ -75012,7 +80995,7 @@ * to the end of the function. * * @method keyTyped - * @param {Object} [event] optional KeyboardEvent callback argument. + * @param {KeyboardEvent} [event] optional KeyboardEvent callback argument. * @example *
      * @@ -75156,10 +81139,10 @@ exports.default = _default; }, { - '../core/main': 290 + '../core/main': 298 } ], - 309: [ + 317: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -75702,7 +81685,7 @@ * behavior for this event, add "return false" to the end of the method. * * @method mouseMoved - * @param {Object} [event] optional MouseEvent callback argument. + * @param {MouseEvent} [event] optional MouseEvent callback argument. * @example *
      * @@ -75754,7 +81737,7 @@ * behavior for this event, add "return false" to the end of the function. * * @method mouseDragged - * @param {Object} [event] optional MouseEvent callback argument. + * @param {MouseEvent} [event] optional MouseEvent callback argument. * @example *
      * @@ -75833,24 +81816,24 @@ * behavior for this event, add "return false" to the end of the function. * * @method mousePressed - * @param {Object} [event] optional MouseEvent callback argument. + * @param {MouseEvent} [event] optional MouseEvent callback argument. * @example *
      * - * // Click within the image to change - * // the value of the rectangle + * // Click anywhere in the webpage to change + * // the color value of the rectangle * - * let value = 0; + * let colorValue = 0; * function draw() { - * fill(value); + * fill(colorValue); * rect(25, 25, 50, 50); * describe('black 50-by-50 rect turns white with mouse click/press.'); * } * function mousePressed() { - * if (value === 0) { - * value = 255; + * if (colorValue === 0) { + * colorValue = 255; * } else { - * value = 0; + * colorValue = 0; * } * } * @@ -75886,7 +81869,7 @@ executeDefault = context.mousePressed(e); if (executeDefault === false) { e.preventDefault(); - } // only safari needs this manual fallback for consistency + } // only safari needs this manual fallback for consistency } else if (navigator.userAgent.toLowerCase().includes('safari') && typeof context.touchStarted === 'function') { executeDefault = context.touchStarted(e); @@ -75904,7 +81887,7 @@ * behavior for this event, add "return false" to the end of the function. * * @method mouseReleased - * @param {Object} [event] optional MouseEvent callback argument. + * @param {MouseEvent} [event] optional MouseEvent callback argument. * @example *
      * @@ -75977,7 +81960,7 @@ * behavior for this event, add "return false" to the end of the function. * * @method mouseClicked - * @param {Object} [event] optional MouseEvent callback argument. + * @param {MouseEvent} [event] optional MouseEvent callback argument. * @example *
      * @@ -76041,7 +82024,7 @@ * https://developer.mozilla.org/en-US/docs/Web/Events/dblclick * * @method doubleClicked - * @param {Object} [event] optional MouseEvent callback argument. + * @param {MouseEvent} [event] optional MouseEvent callback argument. * @example *
      * @@ -76124,7 +82107,7 @@ * may only work as expected if "return false" is included while using Safari. * * @method mouseWheel - * @param {Object} [event] optional WheelEvent callback argument. + * @param {WheelEvent} [event] optional WheelEvent callback argument. * * @example *
      @@ -76238,22 +82221,22 @@ exports.default = _default; }, { - '../core/constants': 278, - '../core/main': 290, - 'core-js/modules/es.array.includes': 174, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.string.includes': 203, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + '../core/constants': 286, + '../core/main': 298, + 'core-js/modules/es.array.includes': 177, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.string.includes': 209, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 310: [ + 318: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.array.includes'); @@ -76339,7 +82322,7 @@ * to the end of the method. * * @method touchStarted - * @param {Object} [event] optional TouchEvent callback argument. + * @param {TouchEvent} [event] optional TouchEvent callback argument. * @example *
      * @@ -76396,7 +82379,7 @@ executeDefault = context.touchStarted(e); if (executeDefault === false) { e.preventDefault(); - } // only safari needs this manual fallback for consistency + } // only safari needs this manual fallback for consistency } else if (navigator.userAgent.toLowerCase().includes('safari') && typeof context.mousePressed === 'function') { executeDefault = context.mousePressed(e); @@ -76414,7 +82397,7 @@ * to the end of the method. * * @method touchMoved - * @param {Object} [event] optional TouchEvent callback argument. + * @param {TouchEvent} [event] optional TouchEvent callback argument. * @example *
      * @@ -76484,7 +82467,7 @@ * to the end of the method. * * @method touchEnded - * @param {Object} [event] optional TouchEvent callback argument. + * @param {TouchEvent} [event] optional TouchEvent callback argument. * @example *
      * @@ -76551,12 +82534,12 @@ exports.default = _default; }, { - '../core/main': 290, - 'core-js/modules/es.array.includes': 174, - 'core-js/modules/es.string.includes': 203 + '../core/main': 298, + 'core-js/modules/es.array.includes': 177, + 'core-js/modules/es.string.includes': 209 } ], - 311: [ + 319: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.array.iterator'); @@ -76632,392 +82615,430 @@ * 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 { - if (canvas.getContext('2d')) { - return canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).data; - } else if (canvas.getContext('webgl')) { - var gl = canvas.getContext('webgl'); - var len = gl.drawingBufferWidth * gl.drawingBufferHeight * 4; - var data = new Uint8Array(len); - gl.readPixels(0, 0, canvas.width, canvas.height, gl.RGBA, gl.UNSIGNED_BYTE, data); - return data; + /* + * Helper functions + */ + /** + * Returns the pixel buffer for a canvas. + * + * @private + * + * @param {Canvas|ImageData} canvas the canvas to get pixels from + * @return {Uint8ClampedArray} a one-dimensional array containing + * the data in the RGBA order, with integer + * values between 0 and 255. + */ + _toPixels: function _toPixels(canvas) { + // Return pixel data if 'canvas' is an ImageData object. + if (canvas instanceof ImageData) { + return canvas.data; + } else { + // Check 2D context support. + if (canvas.getContext('2d')) { + // Retrieve pixel data. + return canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).data; + } else if (canvas.getContext('webgl')) { + //Check WebGL context support + var gl = canvas.getContext('webgl'); + // Calculate the size of pixel data + // (4 bytes per pixel - one byte for each RGBA channel). + var len = gl.drawingBufferWidth * gl.drawingBufferHeight * 4; + var data = new Uint8Array(len); + // Use gl.readPixels to fetch pixel data from the WebGL + // canvas, storing it in the data array as UNSIGNED_BYTE integers. + gl.readPixels(0, 0, canvas.width, canvas.height, gl.RGBA, gl.UNSIGNED_BYTE, data); + return data; + } } - } - }; - /** - * Returns a 32 bit number containing ARGB data at 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 & 4278190080 | data[offset] << 16 & 16711680 | data[offset + 1] << 8 & 65280 | data[offset + 2] & 255; - }; - /** - * 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] & 16711680) >>> 16; - pixels[offset + 1] = (data[i] & 65280) >>> 8; - pixels[offset + 2] = data[i] & 255; - pixels[offset + 3] = (data[i] & 4278190080) >>> 24; - } - }; - /** - * Returns the ImageData object for a canvas - * https://developer.mozilla.org/en-US/docs/Web/API/ImageData - * - * @private - * - * @param {Canvas|ImageData} canvas canvas to get image data from - * @return {ImageData} Holder of pixel data (and width and - * height) for a canvas - */ - 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; + }, + /** + * Returns a 32-bit number containing ARGB data at the ith pixel in the + * 1D array containing pixels data. + * + * @private + * + * @param {Uint8ClampedArray} data array returned by _toPixels() + * @param {Integer} i index of a 1D Image Array + * @return {Integer} 32-bit integer value representing + * ARGB value. + */ + _getARGB: function _getARGB(data, i) { + // Determine the starting position in the 'data' array for the 'i'-th pixel. + var offset = i * 4; + return ( // Combining the extracted components using bitwise OR operations to form the final ARGB value. + data[offset + 3] << 24 & 4278190080 | //Extract alpha component + data[offset] << 16 & 16711680 | //Extract Red component + data[offset + 1] << 8 & 65280 | //Extract green component + data[offset + 2] & 255 //Extract blue component + ); + }, + /** + * Modifies pixels RGBA values to values contained in the data object. + * + * @private + * + * @param {Uint8ClampedArray} pixels array returned by _toPixels() + * @param {Int32Array} data source 1D array where each value + * represents ARGB values + */ + _setPixels: function _setPixels(pixels, data) { + var offset = 0; + for (var i = 0, al = pixels.length; i < al; i++) { + offset = i * 4; + pixels[offset + 0] = (data[i] & 16711680) >>> 16; + pixels[offset + 1] = (data[i] & 65280) >>> 8; + pixels[offset + 2] = data[i] & 255; + pixels[offset + 3] = (data[i] & 4278190080) >>> 24; + } + }, + /** + * Returns the ImageData object for a canvas. + * https://developer.mozilla.org/en-US/docs/Web/API/ImageData + * + * @private + * + * @param {Canvas|ImageData} canvas canvas to get image data from + * @return {ImageData} Holder of pixel data (and width and + * height) for a canvas + */ + _toImageData: function _toImageData(canvas) { + if (canvas instanceof ImageData) { + return canvas; } else { - val = 0; + return canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height); } - 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; + }, + /** + * Returns a blank ImageData object. + * + * @private + * + * @param {Integer} width + * @param {Integer} height + * @return {ImageData} + */ + _createImageData: function _createImageData(width, height) { + Filters._tmpCanvas = document.createElement('canvas'); + Filters._tmpCtx = Filters._tmpCanvas.getContext('2d'); + return this._tmpCtx.createImageData(width, height); + }, + /** + * Applys a filter function to a canvas. + * + * The difference between this and the actual filter functions defined below + * is that the filter functions generally modify the pixel buffer but do + * not actually put that data back to the canvas (where it would actually + * update what is visible). By contrast this method does make the changes + * actually visible in the canvas. + * + * The apply method is the method that callers of this module would generally + * use. It has been separated from the actual filters to support an advanced + * use case of creating a filter chain that executes without actually updating + * the canvas in between everystep. + * + * @private + * @param {HTMLCanvasElement} canvas The input canvas to apply the filter on. + * @param {function(ImageData,Object)} func The filter function to apply to the canvas's pixel data. + * @param {Object} filterParam An optional parameter to pass to the filter function. + */ + apply: function apply(canvas, func, filterParam) { + var pixelsState = canvas.getContext('2d'); + var imageData = pixelsState.getImageData(0, 0, canvas.width, canvas.height); + //Filters can either return a new ImageData object, or just modify + //the one they received. + var newImageData = func(imageData, filterParam); + //If new ImageData is returned, replace the canvas's pixel data with it. + if (newImageData instanceof ImageData) { + pixelsState.putImageData(newImageData, 0, 0, 0, 0, canvas.width, canvas.height); + } else { + //Restore the original pixel. + pixelsState.putImageData(imageData, 0, 0, 0, 0, canvas.width, canvas.height); + } + }, + /* + * Filters + */ + /** + * Converts the image to black and white pixels depending if they are above or + * below the threshold defined by the level parameter. The parameter must be + * between 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used. + * + * Borrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/ + * + * @private + * @param {Canvas} canvas Canvas to apply thershold filter on. + * @param {Float} level Threshold level (0-1). + */ + threshold: function threshold(canvas, level) { + var pixels = Filters._toPixels(canvas); + if (level === undefined) { + level = 0.5; + } // Calculate threshold value on a (0-255) scale. + + var thresh = Math.floor(level * 255); + for (var i = 0; i < pixels.length; i += 4) { + var r = pixels[i]; + var g = pixels[i + 1]; + var b = pixels[i + 2]; + // CIE luminance for RGB + var gray = 0.2126 * r + 0.7152 * g + 0.0722 * b; + var val = void 0; + if (gray >= thresh) { + val = 255; + } else { + val = 0; + } + pixels[i] = pixels[i + 1] = pixels[i + 2] = val; //set pixel to val. + } + }, + /** + * Converts any colors in the image to grayscale equivalents. + * No parameter is used. + * + * Borrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/ + * + * @private + * @param {Canvas} canvas Canvas to apply gray filter on. + */ + gray: function gray(canvas) { + var pixels = Filters._toPixels(canvas); + for (var i = 0; i < pixels.length; i += 4) { + var r = pixels[i]; + var g = pixels[i + 1]; + var b = pixels[i + 2]; + // CIE luminance for RGB + var gray = 0.2126 * r + 0.7152 * g + 0.0722 * b; + pixels[i] = pixels[i + 1] = pixels[i + 2] = gray; // set pixel to gray. + } + }, + /** + * Sets the alpha channel to entirely opaque. No parameter is used. + * + * @private + * @param {Canvas} canvas + */ + opaque: function opaque(canvas) { + var pixels = Filters._toPixels(canvas); + for (var i = 0; i < pixels.length; i += 4) { + pixels[i + 3] = 255; + } + return pixels; + }, + /** + * Sets each pixel to its inverse value. No parameter is used. + * @private + * @param {Canvas} canvas + */ + invert: function invert(canvas) { + var pixels = Filters._toPixels(canvas); + for (var i = 0; i < pixels.length; i += 4) { + pixels[i] = 255 - pixels[i]; + pixels[i + 1] = 255 - pixels[i + 1]; + pixels[i + 2] = 255 - pixels[i + 2]; + } + }, + /** + * Limits each channel of the image to the number of colors specified as + * the parameter. The parameter can be set to values between 2 and 255, but + * results are most noticeable in the lower ranges. + * + * Adapted from java based processing implementation + * + * @private + * @param {Canvas} canvas + * @param {Integer} level + */ + posterize: function posterize(canvas, level) { + var pixels = Filters._toPixels(canvas); + if (level === undefined) { + level = 4; + } + if (level < 2 || level > 255) { + throw new Error('Level must be greater than 2 and less than 255 for posterize'); + } + var levels1 = level - 1; + for (var i = 0; i < pixels.length; i += 4) { + var rlevel = pixels[i]; + var glevel = pixels[i + 1]; + var blevel = pixels[i + 2]; + // New pixel value by posterizing each color. + pixels[i] = (rlevel * level >> 8) * 255 / levels1; + pixels[i + 1] = (glevel * level >> 8) * 255 / levels1; + pixels[i + 2] = (blevel * level >> 8) * 255 / levels1; + } + }, + /** + * Increases the bright areas in an image. + * @private + * @param {Canvas} canvas + */ + dilate: function dilate(canvas) { + var pixels = Filters._toPixels(canvas); + var currIdx = 0; + var maxIdx = pixels.length ? pixels.length / 4 : 0; + var out = new Int32Array(maxIdx); + var currRowIdx, + maxRowIdx, + colOrig, + colOut, + currLum; + var idxRight, + idxLeft, + idxUp, + idxDown; + var colRight, + colLeft, + colUp, + colDown; + var lumRight, + lumLeft, + lumUp, + lumDown; + // Iterates through rows of pixels. + while (currIdx < maxIdx) { + currRowIdx = currIdx; + maxRowIdx = currIdx + canvas.width; + // Iterates through pixels within the current row. + while (currIdx < maxRowIdx) { + // Get original color of current pixel. + colOrig = colOut = Filters._getARGB(pixels, currIdx); + idxLeft = currIdx - 1; + idxRight = currIdx + 1; + idxUp = currIdx - canvas.width; + idxDown = currIdx + canvas.width; + // Adjust the indices to avoid going out of bounds. + if (idxLeft < currRowIdx) { + idxLeft = currIdx; + } + if (idxRight >= maxRowIdx) { + idxRight = currIdx; + } + if (idxUp < 0) { + idxUp = 0; + } + if (idxDown >= maxIdx) { + idxDown = currIdx; + } + colUp = Filters._getARGB(pixels, idxUp); + colLeft = Filters._getARGB(pixels, idxLeft); + colDown = Filters._getARGB(pixels, idxDown); + colRight = Filters._getARGB(pixels, idxRight); + // Compute luminance + currLum = 77 * (colOrig >> 16 & 255) + 151 * (colOrig >> 8 & 255) + 28 * (colOrig & 255); + lumLeft = 77 * (colLeft >> 16 & 255) + 151 * (colLeft >> 8 & 255) + 28 * (colLeft & 255); + lumRight = 77 * (colRight >> 16 & 255) + 151 * (colRight >> 8 & 255) + 28 * (colRight & 255); + lumUp = 77 * (colUp >> 16 & 255) + 151 * (colUp >> 8 & 255) + 28 * (colUp & 255); + lumDown = 77 * (colDown >> 16 & 255) + 151 * (colDown >> 8 & 255) + 28 * (colDown & 255); + // Update the output color based on the highest luminance value + if (lumLeft > currLum) { + colOut = colLeft; + currLum = lumLeft; + } + if (lumRight > currLum) { + colOut = colRight; + currLum = lumRight; + } + if (lumUp > currLum) { + colOut = colUp; + currLum = lumUp; + } + if (lumDown > currLum) { + colOut = colDown; + currLum = lumDown; + } // Store the updated color. + + out[currIdx++] = colOut; + } + } + Filters._setPixels(pixels, out); + }, + /** + * Reduces the bright areas in an image. + * Similar to `dilate()`, but updates the output color based on the lowest luminance value. + * @private + * @param {Canvas} canvas + */ + erode: function erode(canvas) { + var pixels = Filters._toPixels(canvas); + var currIdx = 0; + var maxIdx = pixels.length ? pixels.length / 4 : 0; + var out = new Int32Array(maxIdx); + var currRowIdx, + maxRowIdx, + colOrig, + colOut, + currLum; + var idxRight, + idxLeft, + idxUp, + idxDown; + var colRight, + colLeft, + colUp, + colDown; + var lumRight, + lumLeft, + lumUp, + lumDown; + while (currIdx < maxIdx) { + currRowIdx = currIdx; + maxRowIdx = currIdx + canvas.width; + while (currIdx < maxRowIdx) { + colOrig = colOut = Filters._getARGB(pixels, currIdx); + idxLeft = currIdx - 1; + idxRight = currIdx + 1; + idxUp = currIdx - canvas.width; + idxDown = currIdx + canvas.width; + if (idxLeft < currRowIdx) { + idxLeft = currIdx; + } + if (idxRight >= maxRowIdx) { + idxRight = currIdx; + } + if (idxUp < 0) { + idxUp = 0; + } + if (idxDown >= maxIdx) { + idxDown = currIdx; + } + colUp = Filters._getARGB(pixels, idxUp); + colLeft = Filters._getARGB(pixels, idxLeft); + colDown = Filters._getARGB(pixels, idxDown); + colRight = Filters._getARGB(pixels, idxRight); + //compute luminance + currLum = 77 * (colOrig >> 16 & 255) + 151 * (colOrig >> 8 & 255) + 28 * (colOrig & 255); + lumLeft = 77 * (colLeft >> 16 & 255) + 151 * (colLeft >> 8 & 255) + 28 * (colLeft & 255); + lumRight = 77 * (colRight >> 16 & 255) + 151 * (colRight >> 8 & 255) + 28 * (colRight & 255); + lumUp = 77 * (colUp >> 16 & 255) + 151 * (colUp >> 8 & 255) + 28 * (colUp & 255); + lumDown = 77 * (colDown >> 16 & 255) + 151 * (colDown >> 8 & 255) + 28 * (colDown & 255); + if (lumLeft < currLum) { + colOut = colLeft; + currLum = lumLeft; + } + if (lumRight < currLum) { + colOut = colRight; + currLum = lumRight; + } + if (lumUp < currLum) { + colOut = colUp; + currLum = lumUp; + } + if (lumDown < currLum) { + colOut = colDown; + currLum = lumDown; + } // Store the updated color. + + out[currIdx++] = colOut; + } + } + Filters._setPixels(pixels, out); + }, + blur: function blur(canvas, radius) { + blurARGB(canvas, radius); } }; - /** - * 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 & 255) + 151 * (colOrig >> 8 & 255) + 28 * (colOrig & 255); - lumLeft = 77 * (colLeft >> 16 & 255) + 151 * (colLeft >> 8 & 255) + 28 * (colLeft & 255); - lumRight = 77 * (colRight >> 16 & 255) + 151 * (colRight >> 8 & 255) + 28 * (colRight & 255); - lumUp = 77 * (colUp >> 16 & 255) + 151 * (colUp >> 8 & 255) + 28 * (colUp & 255); - lumDown = 77 * (colDown >> 16 & 255) + 151 * (colDown >> 8 & 255) + 28 * (colDown & 255); - if (lumLeft > currLum) { - colOut = colLeft; - currLum = lumLeft; - } - if (lumRight > currLum) { - colOut = colRight; - currLum = lumRight; - } - if (lumUp > currLum) { - colOut = colUp; - currLum = lumUp; - } - if (lumDown > currLum) { - colOut = colDown; - currLum = lumDown; - } - 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 & 255) + 151 * (colOrig >> 8 & 255) + 28 * (colOrig & 255); - lumLeft = 77 * (colLeft >> 16 & 255) + 151 * (colLeft >> 8 & 255) + 28 * (colLeft & 255); - lumRight = 77 * (colRight >> 16 & 255) + 151 * (colRight >> 8 & 255) + 28 * (colRight & 255); - lumUp = 77 * (colUp >> 16 & 255) + 151 * (colUp >> 8 & 255) + 28 * (colUp & 255); - lumDown = 77 * (colDown >> 16 & 255) + 151 * (colDown >> 8 & 255) + 28 * (colDown & 255); - if (lumLeft < currLum) { - colOut = colLeft; - currLum = lumLeft; - } - if (lumRight < currLum) { - colOut = colRight; - currLum = lumRight; - } - if (lumUp < currLum) { - colOut = colUp; - currLum = lumUp; - } - if (lumDown < currLum) { - colOut = colDown; - currLum = lumDown; - } - out[currIdx++] = colOut; - } - } - Filters._setPixels(pixels, out); - }; // BLUR - // internal kernel stuff for the gaussian blur filter + // BLUR + // Internal kernel stuff for the gaussian blur filter. var blurRadius; var blurKernelSize; var blurKernel; @@ -77037,6 +83058,7 @@ radius = radius < 1 ? 1 : radius < 248 ? radius : 248; if (blurRadius !== radius) { blurRadius = radius; + // Calculating the size of the blur kernel blurKernelSize = 1 + blurRadius << 1; blurKernel = new Int32Array(blurKernelSize); blurMult = new Array(blurKernelSize); @@ -77047,6 +83069,7 @@ bki; var bm, bmi; + // Generating blur kernel values. for (var i = 1, radiusi = radius - 1; i < radius; i++) { blurKernel[radius + i] = blurKernel[radiusi] = bki = radiusi * radiusi; bm = blurMult[radius + i]; @@ -77061,10 +83084,11 @@ bm[k] = bk * k; } } - } // Port of https://github.com/processing/processing/blob/ + } // Port of https://github.com/processing/processing/blob/ // main/core/src/processing/core/PImage.java#L1433 function blurARGB(canvas, radius) { + // Get pixel data. var pixels = Filters._toPixels(canvas); var width = canvas.width; var height = canvas.height; @@ -77093,10 +83117,12 @@ y, i; var bm; + // Horizontal pass. for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { cb = cg = cr = ca = sum = 0; read = x - blurRadius; + // Handle edge cases. if (read < 0) { bk0 = - read; read = 0; @@ -77130,9 +83156,11 @@ yi = 0; ym = - blurRadius; ymi = ym * width; + // Vertical pass. for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { cb = cg = cr = ca = sum = 0; + // Handle edge cases. if (ym < 0) { bk0 = ri = - ym; read = x; @@ -77156,7 +83184,8 @@ sum += blurKernel[i]; ri++; read += width; - } + } // Set final ARGB value + argb[x + yi] = ca / sum << 24 | cr / sum << 16 | cg / sum << 8 | cb / sum; } yi += width; @@ -77165,43 +83194,40 @@ } Filters._setPixels(pixels, argb); } - Filters.blur = function (canvas, radius) { - blurARGB(canvas, radius); - }; var _default = Filters; exports.default = _default; }, { - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.typed-array.copy-within': 215, - 'core-js/modules/es.typed-array.every': 216, - 'core-js/modules/es.typed-array.fill': 217, - 'core-js/modules/es.typed-array.filter': 218, - 'core-js/modules/es.typed-array.find': 220, - 'core-js/modules/es.typed-array.find-index': 219, - 'core-js/modules/es.typed-array.for-each': 223, - 'core-js/modules/es.typed-array.includes': 224, - 'core-js/modules/es.typed-array.index-of': 225, - 'core-js/modules/es.typed-array.int32-array': 227, - 'core-js/modules/es.typed-array.iterator': 228, - 'core-js/modules/es.typed-array.join': 229, - 'core-js/modules/es.typed-array.last-index-of': 230, - 'core-js/modules/es.typed-array.map': 231, - 'core-js/modules/es.typed-array.reduce': 233, - 'core-js/modules/es.typed-array.reduce-right': 232, - 'core-js/modules/es.typed-array.reverse': 234, - 'core-js/modules/es.typed-array.set': 235, - 'core-js/modules/es.typed-array.slice': 236, - 'core-js/modules/es.typed-array.some': 237, - 'core-js/modules/es.typed-array.sort': 238, - 'core-js/modules/es.typed-array.subarray': 239, - 'core-js/modules/es.typed-array.to-locale-string': 240, - 'core-js/modules/es.typed-array.to-string': 241, - 'core-js/modules/es.typed-array.uint8-array': 244 + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.typed-array.copy-within': 223, + 'core-js/modules/es.typed-array.every': 224, + 'core-js/modules/es.typed-array.fill': 225, + 'core-js/modules/es.typed-array.filter': 226, + 'core-js/modules/es.typed-array.find': 228, + 'core-js/modules/es.typed-array.find-index': 227, + 'core-js/modules/es.typed-array.for-each': 231, + 'core-js/modules/es.typed-array.includes': 232, + 'core-js/modules/es.typed-array.index-of': 233, + 'core-js/modules/es.typed-array.int32-array': 235, + 'core-js/modules/es.typed-array.iterator': 236, + 'core-js/modules/es.typed-array.join': 237, + 'core-js/modules/es.typed-array.last-index-of': 238, + 'core-js/modules/es.typed-array.map': 239, + 'core-js/modules/es.typed-array.reduce': 241, + 'core-js/modules/es.typed-array.reduce-right': 240, + 'core-js/modules/es.typed-array.reverse': 242, + 'core-js/modules/es.typed-array.set': 243, + 'core-js/modules/es.typed-array.slice': 244, + 'core-js/modules/es.typed-array.some': 245, + 'core-js/modules/es.typed-array.sort': 246, + 'core-js/modules/es.typed-array.subarray': 247, + 'core-js/modules/es.typed-array.to-locale-string': 248, + 'core-js/modules/es.typed-array.to-string': 249, + 'core-js/modules/es.typed-array.uint8-array': 252 } ], - 312: [ + 320: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -77209,6 +83235,7 @@ _dereq_('core-js/modules/es.symbol.iterator'); _dereq_('core-js/modules/es.array.concat'); _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.for-each'); _dereq_('core-js/modules/es.array.from'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.map'); @@ -77246,13 +83273,11 @@ _dereq_('core-js/modules/es.typed-array.subarray'); _dereq_('core-js/modules/es.typed-array.to-locale-string'); _dereq_('core-js/modules/es.typed-array.to-string'); + _dereq_('core-js/modules/web.dom-collections.for-each'); _dereq_('core-js/modules/web.dom-collections.iterator'); - _dereq_('core-js/modules/es.symbol'); - _dereq_('core-js/modules/es.symbol.description'); - _dereq_('core-js/modules/es.symbol.iterator'); _dereq_('core-js/modules/es.array.concat'); _dereq_('core-js/modules/es.array.filter'); - _dereq_('core-js/modules/es.array.from'); + _dereq_('core-js/modules/es.array.for-each'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.map'); _dereq_('core-js/modules/es.array.slice'); @@ -77289,6 +83314,7 @@ _dereq_('core-js/modules/es.typed-array.subarray'); _dereq_('core-js/modules/es.typed-array.to-locale-string'); _dereq_('core-js/modules/es.typed-array.to-string'); + _dereq_('core-js/modules/web.dom-collections.for-each'); _dereq_('core-js/modules/web.dom-collections.iterator'); Object.defineProperty(exports, '__esModule', { value: true @@ -77318,39 +83344,49 @@ } return arr2; } - } /** - * Creates a new p5.Image (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. - * - * .pixels 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 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. See .pixels for - * more info. It may also be simpler to use set() or get(). - * - * Before accessing the pixels of an image, the data must loaded with the - * loadPixels() function. After the array data has been modified, the - * updatePixels() function must be run to update the changes. + } /** + * @module Image + * @submodule Image + * @for p5 + * @requires core + */ + /** + * This module defines the p5 methods for the p5.Image class + * for drawing images to the main display canvas. + */ + /** + * Creates a new p5.Image object. The new image is + * transparent by default. + * + * `createImage()` uses the `width` and `height` paremeters to set the new + * p5.Image object's dimensions in pixels. The new + * p5.Image can be modified by updating its + * pixels array or by calling its + * get() and + * set() methods. The + * loadPixels() method must be called + * before reading or modifying pixel values. The + * updatePixels() method must be called + * for updates to take effect. * * @method createImage - * @param {Integer} width width in pixels - * @param {Integer} height height in pixels - * @return {p5.Image} the p5.Image object + * @param {Integer} width width in pixels. + * @param {Integer} height height in pixels. + * @return {p5.Image} new p5.Image object. * @example *
      * * 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)); + * for (let x = 0; x < img.width; x += 1) { + * for (let y = 0; y < img.height; y += 1) { + * img.set(x, y, 0); * } * } * img.updatePixels(); * image(img, 17, 17); + * + * describe('A black square drawn in the middle of a gray square.'); * *
      * @@ -77358,39 +83394,42 @@ * * 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)); + * for (let x = 0; x < img.width; x += 1) { + * for (let y = 0; y < img.height; y += 1) { + * let a = map(x, 0, img.width, 0, 255); + * let c = color(0, a); + * img.set(x, y, c); * } * } * img.updatePixels(); * image(img, 17, 17); - * image(img, 34, 34); + * + * describe('A square with a horizontal color gradient that transitions from gray to black.'); * *
      * *
      * - * 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); + * let halfImage = 4 * (d * img.width) * (d * img.height / 2); * 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); + * // Red. + * img.pixels[i] = 0; + * // Green. + * img.pixels[i + 1] = 0; + * // Blue. + * img.pixels[i + 2] = 0; + * // Alpha. + * img.pixels[i + 3] = 255; * } * img.updatePixels(); * image(img, 17, 17); + * + * describe('A black square drawn in the middle of a gray square.'); * *
      - * - * @alt - * 66×66 dark turquoise rect in center of canvas. - * 2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas - * no image displayed */ _main.default.prototype.createImage = function (width, height) { @@ -77398,46 +83437,75 @@ 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. + * Saves 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' + * @param {p5.Framebuffer|p5.Element|HTMLCanvasElement} selectedCanvas reference to a + * specific HTML5 canvas element. + * @param {String} [filename] file name. Defaults to 'untitled'. + * @param {String} [extension] file extension, either 'jpg' or 'png'. Defaults to 'png'. * * @example - *
      + *
      + * * function setup() { - * let c = createCanvas(100, 100); - * background(255, 0, 0); - * saveCanvas(c, 'myCanvas', 'jpg'); + * createCanvas(100, 100); + * background(255); + * saveCanvas(); * } - *
      - *
      - * // 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); + * createCanvas(100, 100); + * background(255); + * saveCanvas('myCanvas.jpg'); + * } + * + *
      + * + *
      + * + * function setup() { + * createCanvas(100, 100); + * background(255); * 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(); + *
      + * + * function setup() { + * let cnv = createCanvas(100, 100); + * background(255); + * saveCanvas(cnv); * } - *
      + *
      + *
      * - * @alt - * no image displayed - * no image displayed - * no image displayed + *
      + * + * function setup() { + * let cnv = createCanvas(100, 100); + * background(255); + * saveCanvas(cnv, 'myCanvas.jpg'); + * } + * + *
      + * + *
      + * + * function setup() { + * let cnv = createCanvas(100, 100); + * background(255); + * saveCanvas(cnv, 'myCanvas', 'jpg'); + * } + * + *
      */ /** * @method saveCanvas @@ -77445,18 +83513,30 @@ * @param {String} [extension] */ _main.default.prototype.saveCanvas = function () { - _main.default._validateParameters('saveCanvas', arguments); // copy arguments to array + _main.default._validateParameters('saveCanvas', arguments); + // copy arguments to array var args = [ ].slice.call(arguments); var htmlCanvas, filename, - extension; + extension, + temporaryGraphics; 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 if (arguments[0] instanceof _main.default.Framebuffer) { + var framebuffer = arguments[0]; + temporaryGraphics = this.createGraphics(framebuffer.width, framebuffer.height); + temporaryGraphics.pixelDensity(pixelDensity()); + framebuffer.loadPixels(); + temporaryGraphics.loadPixels(); + temporaryGraphics.pixels.set(framebuffer.pixels); + temporaryGraphics.updatePixels(); + htmlCanvas = temporaryGraphics.elt; + args.shift(); } else { htmlCanvas = this._curElement && this._curElement.elt; } @@ -77480,12 +83560,15 @@ } htmlCanvas.toBlob(function (blob) { _main.default.prototype.downloadFile(blob, filename, extension); + if (temporaryGraphics) temporaryGraphics.remove(); }, mimeType); - }; // this is the old saveGif, left here for compatibility purposes + }; + // this is the old saveGif, left here for compatibility purposes // the only place I found it being used was on image/p5.Image.js, on the // save function. that has been changed to use this function. _main.default.prototype.encodeAndDownloadGif = function (pImg, filename) { - var props = pImg.gifProperties; //convert loopLimit back into Netscape Block formatting + var props = pImg.gifProperties; + //convert loopLimit back into Netscape Block formatting var loopLimit = props.loopLimit; if (loopLimit === 1) { loopLimit = null; @@ -77494,24 +83577,28 @@ } var buffer = new Uint8Array(pImg.width * pImg.height * props.numFrames); var allFramesPixelColors = [ - ]; // Used to determine the occurrence of unique palettes and the frames + ]; + // Used to determine the occurrence of unique palettes and the frames // which use them var paletteFreqsAndFrames = { - }; // Pass 1: + }; + // 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 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 ? + 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 + } // A way to put use the entire palette as an object key var paletteStr = _toConsumableArray(paletteSet).sort().toString(); if (paletteFreqsAndFrames[paletteStr] === undefined) { @@ -77528,16 +83615,19 @@ allFramesPixelColors.push(pixelColors); } var framesUsingGlobalPalette = [ - ]; // Now to build the global palette + ]; + // Now to build the global palette // Sort all the unique palettes in descending order of their occurrence var palettesSortedByFreq = Object.keys(paletteFreqsAndFrames).sort(function (a, b) { return paletteFreqsAndFrames[b].freq - paletteFreqsAndFrames[a].freq; - }); // The initial global palette is the one with the most occurrence + }); + // The initial global palette is the one with the most occurrence var globalPalette = palettesSortedByFreq[0].split(',').map(function (a) { return parseInt(a); }); framesUsingGlobalPalette = framesUsingGlobalPalette.concat(paletteFreqsAndFrames[globalPalette].frames); - var globalPaletteSet = new Set(globalPalette); // Build a more complete global palette + var globalPaletteSet = new Set(globalPalette); + // Build a more complete global palette // Iterate over the remaining palettes in the order of // their occurrence and see if the colors in this palette which are // not in the global palette can be added there, while keeping the length @@ -77553,12 +83643,13 @@ 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 + } // 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 + 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 = { }; @@ -77566,20 +83657,22 @@ if (!globalIndicesLookup[globalPalette[_i2]]) { globalIndicesLookup[globalPalette[_i2]] = _i2; } - } // force palette to be power of 2 + } // force palette to be power of 2 var powof2 = 1; while (powof2 < globalPalette.length) { powof2 <<= 1; } - globalPalette.length = powof2; // global opts + 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 + }; + // 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 @@ -77590,31 +83683,33 @@ 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 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 + }; + // 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]; + allFramesPixelColors[_i3].forEach(function (color, k) { if (localPaletteRequired) { - if (colorIndicesLookup[_color] === undefined) { - colorIndicesLookup[_color] = palette.length; - palette.push(_color); + if (colorIndicesLookup[color] === undefined) { + colorIndicesLookup[color] = palette.length; + palette.push(color); } - pixelPaletteIndex[_k] = colorIndicesLookup[_color]; + pixelPaletteIndex[k] = colorIndicesLookup[color]; } else { - pixelPaletteIndex[_k] = globalIndicesLookup[_color]; + 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); + if (allFramesPixelColors[_i3 - 1][k] !== color) { + cannotBeTransparent.add(color); } } - } + }); var frameOpts = { - }; // Transparency optimization + }; + // Transparency optimization var canBeTransparent = palette.filter(function (a) { return !cannotBeTransparent.has(a); }); @@ -77623,13 +83718,14 @@ var transparent = canBeTransparent[0]; var transparentIndex = localPaletteRequired ? colorIndicesLookup[transparent] : globalIndicesLookup[transparent]; if (_i3 > 0) { - for (var _k2 = 0; _k2 < allFramesPixelColors[_i3].length; _k2++) { + for (var _k = 0; _k < allFramesPixelColors[_i3].length; _k++) { // If this pixel in this frame has the same color in previous frame - if (allFramesPixelColors[_i3 - 1][_k2] === allFramesPixelColors[_i3][_k2]) { - pixelPaletteIndex[_k2] = transparentIndex; + if (allFramesPixelColors[_i3 - 1][_k] === allFramesPixelColors[_i3][_k]) { + pixelPaletteIndex[_k] = transparentIndex; } } - frameOpts.transparent = transparentIndex; // If this frame has any transparency, do not dispose the previous frame + frameOpts.transparent = transparentIndex; + // If this frame has any transparency, do not dispose the previous frame previousFrame.frameOpts.disposal = 1; } } @@ -77646,7 +83742,7 @@ 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 + } // previous frame object should now have details of this frame previousFrame = { pixelPaletteIndex: pixelPaletteIndex, @@ -77656,7 +83752,8 @@ for (var _i3 = 0; _i3 < props.numFrames; _i3++) { _loop(_i3); } - previousFrame.frameOpts.disposal = 1; // add the last frame + 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())], { @@ -77665,50 +83762,78 @@ _main.default.prototype.downloadFile(blob, filename, extension); }; /** - * Capture a sequence of frames that can be used to create a movie. - * Accepts a callback. For example, you may wish to send the frames - * to a server where they can be stored or converted into a movie. - * If no callback is provided, the browser will pop up save dialogues in an - * attempt to download all of the images that have just been created. With the - * callback provided the image data isn't saved by default but instead passed - * as an argument to the callback function as an array of objects, with the - * size of array equal to the total number of frames. - * - * The arguments `duration` and `framerate` are constrained to be less or equal to 15 and 22, respectively, which means you - * can only download a maximum of 15 seconds worth of frames at 22 frames per second, adding up to 330 frames. - * This is done in order to avoid memory problems since a large enough canvas can fill up the memory in your computer - * very easily and crash your program or even your browser. - * - * To export longer animations, you might look into a library like - * ccapture.js. - * - * @method saveFrames - * @param {String} filename - * @param {String} extension 'jpg' or 'png' - * @param {Number} duration Duration in seconds to save the frames for. This parameter will be constrained to be less or equal to 15. - * @param {Number} framerate Framerate to save the frames in. This parameter will be constrained to be less or equal to 22. - * @param {function(Array)} [callback] A callback function that will be executed + * Captures a sequence of frames from the canvas that can be used to create a + * movie. Frames are downloaded as individual image files by default. + * + * The first parameter, `filename`, sets the prefix for the file names. For + * example, setting the prefix to `'frame'` would generate the image files + * `frame0.png`, `frame1.png`, and so on. The second parameter, `extension`, + * sets the file type to either `'png'` or `'jpg'`. + * + * The third parameter, `duration`, sets the duration to record in seconds. + * The maximum duration is 15 seconds. The fourth parameter, `framerate`, sets + * the number of frames to record per second. The maximum frame rate value is + * 22. Limits are placed on `duration` and `framerate` to avoid using too much + * memory. Recording large canvases can easily crash sketches or even web + * browsers. + * + * The fifth parameter, `callback`, is optional. If a function is passed, + * image files won't be saved by default. The callback function can be used + * to process an array containing the data for each captured frame. The array + * of image data contains a sequence of objects with three properties for each + * frame: `imageData`, `filename`, and `extension`. + * + * @method saveFrames + * @param {String} filename prefix of file name. + * @param {String} extension file extension, either 'jpg' or 'png'. + * @param {Number} duration duration in seconds to record. This parameter will be constrained to be less or equal to 15. + * @param {Number} framerate number of frames to save per second. This parameter will be constrained to be less or equal to 22. + * @param {function(Array)} [callback] callback function that will be executed to handle the image data. This function should accept an array as argument. The array will contain the specified number of frames of objects. Each object has three - properties: imageData - an - image/octet-stream, filename and extension. - * @example - *
      + properties: `imageData`, `filename`, and `extension`. + * @example + *
      + * + * function draw() { + * let r = frameCount % 255; + * let g = 50; + * let b = 100; + * background(r, g, b); + * + * describe('A square repeatedly changes color from blue to pink.'); + * } + * + * function keyPressed() { + * if (key === 's') { + * saveFrames('frame', 'png', 1, 5); + * } + * } + * + *
      + * + *
      + * * function draw() { - * background(mouseX); + * let r = frameCount % 255; + * let g = 50; + * let b = 100; + * background(r, g, b); + * + * describe('A square repeatedly changes color from blue to pink.'); * } * * function mousePressed() { - * saveFrames('out', 'png', 1, 25, data => { + * saveFrames('frame', 'png', 1, 5, data => { + * // Prints an array of objects containing raw image data, + * // filenames, and extensions. * print(data); * }); * } -
      - * - * @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); @@ -77731,27 +83856,9 @@ 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; - } - } + for (var _i4 = 0, _frames = frames; _i4 < _frames.length; _i4++) { + var f = _frames[_i4]; + _main.default.prototype.downloadFile(f.imageData, f.filename, f.ext); } } frames = [ @@ -77799,54 +83906,56 @@ exports.default = _default; }, { - '../core/main': 290, - 'core-js/modules/es.array.concat': 167, - 'core-js/modules/es.array.filter': 171, - 'core-js/modules/es.array.from': 173, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.map': 179, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.object.keys': 194, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.exec': 199, - 'core-js/modules/es.regexp.to-string': 200, - 'core-js/modules/es.set': 201, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.string.replace': 207, - 'core-js/modules/es.string.split': 209, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.typed-array.copy-within': 215, - 'core-js/modules/es.typed-array.every': 216, - 'core-js/modules/es.typed-array.fill': 217, - 'core-js/modules/es.typed-array.filter': 218, - 'core-js/modules/es.typed-array.find': 220, - 'core-js/modules/es.typed-array.find-index': 219, - 'core-js/modules/es.typed-array.for-each': 223, - 'core-js/modules/es.typed-array.includes': 224, - 'core-js/modules/es.typed-array.index-of': 225, - 'core-js/modules/es.typed-array.iterator': 228, - 'core-js/modules/es.typed-array.join': 229, - 'core-js/modules/es.typed-array.last-index-of': 230, - 'core-js/modules/es.typed-array.map': 231, - 'core-js/modules/es.typed-array.reduce': 233, - 'core-js/modules/es.typed-array.reduce-right': 232, - 'core-js/modules/es.typed-array.reverse': 234, - 'core-js/modules/es.typed-array.set': 235, - 'core-js/modules/es.typed-array.slice': 236, - 'core-js/modules/es.typed-array.some': 237, - 'core-js/modules/es.typed-array.sort': 238, - 'core-js/modules/es.typed-array.subarray': 239, - 'core-js/modules/es.typed-array.to-locale-string': 240, - 'core-js/modules/es.typed-array.to-string': 241, - 'core-js/modules/es.typed-array.uint32-array': 243, - 'core-js/modules/es.typed-array.uint8-array': 244, - 'core-js/modules/web.dom-collections.iterator': 248, - 'omggif': 262 + '../core/main': 298, + 'core-js/modules/es.array.concat': 169, + 'core-js/modules/es.array.filter': 173, + 'core-js/modules/es.array.for-each': 175, + 'core-js/modules/es.array.from': 176, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.map': 182, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.object.keys': 199, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.set': 207, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.string.replace': 214, + 'core-js/modules/es.string.split': 216, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.typed-array.copy-within': 223, + 'core-js/modules/es.typed-array.every': 224, + 'core-js/modules/es.typed-array.fill': 225, + 'core-js/modules/es.typed-array.filter': 226, + 'core-js/modules/es.typed-array.find': 228, + 'core-js/modules/es.typed-array.find-index': 227, + 'core-js/modules/es.typed-array.for-each': 231, + 'core-js/modules/es.typed-array.includes': 232, + 'core-js/modules/es.typed-array.index-of': 233, + 'core-js/modules/es.typed-array.iterator': 236, + 'core-js/modules/es.typed-array.join': 237, + 'core-js/modules/es.typed-array.last-index-of': 238, + 'core-js/modules/es.typed-array.map': 239, + 'core-js/modules/es.typed-array.reduce': 241, + 'core-js/modules/es.typed-array.reduce-right': 240, + 'core-js/modules/es.typed-array.reverse': 242, + 'core-js/modules/es.typed-array.set': 243, + 'core-js/modules/es.typed-array.slice': 244, + 'core-js/modules/es.typed-array.some': 245, + 'core-js/modules/es.typed-array.sort': 246, + 'core-js/modules/es.typed-array.subarray': 247, + 'core-js/modules/es.typed-array.to-locale-string': 248, + 'core-js/modules/es.typed-array.to-string': 249, + 'core-js/modules/es.typed-array.uint32-array': 251, + 'core-js/modules/es.typed-array.uint8-array': 252, + 'core-js/modules/web.dom-collections.for-each': 255, + 'core-js/modules/web.dom-collections.iterator': 256, + 'omggif': 270 } ], - 313: [ + 321: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -78037,56 +84146,85 @@ _next(undefined); }); }; - } /** - * Loads an image from a path and creates a p5.Image from it. + } /** + * @module Image + * @submodule Loading & Displaying + * @for p5 + * @requires core + */ + /** + * Loads an image to create a p5.Image object. * - * 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 loadImage() call in preload(). - * You may also supply a callback function to handle the image when it's ready. + * `loadImage()` interprets the first parameter one of three ways. If the path + * to an image file is provided, `loadImage()` will load it. Paths to local + * files should be relative, such as `'assets/thundercat.jpg'`. URLs such as + * `'https://example.com/thundercat.jpg'` may be blocked due to browser + * security. Raw image data can also be passed as a base64 encoded image in + * the form `'data:image/png;base64,arandomsequenceofcharacters'`. * - * The 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. + * The second parameter is optional. If a function is passed, it will be + * called once the image has loaded. The callback function can optionally use + * the new p5.Image object. + * + * The third parameter is also optional. If a function is passed, it will be + * called if the image fails to load. The callback function can optionally use + * the event error. + * + * Images can take time to load. Calling `loadImage()` in + * preload() ensures images load before they're + * used in setup() or draw(). * * @method loadImage - * @param {String} path Path of the image to be loaded - * @param {function(p5.Image)} [successCallback] Function to be called once - * the image is loaded. Will be passed the - * p5.Image. - * @param {function(Event)} [failureCallback] called with event error if - * the image fails to load. - * @return {p5.Image} the p5.Image object + * @param {String} path path of the image to be loaded or base64 encoded image. + * @param {function(p5.Image)} [successCallback] function called with + * p5.Image once it + * loads. + * @param {function(Event)} [failureCallback] function called with event + * error if the image fails to load. + * @return {p5.Image} the p5.Image object. * @example *
      * * let img; + * * function preload() { * img = loadImage('assets/laDefense.jpg'); * } + * * function setup() { * image(img, 0, 0); + * describe('Image of the underside of a white umbrella and a gridded ceiling.'); * } * *
      + * *
      * * function setup() { - * // here we use a callback to display the image after loading * loadImage('assets/laDefense.jpg', img => { * image(img, 0, 0); * }); + * describe('Image of the underside of a white umbrella and a gridded ceiling.'); * } * *
      * - * @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 + *
      + * + * function setup() { + * loadImage('assets/laDefense.jpg', success, failure); + * } + * + * function success(img) { + * image(img, 0, 0); + * describe('Image of the underside of a white umbrella and a gridded ceiling.'); + * } + * + * function failure(event) { + * console.error('Oops!', event); + * } + * + *
      */ _main.default.prototype.loadImage = function (path, successCallback, failureCallback) { @@ -78124,7 +84262,8 @@ 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.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') { @@ -78140,14 +84279,15 @@ } else { console.error(e); } - }; // Set crossOrigin in case image is served with CORS headers. + }; + // 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 + } // start loading the image img.src = path; } @@ -78164,78 +84304,57 @@ return pImg; }; /** - * Generates a gif of your current animation and downloads it to your computer! - * - * The duration argument specifies how many seconds you want to record from your animation. - * This value is then converted to the necessary number of frames to generate it, depending - * on the value of units. More on that on the next paragraph. + * Generates a gif from a sketch and saves it to a file. `saveGif()` may be + * called in setup() or at any point while a sketch + * is running. * - * An optional object that can contain two more arguments: delay (number) and units (string). + * The first parameter, `fileName`, sets the gif's file name. The second + * parameter, `duration`, sets the gif's duration in seconds. * - * `delay`, specifying how much time we should wait before recording - * - * `units`, a string that can be either 'seconds' or 'frames'. By default it's 'seconds'. - * - * `units` specifies how the duration and delay arguments will behave. - * If 'seconds', these arguments will correspond to seconds, meaning that 3 seconds worth of animation - * will be created. If 'frames', the arguments now correspond to the number of frames you want your - * animation to be, if you are very sure of this number. - * - * This may be called in setup, or, like in the example below, inside an event function, - * like keyPressed or mousePressed. + * The third parameter, `options`, is optional. If an object is passed, + * `saveGif()` will use its properties to customize the gif. `saveGif()` + * recognizes the properties `delay`, `units`, `silent`, + * `notificationDuration`, and `notificationID`. * * @method saveGif - * @param {String} filename File name of your gif - * @param {Number} duration Duration in seconds that you wish to capture from your sketch - * @param {Object} options An optional object that can contain two more arguments: delay, specifying - * how much time we should wait before recording, and units, a string that can be either 'seconds' or - * 'frames'. By default it's 'seconds'. + * @param {String} filename file name of gif. + * @param {Number} duration duration in seconds to capture from the sketch. + * @param {Object} [options] an object that can contain five more properties: + * `delay`, a Number specifying how much time to wait before recording; + * `units`, a String that can be either 'seconds' or 'frames'. By default it's 'seconds’; + * `silent`, a Boolean that defines presence of progress notifications. By default it’s `false`; + * `notificationDuration`, a Number that defines how long in seconds the final notification + * will live. By default it's `0`, meaning the notification will never be removed; + * `notificationID`, a String that specifies the id of the notification's DOM element. By default it’s `'progressBar’`. * * @example *
      * - * function setup() { - * createCanvas(100, 100); - * } - * * function draw() { - * colorMode(RGB); - * background(30); - * - * // create a bunch of circles that move in... circles! - * for (let i = 0; i < 10; i++) { - * let opacity = map(i, 0, 10, 0, 255); - * noStroke(); - * fill(230, 250, 90, opacity); - * circle( - * 30 * sin(frameCount / (30 - i)) + width / 2, - * 30 * cos(frameCount / (30 - i)) + height / 2, - * 10 - * ); - * } + * background(200); + * let c = frameCount % 255; + * fill(c); + * circle(50, 50, 25); + * + * describe('A circle drawn in the middle of a gray square. The circle changes color from black to white, then repeats.'); * } * - * // you can put it in the mousePressed function, - * // or keyPressed for example * function keyPressed() { - * // this will download the first 5 seconds of the animation! * if (key === 's') { * saveGif('mySketch', 5); * } * } * *
      - * - * @alt - * animation of a group of yellow circles moving in circles over a dark background */ - _main.default.prototype.saveGif = /*#__PURE__*/ - function () { - var _ref = _asyncToGenerator( /*#__PURE__*/ - regeneratorRuntime.mark(function _callee(fileName, duration) { + _main.default.prototype.saveGif = /*#__PURE__*/ function () { + var _ref = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee(fileName, duration) { var options, delay, units, + silent, + notificationDuration, + notificationID, _frameRate, gifFrameDelay, nFrames, @@ -78244,7 +84363,6 @@ frameIterator, lastPixelDensity, frames, - progressBarIdName, p, pixels, gl, @@ -78269,7 +84387,10 @@ case 0: options = _args.length > 2 && _args[2] !== undefined ? _args[2] : { delay: 0, - units: 'seconds' + units: 'seconds', + silent: false, + notificationDuration: 0, + notificationID: 'progressBar' }; if (!(typeof fileName !== 'string')) { _context.next = 3; @@ -78286,24 +84407,45 @@ // extract variables for more comfortable use delay = options && options.delay || 0; // in seconds units = options && options.units || 'seconds'; // either 'seconds' or 'frames' - // if arguments in the options object are not correct, cancel operation + silent = options && options.silent || false; + notificationDuration = options && options.notificationDuration || 0; + notificationID = options && options.notificationID || 'progressBar'; // if arguments in the options object are not correct, cancel operation if (!(typeof delay !== 'number')) { - _context.next = 9; + _context.next = 12; break; } throw TypeError('Delay parameter must be a number'); - case 9: + case 12: if (!(units !== 'seconds' && units !== 'frames')) { - _context.next = 11; + _context.next = 14; break; } throw TypeError('Units parameter must be either "frames" or "seconds"'); - case 11: - this._recording = true; // get the project's framerate + case 14: + if (!(typeof silent !== 'boolean')) { + _context.next = 16; + break; + } + throw TypeError('Silent parameter must be a boolean'); + case 16: + if (!(typeof notificationDuration !== 'number')) { + _context.next = 18; + break; + } + throw TypeError('Notification duration parameter must be a number'); + case 18: + if (!(typeof notificationID !== 'string')) { + _context.next = 20; + break; + } + throw TypeError('Notification ID parameter must be a string'); + case 20: + this._recording = true; + // get the project's framerate _frameRate = this._targetFrameRate; // if it is undefined or some non useful value, assume it's 60 if (_frameRate === Infinity || _frameRate === undefined || _frameRate === 0) { _frameRate = 60; - } // calculate frame delay based on frameRate + } // calculate frame delay based on frameRate // this delay has nothing to do with the // delay in options, but rather is the delay // we have to specify to the gif encoder between frames. @@ -78311,7 +84453,8 @@ gifFrameDelay = 1 / _frameRate * 1000; // constrain it to be always greater than 20, // otherwise it won't work in some browsers and systems // reference: https://stackoverflow.com/questions/64473278/gif-frame-duration-seems-slower-than-expected - gifFrameDelay = gifFrameDelay < 20 ? 20 : gifFrameDelay; // check the mode we are in and how many frames + gifFrameDelay = gifFrameDelay < 20 ? 20 : gifFrameDelay; + // check the mode we are in and how many frames // that duration translates to nFrames = units === 'seconds' ? duration * _frameRate : duration; nFramesDelay = units === 'seconds' ? delay * _frameRate : delay; @@ -78319,30 +84462,40 @@ frameIterator = nFramesDelay; this.frameCount = frameIterator; lastPixelDensity = this._pixelDensity; - this.pixelDensity(1); // We first take every frame that we are going to use for the animation + this.pixelDensity(1); + // We first take every frame that we are going to use for the animation frames = [ ]; - progressBarIdName = 'p5.gif.progressBar'; - if (document.getElementById(progressBarIdName) !== null) document.getElementById(progressBarIdName).remove(); - p = this.createP(''); - p.id('progressBar'); - p.style('font-size', '16px'); - p.style('font-family', 'Montserrat'); - p.style('background-color', '#ffffffa0'); - p.style('padding', '8px'); - p.style('border-radius', '10px'); - p.position(0, 0); - if (this.drawingContext instanceof WebGLRenderingContext) { + if (document.getElementById(notificationID) !== null) document.getElementById(notificationID).remove(); + if (!silent) { + p = this.createP(''); + p.id(notificationID); + p.style('font-size', '16px'); + p.style('font-family', 'Montserrat'); + p.style('background-color', '#ffffffa0'); + p.style('padding', '8px'); + p.style('border-radius', '10px'); + p.position(0, 0); + } + if (this._renderer instanceof _main.default.RendererGL) { // if we have a WEBGL context, initialize the pixels array // and the gl context to use them inside the loop - gl = document.getElementById('defaultCanvas0').getContext('webgl'); + gl = this.drawingContext; pixels = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); - } // stop the loop since we are going to manually redraw + } // stop the loop since we are going to manually redraw this.noLoop(); - case 36: + // Defer execution until the rest of the call stack finishes, allowing the + // rest of `setup` to be called (and, importantly, canvases hidden in setup + // to be unhidden.) + // + // Waiting on this empty promise means we'll continue as soon as setup + // finishes without waiting for another frame. + _context.next = 39; + return Promise.resolve(); + case 39: if (!(frameIterator < totalNumberOfFrames)) { - _context.next = 47; + _context.next = 50; break; } /* we draw the next frame. this is important, since @@ -78351,10 +84504,11 @@ to be drawn and immediately save it to a buffer and continue */ - this.redraw(); // depending on the context we'll extract the pixels one way + this.redraw(); + // depending on the context we'll extract the pixels one way // or another data = undefined; - if (this.drawingContext instanceof WebGLRenderingContext) { + if (this._renderer instanceof _main.default.RendererGL) { pixels = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, pixels); data = _flipPixels(pixels); @@ -78363,18 +84517,21 @@ } frames.push(data); frameIterator++; - p.html('Saved frame ' + frames.length.toString() + ' out of ' + nFrames.toString()); - _context.next = 45; + if (!silent) { + p.html('Saved frame ' + frames.length.toString() + ' out of ' + nFrames.toString()); + } + _context.next = 48; return new Promise(function (resolve) { return setTimeout(resolve, 0); }); - case 45: - _context.next = 36; + case 48: + _context.next = 39; break; - case 47: - p.html('Frames processed, generating color palette...'); + case 50: + if (!silent) p.html('Frames processed, generating color palette...'); this.loop(); - this.pixelDensity(lastPixelDensity); // create the gif encoder and the colorspace format + this.pixelDensity(lastPixelDensity); + // create the gif encoder and the colorspace format gif = (0, _gifenc.GIFEncoder) (); // calculate the global palette for this set of frames globalPalette = _generateGlobalPalette(frames); // Rather than using applyPalette() from the gifenc library, we use our // own function to map frame pixels to a palette color. This way, we can @@ -78399,11 +84556,11 @@ prevIndexedFrame = [ ]; i = 0; - case 57: + case 60: if (!(i < frames.length)) { - _context.next = 68; + _context.next = 71; break; - } //const indexedFrame = applyPalette(frames[i], globalPaletteWithoutAlpha, 'rgba565'); + } //const indexedFrame = applyPalette(frames[i], globalPaletteWithoutAlpha, 'rgba565'); indexedFrame = getIndexedFrame(frames[i]); // Make a copy of the palette-applied frame before editing the original // to use transparent pixels @@ -78423,7 +84580,7 @@ if (indexedFrame[_i] === prevIndexedFrame[_i]) { indexedFrame[_i] = transparentIndex; } - } // Write frame into the encoder + } // Write frame into the encoder gif.writeFrame(indexedFrame, this.width, this.height, { delay: gifFrameDelay, @@ -78433,18 +84590,22 @@ }); } prevIndexedFrame = originalIndexedFrame; - p.html('Rendered frame ' + i.toString() + ' out of ' + nFrames.toString()); // this just makes the process asynchronous, preventing + if (!silent) { + p.html('Rendered frame ' + i.toString() + ' out of ' + nFrames.toString()); + } // this just makes the process asynchronous, preventing // that the encoding locks up the browser - _context.next = 65; + + _context.next = 68; return new Promise(function (resolve) { return setTimeout(resolve, 0); }); - case 65: + case 68: i++; - _context.next = 57; + _context.next = 60; break; - case 68: - gif.finish(); // Get a direct typed array view into the buffer to avoid copying it + case 71: + gif.finish(); + // Get a direct typed array view into the buffer to avoid copying it buffer = gif.bytesView(); extension = 'gif'; blob = new Blob([buffer], { @@ -78454,9 +84615,14 @@ ]; this._recording = false; this.loop(); - p.html('Done. Downloading your gif!🌸'); + if (!silent) { + p.html('Done. Downloading your gif!🌸'); + if (notificationDuration > 0) setTimeout(function () { + return p.remove(); + }, notificationDuration * 1000); + } _main.default.prototype.downloadFile(blob, fileName, extension); - case 77: + case 80: case 'end': return _context.stop(); } @@ -78474,13 +84640,17 @@ // this stack overflow answer: // https://stackoverflow.com/questions/41969562/how-can-i-flip-the-result-of-webglrenderingcontext-readpixels var halfHeight = parseInt(height / 2); - var bytesPerRow = width * 4; // make a temp buffer to hold one row + var bytesPerRow = width * 4; + // make a temp buffer to hold one row var temp = new Uint8Array(width * 4); for (var y = 0; y < halfHeight; ++y) { var topOffset = y * bytesPerRow; - var bottomOffset = (height - y - 1) * bytesPerRow; // make copy of a row on the top half - temp.set(pixels.subarray(topOffset, topOffset + bytesPerRow)); // copy a row from the bottom half to the top - pixels.copyWithin(topOffset, bottomOffset, bottomOffset + bytesPerRow); // copy the copy of the top half row to the bottom half + var bottomOffset = (height - y - 1) * bytesPerRow; + // make copy of a row on the top half + temp.set(pixels.subarray(topOffset, topOffset + bytesPerRow)); + // copy a row from the bottom half to the top + pixels.copyWithin(topOffset, bottomOffset, bottomOffset + bytesPerRow); + // copy the copy of the top half row to the bottom half pixels.set(temp, bottomOffset); } return pixels; @@ -78488,17 +84658,19 @@ function _generateGlobalPalette(frames) { // make an array the size of every possible color in every possible frame // that is: width * height * frames. - var allColors = new Uint8Array(frames.length * frames[0].length); // put every frame one after the other in sequence. + var allColors = new Uint8Array(frames.length * frames[0].length); + // put every frame one after the other in sequence. // this array will hold absolutely every pixel from the animation. // the set function on the Uint8Array works super fast tho! for (var f = 0; f < frames.length; f++) { allColors.set(frames[f], f * frames[0].length); - } // quantize this massive array into 256 colors and return it! + } // quantize this massive array into 256 colors and return it! var colorPalette = (0, _gifenc.quantize) (allColors, 256, { format: 'rgba4444', oneBitAlpha: true - }); // when generating the palette, we have to leave space for 1 of the + }); + // when generating the palette, we have to leave space for 1 of the // indices to be a random color that does not appear anywhere in our // animation to use for transparency purposes. So, if the palette is full // (has 256 colors), we overwrite the last one with a random, fully transparent @@ -78532,70 +84704,72 @@ ]; var numFrames = gifReader.numFrames(); var framePixels = new Uint8ClampedArray(pImg.width * pImg.height * 4); - if (numFrames > 1) { - var loadGIFFrameIntoImage = function loadGIFFrameIntoImage(frameNum, gifReader) { - try { - gifReader.decodeAndBlitFrameRGBA(frameNum, framePixels); - } catch (e) { - _main.default._friendlyFileLoadError(8, pImg.src); - if (typeof failureCallback === 'function') { - failureCallback(e); - } else { - console.error(e); - } - } - }; - for (var j = 0; j < numFrames; j++) { - var frameInfo = gifReader.frameInfo(j); - var prevFrameData = pImg.drawingContext.getImageData(0, 0, pImg.width, pImg.height); - framePixels = prevFrameData.data.slice(); - loadGIFFrameIntoImage(j, gifReader); - var imageData = new ImageData(framePixels, pImg.width, pImg.height); - pImg.drawingContext.putImageData(imageData, 0, 0); - var frameDelay = frameInfo.delay; // To maintain the default of 10FPS when frameInfo.delay equals to 0 - if (frameDelay === 0) { - frameDelay = 10; + 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); } - frames.push({ - image: pImg.drawingContext.getImageData(0, 0, pImg.width, pImg.height), - delay: frameDelay * 10 //GIF stores delay in one-hundredth of a second, shift to ms - }); // Some GIFs are encoded so that they expect the previous frame - // to be under the current frame. This can occur at a sub-frame level - // - // Values : 0 - No disposal specified. The decoder is - // not required to take any action. - // 1 - Do not dispose. The graphic is to be left - // in place. - // 2 - Restore to background color. The area used by the - // graphic must be restored to the background color. - // 3 - Restore to previous. The decoder is required to - // restore the area overwritten by the graphic with - // what was there prior to rendering the graphic. - // 4-7 - To be defined. - if (frameInfo.disposal === 2) { - // Restore background color - pImg.drawingContext.clearRect(frameInfo.x, frameInfo.y, frameInfo.width, frameInfo.height); - } else if (frameInfo.disposal === 3) { - // Restore previous - pImg.drawingContext.putImageData(prevFrameData, 0, 0, frameInfo.x, frameInfo.y, frameInfo.width, frameInfo.height); - } - } //Uses Netscape block encoding - //to repeat forever, this will be 0 - //to repeat just once, this will be null - //to repeat N times (1 1) { pImg.gifProperties = { displayIndex: 0, loopLimit: loopLimit, @@ -78747,134 +84921,156 @@ return iVal; } } /** - * Draw an image to the p5.js canvas. - * - * This function can be used with different numbers of parameters. The - * simplest use requires only three parameters: img, x, and y—where (x, y) is - * the position of the image. Two more parameters can optionally be added to - * specify the width and height of the image. - * - * This function can also be used with eight Number parameters. To - * differentiate between all these parameters, p5.js uses the language of - * "destination rectangle" (which corresponds to "dx", "dy", etc.) and "source - * image" (which corresponds to "sx", "sy", etc.) below. Specifying the - * "source image" dimensions can be useful when you want to display a - * subsection of the source image instead of the whole thing. Here's a diagram - * to explain further: + * Draws a source image to the canvas. + * + * The first parameter, `img`, is the source image to be drawn. The second and + * third parameters, `dx` and `dy`, set the coordinates of the destination + * image's top left corner. See imageMode() for + * other ways to position images. + * + * Here's a diagram that explains how optional parameters work in `image()`: + * * * - * This function can also be used to draw images without distorting the orginal aspect ratio, - * by adding 9th parameter, fit, which can either be COVER or CONTAIN. - * CONTAIN, as the name suggests, contains the whole image within the specified destination box - * without distorting the image ratio. - * COVER covers the entire destination box. + * The fourth and fifth parameters, `dw` and `dh`, are optional. They set the + * the width and height to draw the destination image. By default, `image()` + * draws the full source image at its original size. * + * The sixth and seventh parameters, `sx` and `sy`, are also optional. + * These coordinates define the top left corner of a subsection to draw from + * the source image. * + * The eighth and ninth parameters, `sw` and `sh`, are also optional. + * They define the width and height of a subsection to draw from the source + * image. By default, `image()` draws the full subsection that begins at + * (`sx`, `sy`) and extends to the edges of the source image. + * + * The ninth parameter, `fit`, is also optional. It enables a subsection of + * the source image to be drawn without affecting its aspect ratio. If + * `CONTAIN` is passed, the full subsection will appear within the destination + * rectangle. If `COVER` is passed, the subsection will completely cover the + * destination rectangle. This may have the effect of zooming into the + * subsection. + * + * The tenth and eleventh paremeters, `xAlign` and `yAlign`, are also + * optional. They determine how to align the fitted subsection. `xAlign` can + * be set to either `LEFT`, `RIGHT`, or `CENTER`. `yAlign` can be set to + * either `TOP`, `BOTTOM`, or `CENTER`. By default, both `xAlign` and `yAlign` + * are set to `CENTER`. * * @method image - * @param {p5.Image|p5.Element|p5.Texture} 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 + * @param {p5.Image|p5.Element|p5.Texture|p5.Framebuffer|p5.FramebufferTexture} img image to display. + * @param {Number} x x-coordinate of the top-left corner of the image. + * @param {Number} y y-coordinate of the top-left corner of the image. + * @param {Number} [width] width to draw the image. + * @param {Number} [height] height to draw the image. * @example *
      * * let img; + * * 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 + * background(50); * image(img, 0, 0); + * + * describe('An image of the underside of a white umbrella with a gridded ceiling above.'); * } * *
      + * *
      * * let img; + * * function preload() { * img = loadImage('assets/laDefense.jpg'); * } + * * function setup() { * background(50); - * // Top-left corner of the img is at (10, 10) - * // Width and height are 50×50 - * image(img, 10, 10, 50, 50); + * image(img, 10, 10); + * + * describe('An image of the underside of a white umbrella with a gridded ceiling above. The image has dark gray borders on its left and top.'); * } * *
      + * *
      * + * let img; + * + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * * function setup() { - * // Here, we use a callback to display the image after loading - * loadImage('assets/laDefense.jpg', img => { - * image(img, 0, 0); - * }); + * background(50); + * image(img, 0, 0, 50, 50); + * + * describe('An image of the underside of a white umbrella with a gridded ceiling above. The image is drawn in the top left corner of a dark gray square.'); * } * *
      + * *
      * * let img; + * * function preload() { - * img = loadImage('assets/gradient.png'); + * img = loadImage('assets/laDefense.jpg'); * } + * * function setup() { - * // 1. Background image - * // Top-left corner of the img is at (0, 0) - * // Width and height are the img's original width and height, 100×100 - * image(img, 0, 0); - * // 2. Top right image - * // Top-left corner of destination rectangle is at (50, 0) - * // Destination rectangle width and height are 40×20 - * // The next parameters are relative to the source image: - * // - Starting at position (50, 50) on the source image, capture a 50×50 - * // subsection - * // - Draw this subsection to fill the dimensions of the destination rectangle - * image(img, 50, 0, 40, 20, 50, 50, 50, 50); + * background(50); + * image(img, 25, 25, 50, 50, 25, 25, 50, 50); + * + * describe('An image of a gridded ceiling drawn in the center of a dark gray square.'); * } * *
      + * *
      * * let img; + * * function preload() { - * // dimensions of image are 780 x 440 - * // dimensions of canvas are 100 x 100 * img = loadImage('assets/moonwalk.jpg'); * } + * * function setup() { - * // CONTAIN the whole image without distorting the image's aspect ratio - * // CONTAIN the image within the specified destination box and display at LEFT,CENTER position - * background(color('green')); - * image(img, 0, 0, width, height, 0, 0, img.width, img.height, CONTAIN, LEFT); + * background(50); + * image(img, 0, 0, width, height, 0, 0, img.width, img.height, CONTAIN); + * + * describe('An image of an astronaut on the moon. The top and bottom borders of the image are dark gray.'); * } * *
      + * *
      * * let img; + * * function preload() { - * img = loadImage('assets/laDefense50.png'); // dimensions of image are 50 x 50 + * // Image is 50 x 50 pixels. + * img = loadImage('assets/laDefense50.png'); * } + * * function setup() { - * // COVER the whole destination box without distorting the image's aspect ratio - * // COVER the specified destination box which is of dimension 100 x 100 - * // Without specifying xAlign or yAlign, the image will be - * // centered in the destination box in both axes + * background(50); * image(img, 0, 0, width, height, 0, 0, img.width, img.height, COVER); + * + * describe('A pixelated image of the underside of a white umbrella with a gridded ceiling above.'); * } * *
      - * @alt - * image of the underside of a white umbrella and gridded ceiling above - * image of the underside of a white umbrella and gridded ceiling above */ /** * @method image - * @param {p5.Image|p5.Element|p5.Texture} img + * @param {p5.Image|p5.Element|p5.Texture|p5.Framebuffer|p5.FramebufferTexture} img * @param {Number} dx the x-coordinate of the destination * rectangle in which to draw the source image * @param {Number} dy the y-coordinate of the destination @@ -78902,10 +85098,14 @@ var defH = img.height; yAlign = yAlign || constants.CENTER; xAlign = xAlign || constants.CENTER; + if (img.elt) { + defW = defW !== undefined ? defW : img.elt.width; + defH = defH !== undefined ? defH : img.elt.height; + } if (img.elt && img.elt.videoWidth && !img.canvas) { // video no canvas - defW = img.elt.videoWidth; - defH = img.elt.videoHeight; + defW = defW !== undefined ? defW : img.elt.videoWidth; + defH = defH !== undefined ? defH : img.elt.videoHeight; } var _dx = dx; var _dy = dy; @@ -78913,10 +85113,11 @@ var _dh = dHeight || defH; var _sx = sx || 0; var _sy = sy || 0; - var _sw = sWidth || defW; - var _sh = sHeight || defH; + var _sw = sWidth !== undefined ? sWidth : defW; + var _sh = sHeight !== undefined ? sHeight : defH; _sw = _sAssign(_sw, defW); - _sh = _sAssign(_sh, defH); // This part needs cleanup and unit tests + _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; @@ -78936,42 +85137,50 @@ _sh *= pd; _sw *= pd; var vals = _helpers.default.modeAdjust(_dx, _dy, _dw, _dh, this._renderer._imageMode); - vals = _imageFit(fit, xAlign, yAlign, vals.x, vals.y, vals.w, vals.h, _sx, _sy, _sw, _sh); // tint the image if there is a tint + vals = _imageFit(fit, xAlign, yAlign, vals.x, vals.y, vals.w, vals.h, _sx, _sy, _sw, _sh); + // tint the image if there is a tint this._renderer.image(img, vals.sx, vals.sy, vals.sw, vals.sh, vals.dx, vals.dy, vals.dw, vals.dh); }; /** - * Sets the fill value for displaying images. Images can be tinted to - * specified colors or made transparent by including an alpha value. + * Tints images using a specified color. * - * To apply transparency to an image without affecting its color, use - * white as the tint color and specify an alpha value. For instance, - * tint(255, 128) will make an image 50% transparent (assuming the default - * alpha range of 0-255, which can be changed with colorMode()). + * The version of `tint()` with one parameter interprets it one of four ways. + * If the parameter is a number, it's interpreted as a grayscale value. If the + * parameter is a string, it's interpreted as a CSS color string. An array of + * `[R, G, B, A]` values or a p5.Color object can + * also be used to set the tint color. * - * The value for the gray parameter must be less than or equal to the current - * maximum value as specified by colorMode(). The default maximum value is - * 255. + * The version of `tint()` with two parameters uses the first one as a + * grayscale value and the second as an alpha value. For example, calling + * `tint(255, 128)` will make an image 50% transparent. + * + * The version of `tint()` with three parameters interprets them as RGB or + * HSB values, depending on the current + * colorMode(). The optional fourth parameter + * sets the alpha value. For example, `tint(255, 0, 0, 100)` will give images + * a red tint and make them transparent. * * @method tint - * @param {Number} v1 red or hue value 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} v1 red or hue value. + * @param {Number} v2 green or saturation value. + * @param {Number} v3 blue or brightness. * @param {Number} [alpha] * * @example *
      * * let img; + * * function preload() { * img = loadImage('assets/laDefense.jpg'); * } + * * function setup() { * image(img, 0, 0); - * tint(0, 153, 204); // Tint blue + * tint('red'); * image(img, 50, 0); + * + * describe('Two images of an umbrella and a ceiling side-by-side. The image on the right has a red tint.'); * } * *
      @@ -78979,13 +85188,17 @@ *
      * * 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 + * tint(255, 0, 0); * image(img, 50, 0); + * + * describe('Two images of an umbrella and a ceiling side-by-side. The image on the right has a red tint.'); * } * *
      @@ -78993,35 +85206,52 @@ *
      * * let img; + * * function preload() { * img = loadImage('assets/laDefense.jpg'); * } + * * function setup() { * image(img, 0, 0); - * tint(255, 126); // Apply transparency without changing color + * tint(255, 0, 0, 100); * image(img, 50, 0); + * + * describe('Two images of an umbrella and a ceiling side-by-side. The image on the right has a transparent red tint.'); * } * *
      * - * @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 + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * image(img, 0, 0); + * tint(255, 180); + * image(img, 50, 0); + * + * describe('Two images of an umbrella and a ceiling side-by-side. The image on the right is transparent.'); + * } + * + *
      */ /** * @method tint - * @param {String} value a color string + * @param {String} value CSS color string. */ /** * @method tint - * @param {Number} gray a gray value + * @param {Number} gray grayscale value. * @param {Number} [alpha] */ /** * @method tint - * @param {Number[]} values an array containing the red,green,blue & - * and alpha components of the color + * @param {Number[]} values array containing the red, green, blue & + * alpha components of the color. */ /** * @method tint @@ -79036,28 +85266,28 @@ this._renderer._tint = c.levels; }; /** - * Removes the current fill value for displaying images and reverts to - * displaying images with their original hues. + * Removes the current tint set by tint() and restores + * images to their original colors. * * @method noTint * @example *
      * * let img; + * * function preload() { - * img = loadImage('assets/bricks.jpg'); + * img = loadImage('assets/laDefense.jpg'); * } * function setup() { - * tint(0, 153, 204); // Tint blue + * tint('red'); * image(img, 0, 0); - * noTint(); // Disable tint + * noTint(); * image(img, 50, 0); + * + * describe('Two images of an umbrella and a ceiling side-by-side. The image on the left has a red tint.'); * } * *
      - * - * @alt - * 2 side by side images of bricks, left image with blue tint */ _main.default.prototype.noTint = function () { this._renderer._tint = null; @@ -79072,34 +85302,41 @@ */ _main.default.prototype._getTintedImageCanvas = _main.default.Renderer2D.prototype._getTintedImageCanvas; /** - * Set image mode. Modifies the location from which images are drawn by - * changing the way in which parameters given to image() are interpreted. - * The default mode is imageMode(CORNER), which interprets the second and - * third parameters of image() as the upper-left corner of the image. If - * two additional parameters are specified, they are used to set the image's - * width and height. + * Changes the location from which images are drawn when + * image() is called. * - * imageMode(CORNERS) interprets the second and third parameters of image() - * as the location of one corner, and the fourth and fifth parameters as the - * opposite corner. + * By default, the first + * two parameters of image() are the x- and + * y-coordinates of the image's upper-left corner. The next parameters are + * its width and height. This is the same as calling `imageMode(CORNER)`. + * + * `imageMode(CORNERS)` also uses the first two parameters of + * image() as the x- and y-coordinates of the image's + * top-left corner. The third and fourth parameters are the coordinates of its + * bottom-right corner. * - * imageMode(CENTER) interprets the second and third parameters of image() - * as the image's center point. If two additional parameters are specified, - * they are used to set the image's width and height. + * `imageMode(CENTER)` uses the first two parameters of + * image() as the x- and y-coordinates of the image's + * center. The next parameters are its width and height. * * @method imageMode - * @param {Constant} mode either CORNER, CORNERS, or CENTER + * @param {Constant} mode either CORNER, CORNERS, or CENTER. * @example * *
      * * let img; + * * function preload() { * img = loadImage('assets/bricks.jpg'); * } + * * function setup() { + * background(200); * imageMode(CORNER); * image(img, 10, 10, 50, 50); + * + * describe('A square image of a brick wall is drawn at the top left of a gray square.'); * } * *
      @@ -79107,12 +85344,17 @@ *
      * * let img; + * * function preload() { * img = loadImage('assets/bricks.jpg'); * } + * * function setup() { + * background(200); * imageMode(CORNERS); * image(img, 10, 10, 90, 40); + * + * describe('An image of a brick wall is drawn on a gray square. The image is squeezed into a small rectangular area.'); * } * *
      @@ -79120,20 +85362,20 @@ *
      * * let img; + * * function preload() { * img = loadImage('assets/bricks.jpg'); * } + * * function setup() { + * background(200); * imageMode(CENTER); * image(img, 50, 50, 80, 80); + * + * describe('A square image of a brick wall is drawn on a gray square.'); * } * *
      - * - * @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); @@ -79145,65 +85387,64 @@ exports.default = _default; }, { - '../core/constants': 278, - '../core/friendly_errors/fes_core': 281, - '../core/friendly_errors/file_errors': 282, - '../core/friendly_errors/validate_params': 285, - '../core/helpers': 286, - '../core/main': 290, - 'core-js/modules/es.array.copy-within': 168, - 'core-js/modules/es.array.includes': 174, - 'core-js/modules/es.array.index-of': 175, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.promise': 196, - 'core-js/modules/es.regexp.to-string': 200, - 'core-js/modules/es.string.includes': 203, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.typed-array.copy-within': 215, - 'core-js/modules/es.typed-array.every': 216, - 'core-js/modules/es.typed-array.fill': 217, - 'core-js/modules/es.typed-array.filter': 218, - 'core-js/modules/es.typed-array.find': 220, - 'core-js/modules/es.typed-array.find-index': 219, - 'core-js/modules/es.typed-array.for-each': 223, - 'core-js/modules/es.typed-array.includes': 224, - 'core-js/modules/es.typed-array.index-of': 225, - 'core-js/modules/es.typed-array.iterator': 228, - 'core-js/modules/es.typed-array.join': 229, - 'core-js/modules/es.typed-array.last-index-of': 230, - 'core-js/modules/es.typed-array.map': 231, - 'core-js/modules/es.typed-array.reduce': 233, - 'core-js/modules/es.typed-array.reduce-right': 232, - 'core-js/modules/es.typed-array.reverse': 234, - 'core-js/modules/es.typed-array.set': 235, - 'core-js/modules/es.typed-array.slice': 236, - 'core-js/modules/es.typed-array.some': 237, - 'core-js/modules/es.typed-array.sort': 238, - 'core-js/modules/es.typed-array.subarray': 239, - 'core-js/modules/es.typed-array.to-locale-string': 240, - 'core-js/modules/es.typed-array.to-string': 241, - 'core-js/modules/es.typed-array.uint8-array': 244, - 'core-js/modules/es.typed-array.uint8-clamped-array': 245, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248, - 'gifenc': 255, - 'omggif': 262, - 'regenerator-runtime/runtime': 266 + '../core/constants': 286, + '../core/friendly_errors/fes_core': 289, + '../core/friendly_errors/file_errors': 290, + '../core/friendly_errors/validate_params': 293, + '../core/helpers': 294, + '../core/main': 298, + 'core-js/modules/es.array.copy-within': 170, + 'core-js/modules/es.array.includes': 177, + 'core-js/modules/es.array.index-of': 178, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.promise': 201, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.includes': 209, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.typed-array.copy-within': 223, + 'core-js/modules/es.typed-array.every': 224, + 'core-js/modules/es.typed-array.fill': 225, + 'core-js/modules/es.typed-array.filter': 226, + 'core-js/modules/es.typed-array.find': 228, + 'core-js/modules/es.typed-array.find-index': 227, + 'core-js/modules/es.typed-array.for-each': 231, + 'core-js/modules/es.typed-array.includes': 232, + 'core-js/modules/es.typed-array.index-of': 233, + 'core-js/modules/es.typed-array.iterator': 236, + 'core-js/modules/es.typed-array.join': 237, + 'core-js/modules/es.typed-array.last-index-of': 238, + 'core-js/modules/es.typed-array.map': 239, + 'core-js/modules/es.typed-array.reduce': 241, + 'core-js/modules/es.typed-array.reduce-right': 240, + 'core-js/modules/es.typed-array.reverse': 242, + 'core-js/modules/es.typed-array.set': 243, + 'core-js/modules/es.typed-array.slice': 244, + 'core-js/modules/es.typed-array.some': 245, + 'core-js/modules/es.typed-array.sort': 246, + 'core-js/modules/es.typed-array.subarray': 247, + 'core-js/modules/es.typed-array.to-locale-string': 248, + 'core-js/modules/es.typed-array.to-string': 249, + 'core-js/modules/es.typed-array.uint8-array': 252, + 'core-js/modules/es.typed-array.uint8-clamped-array': 253, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256, + 'gifenc': 263, + 'omggif': 270, + 'regenerator-runtime/runtime': 274 } ], - 314: [ + 322: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); _dereq_('core-js/modules/es.symbol.description'); _dereq_('core-js/modules/es.symbol.iterator'); - _dereq_('core-js/modules/es.array.filter'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.object.to-string'); _dereq_('core-js/modules/es.string.iterator'); @@ -79211,7 +85452,6 @@ _dereq_('core-js/modules/es.symbol'); _dereq_('core-js/modules/es.symbol.description'); _dereq_('core-js/modules/es.symbol.iterator'); - _dereq_('core-js/modules/es.array.filter'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.object.to-string'); _dereq_('core-js/modules/es.string.iterator'); @@ -79227,1395 +85467,1924 @@ default: obj }; - } /** - * @module Image - * @submodule Image - * @requires core - * @requires constants - * @requires filters - */ + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } /** + * @module Image + * @submodule Image + * @requires core + * @requires constants + * @requires filters + */ /** - * This module defines the p5.Image class and P5 methods for - * drawing images to the main display canvas. - */ + * This module defines the p5.Image class and P5 methods for + * drawing images to the main display canvas. + */ /* * Class methods */ /** - * Creates a new p5.Image. A p5.Image is a canvas backed representation of an - * image. - * - * p5 can display .gif, .jpg and .png images. Images may be displayed - * in 2D and 3D space. Before an image is used, it must be loaded with the - * loadImage() function. The p5.Image class contains fields for the width and - * height of the image, as well as an array called pixels[] that contains the - * values for every pixel in the image. - * - * The methods described below allow easy access to the image's pixels and - * alpha channel and simplify the process of compositing. - * - * Before using the pixels[] array, be sure to use the loadPixels() method on - * the image to make sure that the pixel data is properly loaded. - * @example - *
      - * function setup() { - * let img = createImage(100, 100); // same as new p5.Image(100, 100); - * img.loadPixels(); - * createCanvas(100, 100); - * background(0); - * - * // helper for writing color to array - * function writeColor(image, x, y, red, green, blue, alpha) { - * let index = (x + y * width) * 4; - * image.pixels[index] = red; - * image.pixels[index + 1] = green; - * image.pixels[index + 2] = blue; - * image.pixels[index + 3] = alpha; - * } - * - * let x, y; - * // fill with random colors - * for (y = 0; y < img.height; y++) { - * for (x = 0; x < img.width; x++) { - * let red = random(255); - * let green = random(255); - * let blue = random(255); - * let alpha = 255; - * writeColor(img, x, y, red, green, blue, alpha); - * } - * } - * - * // draw a red line - * y = 0; - * for (x = 0; x < img.width; x++) { - * writeColor(img, x, y, 255, 0, 0, 255); - * } + * A class to describe an image. Images are rectangular grids of pixels that + * can be displayed and modified. * - * // 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); - * } - *
      - * - * @class p5.Image - * @constructor - * @param {Number} width - * @param {Number} height - */ - - _main.default.Image = function (width, height) { - /** - * Image width. - * @property {Number} width - * @readOnly - * @example - *
      - * let img; - * function preload() { - * img = loadImage('assets/rockies.jpg'); - * } - * - * function setup() { - * createCanvas(100, 100); - * image(img, 0, 0); - * for (let i = 0; i < img.width; i++) { - * let c = img.get(i, img.height / 2); - * stroke(c); - * line(i, height / 2, i, height); - * } - * } - *
      - * - * @alt - * rocky mountains in top and horizontal lines in corresponding colors in bottom. - * - */ - this.width = width; - /** - * Image height. - * @property {Number} height - * @readOnly - * @example - *
      - * let img; - * function preload() { - * img = loadImage('assets/rockies.jpg'); - * } - * - * function setup() { - * createCanvas(100, 100); - * image(img, 0, 0); - * for (let i = 0; i < img.height; i++) { - * let c = img.get(img.width / 2, i); - * stroke(c); - * line(0, i, width / 2, i); - * } - * } - *
      - * - * @alt - * rocky mountains on right and vertical lines in corresponding colors on left. - * - */ - this.height = height; - this.canvas = document.createElement('canvas'); - this.canvas.width = this.width; - this.canvas.height = this.height; - this.drawingContext = this.canvas.getContext('2d'); - this._pixelsState = this; - this._pixelDensity = 1; //Object for working with GIFs, defaults to null - this.gifProperties = null; //For WebGL Texturing only: used to determine whether to reupload texture to GPU - this._modified = false; - /** - * Array containing the values for all the pixels in the display window. - * These values are numbers. This array is the size (include an appropriate - * factor for pixelDensity) of the display window x4, - * representing the R, G, B, A values in order for each pixel, moving from - * left to right across each row, then down each column. Retina and other - * high density displays may have more pixels (by a factor of - * pixelDensity^2). - * For example, if the image is 100×100 pixels, there will be 40,000. With - * pixelDensity = 2, there will be 160,000. The first four values - * (indices 0-3) in the array will be the R, G, B, A values of the pixel at - * (0, 0). The second four values (indices 4-7) will contain the R, G, B, A - * values of the pixel at (1, 0). More generally, to set values for a pixel - * at (x, y): - * ```javascript - * let d = pixelDensity(); - * for (let i = 0; i < d; i++) { - * for (let j = 0; j < d; j++) { - * // loop over - * index = 4 * ((y * d + j) * width * d + (x * d + i)); - * pixels[index] = r; - * pixels[index+1] = g; - * pixels[index+2] = b; - * pixels[index+3] = a; - * } - * } - * ``` - * - * Before accessing this array, the data must loaded with the loadPixels() - * function. After the array data has been modified, the updatePixels() - * function must be run to update the changes. - * @property {Number[]} pixels - * @example - *
      - * - * 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); - * - *
      - *
      - * - * 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); - * - *
      - * - * @alt - * 66×66 turquoise rect in center of canvas - * 66×66 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; - 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. + * Existing images can be loaded by calling + * loadImage(). Blank images can be created by + * calling createImage(). `p5.Image` objects + * have methods for common tasks such as applying filters and modifying + * pixel values. * - * @method loadPixels * @example - *
      - * let myImage; - * let halfImage; + *
      + * + * let img; * * function preload() { - * myImage = loadImage('assets/rockies.jpg'); + * img = loadImage('assets/bricks.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(); - * } + * image(img, 0, 0); * - * function draw() { - * image(myImage, 0, 0, width, height); + * describe('An image of a brick wall.'); * } - *
      - * - * @alt - * 2 images of rocky mountains vertically stacked - */ - _main.default.Image.prototype.loadPixels = function () { - _main.default.Renderer2D.prototype.loadPixels.call(this); - this.setModified(true); - }; - /** - * Updates the backing canvas for this image with the contents of - * the [pixels] array. - * - * If this image is an animated GIF then the pixels will be updated - * in the frame that is currently displayed. + *
      + *
      * - * @method updatePixels - * @param {Integer} x x-offset of the target update area for the - * underlying canvas - * @param {Integer} y y-offset of the target update area for the - * underlying canvas - * @param {Integer} w width of the target update area for the - * underlying canvas - * @param {Integer} h height of the target update area for the - * underlying canvas - * @example - *
      - * let myImage; - * let halfImage; + *
      + * + * let img; * * function preload() { - * myImage = loadImage('assets/rockies.jpg'); + * img = loadImage('assets/bricks.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); - * } - *
      - * - * @alt - * 2 images of rocky mountains vertically stacked - */ - /** - * @method updatePixels - */ - _main.default.Image.prototype.updatePixels = function (x, y, w, h) { - _main.default.Renderer2D.prototype.updatePixels.call(this, x, y, w, h); - this.setModified(true); - }; - /** - * Get a region of pixels from an image. - * - * If no params are passed, the whole image is returned. - * If x and y are the only params passed a single pixel is extracted. - * If all params are passed a rectangle region is extracted and a p5.Image - * is returned. - * - * @method get - * @param {Number} x x-coordinate of the pixel - * @param {Number} y y-coordinate of the pixel - * @param {Number} w width - * @param {Number} h height - * @return {p5.Image} the rectangle p5.Image - * @example - *
      - * let myImage; - * let c; - * - * function preload() { - * myImage = loadImage('assets/rockies.jpg'); - * } + * img.filter(GRAY); + * image(img, 0, 0); * - * function setup() { - * background(myImage); - * noStroke(); - * c = myImage.get(60, 90); - * fill(c); - * rect(25, 25, 50, 50); + * describe('A grayscale image of a brick wall.'); * } + * + *
      * - * //get() returns color here - *
      - * - * @alt - * image of rocky mountains with 50×50 green rect in front - */ - /** - * @method get - * @return {p5.Image} the whole p5.Image - */ - /** - * @method get - * @param {Number} x - * @param {Number} y - * @return {Number[]} color of pixel at x,y in array format [R, G, B, A] - */ - _main.default.Image.prototype.get = function (x, y, w, h) { - _main.default._validateParameters('p5.Image.get', arguments); - return _main.default.Renderer2D.prototype.get.apply(this, arguments); - }; - _main.default.Image.prototype._getPixel = _main.default.Renderer2D.prototype._getPixel; - /** - * Set the color of a single pixel or write an image into - * this p5.Image. - * - * Note that for a large number of pixels this will - * be slower than directly manipulating the pixels array - * and then calling updatePixels(). - * - * @method set - * @param {Number} x x-coordinate of the pixel - * @param {Number} y y-coordinate of the pixel - * @param {Number|Number[]|Object} a grayscale value | pixel array | - * a p5.Color | image to copy - * @example *
      * + * background(200); * 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)); + * for (let x = 0; x < img.width; x += 1) { + * for (let y = 0; y < img.height; y += 1) { + * img.set(x, y, 0); * } * } * img.updatePixels(); * image(img, 17, 17); - * image(img, 34, 34); + * + * describe('A black square drawn in the middle of a gray square.'); * *
      * - * @alt - * 2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas + * @class p5.Image + * @constructor + * @param {Number} width + * @param {Number} height */ - _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 - *
      - * let img; - * - * function preload() { - * img = loadImage('assets/rockies.jpg'); - * } - * function draw() { - * image(img, 0, 0); - * } - * - * function mousePressed() { - * img.resize(50, 100); - * } - *
      - * - * @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 + _main.default.Image = /*#__PURE__*/ function () { + function _class(width, height) { + _classCallCheck(this, _class); + /** + * Image width. + * @type {Number} + * @property {Number} width + * @name width + * @readOnly + * @example + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * image(img, 0, 0); + * let x = img.width / 2; + * let y = img.height / 2; + * let d = 20; + * circle(x, y, d); + * + * describe('An image of a mountain landscape with a white circle drawn in the middle.'); + * } + * + *
      + */ + this.width = width; + /** + * Image height. + * @type {Number} + * @property height + * @name height + * @readOnly + * @example + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * image(img, 0, 0); + * let x = img.width / 2; + * let y = img.height / 2; + * let d = 20; + * circle(x, y, d); + * + * describe('An image of a mountain landscape with a white circle drawn in the middle.'); + * } + * + *
      + */ + this.height = height; + this.canvas = document.createElement('canvas'); + this.canvas.width = this.width; + this.canvas.height = this.height; + this.drawingContext = this.canvas.getContext('2d'); + this._pixelsState = this; + this._pixelDensity = 1; + //Object for working with GIFs, defaults to null + this.gifProperties = null; + //For WebGL Texturing only: used to determine whether to reupload texture to GPU + this._modified = false; + /** + * An array containing the color of each pixel in the + * p5.Image object. Colors are stored as numbers + * representing red, green, blue, and alpha (RGBA) values. `img.pixels` is a + * one-dimensional array for performance reasons. + * + * Each pixel occupies four elements in the pixels array, one for each + * RGBA value. For example, the pixel at coordinates (0, 0) stores its + * RGBA values at `img.pixels[0]`, `img.pixels[1]`, `img.pixels[2]`, + * and `img.pixels[3]`, respectively. The next pixel at coordinates (1, 0) + * stores its RGBA values at `img.pixels[4]`, `img.pixels[5]`, + * `img.pixels[6]`, and `img.pixels[7]`. And so on. The `img.pixels` array + * for a 100×100 p5.Image object has + * 100 × 100 × 4 = 40,000 elements. + * + * Accessing the RGBA values for a pixel in the + * p5.Image object requires a little math as + * shown below. The img.loadPixels() + * method must be called before accessing the `img.pixels` array. The + * img.updatePixels() method must be + * called after any changes are made. + * + * @property {Number[]} pixels + * @name pixels + * @example + *
      + * + * let img = createImage(66, 66); + * img.loadPixels(); + * let numPixels = 4 * img.width * img.height; + * for (let i = 0; i < numPixels; i += 4) { + * // Red. + * img.pixels[i] = 0; + * // Green. + * img.pixels[i + 1] = 0; + * // Blue. + * img.pixels[i + 2] = 0; + * // Alpha. + * img.pixels[i + 3] = 255; + * } + * img.updatePixels(); + * image(img, 17, 17); + * + * describe('A black square drawn in the middle of a gray square.'); + * + *
      + * + *
      + * + * let img = createImage(66, 66); + * img.loadPixels(); + * let numPixels = 4 * img.width * img.height; + * for (let i = 0; i < numPixels; i += 4) { + * // Red. + * img.pixels[i] = 255; + * // Green. + * img.pixels[i + 1] = 0; + * // Blue. + * img.pixels[i + 2] = 0; + * // Alpha. + * img.pixels[i + 3] = 255; + * } + * img.updatePixels(); + * image(img, 17, 17); + * + * describe('A red square drawn in the middle of a gray square.'); + * + *
      + */ + this.pixels = [ + ]; + } /** + * Gets or sets the pixel density for high pixel density displays. By default, + * the density will be set to 1. + * + * Call this method with no arguments to get the default density, or pass + * in a number to set the density. If a non-positive number is provided, + * it defaults to 1. + * + * @method pixelDensity + * @param {Number} [density] A scaling factor for the number of pixels per + * side + * @returns {Number} The current density if called without arguments, or the instance for chaining if setting density. + */ + + _createClass(_class, [ + { + key: 'pixelDensity', + value: function pixelDensity(density) { + if (typeof density !== 'undefined') { + // Setter: set the density and handle resize + if (density <= 0) { + var errorObj = { + type: 'INVALID_VALUE', + format: { + types: [ + 'Number' + ] + }, + position: 1 + }; + _main.default._friendlyParamError(errorObj, 'pixelDensity'); + // Default to 1 in case of an invalid value + density = 1; + } + this._pixelDensity = density; + // Adjust canvas dimensions based on pixel density + this.width /= density; + this.height /= density; + return this; // Return the image instance for chaining if needed + } else { + // Getter: return the default density + return this._pixelDensity; } - } - }; - for (var i = 0; i < props.numFrames; i++) { - var resizedImageData = this.drawingContext.createImageData(width, height); - nearestNeighbor(props.frames[i].image, resizedImageData); - props.frames[i].image = resizedImageData; - } - } - tempCanvas.getContext('2d').drawImage(this.canvas, 0, 0, this.canvas.width, this.canvas.height, 0, 0, tempCanvas.width, tempCanvas.height); // Resize the original canvas, which will clear its contents - this.canvas.width = this.width = width; - this.canvas.height = this.height = height; //Copy the image back - this.drawingContext.drawImage(tempCanvas, 0, 0, width, height, 0, 0, width, height); - if (this.pixels.length > 0) { - this.loadPixels(); - } - this.setModified(true); - }; - /** - * Copies a region of pixels from one image to another. If no - * srcImage is specified this is used as the source. If the source - * and destination regions aren't the same size, it will - * automatically resize source pixels to fit the specified - * target region. - * - * @method copy - * @param {p5.Image|p5.Element} srcImage source image - * @param {Integer} sx X coordinate of the source's upper left corner - * @param {Integer} sy Y coordinate of the source's upper left corner - * @param {Integer} sw source image width - * @param {Integer} sh source image height - * @param {Integer} dx X coordinate of the destination's upper left corner - * @param {Integer} dy Y coordinate of the destination's upper left corner - * @param {Integer} dw destination image width - * @param {Integer} dh destination image height - * @example - *
      - * let photo; - * let bricks; - * let x; - * let y; - * - * function preload() { - * photo = loadImage('assets/rockies.jpg'); - * bricks = loadImage('assets/bricks.jpg'); - * } - * - * function setup() { - * x = bricks.width / 2; - * y = bricks.height / 2; - * photo.copy(bricks, 0, 0, x, y, 0, 0, x, y); - * image(photo, 0, 0); - * } - *
      - * - * @alt - * image of rocky mountains and smaller image on top of bricks at top left - */ - /** - * @method copy - * @param {Integer} sx - * @param {Integer} sy - * @param {Integer} sw - * @param {Integer} sh - * @param {Integer} dx - * @param {Integer} dy - * @param {Integer} dw - * @param {Integer} dh - */ - _main.default.Image.prototype.copy = function () { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - _main.default.prototype.copy.apply(this, args); - }; - /** - * Masks part of an image from displaying by loading another - * image and using its alpha channel as an alpha channel for - * this image. Masks are cumulative, once applied to an image - * object, they cannot be removed. - * - * @method mask - * @param {p5.Image} srcImage source image - * @example - *
      - * 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); - * } - *
      - * - * @alt - * image of rocky mountains with white at right - * - * http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/ - */ - // TODO: - Accept an array of alpha values. - _main.default.Image.prototype.mask = function (p5Image) { - if (p5Image === undefined) { - p5Image = this; - } - var currBlend = this.drawingContext.globalCompositeOperation; - var scaleFactor = 1; - if (p5Image instanceof _main.default.Renderer) { - scaleFactor = p5Image._pInst._pixelDensity; - } - var copyArgs = [ - p5Image, - 0, - 0, - scaleFactor * p5Image.width, - scaleFactor * p5Image.height, - 0, - 0, - this.width, - this.height - ]; - this.drawingContext.globalCompositeOperation = 'destination-in'; - if (this.gifProperties) { - for (var i = 0; i < this.gifProperties.frames.length; i++) { - this.drawingContext.putImageData(this.gifProperties.frames[i].image, 0, 0); - _main.default.Image.prototype.copy.apply(this, copyArgs); - this.gifProperties.frames[i].image = this.drawingContext.getImageData(0, 0, this.width, this.height); - } - this.drawingContext.putImageData(this.gifProperties.frames[this.gifProperties.displayIndex].image, 0, 0); - } else { - _main.default.Image.prototype.copy.apply(this, copyArgs); - } - this.drawingContext.globalCompositeOperation = currBlend; - this.setModified(true); - }; - /** - * Applies an image filter to a p5.Image - * - * THRESHOLD - * Converts the image to black and white pixels depending if they are above or - * below the threshold defined by the level parameter. The parameter must be - * between 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used. - * - * GRAY - * Converts any colors in the image to grayscale equivalents. No parameter - * is used. - * - * OPAQUE - * Sets the alpha channel to entirely opaque. No parameter is used. - * - * INVERT - * Sets each pixel to its inverse value. No parameter is used. - * - * POSTERIZE - * Limits each channel of the image to the number of colors specified as the - * parameter. The parameter can be set to values between 2 and 255, but - * results are most noticeable in the lower ranges. - * - * BLUR - * Executes a Gaussian blur with the level parameter specifying the extent - * of the blurring. If no parameter is used, the blur is equivalent to - * Gaussian blur of radius 1. Larger values increase the blur. - * - * ERODE - * Reduces the light areas. No parameter is used. - * - * DILATE - * Increases the light areas. No parameter is used. - * - * filter() does not work in WEBGL mode. - * A similar effect can be achieved in WEBGL mode using custom - * shaders. Adam Ferriss has written - * a selection of shader examples that contains many - * of the effects present in the filter examples. - * - * @method filter - * @param {Constant} filterType either THRESHOLD, GRAY, OPAQUE, INVERT, - * POSTERIZE, ERODE, DILATE or BLUR. - * See Filters.js for docs on - * each available filter - * @param {Number} [filterParam] an optional parameter unique - * to each filter, see above - * @example - *
      - * 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); - * } - *
      - * - * @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 - *
      - * 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); - * } - *
      - *
      - * 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); - * } - *
      - *
      - * 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); - * } - *
      - * - * @alt - * image of rocky mountains. Brick images on left and right. Right overexposed - * image of rockies. Brickwall images on left and right. Right mortar transparent - * image of rockies. Brickwall images on left and right. Right translucent - */ - /** - * @method blend - * @param {Integer} sx - * @param {Integer} sy - * @param {Integer} sw - * @param {Integer} sh - * @param {Integer} dx - * @param {Integer} dy - * @param {Integer} dw - * @param {Integer} dh - * @param {Constant} blendMode - */ - _main.default.Image.prototype.blend = function () { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - _main.default._validateParameters('p5.Image.blend', arguments); - _main.default.prototype.blend.apply(this, args); - this.setModified(true); - }; - /** - * helper method for web GL mode to indicate that an image has been - * changed or unchanged since last upload. gl texture upload will - * set this value to false after uploading the texture. - * @method setModified - * @param {boolean} val sets whether or not the image has been - * modified. - * @private - */ - _main.default.Image.prototype.setModified = function (val) { - this._modified = val; //enforce boolean? - }; - /** - * helper method for web GL mode to figure out if the image - * has been modified and might need to be re-uploaded to texture - * memory between frames. - * @method isModified - * @private - * @return {boolean} a boolean indicating whether or not the - * image has been updated or modified since last texture upload. - */ - _main.default.Image.prototype.isModified = function () { - return this._modified; - }; - /** - * Saves the image to a file and force the browser to download it. - * Accepts two strings for filename and file extension - * Supports png (default), jpg, and gif - *

      - * Note that the file will only be downloaded as an animated GIF - * if the p5.Image was loaded from a GIF file. - * @method save - * @param {String} filename give your file a name - * @param {String} extension 'png' or 'jpg' - * @example - *
      - * let photo; - * - * function preload() { - * photo = loadImage('assets/rockies.jpg'); - * } - * - * function draw() { - * image(photo, 0, 0); - * } - * - * function keyTyped() { - * if (key === 's') { - * photo.save('photo', 'png'); - * } - * } - *
      - * - * @alt - * image of rocky mountains. - */ - _main.default.Image.prototype.save = function (filename, extension) { - if (this.gifProperties) { - _main.default.prototype.encodeAndDownloadGif(this, filename); - } else { - _main.default.prototype.saveCanvas(this.canvas, filename, extension); - } - }; // GIF Section - /** - * Starts an animated GIF over at the beginning state. - * - * @method reset - * @example - *
      - * let gif; - * - * function preload() { - * gif = loadImage('assets/arnott-wallace-wink-loop-once.gif'); - * } - * - * function draw() { - * background(255); - * // The GIF file that we loaded only loops once - * // so it freezes on the last frame after playing through - * image(gif, 0, 0); - * } - * - * function mousePressed() { - * // Click to reset the GIF and begin playback from start - * gif.reset(); - * } - *
      - * @alt - * Animated image of a cartoon face that winks once and then freezes - * When you click it animates again, winks once and freezes - */ - _main.default.Image.prototype.reset = function () { - if (this.gifProperties) { - var props = this.gifProperties; - props.playing = true; - props.timeSinceStart = 0; - props.timeDisplayed = 0; - props.lastChangeTime = 0; - props.loopCount = 0; - props.displayIndex = 0; - this.drawingContext.putImageData(props.frames[0].image, 0, 0); - } - }; - /** - * Gets the index for the frame that is currently visible in an animated GIF. - * - * @method getCurrentFrame - * @return {Number} The index for the currently displaying frame in animated GIF - * @example - *
      - * 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); - * } - *
      - * @alt - * Animated image of a cartoon eye looking around and then - * looking outwards, in the lower-left hand corner a number counts - * up quickly to 124 and then starts back over at 0 - */ - _main.default.Image.prototype.getCurrentFrame = function () { - if (this.gifProperties) { - var props = this.gifProperties; - return props.displayIndex % props.numFrames; - } - }; - /** - * Sets the index of the frame that is currently visible in an animated GIF - * - * @method setFrame - * @param {Number} index the index for the frame that should be displayed - * @example - *
      - * let gif; - * - * function preload() { - * gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif'); - * } - * - * // Move your mouse up and down over canvas to see the GIF - * // frames animate - * function draw() { - * gif.pause(); - * image(gif, 0, 0); - * // Get the highest frame number which is the number of frames - 1 - * let maxFrame = gif.numFrames() - 1; - * // Set the current frame that is mapped to be relative to mouse position - * let frameNumber = floor(map(mouseY, 0, height, 0, maxFrame, true)); - * gif.setFrame(frameNumber); - * } - *
      - * @alt - * A still image of a cartoon eye that looks around when you move your mouse - * up and down over the canvas - */ - _main.default.Image.prototype.setFrame = function (index) { - if (this.gifProperties) { - var props = this.gifProperties; - if (index < props.numFrames && index >= 0) { - props.timeDisplayed = 0; - props.lastChangeTime = 0; - props.displayIndex = index; - this.drawingContext.putImageData(props.frames[index].image, 0, 0); - } else { - console.log('Cannot set GIF to a frame number that is higher than total number of frames or below zero.'); - } - } - }; - /** - * Returns the number of frames in an animated GIF - * - * @method numFrames - * @return {Number} - * @example The number of frames in the animated GIF - *
      - * let gif; - * - * function preload() { - * gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif'); - * } - * - * // Move your mouse up and down over canvas to see the GIF - * // frames animate - * function draw() { - * gif.pause(); - * image(gif, 0, 0); - * // Get the highest frame number which is the number of frames - 1 - * let maxFrame = gif.numFrames() - 1; - * // Set the current frame that is mapped to be relative to mouse position - * let frameNumber = floor(map(mouseY, 0, height, 0, maxFrame, true)); - * gif.setFrame(frameNumber); - * } - *
      - * @alt - * A still image of a cartoon eye that looks around when you move your mouse - * up and down over the canvas - */ - _main.default.Image.prototype.numFrames = function () { - if (this.gifProperties) { - return this.gifProperties.numFrames; - } - }; - /** - * Plays an animated GIF that was paused with - * pause() - * - * @method play - * @example - *
      - * 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(); - * } - *
      - * @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 - *
      - * 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(); - * } - *
      - * @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 - *
      - * 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); - * } - *
      - * @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; + } /** + * Helper function for animating GIF-based images with time + */ + + }, + { + key: '_animateGif', + value: function _animateGif(pInst) { + var props = this.gifProperties; + var curTime = pInst._lastRealFrameTime; + if (props.lastChangeTime === 0) { + props.lastChangeTime = curTime; + } + if (props.playing) { + props.timeDisplayed = curTime - props.lastChangeTime; + var curDelay = props.frames[props.displayIndex].delay; + if (props.timeDisplayed >= curDelay) { + //GIF is bound to 'realtime' so can skip frames + var skips = Math.floor(props.timeDisplayed / curDelay); + props.timeDisplayed = 0; + props.lastChangeTime = curTime; + props.displayIndex += skips; + props.loopCount = Math.floor(props.displayIndex / props.numFrames); + if (props.loopLimit !== null && props.loopCount >= props.loopLimit) { + props.playing = false; + } else { + var ind = props.displayIndex % props.numFrames; + this.drawingContext.putImageData(props.frames[ind].image, 0, 0); + props.displayIndex = ind; + this.setModified(true); + } } } + } /** + * Helper fxn for sharing pixel methods + */ + + }, + { + key: '_setProperty', + value: function _setProperty(prop, value) { + this[prop] = value; + this.setModified(true); + } /** + * Loads the current value of each pixel in the + * p5.Image object into the `img.pixels` array. + * This method must be called before reading or modifying pixel values. + * + * @method loadPixels + * @example + *
      + * + * let img = createImage(66, 66); + * img.loadPixels(); + * for (let x = 0; x < img.width; x += 1) { + * for (let y = 0; y < img.height; y += 1) { + * img.set(x, y, 0); + * } + * } + * img.updatePixels(); + * image(img, 17, 17); + * + * describe('A black square drawn in the middle of a gray square.'); + * + *
      + * + *
      + * + * let img = createImage(66, 66); + * img.loadPixels(); + * let numPixels = 4 * img.width * img.height; + * for (let i = 0; i < numPixels; i += 4) { + * // Red. + * img.pixels[i] = 0; + * // Green. + * img.pixels[i + 1] = 0; + * // Blue. + * img.pixels[i + 2] = 0; + * // Alpha. + * img.pixels[i + 3] = 255; + * } + * img.updatePixels(); + * image(img, 17, 17); + * + * describe('A black square drawn in the middle of a gray square.'); + * + *
      + */ + + }, + { + key: 'loadPixels', + value: function loadPixels() { + _main.default.Renderer2D.prototype.loadPixels.call(this); + this.setModified(true); + } /** + * Updates the canvas with the RGBA values in the + * img.pixels array. + * + * `img.updatePixels()` only needs to be called after changing values in + * the img.pixels array. Such changes can be + * made directly after calling + * img.loadPixels() or by calling + * img.set(). + * + * The optional parameters `x`, `y`, `width`, and `height` define a + * subsection of the p5.Image object to update. + * Doing so can improve performance in some cases. + * + * If the p5.Image object was loaded from a GIF, + * then calling `img.updatePixels()` will update the pixels in current + * frame. + * + * @method updatePixels + * @param {Integer} x x-coordinate of the upper-left corner + * of the subsection to update. + * @param {Integer} y y-coordinate of the upper-left corner + * of the subsection to update. + * @param {Integer} w width of the subsection to update. + * @param {Integer} h height of the subsection to update. + * @example + *
      + * + * let img = createImage(66, 66); + * img.loadPixels(); + * for (let x = 0; x < img.width; x += 1) { + * for (let y = 0; y < img.height; y += 1) { + * img.set(x, y, 0); + * } + * } + * img.updatePixels(); + * image(img, 17, 17); + * + * describe('A black square drawn in the middle of a gray square.'); + * + *
      + * + *
      + * + * let img = createImage(66, 66); + * img.loadPixels(); + * let numPixels = 4 * img.width * img.height; + * for (let i = 0; i < numPixels; i += 4) { + * // Red. + * img.pixels[i] = 0; + * // Green. + * img.pixels[i + 1] = 0; + * // Blue. + * img.pixels[i + 2] = 0; + * // Alpha. + * img.pixels[i + 3] = 255; + * } + * img.updatePixels(); + * image(img, 17, 17); + * + * describe('A black square drawn in the middle of a gray square.'); + * + *
      + */ + /** + * @method updatePixels + */ + + }, + { + key: 'updatePixels', + value: function updatePixels(x, y, w, h) { + _main.default.Renderer2D.prototype.updatePixels.call(this, x, y, w, h); + this.setModified(true); + } /** + * Gets a pixel or a region of pixels from a + * p5.Image object. + * + * `img.get()` is easy to use but it's not as fast as + * img.pixels. Use + * img.pixels to read many pixel values. + * + * The version of `img.get()` with no parameters returns the entire image. + * + * The version of `img.get()` with two parameters interprets them as + * coordinates. It returns an array with the `[R, G, B, A]` values of the + * pixel at the given point. + * + * The version of `img.get()` with four parameters interprets them as + * coordinates and dimensions. It returns a subsection of the canvas as a + * p5.Image object. The first two parameters are + * the coordinates for the upper-left corner of the subsection. The last two + * parameters are the width and height of the subsection. + * + * Use img.get() to work directly with + * p5.Image objects. + * + * @method get + * @param {Number} x x-coordinate of the pixel. + * @param {Number} y y-coordinate of the pixel. + * @param {Number} w width of the subsection to be returned. + * @param {Number} h height of the subsection to be returned. + * @return {p5.Image} subsection as a p5.Image object. + * @example + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * image(img, 0, 0); + * let img2 = get(); + * image(img2, width / 2, 0); + * + * describe('Two identical mountain landscapes shown side-by-side.'); + * } + * + *
      + * + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * image(img, 0, 0); + * let c = img.get(50, 90); + * fill(c); + * noStroke(); + * square(25, 25, 50); + * + * describe('A mountain landscape with an olive green square in its center.'); + * } + * + *
      + * + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * image(img, 0, 0); + * let img2 = img.get(0, 0, img.width / 2, img.height / 2); + * image(img2, width / 2, height / 2); + * + * describe('A mountain landscape drawn on top of another mountain landscape.'); + * } + * + *
      + */ + /** + * @method get + * @return {p5.Image} whole p5.Image + */ + /** + * @method get + * @param {Number} x + * @param {Number} y + * @return {Number[]} color of the pixel at (x, y) in array format `[R, G, B, A]`. + */ + + }, + { + key: 'get', + value: function get(x, y, w, h) { + _main.default._validateParameters('p5.Image.get', arguments); + return _main.default.Renderer2D.prototype.get.apply(this, arguments); } - } - } - }; - var _default = _main.default.Image; - exports.default = _default; - }, - { - '../core/main': 290, - './filters': 311, - 'core-js/modules/es.array.filter': 171, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/web.dom-collections.iterator': 248 - } - ], - 315: [ - function (_dereq_, module, exports) { - 'use strict'; - _dereq_('core-js/modules/es.array.filter'); - _dereq_('core-js/modules/es.array.filter'); - Object.defineProperty(exports, '__esModule', { - value: true - }); - exports.default = void 0; - var _main = _interopRequireDefault(_dereq_('../core/main')); - var _filters = _interopRequireDefault(_dereq_('./filters')); - _dereq_('../color/p5.Color'); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: - obj - }; - } /** - * @module Image - * @submodule Pixels - * @for p5 - * @requires core - */ - /** - * Uint8ClampedArray - * containing the values for all the pixels in the display window. - * These values are numbers. This array is the size (include an appropriate - * factor for pixelDensity) of the display window x4, - * representing the R, G, B, A values in order for each pixel, moving from - * left to right across each row, then down each column. Retina and other - * high density displays will have more pixels[] (by a factor of - * pixelDensity^2). - * For example, if the image is 100×100 pixels, there will be 40,000. On a - * retina display, there will be 160,000. - * - * The first four values (indices 0-3) in the array will be the R, G, B, A - * values of the pixel at (0, 0). The second four values (indices 4-7) will - * contain the R, G, B, A values of the pixel at (1, 0). More generally, to - * set values for a pixel at (x, y): - * ```javascript - * let d = pixelDensity(); - * for (let i = 0; i < d; i++) { - * for (let j = 0; j < d; j++) { - * // loop over - * index = 4 * ((y * d + j) * width * d + (x * d + i)); - * pixels[index] = r; - * pixels[index+1] = g; - * pixels[index+2] = b; - * pixels[index+3] = a; - * } - * } - * ``` - * While the above method is complex, it is flexible enough to work with - * any pixelDensity. Note that set() will automatically take care of - * setting all the appropriate values in pixels[] for a given (x, y) at - * any pixelDensity, but the performance may not be as fast when lots of - * modifications are made to the pixel array. - * - * Before accessing this array, the data must loaded with the loadPixels() - * function. After the array data has been modified, the updatePixels() - * function must be run to update the changes. - * - * Note that this is not a standard javascript array. This means that - * standard javascript functions such as slice() or - * arrayCopy() do not - * work. - * - * @property {Number[]} pixels - * @example - *
      - * - * 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(); - * - *
      - * - * @alt - * top half of canvas pink, bottom grey - */ + }, + { + key: '_getPixel', + value: function _getPixel() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _main.default.Renderer2D.prototype._getPixel.apply(this, args); + } /** + * Sets the color of one or more pixels within a + * p5.Image object. + * + * `img.set()` is easy to use but it's not as fast as + * img.pixels. Use + * img.pixels to set many pixel values. + * + * `img.set()` interprets the first two parameters as x- and y-coordinates. It + * interprets the last parameter as a grayscale value, a `[R, G, B, A]` pixel + * array, a p5.Color object, or another + * p5.Image object. + * + * img.updatePixels() must be called + * after using `img.set()` for changes to appear. + * + * @method set + * @param {Number} x x-coordinate of the pixel. + * @param {Number} y y-coordinate of the pixel. + * @param {Number|Number[]|Object} a grayscale value | pixel array | + * p5.Color object | + * p5.Image to copy. + * @example + *
      + * + * let img = createImage(100, 100); + * img.set(30, 20, 0); + * img.set(85, 20, 0); + * img.set(85, 75, 0); + * img.set(30, 75, 0); + * img.updatePixels(); + * image(img, 0, 0); + * + * describe('Four black dots arranged in a square drawn on a gray background.'); + * + *
      + * + *
      + * + * let img = createImage(100, 100); + * let black = color(0); + * img.set(30, 20, black); + * img.set(85, 20, black); + * img.set(85, 75, black); + * img.set(30, 75, black); + * img.updatePixels(); + * image(img, 0, 0); + * + * describe('Four black dots arranged in a square drawn on a gray background.'); + * + *
      + * + *
      + * + * let img = createImage(66, 66); + * for (let x = 0; x < img.width; x += 1) { + * for (let y = 0; y < img.height; y += 1) { + * let c = map(x, 0, img.width, 0, 255); + * img.set(x, y, c); + * } + * } + * img.updatePixels(); + * image(img, 17, 17); + * + * describe('A square with a horiztonal color gradient from black to white drawn on a gray background.'); + * + *
      + * + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * let img2 = createImage(100, 100); + * img2.set(0, 0, img); + * image(img2, 0, 0); + * + * describe('An image of a mountain landscape.'); + * } + * + *
      + */ - _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 - *
      - * 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); - * } - *
      - *
      - * 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); - * } - *
      - *
      - * 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); - * } - *
      - * - * @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 + }, + { + key: 'set', + value: function set(x, y, imgOrCol) { + _main.default.Renderer2D.prototype.set.call(this, x, y, imgOrCol); + this.setModified(true); + } /** + * Resizes the p5.Image object to a given `width` + * and `height`. The image's original aspect ratio can be kept by passing 0 + * for either `width` or `height`. For example, calling `img.resize(50, 0)` + * on an image that was 500 × 300 pixels will resize it to + * 50 × 30 pixels. + * + * @method resize + * @param {Number} width resized image width. + * @param {Number} height resized image height. + * @example + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * function setup() { + * image(img, 0, 0); + * img.resize(50, 100); + * image(img, 0, 0); + * + * describe('Two images of a mountain landscape. One copy of the image is squeezed horizontally.'); + * } + * + *
      + * + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * function setup() { + * image(img, 0, 0); + * img.resize(0, 30); + * image(img, 0, 0); + * + * describe('Two images of a mountain landscape. The small copy of the image covers the top-left corner of the larger image.'); + * } + * + *
      + * + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * function setup() { + * image(img, 0, 0); + * img.resize(60, 0); + * image(img, 0, 0); + * + * describe('Two images of a mountain landscape. The small copy of the image covers the top-left corner of the larger image.'); + * } + * + *
      + */ + + }, + { + key: 'resize', + value: function resize(width, height) { + // Copy contents to a temporary canvas, resize the original + // and then copy back. + // + // There is a faster approach that involves just one copy and swapping the + // this.canvas reference. We could switch to that approach if (as i think + // is the case) there an expectation that the user would not hold a + // reference to the backing canvas of a p5.Image. But since we do not + // enforce that at the moment, I am leaving in the slower, but safer + // implementation. + // auto-resize + if (width === 0 && height === 0) { + width = this.canvas.width; + height = this.canvas.height; + } else if (width === 0) { + width = this.canvas.width * height / this.canvas.height; + } else if (height === 0) { + height = this.canvas.height * width / this.canvas.width; + } + width = Math.floor(width); + height = Math.floor(height); + var tempCanvas = document.createElement('canvas'); + tempCanvas.width = width; + tempCanvas.height = height; + if (this.gifProperties) { + var props = this.gifProperties; + //adapted from github.com/LinusU/resize-image-data + var nearestNeighbor = function nearestNeighbor(src, dst) { + var pos = 0; + for (var y = 0; y < dst.height; y++) { + for (var x = 0; x < dst.width; x++) { + var srcX = Math.floor(x * src.width / dst.width); + var srcY = Math.floor(y * src.height / dst.height); + var srcPos = (srcY * src.width + srcX) * 4; + dst.data[pos++] = src.data[srcPos++]; // R + dst.data[pos++] = src.data[srcPos++]; // G + dst.data[pos++] = src.data[srcPos++]; // B + dst.data[pos++] = src.data[srcPos++]; // A + } + } + }; + for (var i = 0; i < props.numFrames; i++) { + var resizedImageData = this.drawingContext.createImageData(width, height); + nearestNeighbor(props.frames[i].image, resizedImageData); + props.frames[i].image = resizedImageData; + } + } + tempCanvas.getContext('2d').drawImage(this.canvas, 0, 0, this.canvas.width, this.canvas.height, 0, 0, tempCanvas.width, tempCanvas.height); + // Resize the original canvas, which will clear its contents + this.canvas.width = this.width = width; + this.canvas.height = this.height = height; + //Copy the image back + this.drawingContext.drawImage(tempCanvas, 0, 0, width, height, 0, 0, width, height); + if (this.pixels.length > 0) { + this.loadPixels(); + } + this.setModified(true); + } /** + * + * Copies pixels from a source p5.Image + * to this one. Calling `img.copy()` will scale pixels from the source + * region if it isn't the same size as the destination region. + * + * @method copy + * @param {p5.Image|p5.Element} srcImage source image. + * @param {Integer} sx x-coordinate of the source's upper-left corner. + * @param {Integer} sy y-coordinate of the source's upper-left corner. + * @param {Integer} sw source image width. + * @param {Integer} sh source image height. + * @param {Integer} dx x-coordinate of the destination's upper-left corner. + * @param {Integer} dy y-coordinate of the destination's upper-left corner. + * @param {Integer} dw destination image width. + * @param {Integer} dh destination image height. + * + * @example + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * img.copy(7, 22, 10, 10, 35, 25, 50, 50); + * image(img, 0, 0); + * // Outline copied region. + * stroke(255); + * noFill(); + * square(7, 22, 10); + * + * describe('An image of a mountain landscape. A square region is outlined in white. A larger square contains a pixelated view of the outlined region.'); + * } + * + *
      + * + *
      + * + * let mountains; + * let bricks; + * + * function preload() { + * mountains = loadImage('assets/rockies.jpg'); + * bricks = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * let x = bricks.width / 2; + * let y = bricks.height / 2; + * mountains.copy(bricks, 0, 0, x, y, 0, 0, x, y); + * image(mountains, 0, 0); + * + * describe('An image of a brick wall drawn at the top-left of an image of a mountain landscape.'); + * } + * + *
      + */ + /** + * @method copy + * @param {Integer} sx + * @param {Integer} sy + * @param {Integer} sw + * @param {Integer} sh + * @param {Integer} dx + * @param {Integer} dy + * @param {Integer} dw + * @param {Integer} dh + */ + + }, + { + key: 'copy', + value: function copy() { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + _main.default.prototype.copy.apply(this, args); + } /** + * Masks part of an image from displaying by loading another + * image and using its alpha channel as an alpha channel for + * this image. Masks are cumulative, once applied to an image + * object, they cannot be removed. + * + * @method mask + * @param {p5.Image} srcImage source image. + * + * @example + *
      + * + * let photo; + * let maskImage; + * + * function preload() { + * photo = loadImage('assets/rockies.jpg'); + * maskImage = loadImage('assets/mask2.png'); + * } + * + * function setup() { + * photo.mask(maskImage); + * image(photo, 0, 0); + * + * describe('An image of a mountain landscape. The right side of the image has a faded patch of white.'); + * } + * + *
      + */ + // TODO: - Accept an array of alpha values. + + }, + { + key: 'mask', + value: function mask(p5Image) { + if (p5Image === undefined) { + p5Image = this; + } + var currBlend = this.drawingContext.globalCompositeOperation; + var scaleFactor = 1; + if (p5Image instanceof _main.default.Renderer) { + scaleFactor = p5Image._pInst._pixelDensity; + } + var copyArgs = [ + p5Image, + 0, + 0, + scaleFactor * p5Image.width, + scaleFactor * p5Image.height, + 0, + 0, + this.width, + this.height + ]; + this.drawingContext.globalCompositeOperation = 'destination-in'; + if (this.gifProperties) { + for (var i = 0; i < this.gifProperties.frames.length; i++) { + this.drawingContext.putImageData(this.gifProperties.frames[i].image, 0, 0); + this.copy.apply(this, copyArgs); + this.gifProperties.frames[i].image = this.drawingContext.getImageData(0, 0, this.width, this.height); + } + this.drawingContext.putImageData(this.gifProperties.frames[this.gifProperties.displayIndex].image, 0, 0); + } else { + this.copy.apply(this, copyArgs); + } + this.drawingContext.globalCompositeOperation = currBlend; + this.setModified(true); + } /** + * Applies an image filter to the p5.Image object. + * The preset options are: + * + * `INVERT` + * Inverts the colors in the image. No parameter is used. + * + * `GRAY` + * Converts the image to grayscale. No parameter is used. + * + * `THRESHOLD` + * Converts the image to black and white. Pixels with a grayscale value + * above a given threshold are converted to white. The rest are converted to + * black. The threshold must be between 0.0 (black) and 1.0 (white). If no + * value is specified, 0.5 is used. + * + * `OPAQUE` + * Sets the alpha channel to be entirely opaque. No parameter is used. + * + * `POSTERIZE` + * Limits the number of colors in the image. Each color channel is limited to + * the number of colors specified. Values between 2 and 255 are valid, but + * results are most noticeable with lower values. The default value is 4. + * + * `BLUR` + * Blurs the image. The level of blurring is specified by a blur radius. Larger + * values increase the blur. The default value is 4. A gaussian blur is used + * in `P2D` mode. A box blur is used in `WEBGL` mode. + * + * `ERODE` + * Reduces the light areas. No parameter is used. + * + * `DILATE` + * Increases the light areas. No parameter is used. + * + * @method filter + * @param {Constant} filterType either THRESHOLD, GRAY, OPAQUE, INVERT, + * POSTERIZE, ERODE, DILATE or BLUR. + * @param {Number} [filterParam] parameter unique to each filter. + * @example + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * img.filter(INVERT); + * image(img, 0, 0); + * + * describe('A blue brick wall.'); + * } + * + *
      + * + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * img.filter(GRAY); + * image(img, 0, 0); + * + * describe('A brick wall drawn in grayscale.'); + * } + * + *
      + * + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * img.filter(THRESHOLD); + * image(img, 0, 0); + * + * describe('A brick wall drawn in black and white.'); + * } + * + *
      + * + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * img.filter(OPAQUE); + * image(img, 0, 0); + * + * describe('A red brick wall.'); + * } + * + *
      + * + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * img.filter(POSTERIZE, 3); + * image(img, 0, 0); + * + * describe('An image of a red brick wall drawn with a limited color palette.'); + * } + * + *
      + * + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * img.filter(BLUR, 3); + * image(img, 0, 0); + * + * describe('A blurry image of a red brick wall.'); + * } + * + *
      + * + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * img.filter(DILATE); + * image(img, 0, 0); + * + * describe('A red brick wall with bright lines between each brick.'); + * } + * + *
      + * + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * img.filter(ERODE); + * image(img, 0, 0); + * + * describe('A red brick wall with faint lines between each brick.'); + * } + * + *
      + */ + + }, + { + key: 'filter', + value: function filter(operation, value) { + _filters.default.apply(this.canvas, _filters.default[operation], value); + this.setModified(true); + } /** + * Copies a region of pixels from another + * p5.Image object into this one. The `blendMode` + * parameter blends the images' colors to create different effects. + * + * @method blend + * @param {p5.Image} srcImage source image + * @param {Integer} sx x-coordinate of the source's upper-left corner. + * @param {Integer} sy y-coordinate of the source's upper-left corner. + * @param {Integer} sw source image width. + * @param {Integer} sh source image height. + * @param {Integer} dx x-coordinate of the destination's upper-left corner. + * @param {Integer} dy y-coordinate of the destination's upper-left corner. + * @param {Integer} dw destination image width. + * @param {Integer} dh destination image height. + * @param {Constant} blendMode the blend mode. either + * BLEND, DARKEST, LIGHTEST, DIFFERENCE, + * MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT, + * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL. + * + * Available blend modes are: normal | multiply | screen | overlay | + * darken | lighten | color-dodge | color-burn | hard-light | + * soft-light | difference | exclusion | hue | saturation | + * color | luminosity + * + * http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/ + * @example + *
      + * + * let mountains; + * let bricks; + * + * 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); + * + * describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears faded on the right of the image.'); + * } + * + *
      + * + *
      + * + * let mountains; + * let bricks; + * + * 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); + * + * describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears transparent on the right of the image.'); + * } + * + *
      + * + *
      + * + * let mountains; + * let bricks; + * + * 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); + * + * describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears washed out on the right of the image.'); + * } + * + *
      + */ + /** + * @method blend + * @param {Integer} sx + * @param {Integer} sy + * @param {Integer} sw + * @param {Integer} sh + * @param {Integer} dx + * @param {Integer} dy + * @param {Integer} dw + * @param {Integer} dh + * @param {Constant} blendMode + */ + + }, + { + key: 'blend', + value: function blend() { + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + _main.default._validateParameters('p5.Image.blend', arguments); + _main.default.prototype.blend.apply(this, args); + this.setModified(true); + } /** + * helper method for web GL mode to indicate that an image has been + * changed or unchanged since last upload. gl texture upload will + * set this value to false after uploading the texture. + * @method setModified + * @param {boolean} val sets whether or not the image has been + * modified. + * @private + */ + + }, + { + key: 'setModified', + value: function setModified(val) { + this._modified = val; //enforce boolean? + } /** + * helper method for web GL mode to figure out if the image + * has been modified and might need to be re-uploaded to texture + * memory between frames. + * @method isModified + * @private + * @return {boolean} a boolean indicating whether or not the + * image has been updated or modified since last texture upload. + */ + + }, + { + key: 'isModified', + value: function isModified() { + return this._modified; + } /** + * Saves the p5.Image object to a file. + * The browser will either save the file immediately or prompt the user + * with a dialogue window. + * + * By default, calling `img.save()` will save the image as `untitled.png`. + * + * Calling `img.save()` with one argument, as in `img.save('photo.png')`, + * will set the image's filename and type together. + * + * Calling `img.save()` with two arguments, as in + * `image.save('photo', 'png')`, will set the image's filename and type + * separately. + * + * The image will only be downloaded as an animated GIF if the + * p5.Image object was loaded from a GIF file. + * See saveGif() to create new GIFs. + * @method save + * @param {String} filename filename. Defaults to 'untitled'. + * @param {String} [extension] file extension, either 'png' or 'jpg'. + * Defaults to 'png'. + * @example + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function draw() { + * image(img, 0, 0); + * + * describe('An image of a mountain landscape.'); + * } + * + * function keyPressed() { + * if (key === 's') { + * img.save(); + * } else if (key === 'j') { + * img.save('rockies.jpg'); + * } else if (key === 'p') { + * img.save('rockies', 'png'); + * } + * } + * + *
      + */ + + }, + { + key: 'save', + value: function save(filename, extension) { + if (this.gifProperties) { + _main.default.prototype.encodeAndDownloadGif(this, filename); + } else { + _main.default.prototype.saveCanvas(this.canvas, filename, extension); + } + } // GIF Section + /** + * Restarts an animated GIF at its first frame. + * + * @method reset + * @example + *
      + * + * let gif; + * + * function preload() { + * gif = loadImage('assets/arnott-wallace-wink-loop-once.gif'); + * } + * + * function draw() { + * background(255); + * image(gif, 0, 0); + * + * describe('A cartoon face winks once and then freezes. Clicking resets the face and makes it wink again.'); + * } + * + * function mousePressed() { + * gif.reset(); + * } + * + *
      + */ + + }, + { + key: 'reset', + value: function reset() { + if (this.gifProperties) { + var props = this.gifProperties; + props.playing = true; + props.timeSinceStart = 0; + props.timeDisplayed = 0; + props.lastChangeTime = 0; + props.loopCount = 0; + props.displayIndex = 0; + this.drawingContext.putImageData(props.frames[0].image, 0, 0); + } + } /** + * Gets the index of the current frame in an animated GIF. + * + * @method getCurrentFrame + * @return {Number} index of the GIF's current frame. + * @example + *
      + * + * let gif; + * + * function preload() { + * gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif'); + * } + * + * function draw() { + * let index = gif.getCurrentFrame(); + * image(gif, 0, 0); + * text(index, 10, 90); + * + * describe('A cartoon eye repeatedly looks around, then outwards. A number displayed in the bottom-left corner increases from 0 to 124, then repeats.'); + * } + * + *
      + */ + + }, + { + key: 'getCurrentFrame', + value: function getCurrentFrame() { + if (this.gifProperties) { + var props = this.gifProperties; + return props.displayIndex % props.numFrames; + } + } /** + * Sets the current frame in an animated GIF. + * + * @method setFrame + * @param {Number} index index of the frame to display. + * @example + *
      + * + * let gif; + * let frameSlider; + * + * function preload() { + * gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif'); + * } + * + * function setup() { + * let maxFrame = gif.numFrames() - 1; + * frameSlider = createSlider(0, maxFrame); + * frameSlider.position(10, 80); + * frameSlider.size(80); + * } + * + * function draw() { + * let index = frameSlider.value(); + * gif.setFrame(index); + * image(gif, 0, 0); + * + * describe('A cartoon eye looks around when a slider is moved.'); + * } + * + *
      + */ + + }, + { + key: 'setFrame', + value: function setFrame(index) { + if (this.gifProperties) { + var props = this.gifProperties; + if (index < props.numFrames && index >= 0) { + props.timeDisplayed = 0; + props.lastChangeTime = 0; + props.displayIndex = index; + this.drawingContext.putImageData(props.frames[index].image, 0, 0); + } else { + console.log('Cannot set GIF to a frame number that is higher than total number of frames or below zero.'); + } + } + } /** + * Returns the number of frames in an animated GIF. + * + * @method numFrames + * @return {Number} number of frames in the GIF. + * + * @example + *
      + * + * let gif; + * + * function preload() { + * gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif'); + * } + * + * function draw() { + * image(gif, 0, 0); + * let total = gif.numFrames(); + * let index = gif.getCurrentFrame(); + * text(`${index} / ${total}`, 30, 90); + * + * describe('A cartoon eye looks around. The text "n / 125" is shown at the bottom of the canvas.'); + * } + * + *
      + */ + + }, + { + key: 'numFrames', + value: function numFrames() { + if (this.gifProperties) { + return this.gifProperties.numFrames; + } + } /** + * Plays an animated GIF that was paused with + * img.pause(). + * + * @method play + * + * @example + *
      + * + * let gif; + * + * function preload() { + * gif = loadImage('assets/nancy-liang-wind-loop-forever.gif'); + * } + * + * function draw() { + * background(255); + * image(gif, 0, 0); + * + * describe('A drawing of a child with hair blowing in the wind. The animation freezes when clicked and resumes when released.'); + * } + * + * function mousePressed() { + * gif.pause(); + * } + * + * function mouseReleased() { + * gif.play(); + * } + * + *
      + */ + + }, + { + key: 'play', + value: function play() { + if (this.gifProperties) { + this.gifProperties.playing = true; + } + } /** + * Pauses an animated GIF. The GIF can be resumed by calling + * img.play(). + * + * @method pause + * + * @example + *
      + * + * let gif; + * + * function preload() { + * gif = loadImage('assets/nancy-liang-wind-loop-forever.gif'); + * } + * + * function draw() { + * background(255); + * image(gif, 0, 0); + * + * describe('A drawing of a child with hair blowing in the wind. The animation freezes when clicked and resumes when released.'); + * } + * + * function mousePressed() { + * gif.pause(); + * } + * + * function mouseReleased() { + * gif.play(); + * } + * + *
      + */ + + }, + { + key: 'pause', + value: function pause() { + if (this.gifProperties) { + this.gifProperties.playing = false; + } + } /** + * Changes the delay between frames in an animated GIF. + * + * The second parameter, `index`, is optional. If provided, only the frame + * at `index` will have its delay modified. All other frames will keep + * their default delay. + * + * @method delay + * @param {Number} d delay in milliseconds between switching frames. + * @param {Number} [index] index of the frame that will have its delay modified. + * + * @example + *
      + * + * let gifFast; + * let gifSlow; + * + * function preload() { + * gifFast = loadImage('assets/arnott-wallace-eye-loop-forever.gif'); + * gifSlow = loadImage('assets/arnott-wallace-eye-loop-forever.gif'); + * } + * + * function setup() { + * gifFast.resize(50, 50); + * gifSlow.resize(50, 50); + * gifFast.delay(10); + * gifSlow.delay(100); + * } + * + * function draw() { + * image(gifFast, 0, 0); + * image(gifSlow, 50, 0); + * + * describe('Two animated eyes looking around. The eye on the left moves faster than the eye on the right.'); + * } + * + *
      + * + *
      + * + * let gif; + * + * function preload() { + * gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif'); + * } + * + * function setup() { + * gif.delay(3000, 67); + * } + * + * function draw() { + * image(gif, 0, 0); + * + * describe('An animated eye looking around. It pauses for three seconds while it looks down.'); + * } + * + *
      + */ + + }, + { + key: 'delay', + value: function delay(d, index) { + if (this.gifProperties) { + var props = this.gifProperties; + if (index < props.numFrames && index >= 0) { + props.frames[index].delay = d; + } else { + // change all frames + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = props.frames[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var frame = _step.value; + frame.delay = d; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + } + } + } + ]); + return _class; + }(); + var _default = _main.default.Image; + exports.default = _default; + }, + { + '../core/main': 298, + './filters': 319, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/web.dom-collections.iterator': 256 + } + ], + 323: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.filter'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var _filters = _interopRequireDefault(_dereq_('./filters')); + _dereq_('../color/p5.Color'); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Image + * @submodule Pixels + * @for p5 + * @requires core */ - _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. + * An array containing the color of each pixel on the canvas. Colors are + * stored as numbers representing red, green, blue, and alpha (RGBA) values. + * `pixels` is a one-dimensional array for performance reasons. * - * @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 + * Each pixel occupies four elements in the `pixels` array, one for each RGBA + * value. For example, the pixel at coordinates (0, 0) stores its RGBA values + * at `pixels[0]`, `pixels[1]`, `pixels[2]`, and `pixels[3]`, respectively. + * The next pixel at coordinates (1, 0) stores its RGBA values at `pixels[4]`, + * `pixels[5]`, `pixels[6]`, and `pixels[7]`. And so on. The `pixels` array + * for a 100×100 canvas has 100 × 100 × 4 = 40,000 elements. + * + * Some displays use several smaller pixels to set the color at a single + * point. The pixelDensity() function returns + * the pixel density of the canvas. High density displays often have a + * pixelDensity() of 2. On such a display, the + * `pixels` array for a 100×100 canvas has 200 × 200 × 4 = + * 160,000 elements. + * + * Accessing the RGBA values for a point on the canvas requires a little math + * as shown below. The loadPixels() function + * must be called before accessing the `pixels` array. The + * updatePixels() function must be called + * after any changes are made. + * + * @property {Number[]} pixels * * @example - *
      - * let img; + *
      + * + * loadPixels(); + * let x = 50; + * let y = 50; + * let d = pixelDensity(); + * for (let i = 0; i < d; i += 1) { + * for (let j = 0; j < d; j += 1) { + * let index = 4 * ((y * d + j) * width * d + (x * d + i)); + * // Red. + * pixels[index] = 0; + * // Green. + * pixels[index + 1] = 0; + * // Blue. + * pixels[index + 2] = 0; + * // Alpha. + * pixels[index + 3] = 255; + * } + * } + * updatePixels(); * - * function preload() { - * img = loadImage('assets/rockies.jpg'); + * describe('A black dot in the middle of a gray rectangle.'); + * + *
      + * + *
      + * + * loadPixels(); + * let d = pixelDensity(); + * let halfImage = 4 * (d * width) * (d * height / 2); + * for (let i = 0; i < halfImage; i += 4) { + * // Red. + * pixels[i] = 255; + * // Green. + * pixels[i + 1] = 0; + * // Blue. + * pixels[i + 2] = 0; + * // Alpha. + * pixels[i + 3] = 255; * } + * updatePixels(); * - * 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); + * describe('A red rectangle drawn above a gray rectangle.'); + * + *
      + * + *
      + * + * let pink = color(255, 102, 204); + * loadPixels(); + * let d = pixelDensity(); + * let halfImage = 4 * (d * width) * (d * height / 2); + * 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(); * - * @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 + * describe('A pink rectangle drawn above a gray rectangle.'); + *
      + *
      + */ + + _main.default.prototype.pixels = [ + ]; + /** + * Copies a region of pixels from one image to another. The `blendMode` + * parameter blends the images' colors to create different effects. + * + * @method blend + * @param {p5.Image} srcImage source image. + * @param {Integer} sx x-coordinate of the source's upper-left corner. + * @param {Integer} sy y-coordinate of the source's upper-left corner. + * @param {Integer} sw source image width. + * @param {Integer} sh source image height. + * @param {Integer} dx x-coordinate of the destination's upper-left corner. + * @param {Integer} dy y-coordinate of the destination's upper-left corner. + * @param {Integer} dw destination image width. + * @param {Integer} dh destination image height. + * @param {Constant} blendMode the blend mode. either + * BLEND, DARKEST, LIGHTEST, DIFFERENCE, + * MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT, + * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL. + * + * @example + *
      + * + * let img0; + * let img1; + * + * 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); + * + * describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears faded on the right of the image.'); + * } + * + *
      + * + *
      + * + * let img0; + * let img1; + * + * 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); + * + * describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears transparent on the right of the image.'); + * } + * + *
      + * + *
      + * + * let img0; + * let img1; + * + * 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); + * + * describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears washed out on the right of the image.'); + * } + * + *
      + */ + /** + * @method blend + * @param {Integer} sx + * @param {Integer} sy + * @param {Integer} sw + * @param {Integer} sh + * @param {Integer} dx + * @param {Integer} dy + * @param {Integer} dw + * @param {Integer} dh + * @param {Constant} blendMode + */ + _main.default.prototype.blend = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _main.default._validateParameters('blend', args); + if (this._renderer) { + var _this$_renderer; + (_this$_renderer = this._renderer).blend.apply(_this$_renderer, args); + } else { + _main.default.Renderer2D.prototype.blend.apply(this, args); + } + }; + /** + * Copies pixels from a source image to a region of the canvas. The source + * image can be the canvas itself or a p5.Image + * object. `copy()` will scale pixels from the source region if it isn't the + * same size as the destination region. + * + * @method copy + * @param {p5.Image|p5.Element} srcImage source image. + * @param {Integer} sx x-coordinate of the source's upper-left corner. + * @param {Integer} sy y-coordinate of the source's upper-left corner. + * @param {Integer} sw source image width. + * @param {Integer} sh source image height. + * @param {Integer} dx x-coordinate of the destination's upper-left corner. + * @param {Integer} dy y-coordinate of the destination's upper-left corner. + * @param {Integer} dw destination image width. + * @param {Integer} dh destination image height. + * + * @example + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * background(img); + * copy(img, 7, 22, 10, 10, 35, 25, 50, 50); + * // Show copied region. + * stroke(255); + * noFill(); + * square(7, 22, 10); + * + * describe('An image of a mountain landscape. A square region is outlined in white. A larger square contains a pixelated view of the outlined region.'); + * } + * + *
      */ /** * @method copy @@ -80668,8 +87437,8 @@ _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 + 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; @@ -80684,64 +87453,71 @@ } }; /** - * Applies a filter to the canvas. The presets options are: + * Applies an image filter to the canvas. The preset 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. + * `INVERT` + * Inverts the colors in the image. No parameter is used. * - * GRAY - * Converts any colors in the image to grayscale equivalents. No parameter - * is used. + * `GRAY` + * Converts the image to grayscale. No parameter is used. * - * OPAQUE - * Sets the alpha channel to entirely opaque. No parameter is used. + * `THRESHOLD` + * Converts the image to black and white. Pixels with a grayscale value + * above a given threshold are converted to white. The rest are converted to + * black. The threshold must be between 0.0 (black) and 1.0 (white). If no + * value is specified, 0.5 is used. * - * INVERT - * Sets each pixel to its inverse value. No parameter is used. + * `OPAQUE` + * Sets the alpha channel to entirely opaque. 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. + * `POSTERIZE` + * Limits the number of colors in the image. Each color channel is limited to + * the number of colors specified. Values between 2 and 255 are valid, but + * results are most noticeable with lower values. The default value is 4. * - * BLUR - * 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. + * `BLUR` + * Blurs the image. The level of blurring is specified by a blur radius. Larger + * values increase the blur. The default value is 4. A gaussian blur is used + * in `P2D` mode. A box blur is used in `WEBGL` mode. * - * ERODE + * `ERODE` * Reduces the light areas. No parameter is used. * - * DILATE + * `DILATE` * Increases the light areas. No parameter is used. * - * filter() does not work in WEBGL mode. - * A similar effect can be achieved in WEBGL mode using custom - * shaders. Adam Ferriss has written - * a selection of shader examples that contains many - * of the effects present in the filter examples. + * `filter()` uses WebGL in the background by default because it's faster. + * This can be disabled in `P2D` mode by adding a `false` argument, as in + * `filter(BLUR, false)`. This may be useful to keep computation off the GPU + * or to work around a lack of WebGL support. + * + * In `WEBGL` mode, `filter()` can also use custom shaders. See + * createFilterShader() for more + * information. + * * * @method filter * @param {Constant} filterType either THRESHOLD, GRAY, OPAQUE, INVERT, * POSTERIZE, BLUR, ERODE, DILATE or BLUR. - * See Filters.js for docs on - * each available filter - * @param {Number} [filterParam] an optional parameter unique - * to each filter, see above + * @param {Number} [filterParam] parameter unique to each filter. + * @param {Boolean} [useWebGL] flag to control whether to use fast + * WebGL filters (GPU) or original image + * filters (CPU); defaults to `true`. * * @example *
      * * let img; + * * function preload() { * img = loadImage('assets/bricks.jpg'); * } + * * function setup() { * image(img, 0, 0); - * filter(THRESHOLD); + * filter(INVERT); + * + * describe('A blue brick wall.'); * } * *
      @@ -80749,12 +87525,16 @@ *
      * * let img; + * * function preload() { * img = loadImage('assets/bricks.jpg'); * } + * * function setup() { * image(img, 0, 0); * filter(GRAY); + * + * describe('A brick wall drawn in grayscale.'); * } * *
      @@ -80762,12 +87542,16 @@ *
      * * let img; + * * function preload() { * img = loadImage('assets/bricks.jpg'); * } + * * function setup() { * image(img, 0, 0); - * filter(OPAQUE); + * filter(THRESHOLD); + * + * describe('A brick wall drawn in black and white.'); * } * *
      @@ -80775,12 +87559,16 @@ *
      * * let img; + * * function preload() { * img = loadImage('assets/bricks.jpg'); * } + * * function setup() { * image(img, 0, 0); - * filter(INVERT); + * filter(OPAQUE); + * + * describe('A red brick wall.'); * } * *
      @@ -80788,12 +87576,16 @@ *
      * * let img; + * * function preload() { * img = loadImage('assets/bricks.jpg'); * } + * * function setup() { * image(img, 0, 0); * filter(POSTERIZE, 3); + * + * describe('An image of a red brick wall drawn with limited color palette.'); * } * *
      @@ -80801,12 +87593,16 @@ *
      * * let img; + * * function preload() { * img = loadImage('assets/bricks.jpg'); * } + * * function setup() { * image(img, 0, 0); - * filter(DILATE); + * filter(BLUR, 3); + * + * describe('A blurry image of a red brick wall.'); * } * *
      @@ -80814,12 +87610,16 @@ *
      * * let img; + * * function preload() { * img = loadImage('assets/bricks.jpg'); * } + * * function setup() { * image(img, 0, 0); - * filter(BLUR, 3); + * filter(DILATE); + * + * describe('A red brick wall with bright lines between each brick.'); * } * *
      @@ -80827,81 +87627,172 @@ *
      * * let img; + * * function preload() { * img = loadImage('assets/bricks.jpg'); * } + * * function setup() { * image(img, 0, 0); * filter(ERODE); + * + * describe('A red brick wall with faint lines between each brick.'); * } * *
      * - * @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) { + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * image(img, 0, 0); + * // Don't use WebGL. + * filter(BLUR, 3, false); + * + * describe('A blurry image of a red brick wall.'); + * } + * + *
      + */ + /** + * @method getFilterGraphicsLayer + * @private + * @returns {p5.Graphics} + */ + _main.default.prototype.getFilterGraphicsLayer = function () { + return this._renderer.getFilterGraphicsLayer(); + }; + /** + * @method filter + * @param {Constant} filterType + * @param {Boolean} [useWebGL] + */ + /** + * @method filter + * @param {p5.Shader} shaderFilter shader that's been loaded, with the + * frag shader using a `tex0` uniform. + */ + _main.default.prototype.filter = function () { + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } _main.default._validateParameters('filter', arguments); - if (this.canvas !== undefined) { - _filters.default.apply(this.canvas, _filters.default[operation], value); + var _parseFilterArgs = parseFilterArgs.apply(void 0, args), + shader = _parseFilterArgs.shader, + operation = _parseFilterArgs.operation, + value = _parseFilterArgs.value, + useWebGL = _parseFilterArgs.useWebGL; // when passed a shader, use it directly + if (this._renderer.isP3D && shader) { + _main.default.RendererGL.prototype.filter.call(this._renderer, shader); + return; + } // when opting out of webgl, use old pixels method + + if (!useWebGL && !this._renderer.isP3D) { + if (this.canvas !== undefined) { + _filters.default.apply(this.canvas, _filters.default[operation], value); + } else { + _filters.default.apply(this.elt, _filters.default[operation], value); + } + return; + } + if (!useWebGL && this._renderer.isP3D) { + console.warn('filter() with useWebGL=false is not supported in WEBGL'); + } // when this is a webgl renderer, apply constant shader filter + + if (this._renderer.isP3D) { + _main.default.RendererGL.prototype.filter.call(this._renderer, operation, value); + } // when this is P2D renderer, create/use hidden webgl renderer + else { + var filterGraphicsLayer = this.getFilterGraphicsLayer(); + // copy p2d canvas contents to secondary webgl renderer + // dest + filterGraphicsLayer.copy( // src + this._renderer, // src coods + 0, 0, this.width, this.height, // dest coords + - this.width / 2, - this.height / 2, this.width, this.height); + //clearing the main canvas + this._renderer.clear(); + this._renderer.resetMatrix(); + // filter it with shaders + filterGraphicsLayer.filter.apply(filterGraphicsLayer, args); + // copy secondary webgl renderer back to original p2d canvas + this._renderer._pInst.image(filterGraphicsLayer, 0, 0); + filterGraphicsLayer.clear(); // prevent feedback effects on p2d canvas + } + }; + function parseFilterArgs() { + var _ref; + // args could be: + // - operation, value, [useWebGL] + // - operation, [useWebGL] + // - shader + var result = { + shader: undefined, + operation: undefined, + value: undefined, + useWebGL: true + }; + if ((arguments.length <= 0 ? undefined : arguments[0]) instanceof _main.default.Shader) { + result.shader = arguments.length <= 0 ? undefined : arguments[0]; + return result; } else { - _filters.default.apply(this.elt, _filters.default[operation], value); - } - }; - /** - * Get a region of pixels, or a single pixel, from the canvas. - * - * Returns an array of [R,G,B,A] values for any pixel or grabs a section of - * an image. If no parameters are specified, the entire image is returned. - * Use the x and y parameters to get the value of one pixel. Get a section of - * the display window by specifying additional w and h parameters. When - * getting an image, the x and y parameters define the coordinates for the - * upper-left corner of the image, regardless of the current imageMode(). - * - * Getting the color of a single pixel with get(x, y) is easy, but not as fast - * as grabbing the data directly from pixels[]. The equivalent statement to - * get(x, y) using pixels[] with pixel density d is - * ```javascript - * let x, y, d; // set these to the coordinates - * let off = (y * width + x) * d * 4; - * let components = [ - * pixels[off], - * pixels[off + 1], - * pixels[off + 2], - * pixels[off + 3] - * ]; - * print(components); - * ``` - * See the reference for pixels[] for more information. + result.operation = arguments.length <= 0 ? undefined : arguments[0]; + } + if (arguments.length > 1 && typeof (arguments.length <= 1 ? undefined : arguments[1]) === 'number') { + result.value = arguments.length <= 1 ? undefined : arguments[1]; + } + if ((_ref = arguments.length - 1, _ref < 0 || arguments.length <= _ref ? undefined : arguments[_ref]) === false) { + result.useWebGL = false; + } + return result; + } /** + * Gets a pixel or a region of pixels from the canvas. + * + * `get()` is easy to use but it's not as fast as + * pixels. Use pixels + * to read many pixel values. * - * If you want to extract an array of colors or a subimage from an p5.Image object, - * take a look at p5.Image.get() + * The version of `get()` with no parameters returns the entire canvas. + * + * The version of `get()` with two parameters interprets them as + * coordinates. It returns an array with the `[R, G, B, A]` values of the + * pixel at the given point. + * + * The version of `get()` with four parameters interprets them as coordinates + * and dimensions. It returns a subsection of the canvas as a + * p5.Image object. The first two parameters are the + * coordinates for the upper-left corner of the subsection. The last two + * parameters are the width and height of the subsection. + * + * Use p5.Image.get() to work directly with + * p5.Image objects. * * @method get - * @param {Number} x x-coordinate of the pixel - * @param {Number} y y-coordinate of the pixel - * @param {Number} w width - * @param {Number} h height - * @return {p5.Image} the rectangle p5.Image + * @param {Number} x x-coordinate of the pixel. + * @param {Number} y y-coordinate of the pixel. + * @param {Number} w width of the subsection to be returned. + * @param {Number} h height of the subsection to be returned. + * @return {p5.Image} subsection as a p5.Image object. * @example *
      * * let img; + * * function preload() { * img = loadImage('assets/rockies.jpg'); * } + * * function setup() { * image(img, 0, 0); * let c = get(); * image(c, width / 2, 0); + * + * describe('Two identical mountain landscapes shown side-by-side.'); * } * *
      @@ -80909,49 +87800,69 @@ *
      * * 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); + * square(25, 25, 50); + * + * describe('A mountain landscape with an olive green square in its center.'); * } * *
      * - * @alt - * 2 images of the rocky mountains, side-by-side - * Image of the rocky mountains with 50×50 green rect in center of canvas + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * image(img, 0, 0); + * let c = get(0, 0, width / 2, height / 2); + * image(c, width / 2, height / 2); + * + * describe('A mountain landscape drawn on top of another mountain landscape.'); + * } + * + *
      */ /** * @method get - * @return {p5.Image} the whole p5.Image + * @return {p5.Image} whole canvas as a p5.Image. */ /** * @method get * @param {Number} x * @param {Number} y - * @return {Number[]} color of pixel at x,y in array format [R, G, B, A] + * @return {Number[]} color of the pixel at (x, y) in array format `[R, G, B, A]`. */ + _main.default.prototype.get = function (x, y, w, h) { var _this$_renderer2; _main.default._validateParameters('get', arguments); return (_this$_renderer2 = this._renderer).get.apply(_this$_renderer2, arguments); }; /** - * Loads the pixel data for the display window into the pixels[] array. This - * function must always be called before reading from or writing to pixels[]. - * Note that only changes made with set() or direct manipulation of pixels[] - * will occur. + * Loads the current value of each pixel on the canvas into the + * pixels array. This + * function must be called before reading from or writing to + * pixels. * * @method loadPixels * @example *
      * * let img; + * * function preload() { * img = loadImage('assets/rockies.jpg'); * } @@ -80959,77 +87870,91 @@ * function setup() { * image(img, 0, 0, width, height); * let d = pixelDensity(); - * let halfImage = 4 * (width * d) * (height * d / 2); + * let halfImage = 4 * (d * width) * (d * height / 2); * loadPixels(); - * for (let i = 0; i < halfImage; i++) { + * for (let i = 0; i < halfImage; i += 1) { * pixels[i + halfImage] = pixels[i]; * } * updatePixels(); + * + * describe('Two identical images of mountain landscapes, one on top of the other.'); * } * *
      - * - * @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]; + for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; } _main.default._validateParameters('loadPixels', args); this._renderer.loadPixels(); }; /** - * Changes the color of any pixel, or writes an image directly to the - * display window. - * The x and y parameters specify the pixel to change and the c parameter - * specifies the color value. This can be a p5.Color object, or [R, G, B, A] - * pixel array. It can also be a single grayscale value. - * When setting an image, the x and y parameters define the coordinates for - * the upper-left corner of the image, regardless of the current imageMode(). + * Sets the color of a pixel or draws an image to the canvas. * - * After using set(), you must call updatePixels() for your changes to appear. - * This should be called once all pixels have been set, and must be called before - * calling .get() or drawing the image. + * `set()` is easy to use but it's not as fast as + * pixels. Use pixels + * to set many pixel values. * - * Setting the color of a single pixel with set(x, y) is easy, but not as - * fast as putting the data directly into pixels[]. Setting the pixels[] - * values directly may be complicated when working with a retina display, - * but will perform better when lots of pixels need to be set directly on - * every loop. See the reference for pixels[] for more information. + * `set()` interprets the first two parameters as x- and y-coordinates. It + * interprets the last parameter as a grayscale value, a `[R, G, B, A]` pixel + * array, a p5.Color object, or a + * p5.Image object. If an image is passed, the first + * two parameters set the coordinates for the image's upper-left corner, + * regardless of the current imageMode(). + * + * updatePixels() must be called after using + * `set()` for changes to appear. * * @method set - * @param {Number} x x-coordinate of the pixel - * @param {Number} y y-coordinate of the pixel - * @param {Number|Number[]|Object} c insert a grayscale value | a pixel array | - * a p5.Color object | a p5.Image to copy + * @param {Number} x x-coordinate of the pixel. + * @param {Number} y y-coordinate of the pixel. + * @param {Number|Number[]|Object} c grayscale value | pixel array | + * p5.Color object | p5.Image to copy. * @example *
      * + * set(30, 20, 0); + * set(85, 20, 0); + * set(85, 75, 0); + * set(30, 75, 0); + * updatePixels(); + * + * describe('Four black dots arranged in a square drawn on a gray background.'); + * + *
      + * + *
      + * * let black = color(0); * set(30, 20, black); * set(85, 20, black); * set(85, 75, black); * set(30, 75, black); * updatePixels(); + * + * describe('Four black dots arranged in a square drawn on a gray background.'); * *
      * *
      * - * 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); + * for (let x = 0; x < width; x += 1) { + * for (let y = 0; y < height; y += 1) { + * let c = map(x, 0, width, 0, 255); + * set(x, y, c); * } * } * updatePixels(); + * + * describe('A horiztonal color gradient from black to white.'); * *
      * *
      * * let img; + * * function preload() { * img = loadImage('assets/rockies.jpg'); * } @@ -81037,39 +87962,36 @@ * function setup() { * set(0, 0, img); * updatePixels(); - * line(0, 0, width, height); - * line(0, height, width, 0); + * + * describe('An image of a mountain landscape.'); * } * *
      - * - * @alt - * 4 black points in the shape of a square middle-right of canvas. - * square with orangey-brown gradient lightening at bottom right. - * image of the rocky mountains. with lines like an 'x' through the center. */ _main.default.prototype.set = function (x, y, imgOrCol) { this._renderer.set(x, y, imgOrCol); }; /** - * Updates the display window with the data in the pixels[] array. - * Use in conjunction with loadPixels(). If you're only reading pixels from - * the array, there's no need to call updatePixels() — updating is only - * necessary to apply changes. updatePixels() should be called anytime the - * pixels array is manipulated or set() is called, and only changes made with - * set() or direct changes to pixels[] will occur. + * Updates the canvas with the RGBA values in the + * pixels array. + * + * `updatePixels()` only needs to be called after changing values in the + * pixels array. Such changes can be made directly + * after calling loadPixels() or by calling + * set(). * * @method updatePixels * @param {Number} [x] x-coordinate of the upper-left corner of region - * to update + * 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 + * to update. + * @param {Number} [w] width of region to update. + * @param {Number} [h] height of region to update. * @example *
      * * let img; + * * function preload() { * img = loadImage('assets/rockies.jpg'); * } @@ -81077,20 +87999,21 @@ * function setup() { * image(img, 0, 0, width, height); * let d = pixelDensity(); - * let halfImage = 4 * (width * d) * (height * d / 2); + * let halfImage = 4 * (d * width) * (d * height / 2); * loadPixels(); - * for (let i = 0; i < halfImage; i++) { + * for (let i = 0; i < halfImage; i += 1) { * pixels[i + halfImage] = pixels[i]; * } * updatePixels(); + * + * describe('Two identical images of mountain landscapes, one on top of the other.'); * } * *
      - * @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 + _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; @@ -81101,13 +88024,13 @@ exports.default = _default; }, { - '../color/p5.Color': 276, - '../core/main': 290, - './filters': 311, - 'core-js/modules/es.array.filter': 171 + '../color/p5.Color': 284, + '../core/main': 298, + './filters': 319, + 'core-js/modules/es.array.filter': 173 } ], - 316: [ + 324: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -81118,9 +88041,11 @@ _dereq_('core-js/modules/es.array.index-of'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.last-index-of'); + _dereq_('core-js/modules/es.array.map'); _dereq_('core-js/modules/es.array.slice'); _dereq_('core-js/modules/es.array.splice'); _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.object.from-entries'); _dereq_('core-js/modules/es.object.to-string'); _dereq_('core-js/modules/es.promise'); _dereq_('core-js/modules/es.regexp.exec'); @@ -81175,9 +88100,11 @@ _dereq_('core-js/modules/es.array.index-of'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.last-index-of'); + _dereq_('core-js/modules/es.array.map'); _dereq_('core-js/modules/es.array.slice'); _dereq_('core-js/modules/es.array.splice'); _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.object.from-entries'); _dereq_('core-js/modules/es.object.to-string'); _dereq_('core-js/modules/es.promise'); _dereq_('core-js/modules/es.regexp.exec'); @@ -81241,7 +88168,13 @@ }; } return _typeof(obj); - } /** + } /** + * @module IO + * @submodule Input + * @for p5 + * @requires core + */ + /** * 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. @@ -81352,7 +88285,8 @@ var options; var ret = { }; // object needed for preload - var t = 'json'; // check for explicit data type argument + 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') { @@ -81395,7 +88329,7 @@ * 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 + * Alternatively, the file may 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. @@ -81470,7 +88404,8 @@ 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 + 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; @@ -81603,7 +88538,8 @@ var self = this; this.httpDo(path, 'GET', 'table', function (resp) { var state = { - }; // define constants + }; + // define constants var PRE_TOKEN = 0, MID_TOKEN = 1, POST_TOKEN = 2, @@ -81636,7 +88572,8 @@ currentRecord = null; }; for (; ; ) { - currentChar = resp[offset++]; // EOF + currentChar = resp[offset++]; + // EOF if (currentChar == null) { if (state.escaped) { throw new Error('Unclosed quote in file.'); @@ -81649,7 +88586,7 @@ } if (currentRecord === null) { recordBegin(); - } // Handle opening quote + } // Handle opening quote if (state.currentState === PRE_TOKEN) { if (currentChar === QUOTE) { @@ -81658,7 +88595,7 @@ continue; } state.currentState = MID_TOKEN; - } // mid-token and escaped, look for sequences and end quote + } // mid-token and escaped, look for sequences and end quote if (state.currentState === MID_TOKEN && state.escaped) { if (currentChar === QUOTE) { @@ -81675,7 +88612,7 @@ state.token += currentChar; } continue; - } // fall-through: mid-token or post-token, not escaped + } // fall-through: mid-token or post-token, not escaped if (currentChar === CR) { if (resp[offset] === LF) { @@ -81691,7 +88628,7 @@ } else if (state.currentState === MID_TOKEN) { state.token += currentChar; } - } // set up column names + } // set up column names if (header) { t.columns = records.shift(); @@ -81727,10 +88664,9 @@ } }); return t; - }; // helper function to turn a row into a JSON object + }; + // helper function to turn a row into a JSON object function makeObject(row, headers) { - var ret = { - }; headers = headers || [ ]; if (typeof headers === 'undefined') { @@ -81738,12 +88674,10 @@ 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; + return Object.fromEntries(headers.map(function (key, i) { + return [key, + row[i]]; + })); } /** * 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, @@ -82145,14 +89079,15 @@ 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 + 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 + } // The number of arguments minus callbacks var argsCount = arguments.length - cbCount; var path = arguments.length <= 0 ? undefined : arguments[0]; @@ -82206,7 +89141,7 @@ body: data, headers: headers }); - } // do some sort of smart type checking + } // do some sort of smart type checking if (!type) { if (path.includes('json')) { @@ -82265,7 +89200,8 @@ * @submodule Output * @for p5 */ - window.URL = window.URL || window.webkitURL; // private array of p5.PrintWriter objects + window.URL = window.URL || window.webkitURL; + // private array of p5.PrintWriter objects _main.default.prototype._pWriters = [ ]; /** @@ -82296,7 +89232,8 @@ *
      */ _main.default.prototype.createWriter = function (name, extension) { - var newPW; // check that it doesn't already exist + 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... @@ -82319,7 +89256,8 @@ _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. + this.content = ''; + //Changed to write because it was being overloaded by function below. /** * Writes data to the PrintWriter stream * @method write @@ -82482,7 +89420,8 @@ var arr = [ ]; arr.push(this.content); - _main.default.prototype.writeFile(arr, filename, extension); // remove from _pWriters array and delete self + _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 @@ -82599,7 +89538,8 @@ */ _main.default.prototype.save = function (object, _filename, _options) { // parse the arguments and figure out which things we are saving - var args = arguments; // ================================================= + var args = arguments; + // ================================================= // OPTION 1: saveCanvas... // if no arguments are provided, save canvas var cnv = this._curElement ? this._curElement.elt : this.elt; @@ -82740,7 +89680,8 @@ } pWriter.close(); pWriter.clear(); - }; // ======= + }; + // ======= // HELPERS // ======= function escapeHelper(content) { @@ -82809,7 +89750,7 @@ } } pWriter.write('\n'); - } // make rows + } // make rows for (var i = 0; i < table.rows.length; i++) { var j = void 0; @@ -82841,7 +89782,8 @@ pWriter.print(str); pWriter.print(''); pWriter.print(''); - pWriter.print(' '); // make header if it has values + pWriter.print('
      '); + // make header if it has values if (header[0] !== '0') { pWriter.print(' '); for (var k = 0; k < header.length; k++) { @@ -82850,7 +89792,7 @@ pWriter.print(' '); } pWriter.print(' '); - } // make rows + } // make rows for (var row = 0; row < table.rows.length; row++) { pWriter.print(' '); @@ -82865,7 +89807,7 @@ pWriter.print('
      '); pWriter.print(''); pWriter.print(''); - } // close and clear the pWriter + } // close and clear the pWriter pWriter.close(); pWriter.clear(); @@ -82913,13 +89855,15 @@ } var a = document.createElement('a'); a.href = data; - a.download = filename; // Firefox requires the link to be added to the DOM before click() + 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. + 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'; @@ -82946,10 +89890,11 @@ if (!filename) { filename = 'untitled'; } - var ext = ''; // make sure the file will have a name, see if filename needs extension + 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 + } // append extension if it doesn't exist if (extension) { if (ext !== extension) { @@ -82986,62 +89931,64 @@ exports.default = _default; }, { - '../core/friendly_errors/fes_core': 281, - '../core/friendly_errors/file_errors': 282, - '../core/friendly_errors/validate_params': 285, - '../core/main': 290, - 'core-js/modules/es.array.concat': 167, - 'core-js/modules/es.array.includes': 174, - 'core-js/modules/es.array.index-of': 175, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.last-index-of': 178, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.array.splice': 182, - 'core-js/modules/es.function.name': 183, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.promise': 196, - 'core-js/modules/es.regexp.exec': 199, - 'core-js/modules/es.regexp.to-string': 200, - 'core-js/modules/es.string.includes': 203, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.string.replace': 207, - 'core-js/modules/es.string.split': 209, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.typed-array.copy-within': 215, - 'core-js/modules/es.typed-array.every': 216, - 'core-js/modules/es.typed-array.fill': 217, - 'core-js/modules/es.typed-array.filter': 218, - 'core-js/modules/es.typed-array.find': 220, - 'core-js/modules/es.typed-array.find-index': 219, - 'core-js/modules/es.typed-array.for-each': 223, - 'core-js/modules/es.typed-array.includes': 224, - 'core-js/modules/es.typed-array.index-of': 225, - 'core-js/modules/es.typed-array.iterator': 228, - 'core-js/modules/es.typed-array.join': 229, - 'core-js/modules/es.typed-array.last-index-of': 230, - 'core-js/modules/es.typed-array.map': 231, - 'core-js/modules/es.typed-array.reduce': 233, - 'core-js/modules/es.typed-array.reduce-right': 232, - 'core-js/modules/es.typed-array.reverse': 234, - 'core-js/modules/es.typed-array.set': 235, - 'core-js/modules/es.typed-array.slice': 236, - 'core-js/modules/es.typed-array.some': 237, - 'core-js/modules/es.typed-array.sort': 238, - 'core-js/modules/es.typed-array.subarray': 239, - 'core-js/modules/es.typed-array.to-locale-string': 240, - 'core-js/modules/es.typed-array.to-string': 241, - 'core-js/modules/es.typed-array.uint8-array': 244, - 'core-js/modules/web.dom-collections.iterator': 248, - 'core-js/modules/web.url': 250, - 'es6-promise/auto': 251, - 'fetch-jsonp': 253, - 'file-saver': 254, - 'whatwg-fetch': 267 + '../core/friendly_errors/fes_core': 289, + '../core/friendly_errors/file_errors': 290, + '../core/friendly_errors/validate_params': 293, + '../core/main': 298, + 'core-js/modules/es.array.concat': 169, + 'core-js/modules/es.array.includes': 177, + 'core-js/modules/es.array.index-of': 178, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.last-index-of': 181, + 'core-js/modules/es.array.map': 182, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.array.splice': 185, + 'core-js/modules/es.function.name': 186, + 'core-js/modules/es.object.from-entries': 195, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.promise': 201, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.includes': 209, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.string.replace': 214, + 'core-js/modules/es.string.split': 216, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.typed-array.copy-within': 223, + 'core-js/modules/es.typed-array.every': 224, + 'core-js/modules/es.typed-array.fill': 225, + 'core-js/modules/es.typed-array.filter': 226, + 'core-js/modules/es.typed-array.find': 228, + 'core-js/modules/es.typed-array.find-index': 227, + 'core-js/modules/es.typed-array.for-each': 231, + 'core-js/modules/es.typed-array.includes': 232, + 'core-js/modules/es.typed-array.index-of': 233, + 'core-js/modules/es.typed-array.iterator': 236, + 'core-js/modules/es.typed-array.join': 237, + 'core-js/modules/es.typed-array.last-index-of': 238, + 'core-js/modules/es.typed-array.map': 239, + 'core-js/modules/es.typed-array.reduce': 241, + 'core-js/modules/es.typed-array.reduce-right': 240, + 'core-js/modules/es.typed-array.reverse': 242, + 'core-js/modules/es.typed-array.set': 243, + 'core-js/modules/es.typed-array.slice': 244, + 'core-js/modules/es.typed-array.some': 245, + 'core-js/modules/es.typed-array.sort': 246, + 'core-js/modules/es.typed-array.subarray': 247, + 'core-js/modules/es.typed-array.to-locale-string': 248, + 'core-js/modules/es.typed-array.to-string': 249, + 'core-js/modules/es.typed-array.uint8-array': 252, + 'core-js/modules/web.dom-collections.iterator': 256, + 'core-js/modules/web.url': 258, + 'es6-promise/auto': 259, + 'fetch-jsonp': 261, + 'file-saver': 262, + 'whatwg-fetch': 275 } ], - 317: [ + 325: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.array.concat'); @@ -83053,7 +90000,6 @@ _dereq_('core-js/modules/es.regexp.to-string'); _dereq_('core-js/modules/es.string.match'); _dereq_('core-js/modules/es.string.replace'); - _dereq_('core-js/modules/es.string.trim'); _dereq_('core-js/modules/es.array.concat'); _dereq_('core-js/modules/es.array.index-of'); _dereq_('core-js/modules/es.array.join'); @@ -83063,7 +90009,6 @@ _dereq_('core-js/modules/es.regexp.to-string'); _dereq_('core-js/modules/es.string.match'); _dereq_('core-js/modules/es.string.replace'); - _dereq_('core-js/modules/es.string.trim'); Object.defineProperty(exports, '__esModule', { value: true }); @@ -83074,11 +90019,30 @@ default: obj }; - } /** - * @module IO - * @submodule Table - * @requires core - */ + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } /** + * @module IO + * @submodule Table + * @requires core + */ /** * Table Options * Generic class for handling tabular data, typically from a @@ -83112,11 +90076,13 @@ * @param {p5.TableRow[]} [rows] An array of p5.TableRow objects */ - _main.default.Table = function (rows) { + _main.default.Table = /*#__PURE__*/ function () { /** * An array containing the names of the columns in the table, if the "header" the table is * loaded with the "header" parameter. - * @property columns {String[]} + * @type {String[]} + * @property columns + * @name columns * @example *
      * @@ -83145,1263 +90111,3675 @@ * *
      */ - this.columns = [ - ]; - /** - * An array containing the p5.TableRow objects that make up the - * rows of the table. The same result as calling getRows() - * @property rows {p5.TableRow[]} + function _class(rows) { + _classCallCheck(this, _class); + this.columns = [ + ]; + /** + * An array containing the p5.TableRow objects that make up the + * rows of the table. The same result as calling getRows() + * @type {p5.TableRow[]} + * @property rows + * @name rows + */ + this.rows = [ + ]; + } /** + * Use addRow() to add a new row of data to a p5.Table object. By default, + * an empty row is created. Typically, you would store a reference to + * the new row in a TableRow object (see newRow in the example above), + * and then set individual values using set(). + * + * If a p5.TableRow object is included as a parameter, then that row is + * duplicated and added to the table. + * + * @method addRow + * @param {p5.TableRow} [row] row to be added to the table + * @return {p5.TableRow} the row that was added + * + * @example + *
      + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * //add a row + * let newRow = table.addRow(); + * newRow.setString('id', table.getRowCount() - 1); + * newRow.setString('species', 'Canis Lupus'); + * newRow.setString('name', 'Wolf'); + * + * //print the results + * for (let r = 0; r < table.getRowCount(); r++) + * for (let c = 0; c < table.getColumnCount(); c++) + * print(table.getString(r, c)); + * + * describe('no image displayed'); + * } + * + *
      + */ + + _createClass(_class, [ + { + key: 'addRow', + value: function addRow(row) { + // make sure it is a valid TableRow + var r = row || new _main.default.TableRow(); + if (typeof r.arr === 'undefined' || typeof r.obj === 'undefined') { + //r = new p5.prototype.TableRow(r); + throw new Error('invalid TableRow: '.concat(r)); + } + r.table = this; + this.rows.push(r); + return r; + } /** + * Removes a row from the table object. + * + * @method removeRow + * @param {Integer} id ID number of the row to remove + * + * @example + *
      + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * //remove the first row + * table.removeRow(0); + * + * //print the results + * for (let r = 0; r < table.getRowCount(); r++) + * for (let c = 0; c < table.getColumnCount(); c++) + * print(table.getString(r, c)); + * + * describe('no image displayed'); + * } + * + *
      + */ + + }, + { + key: 'removeRow', + value: function removeRow(id) { + this.rows[id].table = null; // remove reference to table + var chunk = this.rows.splice(id + 1, this.rows.length); + this.rows.pop(); + this.rows = this.rows.concat(chunk); + } /** + * Returns a reference to the specified p5.TableRow. The reference + * can then be used to get and set values of the selected row. + * + * @method getRow + * @param {Integer} rowID ID number of the row to get + * @return {p5.TableRow} p5.TableRow object + * + * @example + *
      + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * let row = table.getRow(1); + * //print it column by column + * //note: a row is an object, not an array + * for (let c = 0; c < table.getColumnCount(); c++) { + * print(row.getString(c)); + * } + * + * describe('no image displayed'); + * } + * + *
      + */ + + }, + { + key: 'getRow', + value: function getRow(r) { + return this.rows[r]; + } /** + * Gets all rows from the table. Returns an array of p5.TableRows. + * + * @method getRows + * @return {p5.TableRow[]} Array of p5.TableRows + * + * @example + *
      + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * let rows = table.getRows(); + * + * //warning: rows is an array of objects + * for (let r = 0; r < rows.length; r++) { + * rows[r].set('name', 'Unicorn'); + * } + * + * //print the results + * for (let r = 0; r < table.getRowCount(); r++) + * for (let c = 0; c < table.getColumnCount(); c++) + * print(table.getString(r, c)); + * + * describe('no image displayed'); + * } + * + *
      + */ + + }, + { + key: 'getRows', + value: function getRows() { + return this.rows; + } /** + * Finds the first row in the Table that contains the value + * provided, and returns a reference to that row. Even if + * multiple rows are possible matches, only the first matching + * row is returned. The column to search may be specified by + * either its ID or title. + * + * @method findRow + * @param {String} value The value to match + * @param {Integer|String} column ID number or title of the + * column to search + * @return {p5.TableRow} + * + * @example + *
      + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * //find the animal named zebra + * let row = table.findRow('Zebra', 'name'); + * //find the corresponding species + * print(row.getString('species')); + * describe('no image displayed'); + * } + * + *
      + */ + + }, + { + key: 'findRow', + value: function findRow(value, column) { + // try the Object + if (typeof column === 'string') { + for (var i = 0; i < this.rows.length; i++) { + if (this.rows[i].obj[column] === value) { + return this.rows[i]; + } + } + } else { + // try the Array + for (var j = 0; j < this.rows.length; j++) { + if (this.rows[j].arr[column] === value) { + return this.rows[j]; + } + } + } // otherwise... + + return null; + } /** + * Finds the rows in the Table that contain the value + * provided, and returns references to those rows. Returns an + * Array, so for must be used to iterate through all the rows, + * as shown in the example above. The column to search may be + * specified by either its ID or title. + * + * @method findRows + * @param {String} value The value to match + * @param {Integer|String} column ID number or title of the + * column to search + * @return {p5.TableRow[]} An Array of TableRow objects + * + * @example + *
      + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * //add another goat + * let newRow = table.addRow(); + * newRow.setString('id', table.getRowCount() - 1); + * newRow.setString('species', 'Scape Goat'); + * newRow.setString('name', 'Goat'); + * + * //find the rows containing animals named Goat + * let rows = table.findRows('Goat', 'name'); + * print(rows.length + ' Goats found'); + * describe('no image displayed'); + * } + * + *
      + */ + + }, + { + key: 'findRows', + value: function findRows(value, column) { + var ret = [ + ]; + if (typeof column === 'string') { + for (var i = 0; i < this.rows.length; i++) { + if (this.rows[i].obj[column] === value) { + ret.push(this.rows[i]); + } + } + } else { + // try the Array + for (var j = 0; j < this.rows.length; j++) { + if (this.rows[j].arr[column] === value) { + ret.push(this.rows[j]); + } + } + } + return ret; + } /** + * Finds the first row in the Table that matches the regular + * expression provided, and returns a reference to that row. + * Even if multiple rows are possible matches, only the first + * matching row is returned. The column to search may be + * specified by either its ID or title. + * + * @method matchRow + * @param {String|RegExp} regexp The regular expression to match + * @param {String|Integer} column The column ID (number) or + * title (string) + * @return {p5.TableRow} TableRow object + * + * @example + *
      + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * //Search using specified regex on a given column, return TableRow object + * let mammal = table.matchRow(new RegExp('ant'), 1); + * print(mammal.getString(1)); + * //Output "Panthera pardus" + * } + * + *
      + */ + + }, + { + key: 'matchRow', + value: function matchRow(regexp, column) { + if (typeof column === 'number') { + for (var j = 0; j < this.rows.length; j++) { + if (this.rows[j].arr[column].match(regexp)) { + return this.rows[j]; + } + } + } else { + for (var i = 0; i < this.rows.length; i++) { + if (this.rows[i].obj[column].match(regexp)) { + return this.rows[i]; + } + } + } + return null; + } /** + * Finds the rows in the Table that match the regular expression provided, + * and returns references to those rows. Returns an array, so for must be + * used to iterate through all the rows, as shown in the example. The + * column to search may be specified by either its ID or title. + * + * @method matchRows + * @param {String} regexp The regular expression to match + * @param {String|Integer} [column] The column ID (number) or + * title (string) + * @return {p5.TableRow[]} An Array of TableRow objects + * @example + *
      + * + * let table; + * + * function setup() { + * table = new p5.Table(); + * + * table.addColumn('name'); + * table.addColumn('type'); + * + * let newRow = table.addRow(); + * newRow.setString('name', 'Lion'); + * newRow.setString('type', 'Mammal'); + * + * newRow = table.addRow(); + * newRow.setString('name', 'Snake'); + * newRow.setString('type', 'Reptile'); + * + * newRow = table.addRow(); + * newRow.setString('name', 'Mosquito'); + * newRow.setString('type', 'Insect'); + * + * newRow = table.addRow(); + * newRow.setString('name', 'Lizard'); + * newRow.setString('type', 'Reptile'); + * + * let rows = table.matchRows('R.*', 'type'); + * for (let i = 0; i < rows.length; i++) { + * print(rows[i].getString('name') + ': ' + rows[i].getString('type')); + * } + * } + * // Sketch prints: + * // Snake: Reptile + * // Lizard: Reptile + * + *
      + */ + + }, + { + key: 'matchRows', + value: function matchRows(regexp, column) { + var ret = [ + ]; + if (typeof column === 'number') { + for (var j = 0; j < this.rows.length; j++) { + if (this.rows[j].arr[column].match(regexp)) { + ret.push(this.rows[j]); + } + } + } else { + for (var i = 0; i < this.rows.length; i++) { + if (this.rows[i].obj[column].match(regexp)) { + ret.push(this.rows[i]); + } + } + } + return ret; + } /** + * Retrieves all values in the specified column, and returns them + * as an array. The column may be specified by either its ID or title. + * + * @method getColumn + * @param {String|Number} column String or Number of the column to return + * @return {Array} Array of column values + * + * @example + *
      + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * //getColumn returns an array that can be printed directly + * print(table.getColumn('species')); + * //outputs ["Capra hircus", "Panthera pardus", "Equus zebra"] + * describe('no image displayed'); + * } + * + *
      + */ + + }, + { + key: 'getColumn', + value: function getColumn(value) { + var ret = [ + ]; + if (typeof value === 'string') { + for (var i = 0; i < this.rows.length; i++) { + ret.push(this.rows[i].obj[value]); + } + } else { + for (var j = 0; j < this.rows.length; j++) { + ret.push(this.rows[j].arr[value]); + } + } + return ret; + } /** + * Removes all rows from a Table. While all rows are removed, + * columns and column titles are maintained. + * + * @method clearRows + * + * @example + *
      + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * table.clearRows(); + * print(table.getRowCount() + ' total rows in table'); + * print(table.getColumnCount() + ' total columns in table'); + * describe('no image displayed'); + * } + * + *
      + */ + + }, + { + key: 'clearRows', + value: function clearRows() { + delete this.rows; + this.rows = [ + ]; + } /** + * Use addColumn() to add a new column to a Table object. + * Typically, you will want to specify a title, so the column + * may be easily referenced later by name. (If no title is + * specified, the new column's title will be null.) + * + * @method addColumn + * @param {String} [title] title of the given column + * + * @example + *
      + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * table.addColumn('carnivore'); + * table.set(0, 'carnivore', 'no'); + * table.set(1, 'carnivore', 'yes'); + * table.set(2, 'carnivore', 'no'); + * + * //print the results + * for (let r = 0; r < table.getRowCount(); r++) + * for (let c = 0; c < table.getColumnCount(); c++) + * print(table.getString(r, c)); + * + * describe('no image displayed'); + * } + * + *
      + */ + + }, + { + key: 'addColumn', + value: function addColumn(title) { + var t = title || null; + this.columns.push(t); + } /** + * Returns the total number of columns in a Table. + * + * @method getColumnCount + * @return {Integer} Number of columns in this table + * @example + *
      + * + * // given the cvs file "blobs.csv" in /assets directory + * // ID, Name, Flavor, Shape, Color + * // Blob1, Blobby, Sweet, Blob, Pink + * // Blob2, Saddy, Savory, Blob, Blue + * + * let table; + * + * function preload() { + * table = loadTable('assets/blobs.csv'); + * } + * + * function setup() { + * createCanvas(200, 100); + * textAlign(CENTER); + * background(255); + * } + * + * function draw() { + * let numOfColumn = table.getColumnCount(); + * text('There are ' + numOfColumn + ' columns in the table.', 100, 50); + * } + * + *
      + */ + + }, + { + key: 'getColumnCount', + value: function getColumnCount() { + return this.columns.length; + } /** + * Returns the total number of rows in a Table. + * + * @method getRowCount + * @return {Integer} Number of rows in this table + * @example + *
      + * + * // given the cvs file "blobs.csv" in /assets directory + * // + * // ID, Name, Flavor, Shape, Color + * // Blob1, Blobby, Sweet, Blob, Pink + * // Blob2, Saddy, Savory, Blob, Blue + * + * let table; + * + * function preload() { + * table = loadTable('assets/blobs.csv'); + * } + * + * function setup() { + * createCanvas(200, 100); + * textAlign(CENTER); + * background(255); + * } + * + * function draw() { + * text('There are ' + table.getRowCount() + ' rows in the table.', 100, 50); + * } + * + *
      + */ + + }, + { + key: 'getRowCount', + value: function getRowCount() { + return this.rows.length; + } /** + * Removes any of the specified characters (or "tokens"). + * + * If no column is specified, then the values in all columns and + * rows are processed. A specific column may be referenced by + * either its ID or title. + * + * @method removeTokens + * @param {String} chars String listing characters to be removed + * @param {String|Integer} [column] Column ID (number) + * or name (string) + * + * @example + *
      + * function setup() { + * let table = new p5.Table(); + * + * table.addColumn('name'); + * table.addColumn('type'); + * + * let newRow = table.addRow(); + * newRow.setString('name', ' $Lion ,'); + * newRow.setString('type', ',,,Mammal'); + * + * newRow = table.addRow(); + * newRow.setString('name', '$Snake '); + * newRow.setString('type', ',,,Reptile'); + * + * table.removeTokens(',$ '); + * print(table.getArray()); + * } + * + * // prints: + * // 0 "Lion" "Mamal" + * // 1 "Snake" "Reptile" + *
      + */ + + }, + { + key: 'removeTokens', + value: function removeTokens(chars, column) { + var escape = function escape(s) { + return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'); + }; + var charArray = [ + ]; + for (var i = 0; i < chars.length; i++) { + charArray.push(escape(chars.charAt(i))); + } + var regex = new RegExp(charArray.join('|'), 'g'); + if (typeof column === 'undefined') { + for (var c = 0; c < this.columns.length; c++) { + for (var d = 0; d < this.rows.length; d++) { + var s = this.rows[d].arr[c]; + s = s.replace(regex, ''); + this.rows[d].arr[c] = s; + this.rows[d].obj[this.columns[c]] = s; + } + } + } else if (typeof column === 'string') { + for (var j = 0; j < this.rows.length; j++) { + var val = this.rows[j].obj[column]; + val = val.replace(regex, ''); + this.rows[j].obj[column] = val; + var pos = this.columns.indexOf(column); + this.rows[j].arr[pos] = val; + } + } else { + for (var k = 0; k < this.rows.length; k++) { + var str = this.rows[k].arr[column]; + str = str.replace(regex, ''); + this.rows[k].arr[column] = str; + this.rows[k].obj[this.columns[column]] = str; + } + } + } /** + * Trims leading and trailing whitespace, such as spaces and tabs, + * from String table values. If no column is specified, then the + * values in all columns and rows are trimmed. A specific column + * may be referenced by either its ID or title. + * + * @method trim + * @param {String|Integer} [column] Column ID (number) + * or name (string) + * @example + *
      + * function setup() { + * let table = new p5.Table(); + * + * table.addColumn('name'); + * table.addColumn('type'); + * + * let newRow = table.addRow(); + * newRow.setString('name', ' Lion ,'); + * newRow.setString('type', ' Mammal '); + * + * newRow = table.addRow(); + * newRow.setString('name', ' Snake '); + * newRow.setString('type', ' Reptile '); + * + * table.trim(); + * print(table.getArray()); + * } + * + * // prints: + * // 0 "Lion" "Mamal" + * // 1 "Snake" "Reptile" + *
      + */ + + }, + { + key: 'trim', + value: function trim(column) { + var regex = new RegExp(' ', 'g'); + if (typeof column === 'undefined') { + for (var c = 0; c < this.columns.length; c++) { + for (var d = 0; d < this.rows.length; d++) { + var s = this.rows[d].arr[c]; + s = s.replace(regex, ''); + this.rows[d].arr[c] = s; + this.rows[d].obj[this.columns[c]] = s; + } + } + } else if (typeof column === 'string') { + for (var j = 0; j < this.rows.length; j++) { + var val = this.rows[j].obj[column]; + val = val.replace(regex, ''); + this.rows[j].obj[column] = val; + var pos = this.columns.indexOf(column); + this.rows[j].arr[pos] = val; + } + } else { + for (var k = 0; k < this.rows.length; k++) { + var str = this.rows[k].arr[column]; + str = str.replace(regex, ''); + this.rows[k].arr[column] = str; + this.rows[k].obj[this.columns[column]] = str; + } + } + } /** + * Use removeColumn() to remove an existing column from a Table + * object. The column to be removed may be identified by either + * its title (a String) or its index value (an int). + * removeColumn(0) would remove the first column, removeColumn(1) + * would remove the second column, and so on. + * + * @method removeColumn + * @param {String|Integer} column columnName (string) or ID (number) + * + * @example + *
      + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * table.removeColumn('id'); + * print(table.getColumnCount()); + * describe('no image displayed'); + * } + * + *
      + */ + + }, + { + key: 'removeColumn', + value: function removeColumn(c) { + var cString; + var cNumber; + if (typeof c === 'string') { + // find the position of c in the columns + cString = c; + cNumber = this.columns.indexOf(c); + } else { + cNumber = c; + cString = this.columns[c]; + } + var chunk = this.columns.splice(cNumber + 1, this.columns.length); + this.columns.pop(); + this.columns = this.columns.concat(chunk); + for (var i = 0; i < this.rows.length; i++) { + var tempR = this.rows[i].arr; + var chip = tempR.splice(cNumber + 1, tempR.length); + tempR.pop(); + this.rows[i].arr = tempR.concat(chip); + delete this.rows[i].obj[cString]; + } + } /** + * Stores a value in the Table's specified row and column. + * The row is specified by its ID, while the column may be specified + * by either its ID or title. + * + * @method set + * @param {Integer} row row ID + * @param {String|Integer} column column ID (Number) + * or title (String) + * @param {String|Number} value value to assign + * + * @example + *
      + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * table.set(0, 'species', 'Canis Lupus'); + * table.set(0, 'name', 'Wolf'); + * + * //print the results + * for (let r = 0; r < table.getRowCount(); r++) + * for (let c = 0; c < table.getColumnCount(); c++) + * print(table.getString(r, c)); + * + * describe('no image displayed'); + * } + * + *
      + */ + + }, + { + key: 'set', + value: function set(row, column, value) { + this.rows[row].set(column, value); + } /** + * Stores a Float value in the Table's specified row and column. + * The row is specified by its ID, while the column may be specified + * by either its ID or title. + * + * @method setNum + * @param {Integer} row row ID + * @param {String|Integer} column column ID (Number) + * or title (String) + * @param {Number} value value to assign + * + * @example + *
      + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * table.setNum(1, 'id', 1); + * + * print(table.getColumn(0)); + * //["0", 1, "2"] + * + * describe('no image displayed'); + * } + * + *
      + */ + + }, + { + key: 'setNum', + value: function setNum(row, column, value) { + this.rows[row].setNum(column, value); + } /** + * Stores a String value in the Table's specified row and column. + * The row is specified by its ID, while the column may be specified + * by either its ID or title. + * + * @method setString + * @param {Integer} row row ID + * @param {String|Integer} column column ID (Number) + * or title (String) + * @param {String} value value to assign + * @example + *
      + * // Given the CSV file "mammals.csv" in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * //add a row + * let newRow = table.addRow(); + * newRow.setString('id', table.getRowCount() - 1); + * newRow.setString('species', 'Canis Lupus'); + * newRow.setString('name', 'Wolf'); + * + * print(table.getArray()); + * + * describe('no image displayed'); + * } + *
      + */ + + }, + { + key: 'setString', + value: function setString(row, column, value) { + this.rows[row].setString(column, value); + } /** + * Retrieves a value from the Table's specified row and column. + * The row is specified by its ID, while the column may be specified by + * either its ID or title. + * + * @method get + * @param {Integer} row row ID + * @param {String|Integer} column columnName (string) or + * ID (number) + * @return {String|Number} + * + * @example + *
      + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * print(table.get(0, 1)); + * //Capra hircus + * print(table.get(0, 'species')); + * //Capra hircus + * describe('no image displayed'); + * } + * + *
      + */ + + }, + { + key: 'get', + value: function get(row, column) { + return this.rows[row].get(column); + } /** + * Retrieves a Float value from the Table's specified row and column. + * The row is specified by its ID, while the column may be specified by + * either its ID or title. + * + * @method getNum + * @param {Integer} row row ID + * @param {String|Integer} column columnName (string) or + * ID (number) + * @return {Number} + * + * @example + *
      + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * print(table.getNum(1, 0) + 100); + * //id 1 + 100 = 101 + * describe('no image displayed'); + * } + * + *
      + */ + + }, + { + key: 'getNum', + value: function getNum(row, column) { + return this.rows[row].getNum(column); + } /** + * Retrieves a String value from the Table's specified row and column. + * The row is specified by its ID, while the column may be specified by + * either its ID or title. + * + * @method getString + * @param {Integer} row row ID + * @param {String|Integer} column columnName (string) or + * ID (number) + * @return {String} + * + * @example + *
      + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * // table is comma separated value "CSV" + * // and has specifiying header for column labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * print(table.getString(0, 0)); // 0 + * print(table.getString(0, 1)); // Capra hircus + * print(table.getString(0, 2)); // Goat + * print(table.getString(1, 0)); // 1 + * print(table.getString(1, 1)); // Panthera pardus + * print(table.getString(1, 2)); // Leopard + * print(table.getString(2, 0)); // 2 + * print(table.getString(2, 1)); // Equus zebra + * print(table.getString(2, 2)); // Zebra + * describe('no image displayed'); + * } + * + *
      + */ + + }, + { + key: 'getString', + value: function getString(row, column) { + return this.rows[row].getString(column); + } /** + * Retrieves all table data and returns as an object. If a column name is + * passed in, each row object will be stored with that attribute as its + * title. + * + * @method getObject + * @param {String} [headerColumn] Name of the column which should be used to + * title each row object (optional) + * @return {Object} + * + * @example + *
      + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * let tableObject = table.getObject(); + * + * print(tableObject); + * //outputs an object + * + * describe('no image displayed'); + * } + * + *
      + */ + + }, + { + key: 'getObject', + value: function getObject(headerColumn) { + var tableObject = { + }; + var obj, + cPos, + index; + for (var i = 0; i < this.rows.length; i++) { + obj = this.rows[i].obj; + if (typeof headerColumn === 'string') { + cPos = this.columns.indexOf(headerColumn); // index of columnID + if (cPos >= 0) { + index = obj[headerColumn]; + tableObject[index] = obj; + } else { + throw new Error('This table has no column named "'.concat(headerColumn, '"')); + } + } else { + tableObject[i] = this.rows[i].obj; + } + } + return tableObject; + } /** + * Retrieves all table data and returns it as a multidimensional array. + * + * @method getArray + * @return {Array} + * + * @example + *
      + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leoperd + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * // table is comma separated value "CSV" + * // and has specifiying header for column labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * let tableArray = table.getArray(); + * for (let i = 0; i < tableArray.length; i++) { + * print(tableArray[i]); + * } + * describe('no image displayed'); + * } + * + *
      + */ + + }, + { + key: 'getArray', + value: function getArray() { + var tableArray = [ + ]; + for (var i = 0; i < this.rows.length; i++) { + tableArray.push(this.rows[i].arr); + } + return tableArray; + } + } + ]); + return _class; + }(); + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 298, + 'core-js/modules/es.array.concat': 169, + 'core-js/modules/es.array.index-of': 178, + 'core-js/modules/es.array.join': 180, + 'core-js/modules/es.array.splice': 185, + 'core-js/modules/es.regexp.constructor': 204, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.match': 211, + 'core-js/modules/es.string.replace': 214 + } + ], + 326: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.from-entries'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.from-entries'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } /** + * @module IO + * @submodule Table + * @requires core */ - this.rows = [ - ]; - }; /** - * Use addRow() to add a new row of data to a p5.Table object. By default, - * an empty row is created. Typically, you would store a reference to - * the new row in a TableRow object (see newRow in the example above), - * and then set individual values using set(). - * - * If a p5.TableRow object is included as a parameter, then that row is - * duplicated and added to the table. - * - * @method addRow - * @param {p5.TableRow} [row] row to be added to the table - * @return {p5.TableRow} the row that was added - * - * @example - *
      - * - * // Given the CSV file "mammals.csv" - * // in the project's "assets" folder: - * // - * // id,species,name - * // 0,Capra hircus,Goat - * // 1,Panthera pardus,Leopard - * // 2,Equus zebra,Zebra - * - * let table; - * - * function preload() { - * //my table is comma separated value "csv" - * //and has a header specifying the columns labels - * table = loadTable('assets/mammals.csv', 'csv', 'header'); - * } - * - * function setup() { - * //add a row - * let newRow = table.addRow(); - * newRow.setString('id', table.getRowCount() - 1); - * newRow.setString('species', 'Canis Lupus'); - * newRow.setString('name', 'Wolf'); + * A TableRow object represents a single row of data values, + * stored in columns, from a table. * - * //print the results - * for (let r = 0; r < table.getRowCount(); r++) - * for (let c = 0; c < table.getColumnCount(); c++) - * print(table.getString(r, c)); + * A Table Row contains both an ordered array, and an unordered + * JSON object. * - * describe('no image displayed'); - * } - * - *
      + * @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.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)); + + _main.default.TableRow = /*#__PURE__*/ function () { + function _class(str, separator) { + _classCallCheck(this, _class); + var arr = [ + ]; + if (str) { + separator = separator || ','; + arr = str.split(separator); + } + this.arr = arr; + this.obj = Object.fromEntries(arr.entries()); + this.table = null; + } /** + * Stores a value in the TableRow's specified column. + * The column may be specified by either its ID or title. + * + * @method set + * @param {String|Integer} column Column ID (Number) + * or Title (String) + * @param {String|Number} value The value to be stored + * + * @example + *
      + * // Given the CSV file "mammals.csv" in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * let rows = table.getRows(); + * for (let r = 0; r < rows.length; r++) { + * rows[r].set('name', 'Unicorn'); + * } + * + * //print the results + * print(table.getArray()); + * + * describe('no image displayed'); + * } + *
      + */ + + _createClass(_class, [ + { + key: 'set', + value: function set(column, value) { + // if typeof column is string, use .obj + if (typeof column === 'string') { + var cPos = this.table.columns.indexOf(column); // index of columnID + if (cPos >= 0) { + this.obj[column] = value; + this.arr[cPos] = value; + } else { + throw new Error('This table has no column named "'.concat(column, '"')); + } + } else { + // if typeof column is number, use .arr + if (column < this.table.columns.length) { + this.arr[column] = value; + var cTitle = this.table.columns[column]; + this.obj[cTitle] = value; + } else { + throw new Error('Column #'.concat(column, ' is out of the range of this table')); + } + } + } /** + * Stores a Float value in the TableRow's specified column. + * The column may be specified by either its ID or title. + * + * @method setNum + * @param {String|Integer} column Column ID (Number) + * or Title (String) + * @param {Number|String} value The value to be stored + * as a Float + * @example + *
      + * // Given the CSV file "mammals.csv" in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * let rows = table.getRows(); + * for (let r = 0; r < rows.length; r++) { + * rows[r].setNum('id', r + 10); + * } + * + * print(table.getArray()); + * + * describe('no image displayed'); + * } + *
      + */ + + }, + { + key: 'setNum', + value: function setNum(column, value) { + var floatVal = parseFloat(value); + this.set(column, floatVal); + } /** + * Stores a String value in the TableRow's specified column. + * The column may be specified by either its ID or title. + * + * @method setString + * @param {String|Integer} column Column ID (Number) + * or Title (String) + * @param {String|Number|Boolean|Object} value The value to be stored + * as a String + * @example + *
      + * // Given the CSV file "mammals.csv" in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * let rows = table.getRows(); + * for (let r = 0; r < rows.length; r++) { + * let name = rows[r].getString('name'); + * rows[r].setString('name', 'A ' + name + ' named George'); + * } + * + * print(table.getArray()); + * + * describe('no image displayed'); + * } + *
      + */ + + }, + { + key: 'setString', + value: function setString(column, value) { + var stringVal = value.toString(); + this.set(column, stringVal); + } /** + * Retrieves a value from the TableRow's specified column. + * The column may be specified by either its ID or title. + * + * @method get + * @param {String|Integer} column columnName (string) or + * ID (number) + * @return {String|Number} + * + * @example + *
      + * // Given the CSV file "mammals.csv" in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * let names = []; + * let rows = table.getRows(); + * for (let r = 0; r < rows.length; r++) { + * names.push(rows[r].get('name')); + * } + * + * print(names); + * + * describe('no image displayed'); + * } + *
      + */ + + }, + { + key: 'get', + value: function get(column) { + if (typeof column === 'string') { + return this.obj[column]; + } else { + return this.arr[column]; + } + } /** + * Retrieves a Float value from the TableRow's specified + * column. The column may be specified by either its ID or + * title. + * + * @method getNum + * @param {String|Integer} column columnName (string) or + * ID (number) + * @return {Number} Float Floating point number + * @example + *
      + * // Given the CSV file "mammals.csv" in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * let rows = table.getRows(); + * let minId = Infinity; + * let maxId = -Infinity; + * for (let r = 0; r < rows.length; r++) { + * let id = rows[r].getNum('id'); + * minId = min(minId, id); + * maxId = min(maxId, id); + * } + * print('minimum id = ' + minId + ', maximum id = ' + maxId); + * describe('no image displayed'); + * } + *
      + */ + + }, + { + key: 'getNum', + value: function getNum(column) { + var ret; + if (typeof column === 'string') { + ret = parseFloat(this.obj[column]); + } else { + ret = parseFloat(this.arr[column]); + } + if (ret.toString() === 'NaN') { + throw 'Error: '.concat(this.obj[column], ' is NaN (Not a Number)'); + } + return ret; + } /** + * Retrieves an String value from the TableRow's specified + * column. The column may be specified by either its ID or + * title. + * + * @method getString + * @param {String|Integer} column columnName (string) or + * ID (number) + * @return {String} String + * @example + *
      + * // Given the CSV file "mammals.csv" in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * let rows = table.getRows(); + * let longest = ''; + * for (let r = 0; r < rows.length; r++) { + * let species = rows[r].getString('species'); + * if (longest.length < species.length) { + * longest = species; + * } + * } + * + * print('longest: ' + longest); + * + * describe('no image displayed'); + * } + *
      + */ + + }, + { + key: 'getString', + value: function getString(column) { + if (typeof column === 'string') { + return this.obj[column].toString(); + } else { + return this.arr[column].toString(); + } + } + } + ]); + return _class; + }(); + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 298, + 'core-js/modules/es.array.index-of': 178, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.object.from-entries': 195, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.split': 216, + 'core-js/modules/web.dom-collections.iterator': 256 + } + ], + 327: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.number.constructor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.number.constructor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); } - r.table = this; - this.rows.push(r); - return r; - }; + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } /** + * @module IO + * @submodule Input + * @requires core + */ /** - * Removes a row from the table object. - * - * @method removeRow - * @param {Integer} id ID number of the row to remove + * XML is a representation of an XML object, able to parse XML code. Use + * loadXML() to load external XML files and create XML objects. * + * @class p5.XML + * @constructor * @example - *
      - * - * // Given the CSV file "mammals.csv" - * // in the project's "assets" folder: + *
      + * // The following short XML file called "mammals.xml" is parsed + * // in the code below. * // - * // id,species,name - * // 0,Capra hircus,Goat - * // 1,Panthera pardus,Leopard - * // 2,Equus zebra,Zebra + * // + * // <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 table; + * let xml; * * function preload() { - * //my table is comma separated value "csv" - * //and has a header specifying the columns labels - * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * xml = loadXML('assets/mammals.xml'); * } * * function setup() { - * //remove the first row - * table.removeRow(0); - * - * //print the results - * for (let r = 0; r < table.getRowCount(); r++) - * for (let c = 0; c < table.getColumnCount(); c++) - * print(table.getString(r, c)); - * - * describe('no image displayed'); - * } - * - *
      - */ - _main.default.Table.prototype.removeRow = function (id) { - this.rows[id].table = null; // remove reference to table - var chunk = this.rows.splice(id + 1, this.rows.length); - this.rows.pop(); - this.rows = this.rows.concat(chunk); - }; - /** - * Returns a reference to the specified p5.TableRow. The reference - * can then be used to get and set values of the selected row. - * - * @method getRow - * @param {Integer} rowID ID number of the row to get - * @return {p5.TableRow} p5.TableRow object - * - * @example - *
      - * - * // Given the CSV file "mammals.csv" - * // in the project's "assets" folder: - * // - * // id,species,name - * // 0,Capra hircus,Goat - * // 1,Panthera pardus,Leopard - * // 2,Equus zebra,Zebra - * - * let table; - * - * function preload() { - * //my table is comma separated value "csv" - * //and has a header specifying the columns labels - * table = loadTable('assets/mammals.csv', 'csv', 'header'); - * } + * let children = xml.getChildren('animal'); * - * 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)); + * for (let i = 0; i < children.length; i++) { + * let id = children[i].getNum('id'); + * let coloring = children[i].getString('species'); + * let name = children[i].getContent(); + * print(id + ', ' + coloring + ', ' + name); * } * * describe('no image displayed'); * } - * - *
      + * + * // Sketch prints: + * // 0, Capra hircus, Goat + * // 1, Panthera pardus, Leopard + * // 2, Equus zebra, Zebra + *
      + */ + + _main.default.XML = /*#__PURE__*/ function () { + function _class(DOM) { + _classCallCheck(this, _class); + if (!DOM) { + var xmlDoc = document.implementation.createDocument(null, 'doc'); + this.DOM = xmlDoc.createElement('root'); + } else { + this.DOM = DOM; + } + } /** + * Gets a copy of the element's parent. Returns the parent as another + * p5.XML object. + * + * @method getParent + * @return {p5.XML} element parent + * @example + *
      + * // The following short XML file called "mammals.xml" is parsed + * // in the code below. + * // + * // + * // <mammals> + * // <animal id="0" species="Capra hircus">Goat</animal> + * // <animal id="1" species="Panthera pardus">Leopard</animal> + * // <animal id="2" species="Equus zebra">Zebra</animal> + * // </mammals> + * + * let xml; + * + * function preload() { + * xml = loadXML('assets/mammals.xml'); + * } + * + * function setup() { + * let children = xml.getChildren('animal'); + * let parent = children[1].getParent(); + * print(parent.getName()); + * } + * + * // Sketch prints: + * // mammals + *
      + */ + + _createClass(_class, [ + { + key: 'getParent', + value: function getParent() { + return new _main.default.XML(this.DOM.parentElement); + } /** + * Gets the element's full name, which is returned as a String. + * + * @method getName + * @return {String} the name of the node + * @example<animal + *
      + * // The following short XML file called "mammals.xml" is parsed + * // in the code below. + * // + * // + * // <mammals> + * // <animal id="0" species="Capra hircus">Goat</animal> + * // <animal id="1" species="Panthera pardus">Leopard</animal> + * // <animal id="2" species="Equus zebra">Zebra</animal> + * // </mammals> + * + * let xml; + * + * function preload() { + * xml = loadXML('assets/mammals.xml'); + * } + * + * function setup() { + * print(xml.getName()); + * } + * + * // Sketch prints: + * // mammals + *
      + */ + + }, + { + key: 'getName', + value: function getName() { + return this.DOM.tagName; + } /** + * Sets the element's name, which is specified as a String. + * + * @method setName + * @param {String} the new name of the node + * @example<animal + *
      + * // The following short XML file called "mammals.xml" is parsed + * // in the code below. + * // + * // + * // <mammals> + * // <animal id="0" species="Capra hircus">Goat</animal> + * // <animal id="1" species="Panthera pardus">Leopard</animal> + * // <animal id="2" species="Equus zebra">Zebra</animal> + * // </mammals> + * + * let xml; + * + * function preload() { + * xml = loadXML('assets/mammals.xml'); + * } + * + * function setup() { + * print(xml.getName()); + * xml.setName('fish'); + * print(xml.getName()); + * } + * + * // Sketch prints: + * // mammals + * // fish + *
      + */ + + }, + { + key: 'setName', + value: function setName(name) { + var content = this.DOM.innerHTML; + var attributes = this.DOM.attributes; + var xmlDoc = document.implementation.createDocument(null, 'default'); + var newDOM = xmlDoc.createElement(name); + newDOM.innerHTML = content; + for (var i = 0; i < attributes.length; i++) { + newDOM.setAttribute(attributes[i].nodeName, attributes.nodeValue); + } + this.DOM = newDOM; + } /** + * Checks whether or not the element has any children, and returns the result + * as a boolean. + * + * @method hasChildren + * @return {boolean} + * @example<animal + *
      + * // The following short XML file called "mammals.xml" is parsed + * // in the code below. + * // + * // + * // <mammals> + * // <animal id="0" species="Capra hircus">Goat</animal> + * // <animal id="1" species="Panthera pardus">Leopard</animal> + * // <animal id="2" species="Equus zebra">Zebra</animal> + * // </mammals> + * + * let xml; + * + * function preload() { + * xml = loadXML('assets/mammals.xml'); + * } + * + * function setup() { + * print(xml.hasChildren()); + * } + * + * // Sketch prints: + * // true + *
      + */ + + }, + { + key: 'hasChildren', + value: function hasChildren() { + return this.DOM.children.length > 0; + } /** + * Get the names of all of the element's children, and returns the names as an + * array of Strings. This is the same as looping through and calling getName() + * on each child element individually. + * + * @method listChildren + * @return {String[]} names of the children of the element + * @example<animal + *
      + * // The following short XML file called "mammals.xml" is parsed + * // in the code below. + * // + * // + * // <mammals> + * // <animal id="0" species="Capra hircus">Goat</animal> + * // <animal id="1" species="Panthera pardus">Leopard</animal> + * // <animal id="2" species="Equus zebra">Zebra</animal> + * // </mammals> + * + * let xml; + * + * function preload() { + * xml = loadXML('assets/mammals.xml'); + * } + * + * function setup() { + * print(xml.listChildren()); + * } + * + * // Sketch prints: + * // ["animal", "animal", "animal"] + *
      + */ + + }, + { + key: 'listChildren', + value: function listChildren() { + var arr = [ + ]; + for (var i = 0; i < this.DOM.childNodes.length; i++) { + arr.push(this.DOM.childNodes[i].nodeName); + } + return arr; + } /** + * Returns all of the element's children as an array of p5.XML objects. When + * the name parameter is specified, then it will return all children that match + * that name. + * + * @method getChildren + * @param {String} [name] element name + * @return {p5.XML[]} children of the element + * @example<animal + *
      + * // The following short XML file called "mammals.xml" is parsed + * // in the code below. + * // + * // + * // <mammals> + * // <animal id="0" species="Capra hircus">Goat</animal> + * // <animal id="1" species="Panthera pardus">Leopard</animal> + * // <animal id="2" species="Equus zebra">Zebra</animal> + * // </mammals> + * + * let xml; + * + * function preload() { + * xml = loadXML('assets/mammals.xml'); + * } + * + * function setup() { + * let animals = xml.getChildren('animal'); + * + * for (let i = 0; i < animals.length; i++) { + * print(animals[i].getContent()); + * } + * } + * + * // Sketch prints: + * // "Goat" + * // "Leopard" + * // "Zebra" + *
      + */ + + }, + { + key: 'getChildren', + value: function getChildren(param) { + if (param) { + return elementsToP5XML(this.DOM.getElementsByTagName(param)); + } else { + return elementsToP5XML(this.DOM.children); + } + } /** + * Returns the first of the element's children that matches the name parameter + * or the child of the given index.It returns undefined if no matching + * child is found. + * + * @method getChild + * @param {String|Integer} name element name or index + * @return {p5.XML} + * @example<animal + *
      + * // The following short XML file called "mammals.xml" is parsed + * // in the code below. + * // + * // + * // <mammals> + * // <animal id="0" species="Capra hircus">Goat</animal> + * // <animal id="1" species="Panthera pardus">Leopard</animal> + * // <animal id="2" species="Equus zebra">Zebra</animal> + * // </mammals> + * + * let xml; + * + * function preload() { + * xml = loadXML('assets/mammals.xml'); + * } + * + * function setup() { + * let firstChild = xml.getChild('animal'); + * print(firstChild.getContent()); + * } + * + * // Sketch prints: + * // "Goat" + *
      + *
      + * let xml; + * + * function preload() { + * xml = loadXML('assets/mammals.xml'); + * } + * + * function setup() { + * let secondChild = xml.getChild(1); + * print(secondChild.getContent()); + * } + * + * // Sketch prints: + * // "Leopard" + *
      + */ + + }, + { + key: 'getChild', + value: function getChild(param) { + if (typeof param === 'string') { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = this.DOM.children[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var child = _step.value; + if (child.tagName === param) return new _main.default.XML(child); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } else { + return new _main.default.XML(this.DOM.children[param]); + } + } /** + * Appends a new child to the element. The child can be specified with + * either a String, which will be used as the new tag's name, or as a + * reference to an existing p5.XML object. + * A reference to the newly created child is returned as an p5.XML object. + * + * @method addChild + * @param {p5.XML} node a p5.XML Object which will be the child to be added + * @example + *
      + * // The following short XML file called "mammals.xml" is parsed + * // in the code below. + * // + * // + * // <mammals> + * // <animal id="0" species="Capra hircus">Goat</animal> + * // <animal id="1" species="Panthera pardus">Leopard</animal> + * // <animal id="2" species="Equus zebra">Zebra</animal> + * // </mammals> + * + * let xml; + * + * function preload() { + * xml = loadXML('assets/mammals.xml'); + * } + * + * function setup() { + * let child = new p5.XML(); + * child.setName('animal'); + * child.setAttribute('id', '3'); + * child.setAttribute('species', 'Ornithorhynchus anatinus'); + * child.setContent('Platypus'); + * xml.addChild(child); + * + * let animals = xml.getChildren('animal'); + * print(animals[animals.length - 1].getContent()); + * } + * + * // Sketch prints: + * // "Goat" + * // "Leopard" + * // "Zebra" + *
      + */ + + }, + { + key: 'addChild', + value: function addChild(node) { + if (node instanceof _main.default.XML) { + this.DOM.appendChild(node.DOM); + } else { + // PEND + } + } /** + * Removes the element specified by name or index. + * + * @method removeChild + * @param {String|Integer} name element name or index + * @example + *
      + * // The following short XML file called "mammals.xml" is parsed + * // in the code below. + * // + * // + * // <mammals> + * // <animal id="0" species="Capra hircus">Goat</animal> + * // <animal id="1" species="Panthera pardus">Leopard</animal> + * // <animal id="2" species="Equus zebra">Zebra</animal> + * // </mammals> + * + * let xml; + * + * function preload() { + * xml = loadXML('assets/mammals.xml'); + * } + * + * function setup() { + * xml.removeChild('animal'); + * let children = xml.getChildren(); + * for (let i = 0; i < children.length; i++) { + * print(children[i].getContent()); + * } + * } + * + * // Sketch prints: + * // "Leopard" + * // "Zebra" + *
      + *
      + * let xml; + * + * function preload() { + * xml = loadXML('assets/mammals.xml'); + * } + * + * function setup() { + * xml.removeChild(1); + * let children = xml.getChildren(); + * for (let i = 0; i < children.length; i++) { + * print(children[i].getContent()); + * } + * } + * + * // Sketch prints: + * // "Goat" + * // "Zebra" + *
      + */ + + }, + { + key: 'removeChild', + value: function removeChild(param) { + var ind = - 1; + if (typeof param === 'string') { + for (var i = 0; i < this.DOM.children.length; i++) { + if (this.DOM.children[i].tagName === param) { + ind = i; + break; + } + } + } else { + ind = param; + } + if (ind !== - 1) { + this.DOM.removeChild(this.DOM.children[ind]); + } + } /** + * Counts the specified element's number of attributes, returned as an Number. + * + * @method getAttributeCount + * @return {Integer} + * @example + *
      + * // The following short XML file called "mammals.xml" is parsed + * // in the code below. + * // + * // + * // <mammals> + * // <animal id="0" species="Capra hircus">Goat</animal> + * // <animal id="1" species="Panthera pardus">Leopard</animal> + * // <animal id="2" species="Equus zebra">Zebra</animal> + * // </mammals> + * + * let xml; + * + * function preload() { + * xml = loadXML('assets/mammals.xml'); + * } + * + * function setup() { + * let firstChild = xml.getChild('animal'); + * print(firstChild.getAttributeCount()); + * } + * + * // Sketch prints: + * // 2 + *
      + */ + + }, + { + key: 'getAttributeCount', + value: function getAttributeCount() { + return this.DOM.attributes.length; + } /** + * Gets all of the specified element's attributes, and returns them as an + * array of Strings. + * + * @method listAttributes + * @return {String[]} an array of strings containing the names of attributes + * @example + *
      + * // The following short XML file called "mammals.xml" is parsed + * // in the code below. + * // + * // + * // <mammals> + * // <animal id="0" species="Capra hircus">Goat</animal> + * // <animal id="1" species="Panthera pardus">Leopard</animal> + * // <animal id="2" species="Equus zebra">Zebra</animal> + * // </mammals> + * + * let xml; + * + * function preload() { + * xml = loadXML('assets/mammals.xml'); + * } + * + * function setup() { + * let firstChild = xml.getChild('animal'); + * print(firstChild.listAttributes()); + * } + * + * // Sketch prints: + * // ["id", "species"] + *
      + */ + + }, + { + key: 'listAttributes', + value: function listAttributes() { + var arr = [ + ]; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + try { + for (var _iterator2 = this.DOM.attributes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var attribute = _step2.value; + arr.push(attribute.nodeName); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + return arr; + } /** + * Checks whether or not an element has the specified attribute. + * + * @method hasAttribute + * @param {String} the attribute to be checked + * @return {boolean} true if attribute found else false + * @example + *
      + * // The following short XML file called "mammals.xml" is parsed + * // in the code below. + * // + * // + * // <mammals> + * // <animal id="0" species="Capra hircus">Goat</animal> + * // <animal id="1" species="Panthera pardus">Leopard</animal> + * // <animal id="2" species="Equus zebra">Zebra</animal> + * // </mammals> + * + * let xml; + * + * function preload() { + * xml = loadXML('assets/mammals.xml'); + * } + * + * function setup() { + * let firstChild = xml.getChild('animal'); + * print(firstChild.hasAttribute('species')); + * print(firstChild.hasAttribute('color')); + * } + * + * // Sketch prints: + * // true + * // false + *
      + */ + + }, + { + key: 'hasAttribute', + value: function hasAttribute(name) { + var obj = { + }; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + try { + for (var _iterator3 = this.DOM.attributes[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var attribute = _step3.value; + obj[attribute.nodeName] = attribute.nodeValue; + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + return obj[name] ? true : false; + } /** + * Returns an attribute value of the element as an Number. If the defaultValue + * parameter is specified and the attribute doesn't exist, then defaultValue + * is returned. If no defaultValue is specified and the attribute doesn't + * exist, the value 0 is returned. + * + * @method getNum + * @param {String} name the non-null full name of the attribute + * @param {Number} [defaultValue] the default value of the attribute + * @return {Number} + * @example + *
      + * // The following short XML file called "mammals.xml" is parsed + * // in the code below. + * // + * // + * // <mammals> + * // <animal id="0" species="Capra hircus">Goat</animal> + * // <animal id="1" species="Panthera pardus">Leopard</animal> + * // <animal id="2" species="Equus zebra">Zebra</animal> + * // </mammals> + * + * let xml; + * + * function preload() { + * xml = loadXML('assets/mammals.xml'); + * } + * + * function setup() { + * let firstChild = xml.getChild('animal'); + * print(firstChild.getNum('id')); + * } + * + * // Sketch prints: + * // 0 + *
      + */ + + }, + { + key: 'getNum', + value: function getNum(name, defaultValue) { + var obj = { + }; + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + try { + for (var _iterator4 = this.DOM.attributes[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var attribute = _step4.value; + obj[attribute.nodeName] = attribute.nodeValue; + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + return Number(obj[name]) || defaultValue || 0; + } /** + * Returns an attribute value of the element as an String. If the defaultValue + * parameter is specified and the attribute doesn't exist, then defaultValue + * is returned. If no defaultValue is specified and the attribute doesn't + * exist, null is returned. + * + * @method getString + * @param {String} name the non-null full name of the attribute + * @param {Number} [defaultValue] the default value of the attribute + * @return {String} + * @example + *
      + * // The following short XML file called "mammals.xml" is parsed + * // in the code below. + * // + * // + * // <mammals> + * // <animal id="0" species="Capra hircus">Goat</animal> + * // <animal id="1" species="Panthera pardus">Leopard</animal> + * // <animal id="2" species="Equus zebra">Zebra</animal> + * // </mammals> + * + * let xml; + * + * function preload() { + * xml = loadXML('assets/mammals.xml'); + * } + * + * function setup() { + * let firstChild = xml.getChild('animal'); + * print(firstChild.getString('species')); + * } + * + * // Sketch prints: + * // "Capra hircus" + *
      + */ + + }, + { + key: 'getString', + value: function getString(name, defaultValue) { + var obj = { + }; + var _iteratorNormalCompletion5 = true; + var _didIteratorError5 = false; + var _iteratorError5 = undefined; + try { + for (var _iterator5 = this.DOM.attributes[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { + var attribute = _step5.value; + obj[attribute.nodeName] = attribute.nodeValue; + } + } catch (err) { + _didIteratorError5 = true; + _iteratorError5 = err; + } finally { + try { + if (!_iteratorNormalCompletion5 && _iterator5.return != null) { + _iterator5.return(); + } + } finally { + if (_didIteratorError5) { + throw _iteratorError5; + } + } + } + return obj[name] ? String(obj[name]) : defaultValue || null; + } /** + * Sets the content of an element's attribute. The first parameter specifies + * the attribute name, while the second specifies the new content. + * + * @method setAttribute + * @param {String} name the full name of the attribute + * @param {Number|String|Boolean} value the value of the attribute + * @example + *
      + * // The following short XML file called "mammals.xml" is parsed + * // in the code below. + * // + * // + * // <mammals> + * // <animal id="0" species="Capra hircus">Goat</animal> + * // <animal id="1" species="Panthera pardus">Leopard</animal> + * // <animal id="2" species="Equus zebra">Zebra</animal> + * // </mammals> + * + * let xml; + * + * function preload() { + * xml = loadXML('assets/mammals.xml'); + * } + * + * function setup() { + * let firstChild = xml.getChild('animal'); + * print(firstChild.getString('species')); + * firstChild.setAttribute('species', 'Jamides zebra'); + * print(firstChild.getString('species')); + * } + * + * // Sketch prints: + * // "Capra hircus" + * // "Jamides zebra" + *
      + */ + + }, + { + key: 'setAttribute', + value: function setAttribute(name, value) { + this.DOM.setAttribute(name, value); + } /** + * Returns the content of an element. If there is no such content, + * defaultValue is returned if specified, otherwise null is returned. + * + * @method getContent + * @param {String} [defaultValue] value returned if no content is found + * @return {String} + * @example + *
      + * // The following short XML file called "mammals.xml" is parsed + * // in the code below. + * // + * // + * // <mammals> + * // <animal id="0" species="Capra hircus">Goat</animal> + * // <animal id="1" species="Panthera pardus">Leopard</animal> + * // <animal id="2" species="Equus zebra">Zebra</animal> + * // </mammals> + * + * let xml; + * + * function preload() { + * xml = loadXML('assets/mammals.xml'); + * } + * + * function setup() { + * let firstChild = xml.getChild('animal'); + * print(firstChild.getContent()); + * } + * + * // Sketch prints: + * // "Goat" + *
      + */ + + }, + { + key: 'getContent', + value: function getContent(defaultValue) { + var str; + str = this.DOM.textContent; + str = str.replace(/\s\s+/g, ','); + return str || defaultValue || null; + } /** + * Sets the element's content. + * + * @method setContent + * @param {String} text the new content + * @example + *
      + * // The following short XML file called "mammals.xml" is parsed + * // in the code below. + * // + * // + * // <mammals> + * // <animal id="0" species="Capra hircus">Goat</animal> + * // <animal id="1" species="Panthera pardus">Leopard</animal> + * // <animal id="2" species="Equus zebra">Zebra</animal> + * // </mammals> + * + * let xml; + * + * function preload() { + * xml = loadXML('assets/mammals.xml'); + * } + * + * function setup() { + * let firstChild = xml.getChild('animal'); + * print(firstChild.getContent()); + * firstChild.setContent('Mountain Goat'); + * print(firstChild.getContent()); + * } + * + * // Sketch prints: + * // "Goat" + * // "Mountain Goat" + *
      + */ + + }, + { + key: 'setContent', + value: function setContent(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 + *
      + * let xml; + * + * function preload() { + * xml = loadXML('assets/mammals.xml'); + * } + * + * function setup() { + * print(xml.serialize()); + * } + * + * // Sketch prints: + * // + * // Goat + * // Leopard + * // Zebra + * // + *
      + */ + + }, + { + key: 'serialize', + value: function serialize() { + var xmlSerializer = new XMLSerializer(); + return xmlSerializer.serializeToString(this.DOM); + } + } + ]); + return _class; + }(); + function elementsToP5XML(elements) { + var arr = [ + ]; + for (var i = 0; i < elements.length; i++) { + arr.push(new _main.default.XML(elements[i])); + } + return arr; + } + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 298, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.number.constructor': 191, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.string.replace': 214, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/web.dom-collections.iterator': 256 + } + ], + 328: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.math.hypot'); + _dereq_('core-js/modules/es.number.constructor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.math.hypot'); + _dereq_('core-js/modules/es.number.constructor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Math + * @submodule Calculation + * @for p5 + * @requires core */ - _main.default.Table.prototype.getRow = function (r) { - return this.rows[r]; - }; /** - * Gets all rows from the table. Returns an array of p5.TableRows. - * - * @method getRows - * @return {p5.TableRow[]} Array of p5.TableRows + * Calculates the absolute value of a number. A number's absolute value is its + * distance from zero on the number line. -5 and 5 are both five units away + * from zero, so calling `abs(-5)` and `abs(5)` both return 5. The absolute + * value of a number is always positive. * + * @method abs + * @param {Number} n number to compute. + * @return {Number} absolute value of given number. * @example - *
      + *
      * - * // 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'); - * } + * function draw() { + * // Invert the y-axis. + * scale(1, -1); + * translate(0, -height); * - * //print the results - * for (let r = 0; r < table.getRowCount(); r++) - * for (let c = 0; c < table.getColumnCount(); c++) - * print(table.getString(r, c)); + * let centerX = width / 2; + * let x = frameCount; + * let y = abs(x - centerX); + * point(x, y); * - * describe('no image displayed'); + * describe('A series of black dots that form a "V" shape.'); * } * *
      */ - _main.default.Table.prototype.getRows = function () { - return this.rows; - }; + + _main.default.prototype.abs = Math.abs; /** - * 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} + * Calculates the closest integer value that is greater than or equal to the + * parameter's value. For example, calling `ceil(9.03)` returns the value + * 10. * + * @method ceil + * @param {Number} n number to round up. + * @return {Integer} rounded up number. * @example - *
      + *
      * - * // Given the CSV file "mammals.csv" - * // in the project's "assets" folder: - * // - * // id,species,name - * // 0,Capra hircus,Goat - * // 1,Panthera pardus,Leopard - * // 2,Equus zebra,Zebra + * // Set the range for RGB values from 0 to 1. + * colorMode(RGB, 1); + * noStroke(); * - * let table; + * let r = 0.3; + * fill(r, 0, 0); + * rect(0, 0, width / 2, height); * - * function preload() { - * //my table is comma separated value "csv" - * //and has a header specifying the columns labels - * table = loadTable('assets/mammals.csv', 'csv', 'header'); - * } + * // Round r up to 1. + * r = ceil(r); + * fill(r, 0, 0); + * rect(width / 2, 0, width / 2, height); * - * function setup() { - * //find the animal named zebra - * let row = table.findRow('Zebra', 'name'); - * //find the corresponding species - * print(row.getString('species')); - * describe('no image displayed'); - * } + * describe('Two rectangles. The one on the left is dark red and the one on the right is bright red.'); * *
      */ - _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; - }; + _main.default.prototype.ceil = Math.ceil; /** - * 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 + * Constrains a number between a minimum and maximum value. * + * @method constrain + * @param {Number} n number to constrain. + * @param {Number} low minimum limit. + * @param {Number} high maximum limit. + * @return {Number} constrained number. * @example - *
      + *
      * - * // 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 draw() { + * background(200); * - * function preload() { - * //my table is comma separated value "csv" - * //and has a header specifying the columns labels - * table = loadTable('assets/mammals.csv', 'csv', 'header'); - * } + * let x = constrain(mouseX, 33, 67); + * let y = 50; * - * function setup() { - * //add another goat - * let newRow = table.addRow(); - * newRow.setString('id', table.getRowCount() - 1); - * newRow.setString('species', 'Scape Goat'); - * newRow.setString('name', 'Goat'); + * strokeWeight(5); + * point(x, y); * - * //find the rows containing animals named Goat - * let rows = table.findRows('Goat', 'name'); - * print(rows.length + ' Goats found'); - * describe('no image displayed'); + * describe('A black dot drawn on a gray square follows the mouse from left to right. Its movement is constrained to the middle third of the square.'); * } * *
      - */ - _main.default.Table.prototype.findRows = function (value, column) { - var ret = [ - ]; - if (typeof column === 'string') { - for (var i = 0; i < this.rows.length; i++) { - if (this.rows[i].obj[column] === value) { - ret.push(this.rows[i]); - } - } - } else { - // try the Array - for (var j = 0; j < this.rows.length; j++) { - if (this.rows[j].arr[column] === value) { - ret.push(this.rows[j]); - } - } - } - return ret; - }; - /** - * Finds the first row in the Table that matches the regular - * expression provided, and returns a reference to that row. - * Even if multiple rows are possible matches, only the first - * matching row is returned. The column to search may be - * specified by either its ID or title. - * - * @method matchRow - * @param {String|RegExp} regexp The regular expression to match - * @param {String|Integer} column The column ID (number) or - * title (string) - * @return {p5.TableRow} TableRow object * - * @example - *
      + *
      * - * // Given the CSV file "mammals.csv" - * // in the project's "assets" folder: - * // - * // id,species,name - * // 0,Capra hircus,Goat - * // 1,Panthera pardus,Leopard - * // 2,Equus zebra,Zebra + * function draw() { + * background(200); * - * let table; + * // Set boundaries and draw them. + * let leftWall = width * 0.25; + * let rightWall = width * 0.75; + * line(leftWall, 0, leftWall, height); + * line(rightWall, 0, rightWall, height); * - * function preload() { - * //my table is comma separated value "csv" - * //and has a header specifying the columns labels - * table = loadTable('assets/mammals.csv', 'csv', 'header'); - * } + * // Draw a circle that follows the mouse freely. + * fill(255); + * circle(mouseX, height / 3, 9); * - * 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" + * // Draw a circle that's constrained. + * let xc = constrain(mouseX, leftWall, rightWall); + * fill(0); + * circle(xc, 2 * height / 3, 9); + * + * describe('Two vertical lines. Two circles move horizontally with the mouse. One circle stops at the vertical lines.'); * } * *
      */ - _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; + _main.default.prototype.constrain = function (n, low, high) { + _main.default._validateParameters('constrain', arguments); + return Math.max(Math.min(n, high), low); }; /** - * 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. + * Calculates the distance between two points. * - * @method matchRows - * @param {String} regexp The regular expression to match - * @param {String|Integer} [column] The column ID (number) or - * title (string) - * @return {p5.TableRow[]} An Array of TableRow objects - * @example - *
      - * - * let table; + * The version of `dist()` with four parameters calculates distance in two + * dimensions. * - * function setup() { - * table = new p5.Table(); + * The version of `dist()` with six parameters calculates distance in three + * dimensions. * - * table.addColumn('name'); - * table.addColumn('type'); + * Use p5.Vector.dist() to calculate the + * distance between two p5.Vector objects. * - * let newRow = table.addRow(); - * newRow.setString('name', 'Lion'); - * newRow.setString('type', 'Mammal'); + * @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. * - * newRow = table.addRow(); - * newRow.setString('name', 'Snake'); - * newRow.setString('type', 'Reptile'); + * @example + *
      + * + * let x1 = 10; + * let y1 = 50; + * let x2 = 90; + * let y2 = 50; * - * newRow = table.addRow(); - * newRow.setString('name', 'Mosquito'); - * newRow.setString('type', 'Insect'); + * line(x1, y1, x2, y2); + * strokeWeight(5); + * point(x1, y1); + * point(x2, y2); * - * newRow = table.addRow(); - * newRow.setString('name', 'Lizard'); - * newRow.setString('type', 'Reptile'); + * let d = dist(x1, y1, x2, y2); + * text(d, 43, 40); * - * 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 + * describe('Two dots connected by a horizontal line. The number 80 is written above the center of the line.'); * *
      */ - _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]); - } - } + /** + * @method dist + * @param {Number} x1 + * @param {Number} y1 + * @param {Number} z1 z-coordinate of the first point. + * @param {Number} x2 + * @param {Number} y2 + * @param {Number} z2 z-coordinate of the second point. + * @return {Number} distance between the two points. + */ + _main.default.prototype.dist = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _main.default._validateParameters('dist', args); + if (args.length === 4) { + //2D + return Math.hypot(args[2] - args[0], args[3] - args[1]); + } else if (args.length === 6) { + //3D + return Math.hypot(args[3] - args[0], args[4] - args[1], args[5] - args[2]); } - 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 + * Returns Euler's number e (2.71828...) raised to the power of the `n` + * parameter. * + * @method exp + * @param {Number} n exponent to raise. + * @return {Number} e^n * @example - *
      + *
      * - * // Given the CSV file "mammals.csv" - * // in the project's "assets" folder: - * // - * // id,species,name - * // 0,Capra hircus,Goat - * // 1,Panthera pardus,Leopard - * // 2,Equus zebra,Zebra - * - * let table; + * function draw() { + * // Invert the y-axis. + * scale(1, -1); + * translate(0, -height); * - * function preload() { - * //my table is comma separated value "csv" - * //and has a header specifying the columns labels - * table = loadTable('assets/mammals.csv', 'csv', 'header'); - * } + * let x = frameCount; + * let y = 0.005 * exp(x * 0.1); + * point(x, y); * - * function setup() { - * //getColumn returns an array that can be printed directly - * print(table.getColumn('species')); - * //outputs ["Capra hircus", "Panthera pardus", "Equus zebra"] - * describe('no image displayed'); + * describe('A series of black dots that grow exponentially from left to right.'); * } * *
      */ - _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; - }; + _main.default.prototype.exp = Math.exp; /** - * Removes all rows from a Table. While all rows are removed, - * columns and column titles are maintained. - * - * @method clearRows + * Calculates the closest integer value that is less than or equal to the + * value of the `n` parameter. * + * @method floor + * @param {Number} n number to round down. + * @return {Integer} rounded down number. * @example - *
      + *
      * - * // Given the CSV file "mammals.csv" - * // in the project's "assets" folder: - * // - * // id,species,name - * // 0,Capra hircus,Goat - * // 1,Panthera pardus,Leopard - * // 2,Equus zebra,Zebra + * // Set the range for RGB values from 0 to 1. + * colorMode(RGB, 1); + * noStroke(); * - * let table; + * let r = 0.8; + * fill(r, 0, 0); + * rect(0, 0, width / 2, height); * - * function preload() { - * //my table is comma separated value "csv" - * //and has a header specifying the columns labels - * table = loadTable('assets/mammals.csv', 'csv', 'header'); - * } + * // Round r down to 0. + * r = floor(r); + * fill(r, 0, 0); + * rect(width / 2, 0, width / 2, height); * - * function setup() { - * table.clearRows(); - * print(table.getRowCount() + ' total rows in table'); - * print(table.getColumnCount() + ' total columns in table'); - * describe('no image displayed'); - * } + * describe('Two rectangles. The one on the left is bright red and the one on the right is black.'); * *
      */ - _main.default.Table.prototype.clearRows = function () { - delete this.rows; - this.rows = [ - ]; - }; + _main.default.prototype.floor = Math.floor; /** - * Use addColumn() to add a new column to a Table object. - * Typically, you will want to specify a title, so the column - * may be easily referenced later by name. (If no title is - * specified, the new column's title will be null.) + * Calculates a number between two numbers at a specific increment. The `amt` + * parameter is the amount to interpolate between the two numbers. 0.0 is + * equal to the first number, 0.1 is very near the first number, 0.5 is + * half-way in between, and 1.0 is equal to the second number. The `lerp()` + * function is convenient for creating motion along a straight path and for + * drawing dotted lines. * - * @method addColumn - * @param {String} [title] title of the given column + * If the value of `amt` is less than 0 or more than 1, `lerp()` will return a + * number outside of the original interval. For example, calling + * `lerp(0, 10, 1.5)` will return 15. * + * @method lerp + * @param {Number} start first value. + * @param {Number} stop second value. + * @param {Number} amt number. + * @return {Number} lerped value. * @example - *
      + *
      * - * // 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 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 table; + * let y = 50; * - * function preload() { - * //my table is comma separated value "csv" - * //and has a header specifying the columns labels - * table = loadTable('assets/mammals.csv', 'csv', 'header'); - * } + * strokeWeight(5); * - * function setup() { - * table.addColumn('carnivore'); - * table.set(0, 'carnivore', 'no'); - * table.set(1, 'carnivore', 'yes'); - * table.set(2, 'carnivore', 'no'); + * // Draw the original points in black. + * stroke(0); + * point(a, y); + * point(b, y); * - * //print the results - * for (let r = 0; r < table.getRowCount(); r++) - * for (let c = 0; c < table.getColumnCount(); c++) - * print(table.getString(r, c)); + * // Draw the lerped points in gray. + * stroke(100); + * point(c, y); + * point(d, y); + * point(e, y); * - * describe('no image displayed'); - * } + * describe('Five points in a horizontal line. The outer points are black and the inner points are gray.'); * *
      */ - _main.default.Table.prototype.addColumn = function (title) { - var t = title || null; - this.columns.push(t); + _main.default.prototype.lerp = function (start, stop, amt) { + _main.default._validateParameters('lerp', arguments); + return amt * (stop - start) + start; }; /** - * Returns the total number of columns in a Table. + * 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. * - * @method getColumnCount - * @return {Integer} Number of columns in this table + * @method log + * @param {Number} n number greater than 0. + * @return {Number} natural logarithm of n. * @example *
      * - * // given the cvs file "blobs.csv" in /assets directory - * // ID, Name, Flavor, Shape, Color - * // Blob1, Blobby, Sweet, Blob, Pink - * // Blob2, Saddy, Savory, Blob, Blue - * - * let table; - * - * function preload() { - * table = loadTable('assets/blobs.csv'); - * } + * function draw() { + * // Invert the y-axis. + * scale(1, -1); + * translate(0, -height); * - * function setup() { - * createCanvas(200, 100); - * textAlign(CENTER); - * background(255); - * } + * let x = frameCount; + * let y = 15 * log(x); + * point(x, y); * - * function draw() { - * let numOfColumn = table.getColumnCount(); - * text('There are ' + numOfColumn + ' columns in the table.', 100, 50); + * describe('A series of black dots that get higher slowly from left to right.'); * } * *
      */ - _main.default.Table.prototype.getColumnCount = function () { - return this.columns.length; - }; + _main.default.prototype.log = Math.log; /** - * Returns the total number of rows in a Table. + * Calculates the magnitude, or length, of a vector. A vector is like an arrow + * pointing in space. Vectors are commonly used for programming motion. * - * @method getRowCount - * @return {Integer} Number of rows in this table + * Vectors don't have a "start" position because the same arrow can be drawn + * anywhere. A vector's magnitude can be thought of as the distance from the + * origin (0, 0) to its tip at (x, y). `mag(x, y)` is a shortcut for calling + * `dist(0, 0, x, y)`. + * + * @method mag + * @param {Number} x first component. + * @param {Number} y second component. + * @return {Number} magnitude of vector from (0,0) to (x,y). * @example *
      * - * // given the cvs file "blobs.csv" in /assets directory - * // - * // ID, Name, Flavor, Shape, Color - * // Blob1, Blobby, Sweet, Blob, Pink - * // Blob2, Saddy, Savory, Blob, Blue - * - * let table; - * - * function preload() { - * table = loadTable('assets/blobs.csv'); - * } + * let x = 30; + * let y = 40; + * let m = mag(x, y); * - * function setup() { - * createCanvas(200, 100); - * textAlign(CENTER); - * background(255); - * } + * line(0, 0, x, y); + * text(m, x, y); * - * function draw() { - * text('There are ' + table.getRowCount() + ' rows in the table.', 100, 50); - * } + * describe('A diagonal line is drawn from the top left of the canvas. The number 50 is written at the end of the line.'); * *
      */ - _main.default.Table.prototype.getRowCount = function () { - return this.rows.length; + _main.default.prototype.mag = function (x, y) { + _main.default._validateParameters('mag', arguments); + return Math.hypot(x, y); }; /** - * 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. + * Re-maps a number from one range to another. * - * @method removeTokens - * @param {String} chars String listing characters to be removed - * @param {String|Integer} [column] Column ID (number) - * or name (string) + * For example, calling `map(2, 0, 10, 0, 100)` returns 20. The first three + * arguments set the original value to 2 and the original range from 0 to 10. + * The last two arguments set the target range from 0 to 100. 20's position + * in the target range [0, 100] is proportional to 2's position in the + * original range [0, 10]. * + * @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 - *
      - * function setup() { - * let table = new p5.Table(); + *
      + * + * let n = map(7, 0, 10, 0, 100); + * text(n, 50, 50); * - * table.addColumn('name'); - * table.addColumn('type'); + * describe('The number 70 written in the middle of a gray square.'); + * + *
      * - * let newRow = table.addRow(); - * newRow.setString('name', ' $Lion ,'); - * newRow.setString('type', ',,,Mammal'); + *
      + * + * let x = map(2, 0, 10, 0, width); + * circle(x, 50, 10); * - * newRow = table.addRow(); - * newRow.setString('name', '$Snake '); - * newRow.setString('type', ',,,Reptile'); + * describe('A white circle drawn on the left side of a gray square.'); + * + *
      * - * table.removeTokens(',$ '); - * print(table.getArray()); - * } + *
      + * + * function draw() { + * background(200); * - * // prints: - * // 0 "Lion" "Mamal" - * // 1 "Snake" "Reptile" - *
      + * let c = map(mouseX, 0, width, 0, 255); + * fill(c); + * circle(50, 50, 20); + * + * describe('A circle changes color from black to white as the mouse moves from left to right.'); + * } + *
      + *
      */ - _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; - } + _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 { - 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; - } + return this.constrain(newval, stop2, start2); } }; /** - * Trims leading and trailing whitespace, such as spaces and tabs, - * from String table values. If no column is specified, then the - * values in all columns and rows are trimmed. A specific column - * may be referenced by either its ID or title. - * - * @method trim - * @param {String|Integer} [column] Column ID (number) - * or name (string) - * @example - *
      - * function setup() { - * let table = new p5.Table(); + * Returns the largest value in a sequence of numbers. * - * table.addColumn('name'); - * table.addColumn('type'); + * The version of `max()` with one parameter interprets it as an array of + * numbers and returns the largest number. * - * let newRow = table.addRow(); - * newRow.setString('name', ' Lion ,'); - * newRow.setString('type', ' Mammal '); + * The version of `max()` with two or more parameters interprets them as + * individual numbers and returns the largest number. * - * newRow = table.addRow(); - * newRow.setString('name', ' Snake '); - * newRow.setString('type', ' Reptile '); + * @method max + * @param {Number} n0 first number to compare. + * @param {Number} n1 second number to compare. + * @return {Number} maximum number. + * @example + *
      + * + * let m = max(10, 20); + * text(m, 50, 50); * - * table.trim(); - * print(table.getArray()); - * } + * describe('The number 20 written in the middle of a gray square.'); + * + *
      * - * // prints: - * // 0 "Lion" "Mamal" - * // 1 "Snake" "Reptile" - *
      - */ - _main.default.Table.prototype.trim = function (column) { - var regex = new RegExp(' ', 'g'); - if (typeof column === 'undefined') { - for (var c = 0; c < this.columns.length; c++) { - for (var d = 0; d < this.rows.length; d++) { - var s = this.rows[d].arr[c]; - s = s.replace(regex, ''); - this.rows[d].arr[c] = s; - this.rows[d].obj[this.columns[c]] = s; - } - } - } else if (typeof column === 'string') { - for (var j = 0; j < this.rows.length; j++) { - var val = this.rows[j].obj[column]; - val = val.replace(regex, ''); - this.rows[j].obj[column] = val; - var pos = this.columns.indexOf(column); - this.rows[j].arr[pos] = val; - } - } else { - for (var k = 0; k < this.rows.length; k++) { - var str = this.rows[k].arr[column]; - str = str.replace(regex, ''); - this.rows[k].arr[column] = str; - this.rows[k].obj[this.columns[column]] = str; - } - } - }; - /** - * Use removeColumn() to remove an existing column from a Table - * object. The column to be removed may be identified by either - * its title (a String) or its index value (an int). - * removeColumn(0) would remove the first column, removeColumn(1) - * would remove the second column, and so on. + *
      + * + * let m = max([10, 20]); + * text(m, 50, 50); * - * @method removeColumn - * @param {String|Integer} column columnName (string) or ID (number) + * describe('The number 20 written in the middle of a gray square.'); + * + *
      * - * @example - *
      + *
      * - * // Given the CSV file "mammals.csv" - * // in the project's "assets" folder: - * // - * // id,species,name - * // 0,Capra hircus,Goat - * // 1,Panthera pardus,Leopard - * // 2,Equus zebra,Zebra + * let numbers = [2, 1, 5, 4, 8, 9]; * - * let table; + * // Draw all of the numbers in the array. + * noStroke(); + * let spacing = 15; + * numbers.forEach((n, index) => { + * let x = index * spacing; + * let y = 25; + * text(n, x, y); + * }); + * + * // Draw the maximum value in the array. + * let m = max(numbers); + * let maxX = 33; + * let maxY = 80; * - * function preload() { - * //my table is comma separated value "csv" - * //and has a header specifying the columns labels - * table = loadTable('assets/mammals.csv', 'csv', 'header'); - * } + * textSize(32); + * text(m, maxX, maxY); * - * function setup() { - * table.removeColumn('id'); - * print(table.getColumnCount()); - * describe('no image displayed'); - * } + * describe('The numbers 2 1 5 4 8 9 are written in small text at the top of a gray square. The number 9 is written in large text at the center of the square.'); * *
      */ - _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]; + /** + * @method max + * @param {Number[]} nums numbers to compare. + * @return {Number} + */ + _main.default.prototype.max = function () { + var findMax = function findMax(arr) { + var max = - Infinity; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = arr[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var x = _step.value; + max = x > max ? x : max; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + return max; + }; + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; } - 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]; + if (args[0] instanceof Array) { + return findMax(args[0]); + } else { + return findMax(args); } }; /** - * 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. + * Returns the smallest value in a sequence of numbers. + * + * The version of `min()` with one parameter interprets it as an array of + * numbers and returns the smallest number. * - * @method set - * @param {Integer} row row ID - * @param {String|Integer} column column ID (Number) - * or title (String) - * @param {String|Number} value value to assign + * The version of `min()` with two or more parameters interprets them as + * individual numbers and returns the smallest number. * + * @method min + * @param {Number} n0 first number to compare. + * @param {Number} n1 second number to compare. + * @return {Number} minimum number. * @example - *
      + *
      * - * // 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'); - * } + * let m = min(10, 20); + * text(m, 50, 50); * - * function setup() { - * table.set(0, 'species', 'Canis Lupus'); - * table.set(0, 'name', 'Wolf'); - * - * //print the results - * for (let r = 0; r < table.getRowCount(); r++) - * for (let c = 0; c < table.getColumnCount(); c++) - * print(table.getString(r, c)); - * - * describe('no image displayed'); - * } + * describe('The number 10 written in the middle of a gray square.'); * *
      - */ - _main.default.Table.prototype.set = function (row, column, value) { - this.rows[row].set(column, value); - }; - /** - * Stores a Float value in the Table's specified row and column. - * The row is specified by its ID, while the column may be specified - * by either its ID or title. * - * @method setNum - * @param {Integer} row row ID - * @param {String|Integer} column column ID (Number) - * or title (String) - * @param {Number} value value to assign - * - * @example - *
      + *
      * - * // Given the CSV file "mammals.csv" - * // in the project's "assets" folder: - * // - * // id,species,name - * // 0,Capra hircus,Goat - * // 1,Panthera pardus,Leopard - * // 2,Equus zebra,Zebra + * let m = min([10, 20]); + * text(m, 50, 50); * - * let table; + * describe('The number 10 written in the middle of a gray square.'); + * + *
      * - * function preload() { - * //my table is comma separated value "csv" - * //and has a header specifying the columns labels - * table = loadTable('assets/mammals.csv', 'csv', 'header'); - * } + *
      + * + * let numbers = [2, 1, 5, 4, 8, 9]; * - * function setup() { - * table.setNum(1, 'id', 1); + * // Draw all of the numbers in the array. + * noStroke(); + * let spacing = 15; + * numbers.forEach((n, index) => { + * let x = index * spacing; + * let y = 25; + * text(n, x, y); + * }); + * + * // Draw the minimum value in the array. + * let m = min(numbers); + * let minX = 33; + * let minY = 80; * - * print(table.getColumn(0)); - * //["0", 1, "2"] + * textSize(32); + * text(m, minX, minY); * - * describe('no image displayed'); - * } + * describe('The numbers 2 1 5 4 8 9 are written in small text at the top of a gray square. The number 1 is written in large text at the center of the square.'); * *
      */ - _main.default.Table.prototype.setNum = function (row, column, value) { - this.rows[row].setNum(column, value); + /** + * @method min + * @param {Number[]} nums numbers to compare. + * @return {Number} + */ + _main.default.prototype.min = function () { + var findMin = function findMin(arr) { + var min = Infinity; + 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 x = _step2.value; + min = x < min ? x : min; + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + return min; + }; + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + if (args[0] instanceof Array) { + return findMin(args[0]); + } else { + return findMin(args); + } }; /** - * Stores a String value in the Table's specified row and column. - * The row is specified by its ID, while the column may be specified - * by either its ID or title. - * - * @method setString - * @param {Integer} row row ID - * @param {String|Integer} column column ID (Number) - * or title (String) - * @param {String} value value to assign - * @example - *
      - * // Given the CSV file "mammals.csv" in the project's "assets" folder: - * // - * // id,species,name - * // 0,Capra hircus,Goat - * // 1,Panthera pardus,Leopard - * // 2,Equus zebra,Zebra + * Maps a number from one range to a value between 0 and 1. * - * let table; + * For example, `norm(2, 0, 10)` returns 0.2. 2's position in the original + * range [0, 10] is proportional to 0.2's position in the range [0, 1]. This + * is equivalent to calling `map(2, 0, 10, 0, 1)`. * - * function preload() { - * //my table is comma separated value "csv" - * //and has a header specifying the columns labels - * table = loadTable('assets/mammals.csv', 'csv', 'header'); - * } + * Numbers outside of the original range are not constrained between 0 and 1. + * Out-of-range values are often intentional and useful. * - * function setup() { - * //add a row - * let newRow = table.addRow(); - * newRow.setString('id', table.getRowCount() - 1); - * newRow.setString('species', 'Canis Lupus'); - * newRow.setString('name', 'Wolf'); + * @method norm + * @param {Number} value incoming value to be normalized. + * @param {Number} start lower bound of the value's current range. + * @param {Number} stop upper bound of the value's current range. + * @return {Number} normalized number. + * @example + *
      + * + * function draw() { + * // Set the range for RGB values from 0 to 1. + * colorMode(RGB, 1); * - * print(table.getArray()); + * let r = norm(mouseX, 0, width); + * background(r, 0, 0); * - * describe('no image displayed'); + * describe('A square changes color from black to red as the mouse moves from left to right.'); * } - *
      + *
      + *
      */ - _main.default.Table.prototype.setString = function (row, column, value) { - this.rows[row].setString(column, value); + _main.default.prototype.norm = function (n, start, stop) { + _main.default._validateParameters('norm', arguments); + return this.map(n, start, stop, 0, 1); }; /** - * 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. + * Calculates exponential expressions such as 2^3. * - * @method get - * @param {Integer} row row ID - * @param {String|Integer} column columnName (string) or - * ID (number) - * @return {String|Number} + * For example, `pow(2, 3)` is equivalent to the expression + * 2 × 2 × 2. `pow(2, -3)` is equivalent to 1 ÷ + * (2 × 2 × 2). * + * @method pow + * @param {Number} n base of the exponential expression. + * @param {Number} e power by which to raise the base. + * @return {Number} n^e. * @example - *
      + *
      * - * // 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 base = 3; * - * let table; + * let d = pow(base, 1); + * circle(10, 10, d); * - * function preload() { - * //my table is comma separated value "csv" - * //and has a header specifying the columns labels - * table = loadTable('assets/mammals.csv', 'csv', 'header'); - * } + * d = pow(base, 2); + * circle(20, 20, d); * - * function setup() { - * print(table.get(0, 1)); - * //Capra hircus - * print(table.get(0, 'species')); - * //Capra hircus - * describe('no image displayed'); - * } + * d = pow(base, 3); + * circle(40, 40, d); + * + * d = pow(base, 4); + * circle(80, 80, d); + * + * describe('A series of circles that grow exponentially from top left to bottom right.'); * *
      */ - _main.default.Table.prototype.get = function (row, column) { - return this.rows[row].get(column); - }; + _main.default.prototype.pow = Math.pow; /** - * 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} + * Calculates the integer closest to the `n` parameter. For example, + * `round(133.8)` returns the value 134. * + * @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 - *
      + *
      * - * // 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 x = round(3.7); + * text(x, width / 2, height / 2); * - * let table; + * describe('The number 4 written in middle of canvas.'); + * + *
      * - * function preload() { - * //my table is comma separated value "csv" - * //and has a header specifying the columns labels - * table = loadTable('assets/mammals.csv', 'csv', 'header'); - * } + *
      + * + * let x = round(12.782383, 2); + * text(x, width / 2, height / 2); * - * function setup() { - * print(table.getNum(1, 0) + 100); - * //id 1 + 100 = 101 - * describe('no image displayed'); - * } + * describe('The number 12.78 written in middle of canvas.'); * *
      */ - _main.default.Table.prototype.getNum = function (row, column) { - return this.rows[row].getNum(column); + _main.default.prototype.round = function (n, decimals) { + if (!decimals) { + return Math.round(n); + } + var multiplier = Math.pow(10, decimals); + return Math.round(n * multiplier) / multiplier; }; /** - * 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. + * Squares a number, which means multiplying the number by itself. The value + * returned is always a positive number. * - * @method getString - * @param {Integer} row row ID - * @param {String|Integer} column columnName (string) or - * ID (number) - * @return {String} + * For example, `sq(3)` evaluates 3 × 3 which is 9. `sq(-3)` evaluates + * -3 × -3 which is also 9. Multiplying two negative numbers produces + * a positive number. * + * @method sq + * @param {Number} n number to square. + * @return {Number} squared number. * @example - *
      + *
      * - * // Given the CSV file "mammals.csv" - * // in the project's "assets" folder: - * // - * // id,species,name - * // 0,Capra hircus,Goat - * // 1,Panthera pardus,Leopard - * // 2,Equus zebra,Zebra - * - * let table; + * function draw() { + * // Invert the y-axis. + * scale(1, -1); + * translate(0, -height); * - * function preload() { - * // table is comma separated value "CSV" - * // and has specifiying header for column labels - * table = loadTable('assets/mammals.csv', 'csv', 'header'); - * } + * let x = frameCount; + * let y = 0.01 * sq(x); + * point(x, y); * - * function setup() { - * print(table.getString(0, 0)); // 0 - * print(table.getString(0, 1)); // Capra hircus - * print(table.getString(0, 2)); // Goat - * print(table.getString(1, 0)); // 1 - * print(table.getString(1, 1)); // Panthera pardus - * print(table.getString(1, 2)); // Leopard - * print(table.getString(2, 0)); // 2 - * print(table.getString(2, 1)); // Equus zebra - * print(table.getString(2, 2)); // Zebra - * describe('no image displayed'); + * describe('A series of black dots that get higher quickly from left to right.'); * } * *
      */ - _main.default.Table.prototype.getString = function (row, column) { - return this.rows[row].getString(column); + _main.default.prototype.sq = function (n) { + return n * n; }; /** - * 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. + * Calculates the square root of a number. A number's square root can be + * multiplied by itself to produce the original number. * - * @method getObject - * @param {String} [headerColumn] Name of the column which should be used to - * title each row object (optional) - * @return {Object} + * For example, `sqrt(9)` returns 3 because 3 × 3 = 9. `sqrt()` always + * returns a positive value. `sqrt()` doesn't work with negative arguments + * such as `sqrt(-9)`. * + * @method sqrt + * @param {Number} n non-negative number to square root. + * @return {Number} square root of number. * @example - *
      + *
      * - * // 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(); + * function draw() { + * // Invert the y-axis. + * scale(1, -1); + * translate(0, -height); * - * print(tableObject); - * //outputs an object + * let x = frameCount; + * let y = 5 * sqrt(x); + * point(x, y); * - * describe('no image displayed'); + * describe('A series of black dots that get higher slowly from left to right.'); * } * *
      */ - _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; - }; + _main.default.prototype.sqrt = Math.sqrt; /** - * Retrieves all table data and returns it as a multidimensional array. - * - * @method getArray - * @return {Array} + * Calculates the fractional part of a number. For example, + * `fract(12.34)` returns 0.34. * + * @method fract + * @param {Number} n number whose fractional part will be found. + * @returns {Number} fractional part of n. * @example - *
      + *
      * - * // 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'); - * } + * let n = 56.78; + * text(n, 20, 33); + * let f = fract(n); + * text(f, 20, 66); * - * function setup() { - * let tableArray = table.getArray(); - * for (let i = 0; i < tableArray.length; i++) { - * print(tableArray[i]); - * } - * describe('no image displayed'); - * } + * describe('The number 56.78 written above the number 0.78.'); * *
      */ - _main.default.Table.prototype.getArray = function () { - var tableArray = [ - ]; - for (var i = 0; i < this.rows.length; i++) { - tableArray.push(this.rows[i].arr); + _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; } - return tableArray; }; var _default = _main.default; exports.default = _default; }, { - '../core/main': 290, - 'core-js/modules/es.array.concat': 167, - 'core-js/modules/es.array.index-of': 175, - 'core-js/modules/es.array.join': 177, - 'core-js/modules/es.array.splice': 182, - 'core-js/modules/es.regexp.constructor': 198, - 'core-js/modules/es.regexp.exec': 199, - 'core-js/modules/es.regexp.to-string': 200, - 'core-js/modules/es.string.match': 205, - 'core-js/modules/es.string.replace': 207, - 'core-js/modules/es.string.trim': 211 + '../core/main': 298, + 'core-js/modules/es.array.includes': 177, + 'core-js/modules/es.array.index-of': 178, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.map': 182, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.math.hypot': 188, + 'core-js/modules/es.number.constructor': 191, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.string.includes': 209, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 318: [ + 329: [ function (_dereq_, module, exports) { 'use strict'; - _dereq_('core-js/modules/es.array.index-of'); - _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.regexp.exec'); - _dereq_('core-js/modules/es.regexp.to-string'); - _dereq_('core-js/modules/es.string.split'); - _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.slice'); _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.reflect.construct'); _dereq_('core-js/modules/es.regexp.to-string'); - _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.slice'); Object.defineProperty(exports, '__esModule', { value: true }); @@ -84412,1353 +93790,4608 @@ 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); + } + 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; } - for (var i = 0; i < arr.length; i++) { - var key = i; - var val = arr[i]; - obj[key] = val; + } + 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; + }; } - this.arr = arr; - this.obj = obj; - this.table = null; - }; + return _construct.apply(null, arguments); + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + return _setPrototypeOf(o, p); + } /** + * @module Math + * @submodule Vector + * @for p5 + * @requires core + */ /** - * 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 + * Creates a new p5.Vector object. A vector is like + * an arrow pointing in space. Vectors have both magnitude (length) + * and direction. Calling `createVector()` without arguments sets the new + * vector's components to 0. + * + * p5.Vector objects are often used to program + * motion because they simplify the math. For example, a moving ball has a + * position and a velocity. Position describes where the ball is in space. The + * ball's position vector extends from the origin to the ball's center. + * Velocity describes the ball's speed and the direction it's moving. If the + * ball is moving straight up, its velocity vector points straight up. Adding + * the ball's velocity vector to its position vector moves it, as in + * `pos.add(vel)`. Vector math relies on methods inside the + * p5.Vector class. * + * @method createVector + * @param {Number} [x] x component of the vector. + * @param {Number} [y] y component of the vector. + * @param {Number} [z] z component of the vector. + * @return {p5.Vector} new p5.Vector object. * @example - *
      - * // 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; + *
      + * + * let p1 = createVector(25, 25); + * let p2 = createVector(50, 50); + * let p3 = createVector(75, 75); * - * function preload() { - * //my table is comma separated value "csv" - * //and has a header specifying the columns labels - * table = loadTable('assets/mammals.csv', 'csv', 'header'); - * } + * strokeWeight(5); + * point(p1); + * point(p2); + * point(p3); * - * function setup() { - * let rows = table.getRows(); - * for (let r = 0; r < rows.length; r++) { - * rows[r].set('name', 'Unicorn'); - * } + * describe('Three black dots form a diagonal line from top left to bottom right.'); + * + *
      * - * //print the results - * print(table.getArray()); + *
      + * + * let pos; + * let vel; * - * describe('no image displayed'); + * function setup() { + * createCanvas(100, 100); + * pos = createVector(width / 2, height); + * vel = createVector(0, -1); * } - *
      - */ - _main.default.TableRow.prototype.set = function (column, value) { - // if typeof column is string, use .obj - if (typeof column === 'string') { - var cPos = this.table.columns.indexOf(column); // index of columnID - if (cPos >= 0) { - this.obj[column] = value; - this.arr[cPos] = value; - } else { - throw new Error('This table has no column named "'.concat(column, '"')); - } - } else { - // if typeof column is number, use .arr - if (column < this.table.columns.length) { - this.arr[column] = value; - var cTitle = this.table.columns[column]; - this.obj[cTitle] = value; - } else { - throw new Error('Column #'.concat(column, ' is out of the range of this table')); - } - } - }; - /** - * Stores a Float value in the TableRow's specified column. - * The column may be specified by either its ID or title. - * - * @method setNum - * @param {String|Integer} column Column ID (Number) - * or Title (String) - * @param {Number|String} value The value to be stored - * as a Float - * @example - *
      - * // Given the CSV file "mammals.csv" in the project's "assets" folder: - * // - * // id,species,name - * // 0,Capra hircus,Goat - * // 1,Panthera pardus,Leopard - * // 2,Equus zebra,Zebra * - * let table; + * function draw() { + * background(200); * - * function preload() { - * //my table is comma separated value "csv" - * //and has a header specifying the columns labels - * table = loadTable('assets/mammals.csv', 'csv', 'header'); - * } + * pos.add(vel); * - * function setup() { - * let rows = table.getRows(); - * for (let r = 0; r < rows.length; r++) { - * rows[r].setNum('id', r + 10); + * if (pos.y < 0) { + * pos.y = height; * } * - * print(table.getArray()); + * strokeWeight(5); + * point(pos); * - * describe('no image displayed'); + * describe('A black dot moves from bottom to top on a gray square. The dot reappears at the bottom when it reaches the top.'); * } - *
      + *
      + *
      */ - _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 + + _main.default.prototype.createVector = function (x, y, z) { + if (this instanceof _main.default) { + return _construct(_main.default.Vector, [ + this._fromRadians.bind(this), + this._toRadians.bind(this) + ].concat(Array.prototype.slice.call(arguments))); + } else { + return new _main.default.Vector(x, y, z); + } + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 298, + 'core-js/modules/es.array.concat': 169, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.reflect.construct': 202, + 'core-js/modules/es.regexp.to-string': 206 + } + ], + 330: [ + function (_dereq_, module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } ////////////////////////////////////////////////////////////// + // http://mrl.nyu.edu/~perlin/noise/ + // Adapting from PApplet.java + // which was adapted from toxi + // which was adapted from the german demo group farbrausch + // as used in their demo "art": http://www.farb-rausch.de/fr010src.zip + // someday we might consider using "improved noise" + // http://mrl.nyu.edu/~perlin/paper445.pdf + // See: https://github.com/shiffman/The-Nature-of-Code-Examples-p5.js/ + // blob/main/introduction/Noise1D/noise.js + /** + * @module Math + * @submodule Noise + * @for p5 + * @requires core + */ + + var PERLIN_YWRAPB = 4; + var PERLIN_YWRAP = 1 << PERLIN_YWRAPB; + var PERLIN_ZWRAPB = 8; + var PERLIN_ZWRAP = 1 << PERLIN_ZWRAPB; + var PERLIN_SIZE = 4095; + var perlin_octaves = 4; // default to medium smooth + var perlin_amp_falloff = 0.5; // 50% reduction/octave + var scaled_cosine = function scaled_cosine(i) { + return 0.5 * (1 - Math.cos(i * Math.PI)); + }; + var perlin; // will be initialized lazily by noise() or noiseSeed() + /** + * Returns random numbers that can be tuned to feel more organic. The values + * returned will always be between 0 and 1. + * + * Values returned by random() and + * randomGaussian() can change by large + * amounts between function calls. By contrast, values returned by `noise()` + * can be made "smooth". Calls to `noise()` with similar inputs will produce + * similar outputs. `noise()` is used to create textures, motion, shapes, + * terrains, and so on. Ken Perlin invented `noise()` while animating the + * original Tron film in the 1980s. + * + * `noise()` returns the same value for a given input while a sketch is + * running. It produces different results each time a sketch runs. The + * noiseSeed() function can be used to generate + * the same sequence of Perlin noise values each time a sketch runs. + * + * The character of the noise can be adjusted in two ways. The first way is to + * scale the inputs. `noise()` interprets inputs as coordinates. The sequence + * of noise values will be smoother when the input coordinates are closer. The + * second way is to use the noiseDetail() + * function. + * + * The version of `noise()` with one parameter computes noise values in one + * dimension. This dimension can be thought of as space, as in `noise(x)`, or + * time, as in `noise(t)`. + * + * The version of `noise()` with two parameters computes noise values in two + * dimensions. These dimensions can be thought of as space, as in + * `noise(x, y)`, or space and time, as in `noise(x, t)`. + * + * The version of `noise()` with three parameters computes noise values in + * three dimensions. These dimensions can be thought of as space, as in + * `noise(x, y, z)`, or space and time, as in `noise(x, y, t)`. + * + * @method noise + * @param {Number} x x-coordinate in noise space. + * @param {Number} [y] y-coordinate in noise space. + * @param {Number} [z] z-coordinate in noise space. + * @return {Number} Perlin noise value at specified coordinates. * @example - *
      - * // 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 + *
      + * + * function draw() { + * background(200); * - * let table; + * let x = 100 * noise(0.005 * frameCount); + * let y = 100 * noise(0.005 * frameCount + 10000); * - * function preload() { - * //my table is comma separated value "csv" - * //and has a header specifying the columns labels - * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * strokeWeight(5); + * point(x, y); + * + * describe('A black dot moves randomly on a gray square.'); * } + * + *
      * - * 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'); - * } + *
      + * + * function draw() { + * background(200); * - * print(table.getArray()); + * let noiseLevel = 100; + * let noiseScale = 0.005; + * // Scale input coordinate. + * let nt = noiseScale * frameCount; + * // Compute noise value. + * let x = noiseLevel * noise(nt); + * let y = noiseLevel * noise(nt + 10000); + * // Render. + * strokeWeight(5); + * point(x, y); * - * describe('no image displayed'); + * describe('A black dot moves randomly on a gray square.'); * } - *
      - */ - _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} + *
      + * + * function draw() { + * let noiseLevel = 100; + * let noiseScale = 0.02; + * // Scale input coordinate. + * let x = frameCount; + * let nx = noiseScale * x; + * // Compute noise value. + * let y = noiseLevel * noise(nx); + * // Render. + * line(x, 0, x, y); * - * @example - *
      - * // Given the CSV file "mammals.csv" in the project's "assets" folder: - * // - * // id,species,name - * // 0,Capra hircus,Goat - * // 1,Panthera pardus,Leopard - * // 2,Equus zebra,Zebra + * describe('A hilly terrain drawn in gray against a black sky.'); + * } + * + *
      * - * let table; + *
      + * + * function draw() { + * background(200); * - * function preload() { - * //my table is comma separated value "csv" - * //and has a header specifying the columns labels - * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * let noiseLevel = 100; + * let noiseScale = 0.002; + * for (let x = 0; x < width; x += 1) { + * // Scale input coordinates. + * let nx = noiseScale * x; + * let nt = noiseScale * frameCount; + * // Compute noise value. + * let y = noiseLevel * noise(nx, nt); + * // Render. + * line(x, 0, x, y); + * } + * + * describe('A calm sea drawn in gray against a black sky.'); * } + * + *
      * - * function setup() { - * let names = []; - * let rows = table.getRows(); - * for (let r = 0; r < rows.length; r++) { - * names.push(rows[r].get('name')); + *
      + * + * let noiseLevel = 255; + * let noiseScale = 0.01; + * for (let y = 0; y < height; y += 1) { + * for (let x = 0; x < width; x += 1) { + * // Scale input coordinates. + * let nx = noiseScale * x; + * let ny = noiseScale * y; + * // Compute noise value. + * let c = noiseLevel * noise(nx, ny); + * // Render. + * stroke(c); + * point(x, y); * } + * } * - * print(names); + * describe('A gray cloudy pattern.'); + * + *
      * - * describe('no image displayed'); + *
      + * + * function draw() { + * let noiseLevel = 255; + * let noiseScale = 0.009; + * for (let y = 0; y < height; y += 1) { + * for (let x = 0; x < width; x += 1) { + * // Scale input coordinates. + * let nx = noiseScale * x; + * let ny = noiseScale * y; + * let nt = noiseScale * frameCount; + * // Compute noise value. + * let c = noiseLevel * noise(nx, ny, nt); + * // Render. + * stroke(c); + * point(x, y); + * } + * } + * + * describe('A gray cloudy pattern that changes.'); * } - *
      + *
      + *
      */ - _main.default.TableRow.prototype.get = function (column) { - if (typeof column === 'string') { - return this.obj[column]; - } else { - return this.arr[column]; + _main.default.prototype.noise = function (x) { + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var z = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + if (perlin == null) { + perlin = new Array(PERLIN_SIZE + 1); + for (var i = 0; i < PERLIN_SIZE + 1; i++) { + perlin[i] = Math.random(); + } + } + if (x < 0) { + x = - x; + } + if (y < 0) { + y = - y; + } + if (z < 0) { + z = - z; + } + var xi = Math.floor(x), + yi = Math.floor(y), + zi = Math.floor(z); + var xf = x - xi; + var yf = y - yi; + var zf = z - zi; + var rxf, + ryf; + var r = 0; + var ampl = 0.5; + var n1, + n2, + n3; + for (var o = 0; o < perlin_octaves; o++) { + var of = xi + (yi << PERLIN_YWRAPB) + (zi << PERLIN_ZWRAPB); + rxf = scaled_cosine(xf); + ryf = scaled_cosine(yf); + n1 = perlin[of & PERLIN_SIZE]; + n1 += rxf * (perlin[of + 1 & PERLIN_SIZE] - n1); + n2 = perlin[of + PERLIN_YWRAP & PERLIN_SIZE]; + n2 += rxf * (perlin[of + PERLIN_YWRAP + 1 & PERLIN_SIZE] - n2); + n1 += ryf * (n2 - n1); + of += PERLIN_ZWRAP; + n2 = perlin[of & PERLIN_SIZE]; + n2 += rxf * (perlin[of + 1 & PERLIN_SIZE] - n2); + n3 = perlin[of + PERLIN_YWRAP & PERLIN_SIZE]; + n3 += rxf * (perlin[of + PERLIN_YWRAP + 1 & PERLIN_SIZE] - n3); + n2 += ryf * (n3 - n2); + n1 += scaled_cosine(zf) * (n2 - n1); + r += n1 * ampl; + ampl *= perlin_amp_falloff; + xi <<= 1; + xf *= 2; + yi <<= 1; + yf *= 2; + zi <<= 1; + zf *= 2; + if (xf >= 1) { + xi++; + xf--; + } + if (yf >= 1) { + yi++; + yf--; + } + if (zf >= 1) { + zi++; + zf--; + } } + return r; }; /** - * Retrieves a Float value from the TableRow's specified - * column. The column may be specified by either its ID or - * title. - * - * @method getNum - * @param {String|Integer} column columnName (string) or - * ID (number) - * @return {Number} Float Floating point number - * @example - *
      - * // Given the CSV file "mammals.csv" in the project's "assets" folder: - * // - * // id,species,name - * // 0,Capra hircus,Goat - * // 1,Panthera pardus,Leopard - * // 2,Equus zebra,Zebra + * Adjusts the character of the noise produced by the + * noise() function. * - * let table; + * Perlin noise values are created by adding layers of noise together. The + * noise layers, called octaves, are similar to harmonics in music. Lower + * octaves contribute more to the output signal. They define the overall + * intensity of the noise. Higher octaves create finer-grained details. * - * function preload() { - * //my table is comma separated value "csv" - * //and has a header specifying the columns labels - * table = loadTable('assets/mammals.csv', 'csv', 'header'); - * } + * By default, noise values are created by combining four octaves. Each higher + * octave contributes half as much (50% less) compared to its predecessor. + * `noiseDetail()` changes the number of octaves and the falloff amount. For + * example, calling `noiseDetail(6, 0.25)` ensures that + * noise() will use six octaves. Each higher octave + * will contribute 25% as much (75% less) compared to its predecessor. Falloff + * values between 0 and 1 are valid. However, falloff values greater than 0.5 + * might result in noise values greater than 1. * - * 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); + * @method noiseDetail + * @param {Number} lod number of octaves to be used by the noise. + * @param {Number} falloff falloff factor for each octave. + * @example + *
      + * + * let noiseLevel = 255; + * let noiseScale = 0.02; + * for (let y = 0; y < height; y += 1) { + * for (let x = 0; x < width / 2; x += 1) { + * // Scale input coordinates. + * let nx = noiseScale * x; + * let ny = noiseScale * y; + * + * // Compute noise value. + * noiseDetail(6, 0.25); + * let c = noiseLevel * noise(nx, ny); + * // Render left side. + * stroke(c); + * point(x, y); + * + * // Compute noise value. + * noiseDetail(4, 0.5); + * c = noiseLevel * noise(nx, ny); + * // Render right side. + * stroke(c); + * point(x + width / 2, y); * } - * print('minimum id = ' + minId + ', maximum id = ' + maxId); - * describe('no image displayed'); * } - *
      + * + * describe('Two gray cloudy patterns. The pattern on the right is cloudier than the pattern on the left.'); + *
      + *
      */ - _main.default.TableRow.prototype.getNum = function (column) { - var ret; - if (typeof column === 'string') { - ret = parseFloat(this.obj[column]); - } else { - ret = parseFloat(this.arr[column]); + _main.default.prototype.noiseDetail = function (lod, falloff) { + if (lod > 0) { + perlin_octaves = lod; } - if (ret.toString() === 'NaN') { - throw 'Error: '.concat(this.obj[column], ' is NaN (Not a Number)'); + if (falloff > 0) { + perlin_amp_falloff = falloff; } - return ret; }; /** - * Retrieves an String value from the TableRow's specified - * column. The column may be specified by either its ID or - * title. + * Sets the seed value for noise(). By default, + * noise() produces different results each time + * a sketch is run. Calling `noiseSeed()` with a constant + * argument, such as `noiseSeed(99)`, makes noise() + * produce the same results each time a sketch is run. * - * @method getString - * @param {String|Integer} column columnName (string) or - * ID (number) - * @return {String} String + * @method noiseSeed + * @param {Number} seed seed value. * @example - *
      - * // Given the CSV file "mammals.csv" in the project's "assets" folder: - * // - * // id,species,name - * // 0,Capra hircus,Goat - * // 1,Panthera pardus,Leopard - * // 2,Equus zebra,Zebra - * - * let table; - * - * function preload() { - * //my table is comma separated value "csv" - * //and has a header specifying the columns labels - * table = loadTable('assets/mammals.csv', 'csv', 'header'); - * } - * + *
      + * * function setup() { - * let rows = table.getRows(); - * let longest = ''; - * for (let r = 0; r < rows.length; r++) { - * let species = rows[r].getString('species'); - * if (longest.length < species.length) { - * longest = species; - * } - * } + * noiseSeed(99); + * background(255); + * } * - * print('longest: ' + longest); + * function draw() { + * let noiseLevel = 100; + * let noiseScale = 0.005; + * // Scale input coordinate. + * let nt = noiseScale * frameCount; + * // Compute noise value. + * let x = noiseLevel * noise(nt); + * // Render. + * line(x, 0, x, height); * - * describe('no image displayed'); + * describe('A black rectangle that grows randomly, first to the right and then to the left.'); * } - *
      + *
      + *
      */ - _main.default.TableRow.prototype.getString = function (column) { - if (typeof column === 'string') { - return this.obj[column].toString(); - } else { - return this.arr[column].toString(); + _main.default.prototype.noiseSeed = function (seed) { + // Linear Congruential Generator + // Variant of a Lehman Generator + var lcg = function () { + // Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes + // m is basically chosen to be large (as it is the max period) + // and for its relationships to a and c + var m = 4294967296; + // a - 1 should be divisible by m's prime factors + var a = 1664525; + // c and m should be co-prime + var c = 1013904223; + var seed, + z; + return { + setSeed: function setSeed(val) { + // pick a random seed if val is undefined or null + // the >>> 0 casts the seed to an unsigned 32-bit integer + z = seed = (val == null ? Math.random() * m : val) >>> 0; + }, + getSeed: function getSeed() { + return seed; + }, + rand: function rand() { + // define the recurrence relationship + z = (a * z + c) % m; + // return a float in [0, 1) + // if z = m then z / m = 0 therefore (z % m) / m < 1 always + return z / m; + } + }; + }(); + lcg.setSeed(seed); + perlin = new Array(PERLIN_SIZE + 1); + for (var i = 0; i < PERLIN_SIZE + 1; i++) { + perlin[i] = lcg.rand(); } }; var _default = _main.default; exports.default = _default; }, { - '../core/main': 290, - 'core-js/modules/es.array.index-of': 175, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.exec': 199, - 'core-js/modules/es.regexp.to-string': 200, - 'core-js/modules/es.string.split': 209 + '../core/main': 298 } ], - 319: [ + 331: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); _dereq_('core-js/modules/es.symbol.description'); _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.every'); _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.some'); + _dereq_('core-js/modules/es.math.sign'); _dereq_('core-js/modules/es.number.constructor'); + _dereq_('core-js/modules/es.number.is-finite'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.regexp.exec'); _dereq_('core-js/modules/es.string.iterator'); - _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.sub'); + _dereq_('core-js/modules/es.weak-map'); _dereq_('core-js/modules/web.dom-collections.iterator'); - _dereq_('core-js/modules/es.symbol'); - _dereq_('core-js/modules/es.symbol.description'); - _dereq_('core-js/modules/es.symbol.iterator'); - _dereq_('core-js/modules/es.array.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.every'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.some'); + _dereq_('core-js/modules/es.math.sign'); _dereq_('core-js/modules/es.number.constructor'); - _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.regexp.exec'); - _dereq_('core-js/modules/es.string.iterator'); - _dereq_('core-js/modules/es.string.replace'); - _dereq_('core-js/modules/web.dom-collections.iterator'); + _dereq_('core-js/modules/es.number.is-finite'); + _dereq_('core-js/modules/es.string.sub'); Object.defineProperty(exports, '__esModule', { value: true }); exports.default = void 0; var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; - } /** - * @module IO - * @submodule Input - * @requires core - */ + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } /** + * @module Math + * @submodule Vector + * @requires constants + */ + /// 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; + }; /** - * XML is a representation of an XML object, able to parse XML code. Use - * loadXML() to load external XML files and create XML objects. + * A class to describe a two or three-dimensional vector. A vector is like an + * arrow pointing in space. Vectors have both magnitude (length) and + * direction. * - * @class p5.XML + * `p5.Vector` objects are often used to program motion because they simplify + * the math. For example, a moving ball has a position and a velocity. + * Position describes where the ball is in space. The ball's position vector + * extends from the origin to the ball's center. Velocity describes the ball's + * speed and the direction it's moving. If the ball is moving straight up, its + * velocity vector points straight up. Adding the ball's velocity vector to + * its position vector moves it, as in `pos.add(vel)`. Vector math relies on + * methods inside the `p5.Vector` class. + * + * @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 - *
      - * // The following short XML file called "mammals.xml" is parsed - * // in the code below. - * // - * // - * // <mammals> - * // <animal id="0" species="Capra hircus">Goat</animal> - * // <animal id="1" species="Panthera pardus">Leopard</animal> - * // <animal id="2" species="Equus zebra">Zebra</animal> - * // </mammals> + *
      + * + * let p1 = createVector(25, 25); + * let p2 = createVector(75, 75); * - * let xml; + * strokeWeight(5); + * point(p1); + * point(p2.x, p2.y); * - * function preload() { - * xml = loadXML('assets/mammals.xml'); - * } + * describe('Two black dots on a gray square, one at the top left and the other at the bottom right.'); + * + *
      + * + *
      + * + * let pos; + * let vel; * * function setup() { - * let children = xml.getChildren('animal'); + * createCanvas(100, 100); + * pos = createVector(width / 2, height); + * vel = createVector(0, -1); + * } * - * 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); + * function draw() { + * background(200); + * + * pos.add(vel); + * + * if (pos.y < 0) { + * pos.y = height; * } * - * describe('no image displayed'); - * } + * strokeWeight(5); + * point(pos); * - * // Sketch prints: - * // 0, Capra hircus, Goat - * // 1, Panthera pardus, Leopard - * // 2, Equus zebra, Zebra - *
      + * describe('A black dot moves from bottom to top on a gray square. The dot reappears at the bottom when it reaches the top.'); + * } + *
      + *
      */ + _main.default.Vector = /*#__PURE__*/ function () { + // This is how it comes in with createVector() + // This check if the first argument is a function + function _class() { + _classCallCheck(this, _class); + var x, + y, + z; + if (typeof (arguments.length <= 0 ? undefined : arguments[0]) === 'function') { + this.isPInst = true; + this._fromRadians = arguments.length <= 0 ? undefined : arguments[0]; + this._toRadians = arguments.length <= 1 ? undefined : arguments[1]; + x = (arguments.length <= 2 ? undefined : arguments[2]) || 0; + y = (arguments.length <= 3 ? undefined : arguments[3]) || 0; + z = (arguments.length <= 4 ? undefined : arguments[4]) || 0; + // This is what we'll get with new p5.Vector() + } else { + x = (arguments.length <= 0 ? undefined : arguments[0]) || 0; + y = (arguments.length <= 1 ? undefined : arguments[1]) || 0; + z = (arguments.length <= 2 ? undefined : arguments[2]) || 0; + } /** + * The x component of the vector + * @type {Number} + * @property x + * @name x + */ - _main.default.XML = function (DOM) { - if (!DOM) { - var xmlDoc = document.implementation.createDocument(null, 'doc'); - this.DOM = xmlDoc.createElement('root'); - } else { - this.DOM = DOM; - } - }; - /** - * Gets a copy of the element's parent. Returns the parent as another - * p5.XML object. - * - * @method getParent - * @return {p5.XML} element parent - * @example - *
      - * // The following short XML file called "mammals.xml" is parsed - * // in the code below. - * // - * // - * // <mammals> - * // <animal id="0" species="Capra hircus">Goat</animal> - * // <animal id="1" species="Panthera pardus">Leopard</animal> - * // <animal id="2" species="Equus zebra">Zebra</animal> - * // </mammals> - * - * let xml; + this.x = x; + /** + * The y component of the vector + * @type {Number} + * @property y + * @name y + */ + this.y = y; + /** + * The z component of the vector + * @type {Number} + * @property z + * @name z + */ + this.z = z; + } /** + * Returns a string representation of a vector. This method is useful for + * printing vectors to the console while debugging. + * @method toString + * @return {String} string representation of the vector. + * @example + *
      + * + * function setup() { + * let v = createVector(20, 30); + * // Prints 'p5.Vector Object : [20, 30, 0]'. + * print(v.toString()); + * } + * + *
      + */ + + _createClass(_class, [ + { + key: 'toString', + value: function toString() { + return 'p5.Vector Object : ['.concat(this.x, ', ').concat(this.y, ', ').concat(this.z, ']'); + } /** + * Sets the `x`, `y`, and `z` components of the vector using separate numbers, + * a p5.Vector object, or an array of numbers. + * Calling `set()` with no arguments sets the vector's components to 0. + * + * @method set + * @param {Number} [x] x component of the vector. + * @param {Number} [y] y component of the vector. + * @param {Number} [z] z component of the vector. + * @chainable + * @example + *
      + * + * strokeWeight(5); + * + * // Top left. + * let pos = createVector(25, 25); + * point(pos); + * + * // Top right. + * pos.set(75, 25); + * point(pos); + * + * // Bottom right. + * let p2 = createVector(75, 75); + * pos.set(p2); + * point(pos); + * + * // Bottom left. + * let arr = [25, 75]; + * pos.set(arr); + * point(pos); + * + * describe('Four black dots arranged in a square on a gray background.'); + * + *
      + */ + /** + * @method set + * @param {p5.Vector|Number[]} value vector to set. + * @chainable + */ + + }, + { + key: 'set', + value: function set(x, y, z) { + if (x instanceof _main.default.Vector) { + this.x = x.x || 0; + this.y = x.y || 0; + this.z = x.z || 0; + return this; + } + if (Array.isArray(x)) { + this.x = x[0] || 0; + this.y = x[1] || 0; + this.z = x[2] || 0; + return this; + } + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + return this; + } /** + * Returns a copy of the p5.Vector object. + * + * @method copy + * @return {p5.Vector} copy of the p5.Vector object. + * @example + *
      + * + * let pos = createVector(50, 50); + * let pc = pos.copy(); + * + * strokeWeight(5); + * point(pc); + * + * describe('A black point drawn in the middle of a gray square.'); + * + *
      + */ + + }, + { + key: 'copy', + value: function copy() { + if (this.isPInst) { + return new _main.default.Vector(this._fromRadians, this._toRadians, this.x, this.y, this.z); + } else { + return new _main.default.Vector(this.x, this.y, this.z); + } + } /** + * Adds to a vector's `x`, `y`, and `z` components using separate numbers, + * another p5.Vector object, or an array of numbers. + * Calling `add()` with no arguments has no effect. + * + * The static version of `add()`, as in `p5.Vector.add(v2, v1)`, returns a new + * p5.Vector object and doesn't change the + * originals. + * + * @method add + * @param {Number} x x component of the vector to be added. + * @param {Number} [y] y component of the vector to be added. + * @param {Number} [z] z component of the vector to be added. + * @chainable + * @example + *
      + * + * strokeWeight(5); + * + * // Top left. + * let pos = createVector(25, 25); + * point(pos); + * + * // Top right. + * pos.add(50, 0); + * point(pos); + * + * // Bottom right. + * let p2 = createVector(0, 50); + * pos.add(p2); + * point(pos); + * + * // Bottom left. + * let arr = [-50, 0]; + * pos.add(arr); + * point(pos); + * + * describe('Four black dots arranged in a square on a gray background.'); + * + *
      + * + *
      + * + * // Top left. + * let p1 = createVector(25, 25); + * + * // Center. + * let p2 = createVector(50, 50); + * + * // Bottom right. + * let p3 = p5.Vector.add(p1, p2); + * + * strokeWeight(5); + * point(p1); + * point(p2); + * point(p3); + * + * describe('Three black dots in a diagonal line from top left to bottom right.'); + * + *
      + * + *
      + * + * function draw() { + * background(200); + * + * let origin = createVector(0, 0); + * let v1 = createVector(50, 50); + * drawArrow(origin, v1, 'red'); + * + * let v2 = createVector(-30, 20); + * drawArrow(v1, v2, 'blue'); + * + * let v3 = p5.Vector.add(v1, v2); + * drawArrow(origin, v3, 'purple'); + * + * describe('Three arrows drawn on a gray square. A red arrow extends from the top left corner to the center. A blue arrow extends from the tip of the red arrow. A purple arrow extends from the origin to the tip of the blue arrow.'); + * } + * + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
      + */ + /** + * @method add + * @param {p5.Vector|Number[]} value The vector to add + * @chainable + */ + + }, + { + key: 'add', + value: function add(x, y, z) { + if (x instanceof _main.default.Vector) { + this.x += x.x || 0; + this.y += x.y || 0; + this.z += x.z || 0; + return this; + } + if (Array.isArray(x)) { + this.x += x[0] || 0; + this.y += x[1] || 0; + this.z += x[2] || 0; + return this; + } + this.x += x || 0; + this.y += y || 0; + this.z += z || 0; + return this; + } /** + * Performs modulo (remainder) division with a vector's `x`, `y`, and `z` + * components using separate numbers, another + * p5.Vector object, or an array of numbers. + * + * The static version of `rem()` as in `p5.Vector.rem(v2, v1)`, returns a new + * p5.Vector object and doesn't change the + * originals. + * + * @method rem + * @param {Number} x x component of divisor vector. + * @param {Number} y y component of divisor vector. + * @param {Number} z z component of divisor vector. + * @chainable + * @example + *
      + * + * let v = createVector(3, 4, 5); + * v.rem(2, 3, 4); + * // Prints 'p5.Vector Object : [1, 1, 1]'. + * print(v.toString()); + * + *
      + * + *
      + * + * let v1 = createVector(3, 4, 5); + * let v2 = createVector(2, 3, 4); + * v1.rem(v2); + * + * // Prints 'p5.Vector Object : [1, 1, 1]'. + * print(v1.toString()); + * + *
      + * + *
      + * + * let v = createVector(3, 4, 5); + * let arr = [2, 3, 4]; + * v.rem(arr); + * + * // Prints 'p5.Vector Object : [1, 1, 1]'. + * print(v.toString()); + * + *
      + * + *
      + * + * let v1 = createVector(3, 4, 5); + * let v2 = createVector(2, 3, 4); + * let v3 = p5.Vector.rem(v1, v2); + * + * // Prints 'p5.Vector Object : [1, 1, 1]'. + * print(v3.toString()); + * + *
      + */ + /** + * @method rem + * @param {p5.Vector | Number[]} value divisor vector. + * @chainable + */ + + }, + { + key: 'rem', + value: function rem(x, y, z) { + if (x instanceof _main.default.Vector) { + if ([x.x, + x.y, + x.z].every(Number.isFinite)) { + var xComponent = parseFloat(x.x); + var yComponent = parseFloat(x.y); + var zComponent = parseFloat(x.z); + return calculateRemainder3D.call(this, xComponent, yComponent, zComponent); + } + } else if (Array.isArray(x)) { + if (x.every(function (element) { + return Number.isFinite(element); + })) { + if (x.length === 2) { + return calculateRemainder2D.call(this, x[0], x[1]); + } + if (x.length === 3) { + return calculateRemainder3D.call(this, x[0], x[1], x[2]); + } + } + } else if (arguments.length === 1) { + if (Number.isFinite(arguments[0]) && arguments[0] !== 0) { + this.x = this.x % arguments[0]; + this.y = this.y % arguments[0]; + this.z = this.z % arguments[0]; + return this; + } + } else if (arguments.length === 2) { + var vectorComponents = Array.prototype.slice.call(arguments); + if (vectorComponents.every(function (element) { + return Number.isFinite(element); + })) { + if (vectorComponents.length === 2) { + return calculateRemainder2D.call(this, vectorComponents[0], vectorComponents[1]); + } + } + } else if (arguments.length === 3) { + var _vectorComponents = Array.prototype.slice.call(arguments); + if (_vectorComponents.every(function (element) { + return Number.isFinite(element); + })) { + if (_vectorComponents.length === 3) { + return calculateRemainder3D.call(this, _vectorComponents[0], _vectorComponents[1], _vectorComponents[2]); + } + } + } + } /** + * Subtracts from a vector's `x`, `y`, and `z` components using separate + * numbers, another p5.Vector object, or an array of + * numbers. Calling `sub()` with no arguments has no effect. + * + * The static version of `sub()`, as in `p5.Vector.sub(v2, v1)`, returns a new + * p5.Vector object and doesn't change the + * originals. + * + * @method sub + * @param {Number} x x component of the vector to subtract. + * @param {Number} [y] y component of the vector to subtract. + * @param {Number} [z] z component of the vector to subtract. + * @chainable + * @example + *
      + * + * strokeWeight(5); + * + * // Bottom right. + * let pos = createVector(75, 75); + * point(pos); + * + * // Top right. + * pos.sub(0, 50); + * point(pos); + * + * // Top left. + * let p2 = createVector(50, 0); + * pos.sub(p2); + * point(pos); + * + * // Bottom left. + * let arr = [0, -50]; + * pos.sub(arr); + * point(pos); + * + * describe('Four black dots arranged in a square on a gray background.'); + * + *
      + * + *
      + * + * // Bottom right. + * let p1 = createVector(75, 75); + * + * // Center. + * let p2 = createVector(50, 50); + * + * // Top left. + * let p3 = p5.Vector.sub(p1, p2); + * + * strokeWeight(5); + * point(p1); + * point(p2); + * point(p3); + * + * describe('Three black dots in a diagonal line from top left to bottom right.'); + * + *
      + * + *
      + * + * function draw() { + * background(200); + * + * let origin = createVector(0, 0); + * let v1 = createVector(50, 50); + * drawArrow(origin, v1, 'red'); + * + * let v2 = createVector(20, 70); + * drawArrow(origin, v2, 'blue'); + * + * let v3 = p5.Vector.sub(v2, v1); + * drawArrow(v1, v3, 'purple'); + * + * describe('Three arrows drawn on a gray square. A red and a blue arrow extend from the top left. A purple arrow extends from the tip of the red arrow to the tip of the blue arrow.'); + * } + * + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
      + */ + /** + * @method sub + * @param {p5.Vector|Number[]} value the vector to subtract + * @chainable + */ + + }, + { + key: 'sub', + value: function sub(x, y, z) { + if (x instanceof _main.default.Vector) { + this.x -= x.x || 0; + this.y -= x.y || 0; + this.z -= x.z || 0; + return this; + } + if (Array.isArray(x)) { + this.x -= x[0] || 0; + this.y -= x[1] || 0; + this.z -= x[2] || 0; + return this; + } + this.x -= x || 0; + this.y -= y || 0; + this.z -= z || 0; + return this; + } /** + * Multiplies a vector's `x`, `y`, and `z` components by the same number, + * separate numbers, the components of another + * p5.Vector object, or an array of numbers. Calling + * `mult()` with no arguments has no effect. + * + * The static version of `mult()`, as in `p5.Vector.mult(v, 2)`, returns a new + * p5.Vector object and doesn't change the + * originals. + * + * @method mult + * @param {Number} n The number to multiply with the vector + * @chainable + * @example + *
      + * + * strokeWeight(5); + * + * let p = createVector(25, 25); + * point(p); + * + * p.mult(2); + * point(p); + * + * describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the center.'); + * + *
      + * + *
      + * + * strokeWeight(5); + * + * let p = createVector(25, 25); + * point(p); + * + * p.mult(2, 3); + * point(p); + * + * describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); + * + *
      + * + *
      + * + * strokeWeight(5); + * + * let p = createVector(25, 25); + * point(p); + * + * let arr = [2, 3]; + * p.mult(arr); + * point(p); + * + * describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); + * + *
      + * + *
      + * + * strokeWeight(5); + * + * let p = createVector(25, 25); + * point(p); + * + * let p2 = createVector(2, 3); + * p.mult(p2); + * point(p); + * + * describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); + * + *
      + * + *
      + * + * strokeWeight(5); + * + * let p = createVector(25, 25); + * point(p); + * + * let p2 = createVector(2, 3); + * let p3 = p5.Vector.mult(p, p2); + * point(p3); + * + * describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); + * + *
      + * + *
      + * + * function draw() { + * background(200); + * + * let origin = createVector(0, 0); + * let v1 = createVector(25, 25); + * drawArrow(origin, v1, 'red'); + * + * let v2 = p5.Vector.mult(v1, 2); + * drawArrow(origin, v2, 'blue'); + * + * describe('Two arrows extending from the top left corner. The blue arrow is twice the length of the red arrow.'); + * } + * + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
      + */ + /** + * @method mult + * @param {Number} x number to multiply with the x component of the vector. + * @param {Number} y number to multiply with the y component of the vector. + * @param {Number} [z] number to multiply with the z component of the vector. + * @chainable + */ + /** + * @method mult + * @param {Number[]} arr array to multiply with the components of the vector. + * @chainable + */ + /** + * @method mult + * @param {p5.Vector} v vector to multiply with the components of the original vector. + * @chainable + */ + + }, + { + key: 'mult', + value: function mult(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 (Array.isArray(x)) { + if (x.every(function (element) { + return Number.isFinite(element); + }) && x.every(function (element) { + return typeof element === 'number'; + })) { + if (x.length === 1) { + this.x *= x[0]; + this.y *= x[0]; + this.z *= x[0]; + } else if (x.length === 2) { + this.x *= x[0]; + this.y *= x[1]; + } else if (x.length === 3) { + this.x *= x[0]; + this.y *= x[1]; + this.z *= x[2]; + } + } else { + console.warn('p5.Vector.prototype.mult:', 'x contains elements that are either undefined or not finite numbers'); + } + return this; + } + var vectorComponents = 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 a vector's `x`, `y`, and `z` components by the same number, + * separate numbers, the components of another + * p5.Vector object, or an array of numbers. Calling + * `div()` with no arguments has no effect. + * + * The static version of `div()`, as in `p5.Vector.div(v, 2)`, returns a new + * p5.Vector object and doesn't change the + * originals. + * + * @method div + * @param {number} n The number to divide the vector by + * @chainable + * @example + *
      + * + * strokeWeight(5); + * + * let p = createVector(50, 50); + * point(p); + * + * p.div(2); + * point(p); + * + * describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the center.'); + * + *
      + * + *
      + * + * strokeWeight(5); + * + * let p = createVector(50, 75); + * point(p); + * + * p.div(2, 3); + * point(p); + * + * describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); + * + *
      + * + *
      + * + * strokeWeight(5); + * + * let p = createVector(50, 75); + * point(p); + * + * let arr = [2, 3]; + * p.div(arr); + * point(p); + * + * describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); + * + *
      + * + *
      + * + * strokeWeight(5); + * + * let p = createVector(50, 75); + * point(p); + * + * let p2 = createVector(2, 3); + * p.div(p2); + * point(p); + * + * describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); + * + *
      + * + *
      + * + * strokeWeight(5); + * + * let p = createVector(50, 75); + * point(p); + * + * let p2 = createVector(2, 3); + * let p3 = p5.Vector.div(p, p2); + * point(p3); + * + * describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); + * + *
      + * + *
      + * + * function draw() { + * background(200); + * + * let origin = createVector(0, 0); + * let v1 = createVector(50, 50); + * drawArrow(origin, v1, 'red'); + * + * let v2 = p5.Vector.div(v1, 2); + * drawArrow(origin, v2, 'blue'); + * + * describe('Two arrows extending from the top left corner. The blue arrow is half the length of the red arrow.'); + * } + * + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
      + */ + /** + * @method div + * @param {Number} x number to divide with the x component of the vector. + * @param {Number} y number to divide with the y component of the vector. + * @param {Number} [z] number to divide with the z component of the vector. + * @chainable + */ + /** + * @method div + * @param {Number[]} arr array to divide the components of the vector by. + * @chainable + */ + /** + * @method div + * @param {p5.Vector} v vector to divide the components of the original vector by. + * @chainable + */ + + }, + { + key: 'div', + value: function div(x, y, z) { + if (x instanceof _main.default.Vector) { + // new p5.Vector will check that values are valid upon construction but it's possible + // that someone could change the value of a component after creation, which is why we still + // perform this check + if (Number.isFinite(x.x) && Number.isFinite(x.y) && Number.isFinite(x.z) && typeof x.x === 'number' && typeof x.y === 'number' && typeof x.z === 'number') { + var isLikely2D = x.z === 0 && this.z === 0; + if (x.x === 0 || x.y === 0 || !isLikely2D && x.z === 0) { + console.warn('p5.Vector.prototype.div:', 'divide by 0'); + return this; + } + this.x /= x.x; + this.y /= x.y; + if (!isLikely2D) { + this.z /= x.z; + } + } else { + console.warn('p5.Vector.prototype.div:', 'x contains components that are either undefined or not finite numbers'); + } + return this; + } + if (Array.isArray(x)) { + 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; + } /** + * Returns the magnitude (length) of the vector. + * + * @method mag + * @return {Number} magnitude of the vector. + * @example + *
      + * + * let p = createVector(30, 40); + * line(0, 0, p.x, p.y); + * + * let m = p.mag(); + * text(m, p.x, p.y); + * + * describe('A diagonal black line extends from the top left corner of a gray square. The number 50 is written at the end of the line.'); + * + *
      + */ + + }, + { + key: 'mag', + value: function mag() { + return Math.sqrt(this.magSq()); + } /** + * Returns the magnitude (length) of the vector squared. + * + * @method magSq + * @return {number} squared magnitude of the vector. + * @example + *
      + * + * let p = createVector(30, 40); + * line(0, 0, p.x, p.y); + * + * let m = p.magSq(); + * text(m, p.x, p.y); + * + * describe('A diagonal black line extends from the top left corner of a gray square. The number 2500 is written at the end of the line.'); + * + *
      + */ + + }, + { + key: 'magSq', + value: function magSq() { + var x = this.x; + var y = this.y; + var z = this.z; + return x * x + y * y + z * z; + } /** + * Returns the dot product of two vectors. The dot product is a number that + * describes the overlap between two vectors. Visually, the dot product can be + * thought of as the "shadow" one vector casts on another. The dot product's + * magnitude is largest when two vectors point in the same or opposite + * directions. Its magnitude is 0 when two vectors form a right angle. + * + * The version of `dot()` with one parameter interprets it as another + * p5.Vector object. + * + * The version of `dot()` with multiple parameters interprets them as the + * `x`, `y`, and `z` components of another vector. + * + * The static version of `dot()`, as in `p5.Vector.dot(v1, v2)`, is the same + * as calling `v1.dot(v2)`. + * + * @method dot + * @param {Number} x x component of the vector. + * @param {Number} [y] y component of the vector. + * @param {Number} [z] z component of the vector. + * @return {Number} dot product. + * + * @example + *
      + * + * let v1 = createVector(3, 4); + * let v2 = createVector(3, 0); + * let dp = v1.dot(v2); + * // Prints "9" to the console. + * print(dp); + * + *
      + * + *
      + * + * let v1 = createVector(1, 0); + * let v2 = createVector(0, 1); + * let dp = p5.Vector.dot(v1, v2); + * // Prints "0" to the console. + * print(dp); + * + *
      + * + *
      + * + * function draw() { + * background(200); + * + * let v0 = createVector(width / 2, height / 2); + * let v1 = createVector(30, 0); + * drawArrow(v0, v1, 'black'); + * + * let v2 = createVector(mouseX - width / 2, mouseY - height / 2); + * drawArrow(v0, v2, 'red'); + * + * let dp = v2.dot(v1); + * text(`v2 • v1 = ${dp}`, 15, 20); + * + * describe('Two arrows drawn on a gray square. A black arrow points to the right and a red arrow follows the mouse. The text "v1 • v2 = something" changes as the mouse moves.'); + * } + * + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
      + */ + /** + * @method dot + * @param {p5.Vector} v p5.Vector to be dotted. + * @return {Number} + */ + + }, + { + key: 'dot', + value: function dot(x, y, z) { + if (x instanceof _main.default.Vector) { + return this.dot(x.x, x.y, x.z); + } + return this.x * (x || 0) + this.y * (y || 0) + this.z * (z || 0); + } /** + * Returns the cross product of two vectors. The cross product is a vector + * that points straight out of the plane created by two vectors. The cross + * product's magnitude is the area of the parallelogram formed by the original + * two vectors. + * + * The static version of `cross()`, as in `p5.Vector.cross(v1, v2)`, is the same + * as calling `v1.cross(v2)`. + * + * @method cross + * @param {p5.Vector} v p5.Vector to be crossed. + * @return {p5.Vector} cross product as a p5.Vector. + * @example + *
      + * + * let v1 = createVector(1, 0); + * let v2 = createVector(3, 4); + * let cp = v1.cross(v2); + * // Prints "p5.Vector Object : [0, 0, 4]" to the console. + * print(cp.toString()); + * + *
      + * + *
      + * + * let v1 = createVector(1, 0); + * let v2 = createVector(3, 4); + * let cp = p5.Vector.cross(v1, v2); + * // Prints "p5.Vector Object : [0, 0, 4]" to the console. + * print(cp.toString()); + * + *
      + */ + + }, + { + key: 'cross', + value: function cross(v) { + var x = this.y * v.z - this.z * v.y; + var y = this.z * v.x - this.x * v.z; + var z = this.x * v.y - this.y * v.x; + if (this.isPInst) { + return new _main.default.Vector(this._fromRadians, this._toRadians, x, y, z); + } else { + return new _main.default.Vector(x, y, z); + } + } /** + * Returns the distance between two points represented by vectors. A point's + * coordinates can be thought of as a vector's components. + * + * The static version of `dist()`, as in `p5.Vector.dist(v1, v2)`, is the same + * as calling `v1.dist(v2)`. + * + * Use dist() to calculate the distance between points + * using coordinates as in `dist(x1, y1, x2, y2)`. + * + * @method dist + * @param {p5.Vector} v x, y, and z coordinates of a p5.Vector. + * @return {Number} distance. + * @example + *
      + * + * let v1 = createVector(1, 0); + * let v2 = createVector(0, 1); + * let d = v1.dist(v2); + * // Prints "1.414..." to the console. + * print(d); + * + *
      + * + *
      + * + * let v1 = createVector(1, 0); + * let v2 = createVector(0, 1); + * let d = p5.Vector.dist(v1, v2); + * // Prints "1.414..." to the console. + * print(d); + * + *
      + * + *
      + * + * function draw() { + * background(200); + * + * let origin = createVector(0, 0); + * let v1 = createVector(50, 50); + * drawArrow(origin, v1, 'red'); + * + * let v2 = createVector(20, 70); + * drawArrow(origin, v2, 'blue'); + * + * let v3 = p5.Vector.sub(v2, v1); + * drawArrow(v1, v3, 'purple'); + * + * let m = floor(v3.mag()); + * text(m, 50, 75); + * + * describe('Three arrows drawn on a gray square. A red and a blue arrow extend from the top left. A purple arrow extends from the tip of the red arrow to the tip of the blue arrow. The number 36 is written in black near the purple arrow.'); + * } + * + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
      + */ + + }, + { + key: 'dist', + value: function dist(v) { + return v.copy().sub(this).mag(); + } /** + * Scales the components of a p5.Vector object so + * that its magnitude is 1. + * + * The static version of `normalize()`, as in `p5.Vector.normalize(v)`, + * returns a new p5.Vector object and doesn't change + * the original. + * + * @method normalize + * @return {p5.Vector} normalized p5.Vector. + * @example + *
      + * + * let v = createVector(10, 20, 2); + * v.normalize(); + * // Prints "p5.Vector Object : [0.445..., 0.890..., 0.089...]" to the console. + * print(v.toString()); + * + *
      + * + *
      + * + * let v0 = createVector(10, 20, 2); + * let v1 = p5.Vector.normalize(v0); + * // Prints "p5.Vector Object : [10, 20, 2]" to the console. + * print(v0.toString()); + * // Prints "p5.Vector Object : [0.445..., 0.890..., 0.089...]" to the console. + * print(v1.toString()); + * + *
      + * + *
      + * + * function draw() { + * background(240); + * + * let v0 = createVector(50, 50); + * let v1 = createVector(mouseX - 50, mouseY - 50); + * + * let r = 25; + * drawArrow(v0, v1, 'red'); + * v1.normalize(); + * drawArrow(v0, v1.mult(r), 'blue'); + * + * noFill(); + * circle(50, 50, r * 2); + * + * describe("A red and blue arrow extend from the center of a circle. Both arrows follow the mouse, but the blue arrow's length is fixed to the circle's radius."); + * } + * + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
      + */ + + }, + { + key: 'normalize', + value: function normalize() { + var len = this.mag(); + // here we multiply by the reciprocal instead of calling 'div()' + // since div duplicates this zero check. + if (len !== 0) this.mult(1 / len); + return this; + } /** + * Limits a vector's magnitude to a maximum value. + * + * The static version of `limit()`, as in `p5.Vector.limit(v, 5)`, returns a + * new p5.Vector object and doesn't change the + * original. + * + * @method limit + * @param {Number} max maximum magnitude for the vector. + * @chainable + * @example + *
      + * + * let v = createVector(10, 20, 2); + * v.limit(5); + * // Prints "p5.Vector Object : [2.227..., 4.454..., 0.445...]" to the console. + * print(v.toString()); + * + *
      + * + *
      + * + * let v0 = createVector(10, 20, 2); + * let v1 = p5.Vector.limit(v0, 5); + * // Prints "p5.Vector Object : [2.227..., 4.454..., 0.445...]" to the console. + * print(v1.toString()); + * + *
      + * + *
      + * + * function draw() { + * background(240); + * + * let v0 = createVector(50, 50); + * let v1 = createVector(mouseX - 50, mouseY - 50); + * + * let r = 25; + * drawArrow(v0, v1, 'red'); + * drawArrow(v0, v1.limit(r), 'blue'); + * + * noFill(); + * circle(50, 50, r * 2); + * + * describe("A red and blue arrow extend from the center of a circle. Both arrows follow the mouse, but the blue arrow never crosses the circle's edge."); + * } + * + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
      + */ + + }, + { + key: 'limit', + value: function limit(max) { + var mSq = this.magSq(); + if (mSq > max * max) { + this.div(Math.sqrt(mSq)) //normalize it + .mult(max); + } + return this; + } /** + * Sets a vector's magnitude to a given value. + * + * The static version of `setMag()`, as in `p5.Vector.setMag(v, 10)`, returns + * a new p5.Vector object and doesn't change the + * original. + * + * @method setMag + * @param {number} len new length for this vector. + * @chainable + * @example + *
      + * + * let v = createVector(3, 4, 0); + * // Prints "5" to the console. + * print(v.mag()); + * + * v.setMag(10); + * // Prints "p5.Vector Object : [6, 8, 0]" to the console. + * print(v.toString()); + * + *
      + * + *
      + * + * let v0 = createVector(3, 4, 0); + * let v1 = p5.Vector.setMag(v0, 10); + * // Prints "5" to the console. + * print(v0.mag()); + * // Prints "p5.Vector Object : [6, 8, 0]" to the console. + * print(v1.toString()); + * + *
      + * + *
      + * + * function draw() { + * background(240); + * + * let origin = createVector(0, 0); + * let v = createVector(50, 50); + * + * drawArrow(origin, v, 'red'); + * + * v.setMag(30); + * drawArrow(origin, v, 'blue'); + * + * describe('Two arrows extend from the top left corner of a square toward its center. The red arrow reaches the center and the blue arrow only extends part of the way.'); + * } + * + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
      + */ + + }, + { + key: 'setMag', + value: function setMag(n) { + return this.normalize().mult(n); + } /** + * Calculates the angle a 2D vector makes with the positive x-axis. Angles + * increase in the clockwise direction. + * + * If the vector was created with + * createVector(), `heading()` returns angles + * in the units of the current angleMode(). + * + * The static version of `heading()`, as in `p5.Vector.heading(v)`, works the + * same way. + * + * @method heading + * @return {Number} angle of rotation. + * @example + *
      + * + * let v = createVector(1, 1); + * // Prints "0.785..." to the console. + * print(v.heading()); + * + * angleMode(DEGREES); + * // Prints "45" to the console. + * print(v.heading()); + * + *
      + * + *
      + * + * let v = createVector(1, 1); + * // Prints "0.785..." to the console. + * print(p5.Vector.heading(v)); + * + * angleMode(DEGREES); + * // Prints "45" to the console. + * print(p5.Vector.heading(v)); + * + *
      + * + *
      + * + * function draw() { + * background(200); + * + * let origin = createVector(0, 0); + * let v = createVector(50, 50); + * + * drawArrow(origin, v, 'black'); + * + * angleMode(RADIANS); + * let h = round(v.heading(), 2); + * text(`Radians: ${h}`, 20, 70); + * angleMode(DEGREES); + * h = v.heading(); + * text(`Degrees: ${h}`, 20, 85); + * + * describe('A black arrow extends from the top left of a square to its center. The text "Radians: 0.79" and "Degrees: 45" is written near the tip of the arrow.'); + * } + * + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
      + */ + + }, + { + key: 'heading', + value: function heading() { + var h = Math.atan2(this.y, this.x); + if (this.isPInst) return this._fromRadians(h); + return h; + } /** + * Rotates a 2D vector to a specific angle without changing its magnitude. + * By convention, the positive x-axis has an angle of 0. Angles increase in + * the clockwise direction. + * + * If the vector was created with + * createVector(), `setHeading()` uses + * the units of the current angleMode(). + * + * @method setHeading + * @param {number} angle angle of rotation. + * @chainable + * @example + *
      + * + * let v = createVector(0, 1); + * // Prints "1.570..." to the console. + * print(v.heading()); + * + * v.setHeading(PI); + * // Prints "3.141..." to the console. + * print(v.heading()); + * + *
      + * + *
      + * + * angleMode(DEGREES); + * let v = createVector(0, 1); + * // Prints "90" to the console. + * print(v.heading()); + * + * v.setHeading(180); + * // Prints "180" to the console. + * print(v.heading()); + * + *
      + * + *
      + * + * function draw() { + * background(200); + * + * let v0 = createVector(50, 50); + * let v1 = createVector(30, 0); + * + * drawArrow(v0, v1, 'red'); + * + * v1.setHeading(HALF_PI); + * drawArrow(v0, v1, 'blue'); + * + * describe('Two arrows extend from the center of a gray square. The red arrow points to the right and the blue arrow points down.'); + * } + * + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
      + */ + + }, + { + key: 'setHeading', + value: function setHeading(a) { + if (this.isPInst) a = this._toRadians(a); + var m = this.mag(); + this.x = m * Math.cos(a); + this.y = m * Math.sin(a); + return this; + } /** + * Rotates a 2D vector by an angle without changing its magnitude. + * By convention, the positive x-axis has an angle of 0. Angles increase in + * the clockwise direction. + * + * If the vector was created with + * createVector(), `rotate()` uses + * the units of the current angleMode(). + * + * The static version of `rotate()`, as in `p5.Vector.rotate(v, PI)`, + * returns a new p5.Vector object and doesn't change + * the original. + * + * @method rotate + * @param {number} angle angle of rotation. + * @chainable + * @example + *
      + * + * let v = createVector(1, 0); + * // Prints "p5.Vector Object : [1, 0, 0]" to the console. + * print(v.toString()); + * v.rotate(HALF_PI); + * // Prints "p5.Vector Object : [0, 1, 0]" to the console. + * print(v.toString()); + * + *
      + * + *
      + * + * angleMode(DEGREES); + * let v = createVector(1, 0); + * // Prints "p5.Vector Object : [1, 0, 0]" to the console. + * print(v.toString()); + * v.rotate(90); + * // Prints "p5.Vector Object : [0, 1, 0]" to the console. + * print(v.toString()); + * + *
      + * + *
      + * + * let v0 = createVector(1, 0); + * let v1 = p5.Vector.rotate(v0, HALF_PI); + * // Prints "p5.Vector Object : [1, 0, 0]" to the console. + * print(v0.toString()); + * // Prints "p5.Vector Object : [0, 1, 0]" to the console. + * print(v1.toString()); + * + *
      + * + *
      + * + * angleMode(DEGREES); + * let v0 = createVector(1, 0); + * let v1 = p5.Vector.rotate(v0, 90); + * // Prints "p5.Vector Object : [1, 0, 0]" to the console. + * print(v0.toString()); + * // Prints "p5.Vector Object : [0, 1, 0]" to the console. + * print(v1.toString()); + * + *
      + * + *
      + * + * let v0; + * let v1; + * + * function setup() { + * v0 = createVector(50, 50); + * v1 = createVector(30, 0); + * } + * + * function draw() { + * background(240); + * + * v1.rotate(0.01); + * + * drawArrow(v0, v1, 'black'); + * + * describe('A black arrow extends from the center of a gray square. The arrow rotates counterclockwise.'); + * } + * + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
      + */ + + }, + { + key: 'rotate', + value: function rotate(a) { + var newHeading = this.heading() + a; + if (this.isPInst) newHeading = this._toRadians(newHeading); + var mag = this.mag(); + this.x = Math.cos(newHeading) * mag; + this.y = Math.sin(newHeading) * mag; + return this; + } /** + * Returns the angle between two vectors. The angles returned are signed, + * which means that `v1.angleBetween(v2) === -v2.angleBetween(v1)`. + * + * If the vector was created with + * createVector(), `angleBetween()` returns + * angles in the units of the current + * angleMode(). + * + * @method angleBetween + * @param {p5.Vector} value x, y, and z components of a p5.Vector. + * @return {Number} angle between the vectors. + * @example + *
      + * + * let v0 = createVector(1, 0); + * let v1 = createVector(0, 1); + * // Prints "1.570..." to the console. + * print(v0.angleBetween(v1)); + * // Prints "-1.570..." to the console. + * print(v1.angleBetween(v0)); + * + *
      + * + *
      + * + * angleMode(DEGREES); + * let v0 = createVector(1, 0); + * let v1 = createVector(0, 1); + * // Prints "90" to the console. + * print(v0.angleBetween(v1)); + * // Prints "-90" to the console. + * print(v1.angleBetween(v0)); + * + *
      + * + *
      + * + * let v0 = createVector(1, 0); + * let v1 = createVector(0, 1); + * // Prints "1.570..." to the console. + * print(p5.Vector.angleBetween(v0, v1)); + * // Prints "-1.570..." to the console. + * print(p5.Vector.angleBetween(v1, v0)); + * + *
      + * + *
      + * + * angleMode(DEGREES); + * let v0 = createVector(1, 0); + * let v1 = createVector(0, 1); + * // Prints "90" to the console. + * print(p5.Vector.angleBetween(v0, v1)); + * // Prints "-90" to the console. + * print(p5.Vector.angleBetween(v1, v0)); + * + *
      + * + *
      + * + * function draw() { + * background(200); + * + * let v0 = createVector(50, 50); + * let v1 = createVector(30, 0); + * let v2 = createVector(0, 30); + * + * drawArrow(v0, v1, 'red'); + * drawArrow(v0, v2, 'blue'); + * + * angleMode(RADIANS); + * let angle = round(v1.angleBetween(v2), 2); + * text(`Radians: ${angle}`, 20, 20); + * angleMode(DEGREES); + * angle = round(v1.angleBetween(v2), 2); + * text(`Degrees: ${angle}`, 20, 35); + * + * describe('Two arrows extend from the center of a gray square. A red arrow points to the right and a blue arrow points down. The text "Radians: 1.57" and "Degrees: 90" is written above the arrows.'); + * } + * + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
      + */ + + }, + { + key: 'angleBetween', + value: function angleBetween(v) { + var magSqMult = this.magSq() * v.magSq(); + // Returns NaN if either vector is the zero vector. + if (magSqMult === 0) { + return NaN; + } + var u = this.cross(v); + // The dot product computes the cos value, and the cross product computes + // the sin value. Find the angle based on them. In addition, in the case of + // 2D vectors, a sign is added according to the direction of the vector. + var angle = Math.atan2(u.mag(), this.dot(v)) * Math.sign(u.z || 1); + if (this.isPInst) { + angle = this._fromRadians(angle); + } + return angle; + } /** + * Calculates new `x`, `y`, and `z` components that are proportionally the + * same distance between two vectors. The `amt` parameter is the amount to + * interpolate between the old vector and the new vector. 0.0 keeps all + * components equal to the old vector's, 0.5 is halfway between, and 1.0 sets + * all components equal to the new vector's. + * + * The static version of `lerp()`, as in `p5.Vector.lerp(v0, v1, 0.5)`, + * returns a new p5.Vector object and doesn't change + * the original. + * + * @method lerp + * @param {Number} x x component. + * @param {Number} y y component. + * @param {Number} z z component. + * @param {Number} amt amount of interpolation between 0.0 (old vector) + * and 1.0 (new vector). 0.5 is halfway between. + * @chainable + * + * @example + *
      + * + * let v0 = createVector(1, 1, 1); + * let v1 = createVector(3, 3, 3); + * v0.lerp(v1, 0.5); + * // Prints "p5.Vector Object : [2, 2, 2]" to the console. + * print(v0.toString()); + * + *
      + * + *
      + * + * let v = createVector(1, 1, 1); + * v.lerp(3, 3, 3, 0.5); + * // Prints "p5.Vector Object : [2, 2, 2]" to the console. + * print(v.toString()); + * + *
      + * + *
      + * + * let v0 = createVector(1, 1, 1); + * let v1 = createVector(3, 3, 3); + * let v2 = p5.Vector.lerp(v0, v1, 0.5); + * // Prints "p5.Vector Object : [2, 2, 2]" to the console. + * print(v2.toString()); + * + *
      + * + *
      + * + * function draw() { + * background(200); + * + * let v0 = createVector(50, 50); + * let v1 = createVector(30, 0); + * let v2 = createVector(0, 30); + * let v3 = p5.Vector.lerp(v1, v2, 0.5); + * + * drawArrow(v0, v1, 'red'); + * drawArrow(v0, v2, 'blue'); + * drawArrow(v0, v3, 'purple'); + * + * describe('Three arrows extend from the center of a gray square. A red arrow points to the right, a blue arrow points down, and a purple arrow points to the bottom right.'); + * } + * + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
      + */ + /** + * @method lerp + * @param {p5.Vector} v p5.Vector to lerp toward. + * @param {Number} amt + * @chainable + */ + + }, + { + key: 'lerp', + value: function lerp(x, y, z, amt) { + if (x instanceof _main.default.Vector) { + return this.lerp(x.x, x.y, x.z, y); + } + this.x += (x - this.x) * amt || 0; + this.y += (y - this.y) * amt || 0; + this.z += (z - this.z) * amt || 0; + return this; + } /** + * Calculates a new heading and magnitude that are between two vectors. The + * `amt` parameter is the amount to interpolate between the old vector and + * the new vector. 0.0 keeps the heading and magnitude equal to the old + * vector's, 0.5 sets them halfway between, and 1.0 sets the heading and + * magnitude equal to the new vector's. + * + * `slerp()` differs from lerp() because + * it interpolates magnitude. Calling `v0.slerp(v1, 0.5)` sets `v0`'s + * magnitude to a value halfway between its original magnitude and `v1`'s. + * Calling `v0.lerp(v1, 0.5)` makes no such guarantee. + * + * The static version of `slerp()`, as in `p5.Vector.slerp(v0, v1, 0.5)`, + * returns a new p5.Vector object and doesn't change + * the original. + * + * @method slerp + * @param {p5.Vector} v p5.Vector to slerp toward. + * @param {Number} amt amount of interpolation between 0.0 (old vector) + * and 1.0 (new vector). 0.5 is halfway between. + * @return {p5.Vector} + * + * @example + *
      + * + * let v0 = createVector(3, 0); + * // Prints "3" to the console. + * print(v0.mag()); + * // Prints "0" to the console. + * print(v0.heading()); + * + * let v1 = createVector(0, 1); + * // Prints "1" to the console. + * print(v1.mag()); + * // Prints "1.570..." to the console. + * print(v1.heading()); + * + * v0.slerp(v1, 0.5); + * // Prints "2" to the console. + * print(v0.mag()); + * // Prints "0.785..." to the console. + * print(v0.heading()); + * + *
      + * + *
      + * + * let v0 = createVector(3, 0); + * // Prints "3" to the console. + * print(v0.mag()); + * // Prints "0" to the console. + * print(v0.heading()); + * + * let v1 = createVector(0, 1); + * // Prints "1" to the console. + * print(v1.mag()); + * // Prints "1.570..." to the console. + * print(v1.heading()); + * + * let v3 = p5.Vector.slerp(v0, v1, 0.5); + * // Prints "2" to the console. + * print(v3.mag()); + * // Prints "0.785..." to the console. + * print(v3.heading()); + * + *
      + * + *
      + * + * function draw() { + * background(200); + * + * let v0 = createVector(50, 50); + * let v1 = createVector(20, 0); + * let v2 = createVector(-40, 0); + * let v3 = p5.Vector.slerp(v1, v2, 0.5); + * + * drawArrow(v0, v1, 'red'); + * drawArrow(v0, v2, 'blue'); + * drawArrow(v0, v3, 'purple'); + * + * describe('Three arrows extend from the center of a gray square. A red arrow points to the right, a blue arrow points to the left, and a purple arrow points down.'); + * } + * + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
      + */ + + }, + { + key: 'slerp', + value: function slerp(v, amt) { + // edge cases. + if (amt === 0) { + return this; + } + if (amt === 1) { + return this.set(v); + } // calculate magnitudes + + var selfMag = this.mag(); + var vMag = v.mag(); + var magmag = selfMag * vMag; + // if either is a zero vector, linearly interpolate by these vectors + if (magmag === 0) { + this.mult(1 - amt).add(v.x * amt, v.y * amt, v.z * amt); + return this; + } // the cross product of 'this' and 'v' is the axis of rotation + + var axis = this.cross(v); + var axisMag = axis.mag(); + // Calculates the angle between 'this' and 'v' + var theta = Math.atan2(axisMag, this.dot(v)); + // However, if the norm of axis is 0, normalization cannot be performed, + // so we will divide the cases + if (axisMag > 0) { + axis.x /= axisMag; + axis.y /= axisMag; + axis.z /= axisMag; + } else if (theta < Math.PI * 0.5) { + // if the norm is 0 and the angle is less than PI/2, + // the angle is very close to 0, so do linear interpolation. + this.mult(1 - amt).add(v.x * amt, v.y * amt, v.z * amt); + return this; + } else { + // If the norm is 0 and the angle is more than PI/2, the angle is + // very close to PI. + // In this case v can be regarded as '-this', so take any vector + // that is orthogonal to 'this' and use that as the axis. + if (this.z === 0 && v.z === 0) { + // if both this and v are 2D vectors, use (0,0,1) + // this makes the result also a 2D vector. + axis.set(0, 0, 1); + } else if (this.x !== 0) { + // if the x components is not 0, use (y, -x, 0) + axis.set(this.y, - this.x, 0).normalize(); + } else { + // if the x components is 0, use (1,0,0) + axis.set(1, 0, 0); + } + } // Since 'axis' is a unit vector, ey is a vector of the same length as 'this'. + + var ey = axis.cross(this); + // interpolate the length with 'this' and 'v'. + var lerpedMagFactor = 1 - amt + amt * vMag / selfMag; + // imagine a situation where 'axis', 'this', and 'ey' are pointing + // along the z, x, and y axes, respectively. + // rotates 'this' around 'axis' by amt * theta towards 'ey'. + var cosMultiplier = lerpedMagFactor * Math.cos(amt * theta); + var sinMultiplier = lerpedMagFactor * Math.sin(amt * theta); + // then, calculate 'result'. + this.x = this.x * cosMultiplier + ey.x * sinMultiplier; + this.y = this.y * cosMultiplier + ey.y * sinMultiplier; + this.z = this.z * cosMultiplier + ey.z * sinMultiplier; + return this; + } /** + * Reflects a vector about a line in 2D or a plane in 3D. The orientation of + * the line or plane is described by a normal vector that points away from the + * shape. + * + * The static version of `reflect()`, as in `p5.Vector.reflect(v, n)`, + * returns a new p5.Vector object and doesn't change + * the original. + * + * @method reflect + * @param {p5.Vector} surfaceNormal p5.Vector + * to reflect about. + * @chainable + * @example + *
      + * + * let n = createVector(0, 1); + * let v = createVector(4, 6); + * v.reflect(n); + * // Prints "p5.Vector Object : [4, -6, 0]" to the console. + * print(v.toString()); + * + *
      + * + *
      + * + * let n = createVector(0, 1); + * let v0 = createVector(4, 6); + * let v1 = p5.Vector.reflect(v0, n); + * // Prints "p5.Vector Object : [4, -6, 0]" to the console. + * print(v1.toString()); + * + *
      + * + *
      + * + * function draw() { + * background(200); + * + * line(50, 0, 50, 100); + * let n = createVector(1, 0); + * + * let v0 = createVector(50, 50); + * let v1 = createVector(30, 40); + * let v2 = p5.Vector.reflect(v1, n); + * + * n.setMag(30); + * drawArrow(v0, n, 'black'); + * drawArrow(v0, v1, 'red'); + * drawArrow(v0, v2, 'blue'); + * + * describe('Three arrows extend from the center of a gray square with a vertical line down its middle. A black arrow points to the right, a blue arrow points to the bottom left, and a red arrow points to the bottom right.'); + * } + * + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
      + */ + + }, + { + key: 'reflect', + value: function reflect(surfaceNormal) { + surfaceNormal.normalize(); + return this.sub(surfaceNormal.mult(2 * this.dot(surfaceNormal))); + } /** + * Returns the vector's components as an array of numbers. + * + * @method array + * @return {Number[]} array with the vector's components. + * @example + *
      + * + * let v = createVector(20, 30); + * // Prints "[20, 30, 0]" to the console. + * print(v.array()); + * + *
      + */ + + }, + { + key: 'array', + value: function array() { + return [this.x || 0, + this.y || 0, + this.z || 0]; + } /** + * Returns `true` if the vector's components are all the same as another + * vector's and `false` if not. + * + * The version of `equals()` with one parameter interprets it as another + * p5.Vector object. + * + * The version of `equals()` with multiple parameters interprets them as the + * components of another vector. Any missing parameters are assigned the value + * 0. + * + * The static version of `equals()`, as in `p5.Vector.equals(v0, v1)`, + * interprets both parameters as p5.Vector objects. + * + * @method equals + * @param {Number} [x] x component of the vector. + * @param {Number} [y] y component of the vector. + * @param {Number} [z] z component of the vector. + * @return {Boolean} whether the vectors are equal. + * @example + *
      + * + * let v0 = createVector(10, 20, 30); + * let v1 = createVector(10, 20, 30); + * let v2 = createVector(0, 0, 0); + * + * // Prints "true" to the console. + * print(v0.equals(v1)); + * // Prints "false" to the console. + * print(v0.equals(v2)); + * + *
      + * + *
      + * + * let v0 = createVector(5, 10, 20); + * let v1 = createVector(5, 10, 20); + * let v2 = createVector(13, 10, 19); + * + * // Prints "true" to the console. + * print(v0.equals(v1.x, v1.y, v1.z)); + * // Prints "false" to the console. + * print(v0.equals(v2.x, v2.y, v2.z)); + * + *
      + * + *
      + * + * let v0 = createVector(10, 20, 30); + * let v1 = createVector(10, 20, 30); + * let v2 = createVector(0, 0, 0); + * + * // Prints "true" to the console. + * print(p5.Vector.equals(v0, v1)); + * // Prints "false" to the console. + * print(p5.Vector.equals(v0, v2)); + * + *
      + */ + /** + * @method equals + * @param {p5.Vector|Array} value vector to compare. + * @return {Boolean} + */ + + }, + { + key: 'equals', + value: function equals(x, y, z) { + var a, + b, + c; + if (x instanceof _main.default.Vector) { + a = x.x || 0; + b = x.y || 0; + c = x.z || 0; + } else if (Array.isArray(x)) { + a = x[0] || 0; + b = x[1] || 0; + c = x[2] || 0; + } else { + a = x || 0; + b = y || 0; + c = z || 0; + } + return this.x === a && this.y === b && this.z === c; + } // Static Methods + /** + * Make a new 2D vector from an angle. + * + * @method fromAngle + * @static + * @param {Number} angle desired angle, in radians. Unaffected by angleMode(). + * @param {Number} [length] length of the new vector (defaults to 1). + * @return {p5.Vector} new p5.Vector object. + * @example + *
      + * + * let v = p5.Vector.fromAngle(0); + * // Prints "p5.Vector Object : [1, 0, 0]" to the console. + * print(v.toString()); + * + *
      + * + *
      + * + * function draw() { + * background(200); + * + * let v0 = createVector(50, 50); + * let v1 = p5.Vector.fromAngle(0, 30); + * + * drawArrow(v0, v1, 'black'); + * + * describe('A black arrow extends from the center of a gray square. It points to the right.'); + * } + * + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
      + */ + + } + ], [ + { + key: 'fromAngle', + value: function fromAngle(angle, 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 polar angle in radians (zero is up). + * @param {Number} phi azimuthal angle in radians + * (zero is out of the screen). + * @param {Number} [length] length of the new vector (defaults to 1). + * @return {p5.Vector} new p5.Vector object. + * @example + *
      + * + * let v = p5.Vector.fromAngles(0, 0); + * // Prints "p5.Vector Object : [0, -1, 0]" to the console. + * print(v.toString()); + * + *
      + * + *
      + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * } + * + * function draw() { + * background(0); + * + * fill(255); + * noStroke(); + * + * let theta = frameCount * 0.05; + * let phi = 0; + * let v = p5.Vector.fromAngles(theta, phi, 100); + * let c = color('deeppink'); + * pointLight(c, v); + * + * sphere(35); + * + * describe('A light shines on a pink sphere as it orbits.'); + * } + * + *
      + */ + + }, + { + key: 'fromAngles', + value: function fromAngles(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 with a random heading. + * + * @method random2D + * @static + * @return {p5.Vector} new p5.Vector object. + * @example + *
      + * + * let v = p5.Vector.random2D(); + * // Prints "p5.Vector Object : [x, y, 0]" to the console + * // where x and y are small random numbers. + * print(v.toString()); + * + *
      + * + *
      + * + * function draw() { + * background(200); + * + * frameRate(1); + * + * let v0 = createVector(50, 50); + * let v1 = p5.Vector.random2D(); + * v1.mult(30); + * drawArrow(v0, v1, 'black'); + * + * describe('A black arrow in extends from the center of a gray square. It changes direction once per second.'); + * } + * + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
      + */ + + }, + { + key: 'random2D', + value: function random2D() { + return this.fromAngle(Math.random() * constants.TWO_PI); + } /** + * Make a new 3D unit vector with a random heading. + * + * @method random3D + * @static + * @return {p5.Vector} new p5.Vector object. + * @example + *
      + * + * let v = p5.Vector.random3D(); + * // Prints "p5.Vector Object : [x, y, z]" to the console + * // where x, y, and z are small random numbers. + * print(v.toString()); + * + *
      + */ + + }, + { + key: 'random3D', + value: function random3D() { + var angle = Math.random() * constants.TWO_PI; + var vz = Math.random() * 2 - 1; + var vzBase = Math.sqrt(1 - vz * vz); + var vx = vzBase * Math.cos(angle); + var vy = vzBase * Math.sin(angle); + return new _main.default.Vector(vx, vy, vz); + } // Returns a copy of a vector. + /** + * @method copy + * @static + * @param {p5.Vector} v the p5.Vector to create a copy of + * @return {p5.Vector} the copy of the p5.Vector object + */ + + }, + { + key: 'copy', + value: function copy(v) { + return v.copy(v); + } // Adds two vectors together and returns a new one. + /** + * @method add + * @static + * @param {p5.Vector} v1 A p5.Vector to add + * @param {p5.Vector} v2 A p5.Vector to add + * @param {p5.Vector} [target] vector to receive the result. + * @return {p5.Vector} resulting p5.Vector. + */ + + }, + { + key: 'add', + value: function add(v1, v2, target) { + if (!target) { + target = v1.copy(); + if (arguments.length === 3) { + _main.default._friendlyError('The target parameter is undefined, it should be of type p5.Vector', 'p5.Vector.add'); + } + } else { + target.set(v1); + } + target.add(v2); + return target; + } // Returns a vector remainder when it is divided by another vector + /** + * @method rem + * @static + * @param {p5.Vector} v1 The dividend p5.Vector + * @param {p5.Vector} v2 The divisor p5.Vector + */ + /** + * @method rem + * @static + * @param {p5.Vector} v1 + * @param {p5.Vector} v2 + * @return {p5.Vector} The resulting p5.Vector + */ + + }, + { + key: 'rem', + value: function rem(v1, v2) { + if (v1 instanceof _main.default.Vector && v2 instanceof _main.default.Vector) { + var target = v1.copy(); + target.rem(v2); + return target; + } + } /* + * Subtracts one p5.Vector from another and returns a new one. The second + * vector (`v2`) is subtracted from the first (`v1`), resulting in `v1-v2`. + */ + /** + * @method sub + * @static + * @param {p5.Vector} v1 A p5.Vector to subtract from + * @param {p5.Vector} v2 A p5.Vector to subtract + * @param {p5.Vector} [target] vector to receive the result. + * @return {p5.Vector} The resulting p5.Vector + */ + + }, + { + key: 'sub', + value: function sub(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} resulting new p5.Vector. + */ + /** + * @method mult + * @static + * @param {p5.Vector} v + * @param {Number} n + * @param {p5.Vector} [target] vector to receive the result. + */ + /** + * @method mult + * @static + * @param {p5.Vector} v0 + * @param {p5.Vector} v1 + * @param {p5.Vector} [target] + */ + /** + * @method mult + * @static + * @param {p5.Vector} v0 + * @param {Number[]} arr + * @param {p5.Vector} [target] + */ + + }, + { + key: 'mult', + value: function mult(v, n, target) { + if (!target) { + target = v.copy(); + if (arguments.length === 3) { + _main.default._friendlyError('The target parameter is undefined, it should be of type p5.Vector', 'p5.Vector.mult'); + } + } else { + target.set(v); + } + target.mult(n); + return target; + } /** + * Rotates the vector (only 2D vectors) by the given angle; magnitude remains the same. Returns a new vector. + */ + /** + * @method rotate + * @static + * @param {p5.Vector} v + * @param {Number} angle + * @param {p5.Vector} [target] The vector to receive the result + */ + + }, + { + key: 'rotate', + value: function rotate(v, a, target) { + if (arguments.length === 2) { + target = v.copy(); + } else { + if (!(target instanceof _main.default.Vector)) { + _main.default._friendlyError('The target parameter should be of type p5.Vector', 'p5.Vector.rotate'); + } + target.set(v); + } + target.rotate(a); + return target; + } /** + * Divides a vector by a scalar and returns a new vector. + */ + /** + * @method div + * @static + * @param {Number} x + * @param {Number} y + * @param {Number} [z] + * @return {p5.Vector} The resulting new p5.Vector + */ + /** + * @method div + * @static + * @param {p5.Vector} v + * @param {Number} n + * @param {p5.Vector} [target] The vector to receive the result + */ + /** + * @method div + * @static + * @param {p5.Vector} v0 + * @param {p5.Vector} v1 + * @param {p5.Vector} [target] + */ + /** + * @method div + * @static + * @param {p5.Vector} v0 + * @param {Number[]} arr + * @param {p5.Vector} [target] + */ + + }, + { + key: 'div', + value: 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 first p5.Vector. + * @param {p5.Vector} v2 second p5.Vector. + * @return {Number} dot product. + */ + + }, + { + key: 'dot', + value: function dot(v1, v2) { + return v1.dot(v2); + } /** + * Calculates the cross product of two vectors. + */ + /** + * @method cross + * @static + * @param {p5.Vector} v1 first p5.Vector. + * @param {p5.Vector} v2 second p5.Vector. + * @return {Number} cross product. + */ + + }, + { + key: 'cross', + value: function cross(v1, v2) { + return v1.cross(v2); + } /** + * Calculates the Euclidean distance between two points (considering a + * point as a vector object). + */ + /** + * @method dist + * @static + * @param {p5.Vector} v1 The first p5.Vector + * @param {p5.Vector} v2 The second p5.Vector + * @return {Number} The distance + */ + + }, + { + key: 'dist', + value: function dist(v1, v2) { + return v1.dist(v2); + } /** + * Linear interpolate a vector to another vector and return the result as a + * new vector. + */ + /** + * @method lerp + * @static + * @param {p5.Vector} v1 + * @param {p5.Vector} v2 + * @param {Number} amt + * @param {p5.Vector} [target] The vector to receive the result + * @return {p5.Vector} The lerped value + */ + + }, + { + key: 'lerp', + value: function lerp(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; + } /** + * Performs spherical linear interpolation with the other vector + * and returns the resulting vector. + * This works in both 3D and 2D. As for 2D, the result of slerping + * between 2D vectors is always a 2D vector. + */ + /** + * @method slerp + * @static + * @param {p5.Vector} v1 old vector. + * @param {p5.Vector} v2 new vector. + * @param {Number} amt + * @param {p5.Vector} [target] vector to receive the result. + * @return {p5.Vector} slerped vector between v1 and v2 + */ + + }, + { + key: 'slerp', + value: function slerp(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.slerp'); + } + } else { + target.set(v1); + } + target.slerp(v2, amt); + return target; + } /** + * Calculates the magnitude (length) of the vector and returns the result as + * a float (this is simply the equation `sqrt(x*x + y*y + z*z)`.) + */ + /** + * @method mag + * @static + * @param {p5.Vector} vecT The vector to return the magnitude of + * @return {Number} The magnitude of vecT + */ + + }, + { + key: 'mag', + value: function mag(vecT) { + return vecT.mag(); + } /** + * Calculates the squared magnitude of the vector and returns the result + * as a float (this is simply the equation (x\*x + y\*y + z\*z).) + * Faster if the real length is not required in the + * case of comparing vectors, etc. + */ + /** + * @method magSq + * @static + * @param {p5.Vector} vecT the vector to return the squared magnitude of + * @return {Number} the squared magnitude of vecT + */ + + }, + { + key: 'magSq', + value: function magSq(vecT) { + return vecT.magSq(); + } /** + * Normalize the vector to length 1 (make it a unit vector). + */ + /** + * @method normalize + * @static + * @param {p5.Vector} v The vector to normalize + * @param {p5.Vector} [target] The vector to receive the result + * @return {p5.Vector} The vector v, normalized to a length of 1 + */ + + }, + { + key: 'normalize', + value: function normalize(v, target) { + if (arguments.length < 2) { + target = v.copy(); + } else { + if (!(target instanceof _main.default.Vector)) { + _main.default._friendlyError('The target parameter should be of type p5.Vector', 'p5.Vector.normalize'); + } + target.set(v); + } + return target.normalize(); + } /** + * Limit the magnitude of the vector to the value used for the max + * parameter. + */ + /** + * @method limit + * @static + * @param {p5.Vector} v the vector to limit + * @param {Number} max + * @param {p5.Vector} [target] the vector to receive the result (Optional) + * @return {p5.Vector} v with a magnitude limited to max + */ + + }, + { + key: 'limit', + value: function limit(v, max, target) { + if (arguments.length < 3) { + target = v.copy(); + } else { + if (!(target instanceof _main.default.Vector)) { + _main.default._friendlyError('The target parameter should be of type p5.Vector', 'p5.Vector.limit'); + } + target.set(v); + } + return target.limit(max); + } /** + * Set the magnitude of the vector to the value used for the len + * parameter. + */ + /** + * @method setMag + * @static + * @param {p5.Vector} v the vector to set the magnitude of + * @param {number} len + * @param {p5.Vector} [target] the vector to receive the result (Optional) + * @return {p5.Vector} v with a magnitude set to len + */ + + }, + { + key: 'setMag', + value: function setMag(v, len, target) { + if (arguments.length < 3) { + target = v.copy(); + } else { + if (!(target instanceof _main.default.Vector)) { + _main.default._friendlyError('The target parameter should be of type p5.Vector', 'p5.Vector.setMag'); + } + target.set(v); + } + return target.setMag(len); + } /** + * Calculate the angle of rotation for this vector (only 2D vectors). + * p5.Vectors created using createVector() + * will take the current angleMode into + * consideration, and give the angle in radians or degrees accordingly. + */ + /** + * @method heading + * @static + * @param {p5.Vector} v the vector to find the angle of + * @return {Number} the angle of rotation + */ + + }, + { + key: 'heading', + value: function heading(v) { + return v.heading(); + } /** + * Calculates and returns the angle between two vectors. This function will take + * the angleMode on v1 into consideration, and + * give the angle in radians or degrees accordingly. + */ + /** + * @method angleBetween + * @static + * @param {p5.Vector} v1 the first vector. + * @param {p5.Vector} v2 the second vector. + * @return {Number} angle between the two vectors. + */ + + }, + { + key: 'angleBetween', + value: function angleBetween(v1, v2) { + return v1.angleBetween(v2); + } /** + * Reflect a vector about a normal to a line in 2D, or about a normal to a + * plane in 3D. + */ + /** + * @method reflect + * @static + * @param {p5.Vector} incidentVector vector to be reflected. + * @param {p5.Vector} surfaceNormal + * @param {p5.Vector} [target] vector to receive the result. + * @return {p5.Vector} the reflected vector + */ + + }, + { + key: 'reflect', + value: function reflect(incidentVector, surfaceNormal, target) { + if (arguments.length < 3) { + target = incidentVector.copy(); + } else { + if (!(target instanceof _main.default.Vector)) { + _main.default._friendlyError('The target parameter should be of type p5.Vector', 'p5.Vector.reflect'); + } + target.set(incidentVector); + } + return target.reflect(surfaceNormal); + } /** + * Return a representation of this vector as a float array. This is only + * for temporary use. If used in any other fashion, the contents should be + * copied by using the p5.Vector.copy() + * method to copy into your own vector. + */ + /** + * @method array + * @static + * @param {p5.Vector} v the vector to convert to an array + * @return {Number[]} an Array with the 3 values + */ + + }, + { + key: 'array', + value: function array(v) { + return v.array(); + } /** + * Equality check against a p5.Vector + */ + /** + * @method equals + * @static + * @param {p5.Vector|Array} v1 the first vector to compare + * @param {p5.Vector|Array} v2 the second vector to compare + * @return {Boolean} + */ + + }, + { + key: 'equals', + value: function equals(v1, v2) { + var v; + if (v1 instanceof _main.default.Vector) { + v = v1; + } else if (v1 instanceof Array) { + v = new _main.default.Vector().set(v1); + } else { + _main.default._friendlyError('The v1 parameter should be of type Array or p5.Vector', 'p5.Vector.equals'); + } + return v.equals(v2); + } + } + ]); + return _class; + }(); + var _default = _main.default.Vector; + exports.default = _default; + }, + { + '../core/constants': 286, + '../core/main': 298, + 'core-js/modules/es.array.concat': 169, + 'core-js/modules/es.array.every': 171, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.array.some': 184, + 'core-js/modules/es.math.sign': 190, + 'core-js/modules/es.number.constructor': 191, + 'core-js/modules/es.number.is-finite': 192, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.string.sub': 218, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 + } + ], + 332: [ + function (_dereq_, module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Math + * @submodule Random + * @for p5 + * @requires core + */ + // variables used for random number generators + + var randomStateProp = '_lcg_random_state'; + // Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes + // m is basically chosen to be large (as it is the max period) + // and for its relationships to a and c + var m = 4294967296; + // a - 1 should be divisible by m's prime factors + var a = 1664525; + // c and m should be co-prime + var c = 1013904223; + var y2 = 0; + // Linear Congruential Generator that stores its state at instance[stateProperty] + _main.default.prototype._lcg = function (stateProperty) { + // define the recurrence relationship + this[stateProperty] = (a * this[stateProperty] + c) % m; + // return a float in [0, 1) + // we've just used % m, so / m is always < 1 + return this[stateProperty] / m; + }; + _main.default.prototype._lcgSetSeed = function (stateProperty, val) { + // pick a random seed if val is undefined or null + // the >>> 0 casts the seed to an unsigned 32-bit integer + this[stateProperty] = (val == null ? Math.random() * m : val) >>> 0; + }; + /** + * Sets the seed value for random() and + * randomGaussian(). By default, + * random() and + * randomGaussian() produce different + * results each time a sketch is run. Calling `randomSeed()` with a constant + * argument, such as `randomSeed(99)`, makes these functions produce the same + * results each time a sketch is run. * - * function preload() { - * xml = loadXML('assets/mammals.xml'); - * } + * @method randomSeed + * @param {Number} seed seed value. + * @example + *
      + * + * let x = random(width); + * let y = random(height); + * circle(x, y, 10); * - * function setup() { - * let children = xml.getChildren('animal'); - * let parent = children[1].getParent(); - * print(parent.getName()); - * } + * randomSeed(99); + * x = random(width); + * y = random(height); + * fill(0); + * circle(x, y, 10); * - * // Sketch prints: - * // mammals - *
      + * describe('A white circle appears at a random position. A black circle appears at (27.4, 25.8).'); + *
      + *
      */ - _main.default.XML.prototype.getParent = function () { - return new _main.default.XML(this.DOM.parentElement); + _main.default.prototype.randomSeed = function (seed) { + this._lcgSetSeed(randomStateProp, seed); + this._gaussian_previous = false; }; /** - * Gets the element's full name, which is returned as a String. + * Returns a random number or a random element from an array. * - * @method getName - * @return {String} the name of the node - * @example<animal - *
      - * // The following short XML file called "mammals.xml" is parsed - * // in the code below. - * // - * // - * // <mammals> - * // <animal id="0" species="Capra hircus">Goat</animal> - * // <animal id="1" species="Panthera pardus">Leopard</animal> - * // <animal id="2" species="Equus zebra">Zebra</animal> - * // </mammals> + * `random()` follows uniform distribution, which means that all outcomes are + * equally likely. When `random()` is used to generate numbers, all + * numbers in the output range are equally likely to be returned. When + * `random()` is used to select elements from an array, all elements are + * equally likely to be chosen. * - * let xml; + * By default, `random()` produces different results each time a sketch runs. + * The randomSeed() function can be used to + * generate the same sequence of numbers or choices each time a sketch runs. * - * function preload() { - * xml = loadXML('assets/mammals.xml'); - * } + * The version of `random()` with no parameters returns a random number from 0 + * up to but not including 1. * - * function setup() { - * print(xml.getName()); - * } + * The version of `random()` with one parameter works one of two ways. If the + * argument passed is a number, `random()` returns a random number from 0 up + * to but not including the number. For example, calling `random(5)` returns + * values between 0 and 5. If the argument passed is an array, `random()` + * returns a random element from that array. For example, calling + * `random(['🦁', '🐯', '🐻'])` returns either a lion, tiger, or bear emoji. * - * // Sketch prints: - * // mammals - *
      - */ - _main.default.XML.prototype.getName = function () { - return this.DOM.tagName; - }; - /** - * Sets the element's name, which is specified as a String. + * The version of `random()` with two parameters returns a random number from + * a given range. The arguments passed set the range's lower and upper bounds. + * For example, calling `random(-5, 10.2)` returns values from -5 up to but + * not including 10.2. * - * @method setName - * @param {String} the new name of the node - * @example<animal - *
      - * // The following short XML file called "mammals.xml" is parsed - * // in the code below. - * // - * // - * // <mammals> - * // <animal id="0" species="Capra hircus">Goat</animal> - * // <animal id="1" species="Panthera pardus">Leopard</animal> - * // <animal id="2" species="Equus zebra">Zebra</animal> - * // </mammals> + * @method random + * @param {Number} [min] lower bound (inclusive). + * @param {Number} [max] upper bound (exclusive). + * @return {Number} random number. + * @example + *
      + * + * let x = random(width); + * let y = random(height); * - * let xml; + * strokeWeight(5); + * point(x, y); * - * function preload() { - * xml = loadXML('assets/mammals.xml'); - * } + * describe('A black dot appears in a random posiiton on a gray square.'); + * + *
      * - * function setup() { - * print(xml.getName()); - * xml.setName('fish'); - * print(xml.getName()); - * } + *
      + * + * let animals = ['🦁', '🐯', '🐻']; + * let animal = random(animals); + * text(animal, 50, 50); * - * // Sketch prints: - * // mammals - * // fish - *
      - */ - _main.default.XML.prototype.setName = function (name) { - var content = this.DOM.innerHTML; - var attributes = this.DOM.attributes; - var xmlDoc = document.implementation.createDocument(null, 'default'); - var newDOM = xmlDoc.createElement(name); - newDOM.innerHTML = content; - for (var i = 0; i < attributes.length; i++) { - newDOM.setAttribute(attributes[i].nodeName, attributes.nodeValue); - } - this.DOM = newDOM; - }; - /** - * Checks whether or not the element has any children, and returns the result - * as a boolean. + * describe('An animal face is displayed at random. Either a lion, tiger, or bear.'); + *
      + *
      * - * @method hasChildren - * @return {boolean} - * @example<animal - *
      - * // The following short XML file called "mammals.xml" is parsed - * // in the code below. - * // - * // - * // <mammals> - * // <animal id="0" species="Capra hircus">Goat</animal> - * // <animal id="1" species="Panthera pardus">Leopard</animal> - * // <animal id="2" species="Equus zebra">Zebra</animal> - * // </mammals> + *
      + * + * function draw() { + * background(200); * - * let xml; + * frameRate(5); + * let x = random(width); + * let y = random(height); * - * function preload() { - * xml = loadXML('assets/mammals.xml'); - * } + * strokeWeight(5); + * point(x, y); * - * function setup() { - * print(xml.hasChildren()); + * describe('A black dot moves around randomly on a gray square.'); * } + * + *
      * - * // Sketch prints: - * // true - *
      - */ - _main.default.XML.prototype.hasChildren = function () { - return this.DOM.children.length > 0; - }; - /** - * Get the names of all of the element's children, and returns the names as an - * array of Strings. This is the same as looping through and calling getName() - * on each child element individually. - * - * @method listChildren - * @return {String[]} names of the children of the element - * @example<animal - *
      - * // The following short XML file called "mammals.xml" is parsed - * // in the code below. - * // - * // - * // <mammals> - * // <animal id="0" species="Capra hircus">Goat</animal> - * // <animal id="1" species="Panthera pardus">Leopard</animal> - * // <animal id="2" species="Equus zebra">Zebra</animal> - * // </mammals> + *
      + * + * function draw() { + * background(200); * - * let xml; + * frameRate(5); + * let x = random(45, 55); + * let y = random(45, 55); * - * function preload() { - * xml = loadXML('assets/mammals.xml'); - * } + * strokeWeight(5); + * point(x, y); * - * function setup() { - * print(xml.listChildren()); + * describe('A black dot moves around randomly in the middle of a gray square.'); * } - * - * // Sketch prints: - * // ["animal", "animal", "animal"] - *
      + *
      + *
      */ - _main.default.XML.prototype.listChildren = function () { - var arr = [ - ]; - for (var i = 0; i < this.DOM.childNodes.length; i++) { - arr.push(this.DOM.childNodes[i].nodeName); + /** + * @method random + * @param {Array} choices array to choose from. + * @return {*} random element from the array. + * @example + */ + _main.default.prototype.random = function (min, max) { + _main.default._validateParameters('random', arguments); + var rand; + if (this[randomStateProp] != null) { + rand = this._lcg(randomStateProp); + } else { + rand = Math.random(); + } + if (typeof min === 'undefined') { + return rand; + } else if (typeof max === 'undefined') { + if (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; } - return arr; }; /** - * Returns all of the element's children as an array of p5.XML objects. When - * the name parameter is specified, then it will return all children that match - * that name. + * Returns a random number fitting a Gaussian, or normal, distribution. Normal + * distributions look like bell curves when plotted. Values from a normal + * distribution cluster around a central value called the mean. The cluster's + * standard deviation describes its spread. * - * @method getChildren - * @param {String} [name] element name - * @return {p5.XML[]} children of the element - * @example<animal - *
      - * // The following short XML file called "mammals.xml" is parsed - * // in the code below. - * // - * // - * // <mammals> - * // <animal id="0" species="Capra hircus">Goat</animal> - * // <animal id="1" species="Panthera pardus">Leopard</animal> - * // <animal id="2" species="Equus zebra">Zebra</animal> - * // </mammals> + * By default, `randomGaussian()` produces different results each time a + * sketch runs. The randomSeed() function can be + * used to generate the same sequence of numbers each time a sketch runs. * - * let xml; + * There's no minimum or maximum value that `randomGaussian()` might return. + * Values far from the mean are very unlikely and values near the mean are + * very likely. * - * function preload() { - * xml = loadXML('assets/mammals.xml'); - * } + * The version of `randomGaussian()` with no parameters returns values with a + * mean of 0 and standard deviation of 1. * - * function setup() { - * let animals = xml.getChildren('animal'); + * The version of `randomGaussian()` with one parameter interprets the + * argument passed as the mean. The standard deviation is 1. * - * for (let i = 0; i < animals.length; i++) { - * print(animals[i].getContent()); - * } - * } + * The version of `randomGaussian()` with two parameters interprets the first + * argument passed as the mean and the second as the standard deviation. * - * // Sketch prints: - * // "Goat" - * // "Leopard" - * // "Zebra" - *
      + * @method randomGaussian + * @param {Number} [mean] mean. + * @param {Number} [sd] standard deviation. + * @return {Number} random number. + * @example + *
      + * + * function draw() { + * noStroke(); + * fill(0, 10); + * + * // Uniform distribution. + * let x = random(width); + * let y = 25; + * circle(x, y, 5); + * + * // Gaussian distribution with sd = 1. + * x = randomGaussian(50); + * y = 50; + * circle(x, y, 5); + * + * // Gaussian distribution with sd = 10. + * x = randomGaussian(50, 10); + * y = 75; + * circle(x, y, 5); + * + * describe('Three horizontal black lines are filled in randomly. The top line spans entire canvas. The middle line is very short. The bottom line spans two-thirds of the canvas.'); + * } + * + *
      */ - _main.default.XML.prototype.getChildren = function (param) { - if (param) { - return elementsToP5XML(this.DOM.getElementsByTagName(param)); + _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 { - return elementsToP5XML(this.DOM.children); + 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; }; - function elementsToP5XML(elements) { - var arr = [ - ]; - for (var i = 0; i < elements.length; i++) { - arr.push(new _main.default.XML(elements[i])); + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 298 + } + ], + 333: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; } - return arr; + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; } /** - * Returns the first of the element's children that matches the name parameter - * or the child of the given index.It returns undefined if no matching - * child is found. - * - * @method getChild - * @param {String|Integer} name element name or index - * @return {p5.XML} - * @example<animal - *
      - * // The following short XML file called "mammals.xml" is parsed - * // in the code below. - * // - * // - * // <mammals> - * // <animal id="0" species="Capra hircus">Goat</animal> - * // <animal id="1" species="Panthera pardus">Leopard</animal> - * // <animal id="2" species="Equus zebra">Zebra</animal> - * // </mammals> - * - * let xml; - * - * function preload() { - * xml = loadXML('assets/mammals.xml'); - * } + * @module Math + * @submodule Trigonometry + * @for p5 + * @requires core + * @requires constants + */ + /* + * all DEGREES/RADIANS conversion should be done in the p5 instance + * if possible, using the p5._toRadians(), p5._fromRadians() methods. + */ + + _main.default.prototype._angleMode = constants.RADIANS; + /** + * The inverse of cos(), returns the arc cosine of a + * value. This function expects arguments in the range -1 to 1. By default, + * `acos()` returns values in the range 0 to π (about 3.14). If the + * angleMode() is `DEGREES`, then values are + * returned in the range 0 to 180. * - * function setup() { - * let firstChild = xml.getChild('animal'); - * print(firstChild.getContent()); - * } + * @method acos + * @param {Number} value value whose arc cosine is to be returned. + * @return {Number} arc cosine of the given value. * - * // Sketch prints: - * // "Goat" - *
      - *
      - * let xml; + * @example + *
      + * + * let a = PI; + * let c = cos(a); + * let ac = acos(c); + * text(`${round(a, 3)}`, 35, 25); + * text(`${round(c, 3)}`, 35, 50); + * text(`${round(ac, 3)}`, 35, 75); * - * function preload() { - * xml = loadXML('assets/mammals.xml'); - * } + * describe('The numbers 3.142, -1, and 3.142 written on separate rows.'); + * + *
      * - * function setup() { - * let secondChild = xml.getChild(1); - * print(secondChild.getContent()); - * } + *
      + * + * let a = PI; + * let c = cos(a); + * let ac = acos(c); + * text(`${round(a, 3)}`, 35, 25); + * text(`${round(c, 3)}`, 35, 50); + * text(`${round(ac, 3)}`, 35, 75); * - * // Sketch prints: - * // "Leopard" - *
      + * describe('The numbers 3.927, -0.707, and 2.356 written on separate rows.'); + *
      + *
      */ - - _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]); - } + _main.default.prototype.acos = function (ratio) { + return this._fromRadians(Math.acos(ratio)); }; /** - * Appends a new child to the element. The child can be specified with - * either a String, which will be used as the new tag's name, or as a - * reference to an existing p5.XML object. - * A reference to the newly created child is returned as an p5.XML object. - * - * @method addChild - * @param {p5.XML} node a p5.XML Object which will be the child to be added - * @example - *
      - * // The following short XML file called "mammals.xml" is parsed - * // in the code below. - * // - * // - * // <mammals> - * // <animal id="0" species="Capra hircus">Goat</animal> - * // <animal id="1" species="Panthera pardus">Leopard</animal> - * // <animal id="2" species="Equus zebra">Zebra</animal> - * // </mammals> + * The inverse of sin(), returns the arc sine of a + * value. This function expects input values in the range of -1 to 1. By + * default, `asin()` returns values in the range -π ÷ 2 + * (about -1.57) to π ÷ 2 (about 1.57). If the + * angleMode() is `DEGREES` then values are + * returned in the range -90 to 90. * - * let xml; + * @method asin + * @param {Number} value value whose arc sine is to be returned. + * @return {Number} arc sine of the given value. * - * function preload() { - * xml = loadXML('assets/mammals.xml'); - * } + * @example + *
      + * + * let a = PI / 3; + * let s = sin(a); + * let as = asin(s); + * text(`${round(a, 3)}`, 35, 25); + * text(`${round(s, 3)}`, 35, 50); + * text(`${round(as, 3)}`, 35, 75); * - * 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); + * describe('The numbers 1.047, 0.866, and 1.047 written on separate rows.'); + * + *
      * - * let animals = xml.getChildren('animal'); - * print(animals[animals.length - 1].getContent()); - * } + *
      + * + * let a = PI + PI / 3; + * let s = sin(a); + * let as = asin(s); + * text(`${round(a, 3)}`, 35, 25); + * text(`${round(s, 3)}`, 35, 50); + * text(`${round(as, 3)}`, 35, 75); * - * // Sketch prints: - * // "Goat" - * // "Leopard" - * // "Zebra" - *
      + * describe('The numbers 4.189, -0.866, and -1.047 written on separate rows.'); + *
      + *
      */ - _main.default.XML.prototype.addChild = function (node) { - if (node instanceof _main.default.XML) { - this.DOM.appendChild(node.DOM); - } else { // PEND - } + _main.default.prototype.asin = function (ratio) { + return this._fromRadians(Math.asin(ratio)); }; /** - * Removes the element specified by name or index. + * The inverse of tan(), returns the arc tangent of a + * value. This function expects input values in the range of -Infinity to + * Infinity. By default, `atan()` returns values in the range -π ÷ 2 + * (about -1.57) to π ÷ 2 (about 1.57). If the + * angleMode() is `DEGREES` then values are + * returned in the range -90 to 90. + * + * @method atan + * @param {Number} value value whose arc tangent is to be returned. + * @return {Number} arc tangent of the given value. * - * @method removeChild - * @param {String|Integer} name element name or index * @example - *
      - * // The following short XML file called "mammals.xml" is parsed - * // in the code below. - * // - * // - * // <mammals> - * // <animal id="0" species="Capra hircus">Goat</animal> - * // <animal id="1" species="Panthera pardus">Leopard</animal> - * // <animal id="2" species="Equus zebra">Zebra</animal> - * // </mammals> + *
      + * + * let a = PI / 3; + * let t = tan(a); + * let at = atan(t); + * text(`${round(a, 3)}`, 35, 25); + * text(`${round(t, 3)}`, 35, 50); + * text(`${round(at, 3)}`, 35, 75); * - * let xml; + * describe('The numbers 1.047, 1.732, and 1.047 written on separate rows.'); + * + *
      * - * function preload() { - * xml = loadXML('assets/mammals.xml'); - * } + *
      + * + * let a = PI + PI / 3; + * let t = tan(a); + * let at = atan(t); + * text(`${round(a, 3)}`, 35, 25); + * text(`${round(t, 3)}`, 35, 50); + * text(`${round(at, 3)}`, 35, 75); * - * function setup() { - * xml.removeChild('animal'); - * let children = xml.getChildren(); - * for (let i = 0; i < children.length; i++) { - * print(children[i].getContent()); - * } - * } + * describe('The numbers 4.189, 1.732, and 1.047 written on separate rows.'); + * + *
      + */ + _main.default.prototype.atan = function (ratio) { + return this._fromRadians(Math.atan(ratio)); + }; + /** + * Calculates the angle formed by a specified point, the origin, and the + * positive x-axis. By default, `atan2()` returns values in the range + * -π (about -3.14) to π (3.14). If the + * angleMode() is `DEGREES`, then values are + * returned in the range -180 to 180. The `atan2()` function is most often + * used for orienting geometry to the mouse's position. * - * // Sketch prints: - * // "Leopard" - * // "Zebra" - *
      - *
      - * let xml; + * Note: The y-coordinate of the point is the first parameter and the + * x-coordinate is the second parameter. * - * function preload() { - * xml = loadXML('assets/mammals.xml'); - * } + * @method atan2 + * @param {Number} y y-coordinate of the point. + * @param {Number} x x-coordinate of the point. + * @return {Number} arc tangent of the given point. * - * function setup() { - * xml.removeChild(1); - * let children = xml.getChildren(); - * for (let i = 0; i < children.length; i++) { - * print(children[i].getContent()); - * } - * } + * @example + *
      + * + * function draw() { + * background(200); + * translate(width / 2, height / 2); + * let x = mouseX - width / 2; + * let y = mouseY - height / 2; + * let a = atan2(y, x); + * rotate(a); + * rect(-30, -5, 60, 10); * - * // Sketch prints: - * // "Goat" - * // "Zebra" - *
      + * describe('A rectangle at the center of the canvas rotates with mouse movements.'); + * } + *
      + *
      */ - _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]); - } + _main.default.prototype.atan2 = function (y, x) { + return this._fromRadians(Math.atan2(y, x)); }; /** - * Counts the specified element's number of attributes, returned as an Number. + * Calculates the cosine of an angle. `cos()` is useful for many geometric + * tasks in creative coding. The values returned oscillate between -1 and 1 + * as the input angle increases. `cos()` takes into account the current + * angleMode. + * + * @method cos + * @param {Number} angle the angle. + * @return {Number} cosine of the angle. * - * @method getAttributeCount - * @return {Integer} * @example - *
      - * // The following short XML file called "mammals.xml" is parsed - * // in the code below. - * // - * // - * // <mammals> - * // <animal id="0" species="Capra hircus">Goat</animal> - * // <animal id="1" species="Panthera pardus">Leopard</animal> - * // <animal id="2" species="Equus zebra">Zebra</animal> - * // </mammals> + *
      + * + * function draw() { + * background(200); * - * let xml; + * let t = frameCount; + * let x = 30 * cos(t * 0.05) + 50; + * let y = 50; + * line(50, y, x, y); + * circle(x, y, 20); * - * function preload() { - * xml = loadXML('assets/mammals.xml'); + * describe('A white ball on a string oscillates left and right.'); * } + * + *
      * - * function setup() { - * let firstChild = xml.getChild('animal'); - * print(firstChild.getAttributeCount()); + *
      + * + * function draw() { + * let x = frameCount; + * let y = 30 * cos(x * 0.1) + 50; + * point(x, y); + * + * describe('A series of black dots form a wave pattern.'); * } + * + *
      * - * // Sketch prints: - * // 2 - *
      - */ - _main.default.XML.prototype.getAttributeCount = function () { - return this.DOM.attributes.length; - }; - /** - * Gets all of the specified element's attributes, and returns them as an - * array of Strings. + *
      + * + * function draw() { + * let t = frameCount; + * let x = 30 * cos(t * 0.1) + 50; + * let y = 10 * sin(t * 0.2) + 50; + * point(x, y); * - * @method listAttributes - * @return {String[]} an array of strings containing the names of attributes - * @example - *
      - * // The following short XML file called "mammals.xml" is parsed - * // in the code below. - * // - * // - * // <mammals> - * // <animal id="0" species="Capra hircus">Goat</animal> - * // <animal id="1" species="Panthera pardus">Leopard</animal> - * // <animal id="2" species="Equus zebra">Zebra</animal> - * // </mammals> - * - * let xml; - * - * function preload() { - * xml = loadXML('assets/mammals.xml'); - * } - * - * function setup() { - * let firstChild = xml.getChild('animal'); - * print(firstChild.listAttributes()); + * describe('A series of black dots form an infinity symbol.'); * } - * - * // Sketch prints: - * // ["id", "species"] - *
      + *
      + *
      */ - _main.default.XML.prototype.listAttributes = function () { - var arr = [ - ]; - var _iteratorNormalCompletion2 = true; - var _didIteratorError2 = false; - var _iteratorError2 = undefined; - try { - for (var _iterator2 = this.DOM.attributes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { - var attribute = _step2.value; - arr.push(attribute.nodeName); - } - } catch (err) { - _didIteratorError2 = true; - _iteratorError2 = err; - } finally { - try { - if (!_iteratorNormalCompletion2 && _iterator2.return != null) { - _iterator2.return(); - } - } finally { - if (_didIteratorError2) { - throw _iteratorError2; - } - } - } - return arr; + _main.default.prototype.cos = function (angle) { + return Math.cos(this._toRadians(angle)); }; /** - * Checks whether or not an element has the specified attribute. + * Calculates the sine of an angle. `sin()` is useful for many geometric tasks + * in creative coding. The values returned oscillate between -1 and 1 as the + * input angle increases. `sin()` takes into account the current + * angleMode. + * + * @method sin + * @param {Number} angle the angle. + * @return {Number} sine of the angle. * - * @method hasAttribute - * @param {String} the attribute to be checked - * @return {boolean} true if attribute found else false * @example - *
      - * // The following short XML file called "mammals.xml" is parsed - * // in the code below. - * // - * // - * // <mammals> - * // <animal id="0" species="Capra hircus">Goat</animal> - * // <animal id="1" species="Panthera pardus">Leopard</animal> - * // <animal id="2" species="Equus zebra">Zebra</animal> - * // </mammals> + *
      + * + * function draw() { + * background(200); * - * let xml; + * let t = frameCount; + * let x = 50; + * let y = 30 * sin(t * 0.05) + 50; + * line(x, 50, x, y); + * circle(x, y, 20); * - * function preload() { - * xml = loadXML('assets/mammals.xml'); + * describe('A white ball on a string oscillates up and down.'); * } + * + *
      * - * function setup() { - * let firstChild = xml.getChild('animal'); - * print(firstChild.hasAttribute('species')); - * print(firstChild.hasAttribute('color')); + *
      + * + * function draw() { + * let x = frameCount; + * let y = 30 * sin(x * 0.1) + 50; + * point(x, y); + * + * describe('A series of black dots form a wave pattern.'); * } + * + *
      * - * // Sketch prints: - * // true - * // false - *
      + *
      + * + * function draw() { + * let t = frameCount; + * let x = 30 * cos(t * 0.1) + 50; + * let y = 10 * sin(t * 0.2) + 50; + * point(x, y); + * + * describe('A series of black dots form an infinity symbol.'); + * } + * + *
      */ - _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; + _main.default.prototype.sin = function (angle) { + return Math.sin(this._toRadians(angle)); }; /** - * Returns an attribute value of the element as an Number. If the defaultValue - * parameter is specified and the attribute doesn't exist, then defaultValue - * is returned. If no defaultValue is specified and the attribute doesn't - * exist, the value 0 is returned. - * - * @method getNum - * @param {String} name the non-null full name of the attribute - * @param {Number} [defaultValue] the default value of the attribute - * @return {Number} - * @example - *
      - * // The following short XML file called "mammals.xml" is parsed - * // in the code below. - * // - * // - * // <mammals> - * // <animal id="0" species="Capra hircus">Goat</animal> - * // <animal id="1" species="Panthera pardus">Leopard</animal> - * // <animal id="2" species="Equus zebra">Zebra</animal> - * // </mammals> + * Calculates the tangent of an angle. `tan()` is useful for many geometric + * tasks in creative coding. The values returned range from -Infinity + * to Infinity and repeat periodically as the input angle increases. `tan()` + * takes into account the current angleMode. * - * let xml; + * @method tan + * @param {Number} angle the angle. + * @return {Number} tangent of the angle. * - * function preload() { - * xml = loadXML('assets/mammals.xml'); - * } + * @example + *
      + * + * function draw() { + * let x = frameCount; + * let y = 5 * tan(x * 0.1) + 50; + * point(x, y); * - * function setup() { - * let firstChild = xml.getChild('animal'); - * print(firstChild.getNum('id')); + * describe('A series of identical curves drawn with black dots. Each curve starts from the top of the canvas, continues down at a slight angle, flattens out at the middle of the canvas, then continues to the bottom.'); * } - * - * // Sketch prints: - * // 0 - *
      + *
      + *
      */ - _main.default.XML.prototype.getNum = function (name, defaultValue) { - var obj = { - }; - var _iteratorNormalCompletion4 = true; - var _didIteratorError4 = false; - var _iteratorError4 = undefined; - try { - for (var _iterator4 = this.DOM.attributes[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { - var attribute = _step4.value; - obj[attribute.nodeName] = attribute.nodeValue; - } - } catch (err) { - _didIteratorError4 = true; - _iteratorError4 = err; - } finally { - try { - if (!_iteratorNormalCompletion4 && _iterator4.return != null) { - _iterator4.return(); - } - } finally { - if (_didIteratorError4) { - throw _iteratorError4; - } - } - } - return Number(obj[name]) || defaultValue || 0; + _main.default.prototype.tan = function (angle) { + return Math.tan(this._toRadians(angle)); }; /** - * Returns an attribute value of the element as an String. If the defaultValue - * parameter is specified and the attribute doesn't exist, then defaultValue - * is returned. If no defaultValue is specified and the attribute doesn't - * exist, null is returned. - * - * @method getString - * @param {String} name the non-null full name of the attribute - * @param {Number} [defaultValue] the default value of the attribute - * @return {String} - * @example - *
      - * // The following short XML file called "mammals.xml" is parsed - * // in the code below. - * // - * // - * // <mammals> - * // <animal id="0" species="Capra hircus">Goat</animal> - * // <animal id="1" species="Panthera pardus">Leopard</animal> - * // <animal id="2" species="Equus zebra">Zebra</animal> - * // </mammals> + * Converts an angle measurement in radians to its corresponding value in + * degrees. Degrees and radians are two ways of measuring the same thing. + * There are 360 degrees in a circle and 2 × π (about 6.28) + * radians in a circle. For example, 90° = π ÷ 2 (about 1.57) + * radians. This function doesn't take into account the current + * angleMode(). * - * let xml; - * - * function preload() { - * xml = loadXML('assets/mammals.xml'); - * } + * @method degrees + * @param {Number} radians radians value to convert to degrees. + * @return {Number} converted angle. * - * function setup() { - * let firstChild = xml.getChild('animal'); - * print(firstChild.getString('species')); - * } + * @example + *
      + * + * let rad = QUARTER_PI; + * let deg = degrees(rad); + * text(`${round(rad, 2)} rad = ${deg}˚`, 10, 50); * - * // Sketch prints: - * // "Capra hircus" - *
      + * describe('The text "0.79 rad = 45˚".'); + *
      + *
      */ - _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; + _main.default.prototype.degrees = function (angle) { + return angle * constants.RAD_TO_DEG; }; /** - * Sets the content of an element's attribute. The first parameter specifies - * the attribute name, while the second specifies the new content. - * - * @method setAttribute - * @param {String} name the full name of the attribute - * @param {Number|String|Boolean} value the value of the attribute - * @example - *
      - * // The following short XML file called "mammals.xml" is parsed - * // in the code below. - * // - * // - * // <mammals> - * // <animal id="0" species="Capra hircus">Goat</animal> - * // <animal id="1" species="Panthera pardus">Leopard</animal> - * // <animal id="2" species="Equus zebra">Zebra</animal> - * // </mammals> - * - * let xml; + * Converts an angle measurement in degrees to its corresponding value in + * radians. Degrees and radians are two ways of measuring the same thing. + * There are 360 degrees in a circle and 2 × π (about 6.28) + * radians in a circle. For example, 90° = π ÷ 2 (about 1.57) + * radians. This function doesn't take into account the current + * angleMode(). * - * function preload() { - * xml = loadXML('assets/mammals.xml'); - * } + * @method radians + * @param {Number} degrees degree value to convert to radians. + * @return {Number} converted angle. * - * function setup() { - * let firstChild = xml.getChild('animal'); - * print(firstChild.getString('species')); - * firstChild.setAttribute('species', 'Jamides zebra'); - * print(firstChild.getString('species')); - * } + * @example + *
      + * + * let deg = 45; + * let rad = radians(deg); + * text(`${deg}˚ = ${round(rad, 3)} rad`, 10, 50); * - * // Sketch prints: - * // "Capra hircus" - * // "Jamides zebra" - *
      + * describe('The text "45˚ = 0.785 rad".'); + *
      + *
      */ - _main.default.XML.prototype.setAttribute = function (name, value) { - this.DOM.setAttribute(name, value); + _main.default.prototype.radians = function (angle) { + return angle * constants.DEG_TO_RAD; }; /** - * Returns the content of an element. If there is no such content, - * defaultValue is returned if specified, otherwise null is returned. + * Changes the way trigonometric functions interpret angle values. By default, + * the mode is `RADIANS`. * - * @method getContent - * @param {String} [defaultValue] value returned if no content is found - * @return {String} + * Calling `angleMode()` with no arguments returns current angle mode. + * @method angleMode + * @param {Constant} mode either RADIANS or DEGREES. * @example - *
      - * // The following short XML file called "mammals.xml" is parsed - * // in the code below. - * // - * // - * // <mammals> - * // <animal id="0" species="Capra hircus">Goat</animal> - * // <animal id="1" species="Panthera pardus">Leopard</animal> - * // <animal id="2" species="Equus zebra">Zebra</animal> - * // </mammals> - * - * let xml; + *
      + * + * let r = 40; + * push(); + * rotate(PI / 6); + * line(0, 0, r, 0); + * text('0.524 rad', r, 0); + * pop(); * - * function preload() { - * xml = loadXML('assets/mammals.xml'); - * } + * angleMode(DEGREES); + * push(); + * rotate(60); + * line(0, 0, r, 0); + * text('60˚', r, 0); + * pop(); * - * function setup() { - * let firstChild = xml.getChild('animal'); - * print(firstChild.getContent()); - * } + * describe('Two diagonal lines radiating from the top left corner of a square. The lines are oriented 30 degrees from the edges of the square and 30 degrees apart from each other.'); + * + *
      * - * // Sketch prints: - * // "Goat" - *
      */ - _main.default.XML.prototype.getContent = function (defaultValue) { - var str; - str = this.DOM.textContent; - str = str.replace(/\s\s+/g, ','); - return str || defaultValue || null; + /** + * @method angleMode + * @return {Constant} mode either RADIANS or DEGREES + */ + _main.default.prototype.angleMode = function (mode) { + _main.default._validateParameters('angleMode', arguments); + if (typeof mode === 'undefined') { + return this._angleMode; + } else if (mode === constants.DEGREES || mode === constants.RADIANS) { + this._angleMode = mode; + } }; /** - * Sets the element's content. - * - * @method setContent - * @param {String} text the new content - * @example - *
      - * // The following short XML file called "mammals.xml" is parsed - * // in the code below. - * // - * // - * // <mammals> - * // <animal id="0" species="Capra hircus">Goat</animal> - * // <animal id="1" species="Panthera pardus">Leopard</animal> - * // <animal id="2" species="Equus zebra">Zebra</animal> - * // </mammals> - * - * let xml; - * - * function preload() { - * xml = loadXML('assets/mammals.xml'); - * } - * - * function setup() { - * let firstChild = xml.getChild('animal'); - * print(firstChild.getContent()); - * firstChild.setContent('Mountain Goat'); - * print(firstChild.getContent()); - * } + * converts angles from the current angleMode to RADIANS * - * // Sketch prints: - * // "Goat" - * // "Mountain Goat" - *
      + * @method _toRadians + * @private + * @param {Number} angle + * @returns {Number} */ - _main.default.XML.prototype.setContent = function (content) { - if (!this.DOM.children.length) { - this.DOM.textContent = content; + _main.default.prototype._toRadians = function (angle) { + if (this._angleMode === constants.DEGREES) { + return angle * constants.DEG_TO_RAD; } + return angle; }; /** - * 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 - *
      - * let xml; - * - * function preload() { - * xml = loadXML('assets/mammals.xml'); - * } + * converts angles from the current angleMode to DEGREES * - * function setup() { - * print(xml.serialize()); - * } + * @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 * - * // Sketch prints: - * // - * // Goat - * // Leopard - * // Zebra - * // - *
      + * @method _fromRadians + * @private + * @param {Number} angle + * @returns {Number} */ - _main.default.XML.prototype.serialize = function () { - var xmlSerializer = new XMLSerializer(); - return xmlSerializer.serializeToString(this.DOM); + _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/main': 290, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.number.constructor': 187, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.exec': 199, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.string.replace': 207, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/web.dom-collections.iterator': 248 + '../core/constants': 286, + '../core/main': 298, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 320: [ + 334: [ function (_dereq_, module, exports) { 'use strict'; - _dereq_('core-js/modules/es.array.includes'); - _dereq_('core-js/modules/es.array.index-of'); - _dereq_('core-js/modules/es.array.map'); - _dereq_('core-js/modules/es.array.slice'); - _dereq_('core-js/modules/es.math.hypot'); - _dereq_('core-js/modules/es.number.constructor'); - _dereq_('core-js/modules/es.string.includes'); - _dereq_('core-js/modules/es.array.includes'); - _dereq_('core-js/modules/es.array.index-of'); - _dereq_('core-js/modules/es.array.map'); - _dereq_('core-js/modules/es.array.slice'); - _dereq_('core-js/modules/es.math.hypot'); - _dereq_('core-js/modules/es.number.constructor'); - _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); Object.defineProperty(exports, '__esModule', { value: true }); @@ -85770,1310 +98403,1002 @@ obj }; } /** - * @module Math - * @submodule Calculation + * @module Typography + * @submodule Attributes * @for p5 * @requires core + * @requires constants */ /** - * Calculates the absolute value (magnitude) of a number. Maps to Math.abs(). - * The absolute value of a number is always positive. + * Sets the way text is aligned when text() is called. * - * @method abs - * @param {Number} n number to compute - * @return {Number} absolute value of given number - * @example - *
      - * function setup() { - * let x = -3; - * let y = abs(x); + * By default, calling `text('hi', 10, 20)` places the bottom-left corner of + * the text's bounding box at (10, 20). * - * print(x); // -3 - * print(y); // 3 + * The first parameter, `horizAlign`, changes the way + * text() interprets x-coordinates. By default, the + * x-coordinate sets the left edge of the bounding box. `textAlign()` accepts + * the following values for `horizAlign`: `LEFT`, `CENTER`, or `RIGHT`. * - * describe('no image displayed'); - * } - *
      - */ - - _main.default.prototype.abs = Math.abs; - /** - * Calculates the closest int value that is greater than or equal to the - * value of the parameter. Maps to Math.ceil(). For example, ceil(9.03) - * returns the value 10. + * The second parameter, `vertAlign`, is optional. It changes the way + * text() interprets y-coordinates. By default, the + * y-coordinate sets the bottom edge of the bounding box. `textAlign()` + * accepts the following values for `vertAlign`: `TOP`, `BOTTOM`, `CENTER`, + * or `BASELINE`. * - * @method ceil - * @param {Number} n number to round up - * @return {Integer} rounded up number + * @method textAlign + * @param {Constant} horizAlign horizontal alignment, either LEFT, + * CENTER, or RIGHT. + * @param {Constant} [vertAlign] vertical alignment, either TOP, + * BOTTOM, CENTER, or BASELINE. + * @chainable * @example - *
      - * function 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); + *
      + * + * strokeWeight(0.5); + * line(50, 0, 50, 100); * - * // Reformat the float returned by map and draw it. - * noStroke(); - * text(nfc(ax, 2), ax, ay - 5); - * text(nfc(bx, 1), bx, by - 5); + * textSize(16); + * textAlign(RIGHT); + * text('ABCD', 50, 30); + * textAlign(CENTER); + * text('EFGH', 50, 50); + * textAlign(LEFT); + * text('IJKL', 50, 70); * - * describe(`2 horizontal lines & number sets. increase with - * mouse x. bottom to 2 decimals`); - * } - *
      - */ - _main.default.prototype.ceil = Math.ceil; - /** - * Constrains a value between a minimum and maximum value. + * describe('The letters ABCD displayed at top-left, EFGH at center, and IJKL at bottom-right. A vertical line divides the canvas in half.'); + *
      + *
      * - * @method constrain - * @param {Number} n number to constrain - * @param {Number} low minimum limit - * @param {Number} high maximum limit - * @return {Number} constrained number - * @example - *
      - * function draw() { - * background(200); + *
      + * + * strokeWeight(0.5); * - * let leftWall = 25; - * let rightWall = 75; + * line(0, 12, width, 12); + * textAlign(CENTER, TOP); + * text('TOP', 50, 12); * - * // 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); + * line(0, 37, width, 37); + * textAlign(CENTER, CENTER); + * text('CENTER', 50, 37); * - * // Draw the walls. - * stroke(150); - * line(leftWall, 0, leftWall, height); - * line(rightWall, 0, rightWall, height); + * line(0, 62, width, 62); + * textAlign(CENTER, BASELINE); + * text('BASELINE', 50, 62); * - * // Draw xm and xc as circles. - * noStroke(); - * fill(150); - * ellipse(xm, 33, 9, 9); // Not Constrained - * fill(0); - * ellipse(xc, 66, 9, 9); // Constrained + * line(0, 97, width, 97); + * textAlign(CENTER, BOTTOM); + * text('BOTTOM', 50, 97); * - * describe(`2 vertical lines. 2 ellipses move with mouse X, - * 1 does not move past lines`); - * } - *
      + * describe('The words "TOP", "CENTER", "BASELINE", and "BOTTOM" each drawn relative to a horizontal line. Their positions demonstrate different vertical alignments.'); + *
      + *
      */ - _main.default.prototype.constrain = function (n, low, high) { - _main.default._validateParameters('constrain', arguments); - return Math.max(Math.min(n, high), low); + /** + * @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); }; /** - * Calculates the distance between two points, in either two or three dimensions. - * If you looking for distance between two vectors see p5.Vector.dist() - * - * @method dist - * @param {Number} x1 x-coordinate of the first point - * @param {Number} y1 y-coordinate of the first point - * @param {Number} x2 x-coordinate of the second point - * @param {Number} y2 y-coordinate of the second point - * @return {Number} distance between the two points + * Sets the spacing between lines of text when + * text() is called. Spacing is measured in pixels. * - * @example - *
      - * // Move your mouse inside the canvas to see the - * // change in distance between two points! - * function draw() { - * background(200); - * fill(0); + * Calling `textLeading()` without an argument returns the current spacing. * - * let x1 = 10; - * let y1 = 90; - * let x2 = mouseX; - * let y2 = mouseY; + * @method textLeading + * @param {Number} leading spacing between lines of text in units of pixels. + * @chainable * - * line(x1, y1, x2, y2); - * ellipse(x1, y1, 7, 7); - * ellipse(x2, y2, 7, 7); + * @example + *
      + * + * // "\n" starts a new line of text. + * let lines = 'one\ntwo'; * - * // d is the length of the line - * // the distance from point 1 to point 2. - * let d = dist(x1, y1, x2, y2); + * text(lines, 10, 25); * - * // 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! + * textLeading(30); + * text(lines, 70, 25); * - * describe(`2 ellipses joined by line. 1 ellipse moves with - * mouse X&Y. Distance displayed.`); - * } - *
      + * describe('The words "one" and "two" written on separate lines twice. The words on the left have less vertical spacing than the words on the right.'); + *
      + *
      */ /** - * @method 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 + * @method textLeading + * @return {Number} */ - _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]); - } + _main.default.prototype.textLeading = function (theLeading) { + var _this$_renderer2; + _main.default._validateParameters('textLeading', arguments); + return (_this$_renderer2 = this._renderer).textLeading.apply(_this$_renderer2, arguments); }; /** - * Returns Euler's number e (2.71828...) raised to the power of the n - * parameter. Maps to Math.exp(). - * - * @method exp - * @param {Number} n exponent to raise - * @return {Number} e^n - * @example - *
      - * function draw() { - * background(200); - * - * // Compute the exp() function with a value between 0 and 2 - * let xValue = map(mouseX, 0, width, 0, 2); - * let yValue = exp(xValue); - * - * let y = map(yValue, 0, 8, height, 0); + * Sets the font size when + * text() is called. Font size is measured in pixels. * - * 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); + * Calling `textSize()` without an arugment returns the current size. * - * // 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); - * } + * @method textSize + * @param {Number} size size of the letters in units of pixels + * @chainable * - * endShape(); - * line(0, 0, 0, height); - * line(0, height - 1, width, height - 1); + * @example + *
      + * + * textSize(12); + * text('Font Size 12', 10, 30); + * textSize(14); + * text('Font Size 14', 10, 60); + * textSize(16); + * text('Font Size 16', 10, 90); * - * describe('ellipse moves along a curve with mouse x. e^n displayed.'); - * } - *
      + * describe('The text "Font Size 12" drawn small, "Font Size 14" drawn medium, and "Font Size 16" drawn large.'); + *
      + *
      */ - _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 textSize + * @return {Number} + */ + _main.default.prototype.textSize = function (theSize) { + var _this$_renderer3; + _main.default._validateParameters('textSize', arguments); + return (_this$_renderer3 = this._renderer).textSize.apply(_this$_renderer3, arguments); + }; + /** + * Sets the style for system fonts when + * text() is called. `textStyle()` accepts the + * following values: `NORMAL`, `ITALIC`, `BOLD` or `BOLDITALIC`. * - * @method floor - * @param {Number} n number to round down - * @return {Integer} rounded down number - * @example - *
      - * function draw() { - * background(200); - * //map, mouseX between 0 and 5. - * let ax = map(mouseX, 0, 100, 0, 5); - * let ay = 66; - * - * //Get the floor of the mapped number. - * let bx = floor(map(mouseX, 0, 100, 0, 5)); - * let by = 33; + * `textStyle()` may be overridden by CSS styling. This function doesn't + * affect fonts loaded with loadFont(). * - * // 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); + * @method textStyle + * @param {Constant} style styling for text, either NORMAL, + * ITALIC, BOLD or BOLDITALIC + * @chainable + * @example + *
      + * + * textSize(12); + * textAlign(CENTER); * - * // Reformat the float returned by map and draw it. - * noStroke(); - * text(nfc(ax, 2), ax, ay - 5); - * text(nfc(bx, 1), bx, by - 5); + * textStyle(NORMAL); + * text('Normal', 50, 15); + * textStyle(ITALIC); + * text('Italic', 50, 40); + * textStyle(BOLD); + * text('Bold', 50, 65); + * textStyle(BOLDITALIC); + * text('Bold Italic', 50, 90); * - * describe(`2 horizontal lines & number sets. - * increase with mouse x. bottom to 2 decimals`); - * } - *
      + * describe('The words "Normal" displayed normally, "Italic" in italic, "Bold" in bold, and "Bold Italic" in bold italics.'); + *
      + *
      */ - _main.default.prototype.floor = Math.floor; /** - * Calculates a number between two numbers at a specific increment. The amt - * parameter is the amount to interpolate between the two values where 0.0 - * is equal to the first point, 0.1 is very near the first point, 0.5 is - * half-way in between, and 1.0 is equal to the second point. If the - * value of amt is more than 1.0 or less than 0.0, the number will be - * calculated accordingly in the ratio of the two given numbers. The lerp() - * function is convenient for creating motion along a straight - * path and for drawing dotted lines. + * @method 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); + }; + /** + * Returns the maximum width of a string of text drawn when + * text() is called. * - * @method lerp - * @param {Number} start first value - * @param {Number} stop second value - * @param {Number} amt number - * @return {Number} lerped value + * @method textWidth + * @param {String} str string of text to measure. + * @return {Number} width measured in units of pixels. * @example - *
      + *
      + * * function setup() { * background(200); - * let a = 20; - * let b = 80; - * let c = lerp(a, b, 0.2); - * let d = lerp(a, b, 0.5); - * let e = lerp(a, b, 0.8); - * - * let y = 50; - * - * strokeWeight(5); - * stroke(0); // Draw the original points in black - * point(a, y); - * point(b, y); * - * stroke(100); // Draw the lerp points in gray - * point(c, y); - * point(d, y); - * point(e, y); + * textSize(28); + * strokeWeight(0.5); + * let s = 'yoyo'; + * let w = textWidth(s); + * text(s, 22, 55); + * line(22, 55, 22 + w, 55); * - * describe(`5 points horizontally staggered mid-canvas. - * mid 3 are grey, outer black`); + * describe('The word "yoyo" underlined.'); * } - *
      - */ - _main.default.prototype.lerp = function (start, stop, amt) { - _main.default._validateParameters('lerp', arguments); - return amt * (stop - start) + start; - }; - /** - * Calculates the natural logarithm (the base-e logarithm) of a number. This - * function expects the n parameter to be a value greater than 0.0. Maps to - * Math.log(). + *
      + *
      * - * @method log - * @param {Number} n number greater than 0 - * @return {Number} natural logarithm of n - * @example - *
      - * function draw() { + *
      + * + * function setup() { * 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); + * textSize(28); + * strokeWeight(0.5); + * // "\n" starts a new line. + * let s = 'yo\nyo'; + * let w = textWidth(s); + * text(s, 22, 55); + * line(22, 55, 22 + w, 55); * - * describe(`ellipse moves along a curve with mouse x. - * natural logarithm of n displayed.`); + * describe('The word "yo" written twice, one copy beneath the other. The words are divided by a horizontal line.'); * } - *
      + *
      + *
      */ - _main.default.prototype.log = Math.log; + _main.default.prototype.textWidth = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + args[0] += ''; + _main.default._validateParameters('textWidth', args); + if (args[0].length === 0) { + return 0; + } // Only use the line with the longest width, and replace tabs with double-space + + var textLines = args[0].replace(/\t/g, ' ').split(/\r?\n|\r|\n/g); + var newArr = [ + ]; + // Return the textWidth for every line + for (var i = 0; i < textLines.length; i++) { + newArr.push(this._renderer.textWidth(textLines[i])); + } // Return the largest textWidth + + var largestWidth = Math.max.apply(Math, newArr); + return largestWidth; + }; /** - * Calculates the magnitude (or length) of a vector. A vector is a direction - * in space commonly used in computer graphics and linear algebra. Because it - * has no "start" position, the magnitude of a vector can be thought of as - * the distance from the coordinate 0,0 to its x,y value. Therefore, mag() is - * a shortcut for writing dist(0, 0, x, y). + * 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 mag - * @param {Number} a first value - * @param {Number} b second value - * @return {Number} magnitude of vector from (0,0) to (a,b) + * @method textAscent + * @return {Number} ascent measured in units of pixels. * @example - *
      - * function setup() { - * let x1 = 20; - * let x2 = 80; - * let y1 = 30; - * let y2 = 70; - * - * line(0, 0, x1, y1); - * print(mag(x1, y1)); // Prints "36.05551275463989" - * line(0, 0, x2, y1); - * print(mag(x2, y1)); // Prints "85.44003745317531" - * line(0, 0, x1, y2); - * print(mag(x1, y2)); // Prints "72.80109889280519" - * line(0, 0, x2, y2); - * print(mag(x2, y2)); // Prints "106.3014581273465" - * - * describe('4 lines of different length radiate from top left of canvas.'); + *
      + * + * let font; + * + * function preload() { + * font = loadFont('assets/inconsolata.otf'); * } - *
      - */ - _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). + * function setup() { + * background(200); + * textFont(font); * - * @method map - * @param {Number} value the incoming value to be converted - * @param {Number} start1 lower bound of the value's current range - * @param {Number} stop1 upper bound of the value's current range - * @param {Number} start2 lower bound of the value's target range - * @param {Number} stop2 upper bound of the value's target range - * @param {Boolean} [withinBounds] constrain the value to the newly mapped range - * @return {Number} remapped number - * @example - *
      - * let value = 25; - * let m = map(value, 0, 100, 0, width); - * ellipse(m, 50, 10, 10); - * describe('10×10 white ellipse with in mid left canvas'); -
      - * - *
      - * function setup() { - * noStroke(); - * } + * // Different for each font. + * let fontScale = 0.8; * - * 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); + * let baseY = 75; + * strokeWeight(0.5); * - * describe(`Two 25×25 white ellipses move with mouse x. - * Bottom has more range from X`); - * } -
      - */ - _main.default.prototype.map = function (n, start1, stop1, start2, stop2, withinBounds) { - _main.default._validateParameters('map', arguments); - var newval = (n - start1) / (stop1 - start1) * (stop2 - start2) + start2; - if (!withinBounds) { - return newval; - } - if (start2 < stop2) { - return this.constrain(newval, start2, stop2); - } else { - return this.constrain(newval, stop2, start2); - } - }; - /** - * Determines the largest value in a sequence of numbers, and then returns - * that value. max() accepts any number of Number parameters, or an Array - * of any length. + * // Draw small text. + * textSize(24); + * text('dp', 0, baseY); + * // Draw baseline and ascent. + * let a = textAscent() * fontScale; + * line(0, baseY, 23, baseY); + * line(23, baseY - a, 23, baseY); * - * @method max - * @param {Number} n0 Number to compare - * @param {Number} n1 Number to compare - * @return {Number} maximum Number - * @example - *
      - * function setup() { - * // Change the elements in the array and run the sketch - * // to show how max() works! - * let numArray = [2, 1, 5, 4, 8, 9]; - * fill(0); - * noStroke(); - * text('Array Elements', 0, 10); - * // Draw all numbers in the array - * let spacing = 15; - * let elemsY = 25; - * for (let i = 0; i < numArray.length; i++) { - * text(numArray[i], i * spacing, elemsY); - * } - * let maxX = 33; - * let maxY = 80; - * // Draw the Maximum value in the array. - * textSize(32); - * text(max(numArray), maxX, maxY); + * // Draw large text. + * textSize(48); + * text('dp', 45, baseY); + * // Draw baseline and ascent. + * a = textAscent() * fontScale; + * line(45, baseY, 91, baseY); + * line(91, baseY - a, 91, baseY); * - * describe(`Small text at top reads: Array Elements 2 1 5 4 8 9. - * Large text at center: 9`); + * describe('The letters "dp" written twice in different sizes. Each version has a horizontal baseline. A vertical line extends upward from each baseline to the top of the "d".'); * } - *
      - */ - /** - * @method max - * @param {Number[]} nums Numbers to compare - * @return {Number} + *
      + *
      */ - _main.default.prototype.max = function () { + _main.default.prototype.textAscent = 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); - } + _main.default._validateParameters('textAscent', args); + return this._renderer.textAscent(); }; /** - * Determines the smallest value in a sequence of numbers, and then returns - * that value. min() accepts any number of Number parameters, or an Array - * of any length. + * 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 min - * @param {Number} n0 Number to compare - * @param {Number} n1 Number to compare - * @return {Number} minimum Number + * @method textDescent + * @return {Number} descent measured in units of pixels. * @example - *
      - * function setup() { - * // Change the elements in the array and run the sketch - * // to show how min() works! - * let numArray = [2, 1, 5, 4, 8, 9]; - * fill(0); - * noStroke(); - * text('Array Elements', 0, 10); - * // Draw all numbers in the array - * let spacing = 15; - * let elemsY = 25; - * for (let i = 0; i < numArray.length; i++) { - * text(numArray[i], i * spacing, elemsY); - * } - * let maxX = 33; - * let maxY = 80; - * // Draw the Minimum value in the array. - * textSize(32); - * text(min(numArray), maxX, maxY); + *
      + * + * let font; * - * describe(`Small text at top reads: Array Elements 2 1 5 4 8 9. - * Large text at center: 1`); + * function preload() { + * font = loadFont('assets/inconsolata.otf'); * } - *
      - */ - /** - * @method min - * @param {Number[]} nums Numbers to compare - * @return {Number} - */ - _main.default.prototype.min = function () { - for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - args[_key3] = arguments[_key3]; - } - if (args[0] instanceof Array) { - return Math.min.apply(null, args[0]); - } else { - return Math.min.apply(null, args); - } - }; - /** - * Normalizes a number from another range into a value between 0 and 1. - * Identical to map(value, low, high, 0, 1). - * Numbers outside of the range are not clamped to 0 and 1, because - * out-of-range values are often intentional and useful. (See the example above.) * - * @method norm - * @param {Number} value incoming value to be normalized - * @param {Number} start lower bound of the value's current range - * @param {Number} stop upper bound of the value's current range - * @return {Number} normalized number - * @example - *
      - * function draw() { + * function setup() { * background(200); - * let currentNum = mouseX; - * let lowerBound = 0; - * let upperBound = width; //100; - * let normalized = norm(currentNum, lowerBound, upperBound); - * let lineY = 70; - * stroke(3); - * line(0, lineY, width, lineY); - * //Draw an ellipse mapped to the non-normalized value. - * noStroke(); - * fill(50); - * let s = 7; // ellipse size - * ellipse(currentNum, lineY, s, s); - * - * // Draw the guide - * let guideY = lineY + 15; - * text('0', 0, guideY); - * textAlign(RIGHT); - * text('100', width, guideY); - * - * // Draw the normalized value - * textAlign(LEFT); - * fill(0); - * textSize(32); - * let normalY = 40; - * let normalX = 20; - * text(normalized, normalX, normalY); - * - * describe(`ellipse moves with mouse. 0 shown left, 100 right, - * and updating values center`); - * } - *
      - */ - _main.default.prototype.norm = function (n, start, stop) { - _main.default._validateParameters('norm', arguments); - return this.map(n, start, stop, 0, 1); - }; - /** - * Facilitates exponential expressions. The pow() function is an efficient - * way of multiplying numbers by themselves (or their reciprocals) in large - * quantities. For example, pow(3, 5) is equivalent to the expression - * 3 × 3 × 3 × 3 × 3 and pow(3, -5) is equivalent to 1 / - * 3 × 3 × 3 × 3 × 3. Maps to - * Math.pow(). - * - * @method pow - * @param {Number} n base of the exponential expression - * @param {Number} e power by which to raise the base - * @return {Number} n^e - * @example - *
      - * function setup() { - * //Exponentially increase the size of an ellipse. - * let eSize = 3; // Original Size - * let eLoc = 10; // Original Location - * - * ellipse(eLoc, eLoc, eSize, eSize); - * - * ellipse(eLoc * 2, eLoc * 2, pow(eSize, 2), pow(eSize, 2)); - * - * ellipse(eLoc * 4, eLoc * 4, pow(eSize, 3), pow(eSize, 3)); - * - * ellipse(eLoc * 8, eLoc * 8, pow(eSize, 4), pow(eSize, 4)); - * - * describe('small to large ellipses radiating from top left of canvas'); - * } - *
      - */ - _main.default.prototype.pow = Math.pow; - /** - * Calculates the integer closest to the n parameter. For example, - * round(133.8) returns the value 134. Maps to Math.round(). + * textFont(font); * - * @method round - * @param {Number} n number to round - * @param {Number} [decimals] number of decimal places to round to, default is 0 - * @return {Integer} rounded number - * @example - *
      - * let x = round(3.7); - * text(x, width / 2, height / 2); - * describe('"4" written in middle of canvas'); - *
      - *
      - * let x = round(12.782383, 2); - * text(x, width / 2, height / 2); - * describe('"12.78" written in middle of canvas'); - *
      - *
      - * function draw() { - * background(200); - * //map, mouseX between 0 and 5. - * let ax = map(mouseX, 0, 100, 0, 5); - * let ay = 66; + * // Different for each font. + * let fontScale = 0.9; * - * // Round the mapped number. - * let bx = round(map(mouseX, 0, 100, 0, 5)); - * let by = 33; + * let baseY = 75; + * strokeWeight(0.5); * - * // 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); + * // Draw small text. + * textSize(24); + * text('dp', 0, baseY); + * // Draw baseline and descent. + * let d = textDescent() * fontScale; + * line(0, baseY, 23, baseY); + * line(23, baseY, 23, baseY + d); * - * // Reformat the float returned by map and draw it. - * noStroke(); - * text(nfc(ax, 2), ax, ay - 5); - * text(nfc(bx, 1), bx, by - 5); + * // Draw large text. + * textSize(48); + * text('dp', 45, baseY); + * // Draw baseline and descent. + * d = textDescent() * fontScale; + * line(45, baseY, 91, baseY); + * line(91, baseY, 91, baseY + d); * - * describe('two horizontal lines rounded values displayed on top.'); + * describe('The letters "dp" written twice in different sizes. Each version has a horizontal baseline. A vertical line extends downward from each baseline to the bottom of the "p".'); * } - *
      + *
      + *
      */ - _main.default.prototype.round = function (n, decimals) { - if (!decimals) { - return Math.round(n); + _main.default.prototype.textDescent = function () { + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; } - var multiplier = Math.pow(10, decimals); - return Math.round(n * multiplier) / multiplier; + _main.default._validateParameters('textDescent', args); + return this._renderer.textDescent(); }; /** - * 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 - *
      - * 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); - * - * describe(`horizontal center line squared values displayed on - * top and regular on bottom.`); - * } - *
      + * Helper function to measure ascent and descent. */ - _main.default.prototype.sq = function (n) { - return n * n; + _main.default.prototype._updateTextMetrics = function () { + return this._renderer._updateTextMetrics(); }; /** - * 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 - *
      - * function draw() { - * background(200); - * let eSize = 7; - * let x1 = mouseX; - * let y1 = 80; - * let x2 = sqrt(x1); - * let y2 = 20; + * Sets the style for wrapping text when + * text() is called. `textWrap()` accepts the + * following values: * - * // Draw the non-squared. - * line(0, y1, width, y1); - * ellipse(x1, y1, eSize, eSize); + * `WORD` starts new lines of text at spaces. If a string of text doesn't + * have spaces, it may overflow the text box and the canvas. This is the + * default style. * - * // Draw the squared. - * line(0, y2, width, y2); - * ellipse(x2, y2, eSize, eSize); + * `CHAR` starts new lines as needed to stay within the text box. * - * // 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); + * `textWrap()` only works when the maximum width is set for a text box. For + * example, calling `text('Have a wonderful day', 0, 10, 100)` sets the + * maximum width to 100 pixels. * - * describe(`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. + * Calling `textWrap()` without an argument returns the current style. * - * @method fract - * @param {Number} num Number whose fractional part needs to be found out - * @returns {Number} fractional part of x, i.e, {x} + * @method textWrap + * @param {Constant} style text wrapping style, either WORD or CHAR. + * @return {String} style * @example - *
      - * text(7345.73472742, 10, 25); - * text(fract(7345.73472742), 10, 75); - * describe(`first row having a number and the second having - * the fractional part of the number`); - *
      + *
      + * + * textSize(20); + * textWrap(WORD); + * text('Have a wonderful day', 0, 10, 100); + * + *
      * - *
      - * text(1.4215e-15, 10, 25); - * text(fract(1.4215e-15), 10, 75); - * describe(`first row having a number expressed in scientific - * notation and the second having the fractional part of the number`); - *
      + *
      + * + * textSize(20); + * textWrap(CHAR); + * text('Have a wonderful day', 0, 10, 100); + * + *
      + * + *
      + * + * textSize(20); + * textWrap(CHAR); + * text('祝你有美好的一天', 0, 10, 100); + * + *
      */ - - _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; + _main.default.prototype.textWrap = function (wrapStyle) { + if (wrapStyle !== 'WORD' && wrapStyle !== 'CHAR') { + throw 'Error: textWrap accepts only WORD or CHAR'; } + return this._renderer.textWrap(wrapStyle); }; var _default = _main.default; exports.default = _default; }, { - '../core/main': 290, - 'core-js/modules/es.array.includes': 174, - 'core-js/modules/es.array.index-of': 175, - 'core-js/modules/es.array.map': 179, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.math.hypot': 185, - 'core-js/modules/es.number.constructor': 187, - 'core-js/modules/es.string.includes': 203 + '../core/main': 298, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.string.replace': 214, + 'core-js/modules/es.string.split': 216 } ], - 321: [ + 335: [ function (_dereq_, module, exports) { 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.last-index-of'); _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.reflect.construct'); - _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.last-index-of'); _dereq_('core-js/modules/es.array.slice'); - _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.reflect.construct'); - _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.split'); Object.defineProperty(exports, '__esModule', { value: true }); exports.default = void 0; var _main = _interopRequireDefault(_dereq_('../core/main')); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: - obj + 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 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 _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; } - } - 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; + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj }; } - return _construct.apply(null, arguments); - } - function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { }; - return _setPrototypeOf(o, p); - } /** - * Creates a new p5.Vector (the datatype for storing vectors). This provides a - * two or three-dimensional vector, specifically a Euclidean (also known as - * geometric) vector. A vector is an entity that has both magnitude and - * direction. - * - * @method createVector - * @param {Number} [x] x component of the vector - * @param {Number} [y] y component of the vector - * @param {Number} [z] z component of the vector - * @return {p5.Vector} - * @example - *
      - * let v1; - * function setup() { - * createCanvas(100, 100); - * stroke(255, 0, 255); - * v1 = createVector(width / 2, height / 2); - * } - * - * function draw() { - * background(255); - * line(v1.x, v1.y, mouseX, mouseY); - * describe('draws a line from center of canvas to mouse pointer position.'); - * } - *
      - */ - - _main.default.prototype.createVector = function (x, y, z) { - if (this instanceof _main.default) { - return _construct(_main.default.Vector, [ - this._fromRadians.bind(this), - this._toRadians.bind(this) - ].concat(Array.prototype.slice.call(arguments))); - } else { - return new _main.default.Vector(x, y, z); + var 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]; + } + } } - }; - var _default = _main.default; - exports.default = _default; - }, - { - '../core/main': 290, - 'core-js/modules/es.array.concat': 167, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.reflect.construct': 197, - 'core-js/modules/es.regexp.to-string': 200 - } - ], - 322: [ - function (_dereq_, module, exports) { - 'use strict'; - Object.defineProperty(exports, '__esModule', { - value: true - }); - exports.default = void 0; - var _main = _interopRequireDefault(_dereq_('../core/main')); + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } 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 + } /** + * @module Typography + * @submodule Loading & Displaying * @for p5 * @requires core */ - - var PERLIN_YWRAPB = 4; - var PERLIN_YWRAP = 1 << PERLIN_YWRAPB; - var PERLIN_ZWRAPB = 8; - var PERLIN_ZWRAP = 1 << PERLIN_ZWRAPB; - var PERLIN_SIZE = 4095; - var perlin_octaves = 4; // default to medium smooth - var perlin_amp_falloff = 0.5; // 50% reduction/octave - var scaled_cosine = function scaled_cosine(i) { - return 0.5 * (1 - Math.cos(i * Math.PI)); - }; - var perlin; // will be initialized lazily by noise() or noiseSeed() /** - * Returns the Perlin noise value at specified coordinates. Perlin noise is - * a random sequence generator producing a more naturally ordered, harmonic - * succession of numbers compared to the standard random() function. - * It was invented by Ken Perlin in the 1980s and been used since in - * graphical applications to produce procedural textures, natural motion, - * shapes, terrains etc.

      The main difference to the - * random() function is that Perlin noise is defined in an infinite - * n-dimensional space where each pair of coordinates corresponds to a - * fixed semi-random value (fixed only for the lifespan of the program; see - * the noiseSeed() function). p5.js can compute 1D, 2D and 3D noise, - * depending on the number of coordinates given. The resulting value will - * always be between 0.0 and 1.0. The noise value can be animated by moving - * through the noise space as demonstrated in the example above. The 2nd - * and 3rd dimensions can also be interpreted as time.

      The actual - * noise is structured similar to an audio signal, in respect to the - * function's use of frequencies. Similar to the concept of harmonics in - * physics, Perlin noise is computed over several octaves which are added - * together for the final result.

      Another way to adjust the - * character of the resulting sequence is the scale of the input - * coordinates. As the function works within an infinite space the value of - * the coordinates doesn't matter as such, only the distance between - * successive coordinates does (eg. when using noise() within a - * loop). As a general rule the smaller the difference between coordinates, - * the smoother the resulting noise sequence will be. Steps of 0.005-0.03 - * work best for most applications, but this will differ depending on use. + * Loads a font and creates a p5.Font object. + * `loadFont()` can load fonts in either .otf or .ttf format. Loaded fonts can + * be used to style text on the canvas and in HTML elements. * - * @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 + * The first parameter, `path`, is the path to a font file. + * Paths to local files should be relative. For example, + * `'assets/inconsolata.otf'`. The Inconsolata font used in the following + * examples can be downloaded for free + * here. + * Paths to remote files should be URLs. For example, + * `'https://example.com/inconsolata.otf'`. URLs may be blocked due to browser + * security. + * + * The second parameter, `successCallback`, is optional. If a function is + * passed, it will be called once the font has loaded. The callback function + * may use the new p5.Font object if needed. + * + * The third parameter, `failureCallback`, is also optional. If a function is + * passed, it will be called if the font fails to load. The callback function + * may use the error + * Event + * object if needed. + * + * Fonts can take time to load. Calling `loadFont()` in + * preload() ensures fonts load before they're + * used in setup() or + * draw(). + * + * @method loadFont + * @param {String} path path of the font to be loaded. + * @param {Function} [successCallback] function called with the + * p5.Font object after it + * loads. + * @param {Function} [failureCallback] function called with the error + * Event + * object if the font fails to load. + * @return {p5.Font} p5.Font object. * @example + * *
      * - * let xoff = 0.0; + * let font; * - * function draw() { - * background(204); - * xoff = xoff + 0.01; - * let n = noise(xoff) * width; - * line(n, 0, n, height); - * describe(`vertical line moves left to right with updating - * noise values.`); + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * fill('deeppink'); + * textFont(font); + * textSize(36); + * text('p5*js', 10, 50); + * + * describe('The text "p5*js" written in pink on a white background.'); * } * *
      + * *
      - * let noiseScale=0.02; + * + * function setup() { + * loadFont('assets/inconsolata.otf', font => { + * fill('deeppink'); + * textFont(font); + * textSize(36); + * text('p5*js', 10, 50); * - * 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); - * } - * describe(`horizontal wave pattern effected by mouse x-position - * & updating noise values.`); + * describe('The text "p5*js" written in pink on a white background.'); + * }); + * } + * + *
      + * + *
      + * + * function setup() { + * loadFont('assets/inconsolata.otf', success, failure); + * } + * + * function success(font) { + * fill('deeppink'); + * textFont(font); + * textSize(36); + * text('p5*js', 10, 50); + * + * describe('The text "p5*js" written in pink on a white background.'); + * } + * + * function failure(event) { + * console.error('Oops!', event); + * } + * + *
      + * + *
      + * + * function preload() { + * loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * let p = createP('p5*js'); + * p.style('color', 'deeppink'); + * p.style('font-family', 'Inconsolata'); + * p.style('font-size', '36px'); + * p.position(10, 50); + * + * describe('The text "p5*js" written in pink on a white background.'); * } * *
      */ - _main.default.prototype.noise = function (x) { - var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - var z = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; - if (perlin == null) { - perlin = new Array(PERLIN_SIZE + 1); - for (var i = 0; i < PERLIN_SIZE + 1; i++) { - perlin[i] = Math.random(); - } - } - if (x < 0) { - x = - x; - } - if (y < 0) { - y = - y; - } - if (z < 0) { - z = - z; - } - var xi = Math.floor(x), - yi = Math.floor(y), - zi = Math.floor(z); - var xf = x - xi; - var yf = y - yi; - var zf = z - zi; - var rxf, - ryf; - var r = 0; - var ampl = 0.5; - var n1, - n2, - n3; - for (var o = 0; o < perlin_octaves; o++) { - var of = xi + (yi << PERLIN_YWRAPB) + (zi << PERLIN_ZWRAPB); - rxf = scaled_cosine(xf); - ryf = scaled_cosine(yf); - n1 = perlin[of & PERLIN_SIZE]; - n1 += rxf * (perlin[of + 1 & PERLIN_SIZE] - n1); - n2 = perlin[of + PERLIN_YWRAP & PERLIN_SIZE]; - n2 += rxf * (perlin[of + PERLIN_YWRAP + 1 & PERLIN_SIZE] - n2); - n1 += ryf * (n2 - n1); - of += PERLIN_ZWRAP; - n2 = perlin[of & PERLIN_SIZE]; - n2 += rxf * (perlin[of + 1 & PERLIN_SIZE] - n2); - n3 = perlin[of + PERLIN_YWRAP & PERLIN_SIZE]; - n3 += rxf * (perlin[of + PERLIN_YWRAP + 1 & PERLIN_SIZE] - n3); - n2 += ryf * (n3 - n2); - n1 += scaled_cosine(zf) * (n2 - n1); - r += n1 * ampl; - ampl *= perlin_amp_falloff; - xi <<= 1; - xf *= 2; - yi <<= 1; - yf *= 2; - zi <<= 1; - zf *= 2; - if (xf >= 1) { - xi++; - xf--; + + _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; } - if (yf >= 1) { - yi++; - yf--; + p5Font.font = font; + if (typeof onSuccess !== 'undefined') { + onSuccess(p5Font); } - if (zf >= 1) { - zi++; - zf--; + self._decrementPreload(); + // check that we have an acceptable font type + var validFontTypes = [ + 'ttf', + 'otf', + 'woff', + 'woff2' + ]; + var fileNoPath = path.split('\\').pop().split('/').pop(); + var lastDotIdx = fileNoPath.lastIndexOf('.'); + var fontFamily; + var newStyle; + var fileExt = lastDotIdx < 1 ? null : fileNoPath.slice(lastDotIdx + 1); + // if so, add it to the DOM (name-only) for use with DOM module + if (validFontTypes.includes(fileExt)) { + fontFamily = fileNoPath.slice(0, lastDotIdx !== - 1 ? lastDotIdx : 0); + newStyle = document.createElement('style'); + newStyle.appendChild(document.createTextNode('\n@font-face {\nfont-family: '.concat(fontFamily, ';\nsrc: url(').concat(path, ');\n}\n'))); + document.head.appendChild(newStyle); } - } - return r; + }); + return p5Font; }; /** + * Draws text to the canvas. * - * 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. + * The first parameter, `str`, is the text to be drawn. The second and third + * parameters, `x` and `y`, set the coordinates of the text's bottom-left + * corner. See textAlign() for other ways to + * align text. * - * By default, noise is computed over 4 octaves with each octave contributing - * exactly half as much as its predecessor, starting at 50% strength for the 1st - * octave. This falloff amount can be changed by adding an additional function - * parameter. Eg. a falloff factor of 0.75 means each octave will now have - * 75% impact (25% less) of the previous lower octave. Any value between - * 0.0 and 1.0 is valid, however, note that values greater than 0.5 might - * result in greater than 1.0 values returned by noise(). + * The fourth and fifth parameters, `maxWidth` and `maxHeight`, are optional. + * They set the dimensions of the invisible rectangle containing the text. By + * default, they set its maximum width and height. See + * rectMode() for other ways to define the + * rectangular text box. Text will wrap to fit within the text box. Text + * outside of the box won't be drawn. * - * By changing these parameters, the signal created by the noise() - * function can be adapted to fit very specific needs and characteristics. + * Text can be styled a few ways. Call the fill() + * function to set the text's fill color. Call + * stroke() and + * strokeWeight() to set the text's outline. + * Call textSize() and + * textFont() to set the text's size and font, + * respectively. * - * @method noiseDetail - * @param {Number} lod number of octaves to be used by the noise - * @param {Number} falloff falloff factor for each octave + * Note: `WEBGL` mode only supports fonts loaded with + * loadFont(). Calling + * stroke() has no effect in `WEBGL` mode. + * + * @method text + * @param {String|Object|Array|Number|Boolean} str text to be displayed. + * @param {Number} x x-coordinate of the text box. + * @param {Number} y y-coordinate of the text box. + * @param {Number} [maxWidth] maximum width of the text box. See + * rectMode() for + * other options. + * @param {Number} [maxHeight] maximum height of the text box. See + * rectMode() for + * other options. + * + * @chainable * @example *
      * - * let noiseVal; - * let noiseScale = 0.02; + * function setup() { + * background(200); + * text('hi', 50, 50); + * + * describe('The text "hi" written in black in the middle of a gray square.'); + * } + * + *
      * + *
      + * * function setup() { - * createCanvas(100, 100); + * background('skyblue'); + * textSize(100); + * text('🌈', 0, 100); + * + * describe('A rainbow in a blue sky.'); + * } + * + *
      + * + *
      + * + * function setup() { + * textSize(32); + * fill(255); + * stroke(0); + * strokeWeight(4); + * text('hi', 50, 50); + * + * describe('The text "hi" written in white with a black outline.'); + * } + * + *
      + * + *
      + * + * function setup() { + * background('black'); + * textSize(22); + * fill('yellow'); + * text('rainbows', 6, 20); + * fill('cornflowerblue'); + * text('rainbows', 6, 45); + * fill('tomato'); + * text('rainbows', 6, 70); + * fill('limegreen'); + * text('rainbows', 6, 95); + * + * describe('The text "rainbows" written on several lines, each in a different color.'); + * } + * + *
      + * + *
      + * + * function setup() { + * background(200); + * let s = 'The quick brown fox jumps over the lazy dog.'; + * text(s, 10, 10, 70, 80); + * + * describe('The sample text "The quick brown fox..." written in black across several lines.'); + * } + * + *
      + * + *
      + * + * function setup() { + * background(200); + * rectMode(CENTER); + * let s = 'The quick brown fox jumps over the lazy dog.'; + * text(s, 50, 50, 70, 80); + * + * describe('The sample text "The quick brown fox..." written in black across several lines.'); + * } + * + *
      + * + *
      + * + * let font; + * + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * textFont(font); + * textSize(32); + * textAlign(CENTER, CENTER); * } * * function draw() { * background(0); - * 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); - * } - * } - * describe(`2 vertical grey smokey patterns affected by - * mouse x-position and noise.`); + * rotateY(frameCount / 30); + * text('p5*js', 0, 0); + * + * describe('The text "p5*js" written in white and spinning in 3D.'); * } * *
      */ - _main.default.prototype.noiseDetail = function (lod, falloff) { - if (lod > 0) { - perlin_octaves = lod; - } - if (falloff > 0) { - perlin_amp_falloff = falloff; - } + _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 seed value for noise(). By default, - * noise() produces different results each time - * the program is run. Set the `seed` parameter to a constant to return - * the same pseudo-random numbers each time the software is run. + * Sets the font used by the text() function. + * + * The first parameter, `font`, sets the font. `textFont()` recognizes either + * a p5.Font object or a string with the name of a + * system font. For example, `'Courier New'`. + * + * The second parameter, `size`, is optional. It sets the font size in pixels. + * This has the same effect as calling textSize(). + * + * Note: `WEBGL` mode only supports fonts loaded with + * loadFont(). + * + * @method textFont + * @return {Object} current font or p5 Object. * - * @method noiseSeed - * @param {Number} seed the seed value * @example *
      - * let xoff = 0.0; + * + * function setup() { + * background(200); + * textFont('Courier New'); + * textSize(24); + * text('hi', 35, 55); + * + * describe('The text "hi" written in a black, monospace font on a gray background.'); + * } + * + *
      + * + *
      + * + * function setup() { + * background('black'); + * fill('palegreen'); + * textFont('Courier New', 10); + * text('You turn to the left and see a door. Do you enter?', 5, 5, 90, 90); + * text('>', 5, 70); + * + * describe('A text prompt from a game is written in a green, monospace font on a black background.'); + * } + * + *
      * + *
      + * * function setup() { - * noiseSeed(99); - * stroke(0, 10); + * background(200); + * textFont('Verdana'); + * let currentFont = textFont(); + * text(currentFont, 25, 50); + * + * describe('The text "Verdana" written in a black, sans-serif font on a gray background.'); + * } + * + *
      + * + *
      + * + * let fontRegular; + * let fontItalic; + * let fontBold; + * + * function preload() { + * fontRegular = loadFont('assets/Regular.otf'); + * fontItalic = loadFont('assets/Italic.ttf'); + * fontBold = loadFont('assets/Bold.ttf'); * } * - * function draw() { - * xoff = xoff + .01; - * let n = noise(xoff) * width; - * line(n, 0, n, height); - * describe(`vertical grey lines drawing in pattern affected by noise.`); + * function setup() { + * background(200); + * textFont(fontRegular); + * text('I am Normal', 10, 30); + * textFont(fontItalic); + * text('I am Italic', 10, 50); + * textFont(fontBold); + * text('I am Bold', 10, 70); + * + * describe('The statements "I am Normal", "I am Italic", and "I am Bold" written in black on separate lines. The statements have normal, italic, and bold fonts, respectively.'); * } * *
      */ - _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; + /** + * @method textFont + * @param {Object|String} font font as a p5.Font object or a string. + * @param {Number} [size] font size in pixels. + * @chainable + */ + _main.default.prototype.textFont = function (theFont, theSize) { + _main.default._validateParameters('textFont', arguments); + if (arguments.length) { + if (!theFont) { + throw new Error('null font passed to textFont'); + } + this._renderer._setProperty('_textFont', theFont); + if (theSize) { + this._renderer._setProperty('_textSize', theSize); + if (!this._renderer._leadingSet) { + // only use a default value if not previously set (#5181) + this._renderer._setProperty('_textLeading', theSize * constants._DEFAULT_LEADMULT); } - }; - }(); - lcg.setSeed(seed); - perlin = new Array(PERLIN_SIZE + 1); - for (var i = 0; i < PERLIN_SIZE + 1; i++) { - perlin[i] = lcg.rand(); + } + return this._renderer._applyTextProperties(); } + return this._renderer._textFont; }; var _default = _main.default; exports.default = _default; }, { - '../core/main': 290 + '../core/constants': 286, + '../core/friendly_errors/fes_core': 289, + '../core/friendly_errors/file_errors': 290, + '../core/friendly_errors/validate_params': 293, + '../core/main': 298, + 'core-js/modules/es.array.concat': 169, + 'core-js/modules/es.array.includes': 177, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.last-index-of': 181, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.string.split': 216, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256, + 'opentype.js': 271 } ], - 323: [ + 336: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); _dereq_('core-js/modules/es.symbol.description'); _dereq_('core-js/modules/es.symbol.iterator'); _dereq_('core-js/modules/es.array.concat'); - _dereq_('core-js/modules/es.array.every'); + _dereq_('core-js/modules/es.array.fill'); _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.join'); _dereq_('core-js/modules/es.array.slice'); - _dereq_('core-js/modules/es.array.some'); - _dereq_('core-js/modules/es.math.sign'); - _dereq_('core-js/modules/es.number.constructor'); - _dereq_('core-js/modules/es.number.is-finite'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.number.to-fixed'); _dereq_('core-js/modules/es.object.get-own-property-descriptor'); _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); _dereq_('core-js/modules/es.string.iterator'); - _dereq_('core-js/modules/es.string.sub'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); _dereq_('core-js/modules/es.weak-map'); _dereq_('core-js/modules/web.dom-collections.iterator'); function _typeof2(obj) { @@ -87088,28 +99413,23 @@ } return _typeof2(obj); } - function _typeof(obj) { - if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { - _typeof = function _typeof(obj) { - return _typeof2(obj); - }; - } else { - _typeof = function _typeof(obj) { - return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); - }; - } - return _typeof(obj); - } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); _dereq_('core-js/modules/es.array.concat'); - _dereq_('core-js/modules/es.array.every'); + _dereq_('core-js/modules/es.array.fill'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.join'); _dereq_('core-js/modules/es.array.slice'); - _dereq_('core-js/modules/es.array.some'); - _dereq_('core-js/modules/es.math.sign'); - _dereq_('core-js/modules/es.number.constructor'); - _dereq_('core-js/modules/es.number.is-finite'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.number.to-fixed'); _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.regexp.to-string'); - _dereq_('core-js/modules/es.string.sub'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/web.dom-collections.iterator'); Object.defineProperty(exports, '__esModule', { value: true }); @@ -87162,2438 +99482,1432 @@ default: obj }; - } /** - * @module Math - * @submodule Vector - * @requires constants - */ - /** - * A class to describe a two or three-dimensional vector, specifically - * a Euclidean (also known as geometric) vector. A vector is an entity - * that has both magnitude and direction. The datatype, however, stores - * the components of the vector (`x`, `y` for 2D; or `x`, `y`, `z` for 3D). The magnitude - * and direction can be accessed via the methods p5.Vector.mag() and heading(). - * - * In many of the p5.js examples, you will see p5.Vector used to describe a - * position, velocity, or acceleration. For example, if you consider a rectangle - * moving across the screen, at any given instant it has a position (a vector - * that points from the origin to its location), a velocity (the rate at which - * the object's position changes per time unit, expressed as a vector), and - * acceleration (the rate at which the object's velocity changes per time - * unit, expressed as a vector). - * - * Since vectors represent groupings of values, we cannot simply use - * traditional addition/multiplication/etc. Instead, we'll need to do some - * "vector" math, which is made easy by the methods inside the p5.Vector class. - * - * @class p5.Vector - * @constructor - * @param {Number} [x] x component of the vector - * @param {Number} [y] y component of the vector - * @param {Number} [z] z component of the vector - * @example - *
      - * - * let v1 = createVector(40, 50); - * let v2 = createVector(40, 50); - * - * ellipse(v1.x, v1.y, 50, 50); - * ellipse(v2.x, v2.y, 50, 50); - * v1.add(v2); - * ellipse(v1.x, v1.y, 50, 50); - * - * describe(`2 white ellipses. One center-left the other - * bottom right and off canvas`); - * - *
      - */ - - _main.default.Vector = function Vector() { - var x, - y, - z; // This is how it comes in with createVector() - // This check if the first argument is a function - if ({ - }.toString.call(arguments[0]) === '[object Function]') { - // In this case the vector have an associated p5 instance - this.isPInst = true; - this._fromRadians = arguments[0]; - this._toRadians = arguments[1]; - x = arguments[2] || 0; - y = arguments[3] || 0; - z = arguments[4] || 0; // This is what we'll get with new p5.Vector() + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; } 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} + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } /** + * This module defines the p5.Font class and functions for + * drawing text to the display canvas. + * @module Typography + * @submodule Loading & Displaying + * @requires core + * @requires constants */ - 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} + * A class to describe fonts. + * @class p5.Font + * @constructor + * @param {p5} [pInst] pointer to p5 instance. * @example - *
      - * - * function setup() { - * let v = createVector(20, 30); - * print(String(v)); // prints "p5.Vector Object : [20, 30, 0]" - * } - * - *
      - * *
      * - * function draw() { - * background(240); - * - * let v0 = createVector(0, 0); - * let v1 = createVector(mouseX, mouseY); - * drawArrow(v0, v1, 'black'); - * - * noStroke(); - * text(v1.toString(), 10, 25, 90, 75); - * } - * - * // draw an arrow for a vector at a given base position - * function drawArrow(base, vec, myColor) { - * push(); - * stroke(myColor); - * strokeWeight(3); - * fill(myColor); - * translate(base.x, base.y); - * line(0, 0, vec.x, vec.y); - * rotate(vec.heading()); - * let arrowSize = 7; - * translate(vec.mag() - arrowSize, 0); - * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); - * pop(); - * } - * - *
      - */ - _main.default.Vector.prototype.toString = function p5VectorToString() { - return 'p5.Vector Object : ['.concat(this.x, ', ').concat(this.y, ', ').concat(this.z, ']'); - }; - /** - * Sets the `x`, `y`, and `z` components of the vector using two or three separate - * variables, the data from a p5.Vector, or the values from a float array. - * @method set - * @param {Number} [x] The x component of the vector - * @param {Number} [y] The y component of the vector - * @param {Number} [z] The z component of the vector - * @chainable - * @example - *
      - * - * function setup() { - * let v = createVector(1, 2, 3); - * v.set(4, 5, 6); // Sets vector to [4, 5, 6] + * let font; * - * let v1 = createVector(0, 0, 0); - * let arr = [1, 2, 3]; - * v1.set(arr); // Sets vector to [1, 2, 3] + * function preload() { + * // Creates a p5.Font object. + * font = loadFont('assets/inconsolata.otf'); * } - * - *
      * - *
      - * - * 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); - * } + * fill('deeppink'); + * textFont(font); + * textSize(36); + * text('p5*js', 10, 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(); + * describe('The text "p5*js" written in pink on a white background.'); * } * *
      */ - /** - * @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 p5.Vector object. - * - * @method copy - * @return {p5.Vector} A copy of the p5.Vector object - * @example - *
      - * - * 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" - * - *
      - */ - _main.default.Vector.prototype.copy = function copy() { - if (this.isPInst) { - return new _main.default.Vector(this._fromRadians, this._toRadians, this.x, this.y, this.z); - } else { - return new _main.default.Vector(this.x, this.y, this.z); - } - }; - /** - * Adds `x`, `y`, and `z` components to a vector, adds one vector to another, or - * adds two independent vectors together. The version of the method that adds - * two vectors together is a static method and returns a p5.Vector, the others - * act directly on the vector. Additionally, you may provide arguments to this method as an array. - * See the examples for more context. - * - * @method add - * @param {Number} x The x component of the vector to be added - * @param {Number} [y] The y component of the vector to be added - * @param {Number} [z] The z component of the vector to be added - * @chainable - * @example - *
      - * - * let v = createVector(1, 2, 3); - * v.add(4, 5, 6); - * // v's components are set to [5, 7, 9] - * - *
      - * - *
      - * - * let v = createVector(1, 2, 3); - * // Provide arguments as an array - * let arr = [4, 5, 6]; - * v.add(arr); - * // v's components are set to [5, 7, 9] - * - *
      - * - *
      - * - * // 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); - * - *
      - * - *
      - * - * // 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(); - * } - * - *
      - */ - /** - * @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 the 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 - *
      - * - * let v = createVector(3, 4, 5); - * v.rem(2, 3, 4); - * // v's components are set to [1, 1, 1] - * - *
      - *
      - * - * // 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); - * - *
      - */ - /** - * @method rem - * @param {p5.Vector | Number[]} value The divisor vector - * @chainable - */ - _main.default.Vector.prototype.rem = function rem(x, y, z) { - if (x instanceof _main.default.Vector) { - if (Number.isFinite(x.x) && Number.isFinite(x.y) && Number.isFinite(x.z)) { - var xComponent = parseFloat(x.x); - var yComponent = parseFloat(x.y); - var zComponent = parseFloat(x.z); - return calculateRemainder3D.call(this, xComponent, yComponent, zComponent); - } - } else if (x instanceof Array) { - if (x.every(function (element) { - return Number.isFinite(element); - })) { - if (x.length === 2) { - return calculateRemainder2D.call(this, x[0], x[1]); + + _main.default.Font = /*#__PURE__*/ function () { + function _class(p) { + _classCallCheck(this, _class); + this.parent = p; + this.cache = { + }; + /** + * Underlying + * opentype.js + * font object. + * @property font + * @name font + */ + this.font = undefined; + } /** + * Returns the bounding box for a string of text written using this + * p5.Font. + * + * The first parameter, `str`, is a string of text. The second and third + * parameters, `x` and `y`, are the text's position. By default, they set the + * coordinates of the bounding box's bottom-left corner. See + * textAlign() for more ways to align text. + * + * The fourth parameter, `fontSize`, is optional. It sets the font size used to + * determine the bounding box. By default, `font.textBounds()` will use the + * current textSize(). + * + * @method textBounds + * @param {String} str string of text. + * @param {Number} x x-coordinate of the text. + * @param {Number} y y-coordinate of the text. + * @param {Number} [fontSize] font size. Defaults to the current + * textSize(). + * @return {Object} object describing the bounding box with + * properties x, y, w, and h. + * + * @example + *
      + * + * let font; + * + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * background(200); + * + * let bbox = font.textBounds('p5*js', 35, 53); + * rect(bbox.x, bbox.y, bbox.w, bbox.h); + * + * textFont(font); + * text('p5*js', 35, 53); + * + * describe('The text "p5*js" written in black inside a white rectangle.'); + * } + * + *
      + * + *
      + * + * let font; + * + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * background(200); + * + * textFont(font); + * textSize(15); + * textAlign(CENTER, CENTER); + * + * let bbox = font.textBounds('p5*js', 50, 50); + * rect(bbox.x, bbox.y, bbox.w, bbox.h); + * + * text('p5*js', 50, 50); + * + * describe('The text "p5*js" written in black inside a white rectangle.'); + * } + * + *
      + * + *
      + * + * let font; + * + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * background(200); + * + * let bbox = font.textBounds('p5*js', 31, 53, 15); + * rect(bbox.x, bbox.y, bbox.w, bbox.h); + * + * textFont(font); + * textSize(15); + * text('p5*js', 31, 53); + * + * describe('The text "p5*js" written in black inside a white rectangle.'); + * } + * + *
      + */ + + _createClass(_class, [ + { + key: 'textBounds', + value: function textBounds(str) { + var x = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var y = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var fontSize = arguments.length > 3 ? arguments[3] : undefined; + var opts = arguments.length > 4 ? arguments[4] : undefined; + // Check cache for existing bounds. Take into consideration the text alignment + // settings. Default alignment should match opentype's origin: left-aligned & + // alphabetic baseline. + var p = opts && opts.renderer && opts.renderer._pInst || this.parent; + var ctx = p._renderer.drawingContext; + var alignment = ctx.textAlign || constants.LEFT; + var baseline = ctx.textBaseline || constants.BASELINE; + var cacheResults = false; + var result; + var key; + fontSize = fontSize || p._renderer._textSize; + // NOTE: cache disabled for now pending further discussion of #3436 + if (cacheResults) { + key = cacheKey('textBounds', str, x, y, fontSize, alignment, baseline); + result = this.cache[key]; + } + if (!result) { + var minX = [ + ]; + var minY; + var maxX = [ + ]; + var maxY; + var pos; + var xCoords = [ + ]; + xCoords[0] = [ + ]; + var yCoords = [ + ]; + var scale = this._scale(fontSize); + var lineHeight = p._renderer.textLeading(); + var lineCount = 0; + this.font.forEachGlyph(str, x, y, fontSize, opts, function (glyph, gX, gY, gFontSize) { + var gm = glyph.getMetrics(); + if (glyph.index === 0 || 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; + } /** + * Returns an array of points outlining a string of text written using this + * p5.Font. + * + * The first parameter, `str`, is a string of text. The second and third + * parameters, `x` and `y`, are the text's position. By default, they set the + * coordinates of the bounding box's bottom-left corner. See + * textAlign() for more ways to align text. + * + * The fourth parameter, `fontSize`, is optional. It sets the text's font + * size. By default, `font.textToPoints()` will use the current + * textSize(). + * + * The fifth parameter, `options`, is also optional. `font.textToPoints()` + * expects an object with the following properties: + * + * `sampleFactor` is the ratio of the text's path length to the number of + * samples. It defaults to 0.1. Higher values produce more points along the + * path and are more precise. + * + * `simplifyThreshold` removes collinear points if it's set to a number other + * than 0. The value represents the threshold angle to use when determining + * whether two edges are collinear. + * + * @method textToPoints + * @param {String} str string of text. + * @param {Number} x x-coordinate of the text. + * @param {Number} y y-coordinate of the text. + * @param {Number} [fontSize] font size. Defaults to the current + * textSize(). + * @param {Object} [options] object with sampleFactor and simplifyThreshold + * properties. + * @return {Array} array of point objects, each with x, y, and alpha (path angle) properties. + * @example + *
      + * + * let font; + * + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * background(200); + * let points = font.textToPoints('p5*js', 6, 60, 35, { sampleFactor: 0.5 }); + * points.forEach(p => { + * point(p.x, p.y); + * }); + * + * describe('A set of black dots outlining the text "p5*js" on a gray background.'); + * } + * + *
      + */ + + }, + { + key: 'textToPoints', + value: function textToPoints(txt, x, y, fontSize, options) { + var xOriginal = x; + var result = [ + ]; + var lines = txt.split(/\r?\n|\r|\n/g); + fontSize = fontSize || this.parent._renderer._textSize; + function isSpace(i, text, glyphsLine) { + return glyphsLine[i].name && glyphsLine[i].name === 'space' || text.length === glyphsLine.length && text[i] === ' ' //|| + //(glyphs[i].index && glyphs[i].index === 3) + ; + } + for (var i = 0; i < lines.length; i++) { + var xoff = 0; + x = xOriginal; + var line = lines[i]; + line = line.replace('\t', ' '); + var glyphs = this._getGlyphs(line); + for (var j = 0; j < glyphs.length; j++) { + if (!isSpace(j, line, glyphs)) { + // fix to #1817, #2069 + var gpath = glyphs[j].getPath(x, y, fontSize), + paths = splitPaths(gpath.commands); + for (var k = 0; k < paths.length; k++) { + var pts = pathToPoints(paths[k], options); + for (var l = 0; l < pts.length; l++) { + pts[l].x += xoff; + result.push(pts[l]); + } + } + } + xoff += glyphs[j].advanceWidth * this._scale(fontSize); + } + y = y + this.parent._renderer._textLeading; + } + return result; + } // ----------------------------- End API ------------------------------ + /** + * Returns the set of opentype glyphs for the supplied string. + * + * Note that there is not a strict one-to-one mapping between characters + * and glyphs, so the list of returned glyphs can be larger or smaller + * than the length of the given string. + * + * @private + * @param {String} str the string to be converted + * @return {Array} the opentype glyphs + */ + + }, + { + key: '_getGlyphs', + value: function _getGlyphs(str) { + return this.font.stringToGlyphs(str); + } /** + * Returns an opentype path for the supplied string and position. + * + * @private + * @param {String} line a line of text + * @param {Number} x x-position + * @param {Number} y y-position + * @param {Object} options opentype options (optional) + * @return {Object} the opentype path + */ + + }, + { + key: '_getPath', + value: function _getPath(line, x, y, options) { + var p = options && options.renderer && options.renderer._pInst || this.parent, + renderer = p._renderer, + pos = this._handleAlignment(renderer, line, x, y); + return this.font.getPath(line, pos.x, pos.y, renderer._textSize, options); + } /* + * Creates an SVG-formatted path-data string + * (See http://www.w3.org/TR/SVG/paths.html#PathData) + * from the given opentype path or string/position + * + * @param {Object} path an opentype path, OR the following: + * + * @param {String} line a line of text + * @param {Number} x x-position + * @param {Number} y y-position + * @param {Object} options opentype options (optional), set options.decimals + * to set the decimal precision of the path-data + * + * @return {Object} this p5.Font object + */ + + }, + { + key: '_getPathData', + value: function _getPathData(line, x, y, options) { + var decimals = 3; + // create path from string/position + if (typeof line === 'string' && arguments.length > 2) { + line = this._getPath(line, x, y, options); + } else if (_typeof(x) === 'object') { + // handle options specified in 2nd arg + options = x; + } // handle svg arguments + + if (options && typeof options.decimals === 'number') { + decimals = options.decimals; + } + return line.toPathData(decimals); + } /* + * Creates an SVG element, as a string, + * from the given opentype path or string/position + * + * @param {Object} path an opentype path, OR the following: + * + * @param {String} line a line of text + * @param {Number} x x-position + * @param {Number} y y-position + * @param {Object} options opentype options (optional), set options.decimals + * to set the decimal precision of the path-data in the element, + * options.fill to set the fill color for the element, + * options.stroke to set the stroke color for the element, + * options.strokeWidth to set the strokeWidth for the element. + * + * @return {Object} this p5.Font object + */ + + }, + { + key: '_getSVG', + value: function _getSVG(line, x, y, options) { + var decimals = 3; + // create path from string/position + if (typeof line === 'string' && arguments.length > 2) { + line = this._getPath(line, x, y, options); + } else if (_typeof(x) === 'object') { + // handle options specified in 2nd arg + options = x; + } // handle svg arguments + + if (options) { + if (typeof options.decimals === 'number') { + decimals = options.decimals; + } + if (typeof options.strokeWidth === 'number') { + line.strokeWidth = options.strokeWidth; + } + if (typeof options.fill !== 'undefined') { + line.fill = options.fill; + } + if (typeof options.stroke !== 'undefined') { + line.stroke = options.stroke; + } + } + return line.toSVG(decimals); + } /* + * Renders an opentype path or string/position + * to the current graphics context + * + * @param {Object} path an opentype path, OR the following: + * + * @param {String} line a line of text + * @param {Number} x x-position + * @param {Number} y y-position + * @param {Object} options opentype options (optional) + * + * @return {p5.Font} this p5.Font object + */ + + }, + { + key: '_renderPath', + value: function _renderPath(line, x, y, options) { + var pdata; + var pg = options && options.renderer || this.parent._renderer; + var ctx = pg.drawingContext; + if (_typeof(line) === 'object' && line.commands) { + pdata = line.commands; + } else { + //pos = handleAlignment(p, ctx, line, x, y); + pdata = this._getPath(line, x, y, options).commands; + } + ctx.beginPath(); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = pdata[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var cmd = _step.value; + if (cmd.type === 'M') { + ctx.moveTo(cmd.x, cmd.y); + } else if (cmd.type === 'L') { + ctx.lineTo(cmd.x, cmd.y); + } else if (cmd.type === 'C') { + ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); + } else if (cmd.type === 'Q') { + ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y); + } else if (cmd.type === 'Z') { + ctx.closePath(); + } + } // only draw stroke if manually set by user + + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + if (pg._doStroke && pg._strokeSet && !pg._clipping) { + ctx.stroke(); + } + if (pg._doFill && !pg._clipping) { + // if fill hasn't been set by user, use default-text-fill + if (!pg._fillSet) { + pg._setFill(constants._DEFAULT_TEXT_FILL); + } + ctx.fill(); + } + return this; + } + }, + { + key: '_textWidth', + value: function _textWidth(str, fontSize) { + return this.font.getAdvanceWidth(str, fontSize); } - if (x.length === 3) { - return calculateRemainder3D.call(this, x[0], x[1], x[2]); + }, + { + key: '_textAscent', + value: function _textAscent(fontSize) { + return this.font.ascender * this._scale(fontSize); } - } - } else if (arguments.length === 1) { - if (Number.isFinite(arguments[0]) && arguments[0] !== 0) { - this.x = this.x % arguments[0]; - this.y = this.y % arguments[0]; - this.z = this.z % arguments[0]; - return this; - } - } else if (arguments.length === 2) { - var vectorComponents = Array.prototype.slice.call(arguments); - if (vectorComponents.every(function (element) { - return Number.isFinite(element); - })) { - if (vectorComponents.length === 2) { - return calculateRemainder2D.call(this, vectorComponents[0], vectorComponents[1]); + }, + { + key: '_textDescent', + value: function _textDescent(fontSize) { + return - this.font.descender * this._scale(fontSize); } - } - } else if (arguments.length === 3) { - var _vectorComponents = Array.prototype.slice.call(arguments); - if (_vectorComponents.every(function (element) { - return Number.isFinite(element); - })) { - if (_vectorComponents.length === 3) { - return calculateRemainder3D.call(this, _vectorComponents[0], _vectorComponents[1], _vectorComponents[2]); + }, + { + key: '_scale', + value: function _scale(fontSize) { + return 1 / this.font.unitsPerEm * (fontSize || this.parent._renderer._textSize); + } + }, + { + key: '_handleAlignment', + value: function _handleAlignment(renderer, line, x, y, textWidth) { + var fontSize = renderer._textSize; + if (typeof textWidth === 'undefined') { + textWidth = this._textWidth(line, fontSize); + } + switch (renderer._textAlign) { + case constants.CENTER: + x -= textWidth / 2; + break; + case constants.RIGHT: + x -= textWidth; + break; + } + switch (renderer._textBaseline) { + case constants.TOP: + y += this._textAscent(fontSize); + break; + case constants.CENTER: + y += this._textAscent(fontSize) / 2; + break; + case constants.BOTTOM: + y -= this._textDescent(fontSize); + break; + } + return { + x: x, + y: y + }; } } + ]); + return _class; + }(); + // path-utils + function pathToPoints(cmds, options) { + var opts = parseOpts(options, { + sampleFactor: 0.1, + simplifyThreshold: 0 + }); + var // total-length + len = pointAtLength(cmds, 0, 1), + t = len / (len * opts.sampleFactor), + pts = [ + ]; + for (var i = 0; i < len; i += t) { + pts.push(pointAtLength(cmds, i)); } - }; - /** - * Subtracts `x`, `y`, and `z` components from a vector, subtracts one vector from - * another, or subtracts two independent vectors. The version of the method - * that subtracts two vectors is a static method and returns a p5.Vector, the - * others act directly on the vector. Additionally, you may provide arguments to this method as an array. - * See the examples for more context. - * - * @method sub - * @param {Number} x The x component of the vector to subtract - * @param {Number} [y] The y component of the vector to subtract - * @param {Number} [z] The z component of the vector to subtract - * @chainable - * @example - *
      - * - * let v = createVector(4, 5, 6); - * v.sub(1, 1, 1); - * // v's components are set to [3, 4, 5] - * - *
      - * - *
      - * - * let v = createVector(4, 5, 6); - * // Provide arguments as an array - * let arr = [1, 1, 1]; - * v.sub(arr); - * // v's components are set to [3, 4, 5] - * - *
      - * - *
      - * - * // 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); - * - *
      - * - *
      - * - * // red vector - blue vector = purple vector - * function draw() { - * background(240); - * - * let v0 = createVector(0, 0); - * let v1 = createVector(70, 50); - * drawArrow(v0, v1, 'red'); - * - * let v2 = createVector(mouseX, mouseY); - * drawArrow(v0, v2, 'blue'); - * - * let v3 = p5.Vector.sub(v1, v2); - * drawArrow(v2, v3, 'purple'); - * } - * - * // draw an arrow for a vector at a given base position - * function drawArrow(base, vec, myColor) { - * push(); - * stroke(myColor); - * strokeWeight(3); - * fill(myColor); - * translate(base.x, base.y); - * line(0, 0, vec.x, vec.y); - * rotate(vec.heading()); - * let arrowSize = 7; - * translate(vec.mag() - arrowSize, 0); - * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); - * pop(); - * } - * - *
      - */ - /** - * @method sub - * @param {p5.Vector|Number[]} value the vector to subtract - * @chainable - */ - _main.default.Vector.prototype.sub = function sub(x, y, z) { - if (x instanceof _main.default.Vector) { - this.x -= x.x || 0; - this.y -= x.y || 0; - this.z -= x.z || 0; - return this; - } - if (x instanceof Array) { - this.x -= x[0] || 0; - this.y -= x[1] || 0; - this.z -= x[2] || 0; - return this; + if (opts.simplifyThreshold) { + simplify(pts, opts.simplifyThreshold); } - this.x -= x || 0; - this.y -= y || 0; - this.z -= z || 0; - return this; - }; - /** - * Multiplies the vector by a scalar, multiplies the `x`, `y`, and `z` components from a vector, or multiplies - * the `x`, `y`, and `z` components of two independent vectors. When multiplying a vector by a scalar, the `x`, `y`, - * and `z` components of the vector are all multiplied by the scalar. When multiplying a vector by a vector, - * the `x`, `y`, `z` components of both vectors are multiplied by each other - * (for example, with two vectors `a` and `b`: `a.x * b.x`, `a.y * b.y`, `a.z * b.z`). The static version of this method - * creates a new p5.Vector while the non-static version acts on the vector - * directly. Additionally, you may provide arguments to this function as an array. - * See the examples for more context. - * - * @method mult - * @param {Number} n The number to multiply with the vector - * @chainable - * @example - *
      - * - * let v = createVector(1, 2, 3); - * v.mult(2); - * // v's components are set to [2, 4, 6] - * - *
      - * - *
      - * - * let v0 = createVector(1, 2, 3); - * let v1 = createVector(2, 3, 4); - * v0.mult(v1); // v0's components are set to [2, 6, 12] - * - *
      - * - *
      - * - * let v0 = createVector(1, 2, 3); - * // Provide arguments as an array - * let arr = [2, 3, 4]; - * v0.mult(arr); // v0's components are set to [2, 6, 12] - * - *
      - * - *
      - * - * let v0 = createVector(1, 2, 3); - * let v1 = createVector(2, 3, 4); - * const result = p5.Vector.mult(v0, v1); - * print(result); // result's components are set to [2, 6, 12] - * - *
      - * - *
      - * - * // Static method - * let v1 = createVector(1, 2, 3); - * let v2 = p5.Vector.mult(v1, 2); - * // v2 has components [2, 4, 6] - * print(v2); - * - *
      - * - *
      - * - * function draw() { - * background(240); - * - * let v0 = createVector(50, 50); - * let v1 = createVector(25, -25); - * drawArrow(v0, v1, 'red'); - * - * let num = map(mouseX, 0, width, -2, 2, true); - * let v2 = p5.Vector.mult(v1, num); - * drawArrow(v0, v2, 'blue'); - * - * noStroke(); - * text('multiplied by ' + num.toFixed(2), 5, 90); - * } - * - * // draw an arrow for a vector at a given base position - * function drawArrow(base, vec, myColor) { - * push(); - * stroke(myColor); - * strokeWeight(3); - * fill(myColor); - * translate(base.x, base.y); - * line(0, 0, vec.x, vec.y); - * rotate(vec.heading()); - * let arrowSize = 7; - * translate(vec.mag() - arrowSize, 0); - * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); - * pop(); - * } - * - *
      - */ - /** - * @method mult - * @param {Number} x The number to multiply with the x component of the vector - * @param {Number} y The number to multiply with the y component of the vector - * @param {Number} [z] The number to multiply with the z component of the vector - * @chainable - */ - /** - * @method mult - * @param {Number[]} arr The array to multiply with the components of the vector - * @chainable - */ - /** - * @method mult - * @param {p5.Vector} v The vector to multiply with the components of the original vector - * @chainable - */ - _main.default.Vector.prototype.mult = function mult(x, y, z) { - if (x instanceof _main.default.Vector) { - // new p5.Vector will check that values are valid upon construction but it's possible - // that someone could change the value of a component after creation, which is why we still - // perform this check - if (Number.isFinite(x.x) && Number.isFinite(x.y) && Number.isFinite(x.z) && typeof x.x === 'number' && typeof x.y === 'number' && typeof x.z === 'number') { - this.x *= x.x; - this.y *= x.y; - this.z *= x.z; - } else { - console.warn('p5.Vector.prototype.mult:', 'x contains components that are either undefined or not finite numbers'); + return 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 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]; + 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); } - } else { - console.warn('p5.Vector.prototype.mult:', 'x contains elements that are either undefined or not finite numbers'); + current = [ + ]; } - return this; + current.push(cmdToArr(cmds[i])); } - 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; - } + 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 { - console.warn('p5.Vector.prototype.mult:', 'x, y, or z arguments are either undefined or not a finite number'); - } - return this; - }; - /** - * Divides the vector by a scalar, divides a vector by the `x`, `y`, and `z` arguments, or divides the `x`, `y`, and - * `z` components of two vectors against each other. When dividing a vector by a scalar, the `x`, `y`, - * and `z` components of the vector are all divided by the scalar. When dividing a vector by a vector, - * the `x`, `y`, `z` components of the source vector are treated as the dividend, and the `x`, `y`, `z` components - * of the argument is treated as the divisor. (For example, with two vectors - * `a` and `b`: `a.x / b.x`, `a.y / b.y`, `a.z / b.z`.) If any component of the second vector is 0, a division by 0 - * error will be logged, unless both two vectors have 0 in their `z` components, in which case only the `x` and `y` - * components will be divided. - * The static version of this method creates a - * new p5.Vector while the non-static version acts on the vector directly. - * Additionally, you may provide arguments to this method as an array. - * See the examples for more context. - * - * @method div - * @param {number} n The number to divide the vector by - * @chainable - * @example - *
      - * - * let v = createVector(6, 4, 2); - * v.div(2); //v's components are set to [3, 2, 1] - * - *
      - * - *
      - * - * let v0 = createVector(9, 4, 2); - * let v1 = createVector(3, 2, 4); - * v0.div(v1); // v0's components are set to [3, 2, 0.5] - * - *
      - * - *
      - * - * let v0 = createVector(9, 4, 2); - * // Provide arguments as an array - * let arr = [3, 2, 4]; - * v0.div(arr); // v0's components are set to [3, 2, 0.5] - * - *
      - * - *
      - * - * let v0 = createVector(9, 4, 2); - * let v1 = createVector(3, 2, 4); - * let result = p5.Vector.div(v0, v1); - * print(result); // result's components are set to [3, 2, 0.5] - * - *
      - * - *
      - * - * // Static method - * let v1 = createVector(6, 4, 2); - * let v2 = p5.Vector.div(v1, 2); - * // v2 has components [3, 2, 1] - * print(v2); - * - *
      - * - *
      - * - * function draw() { - * background(240); - * - * let v0 = createVector(0, 100); - * let v1 = createVector(50, -50); - * drawArrow(v0, v1, 'red'); - * - * let num = map(mouseX, 0, width, 10, 0.5, true); - * let v2 = p5.Vector.div(v1, num); - * drawArrow(v0, v2, 'blue'); - * - * noStroke(); - * text('divided by ' + num.toFixed(2), 10, 90); - * } - * - * // draw an arrow for a vector at a given base position - * function drawArrow(base, vec, myColor) { - * push(); - * stroke(myColor); - * strokeWeight(3); - * fill(myColor); - * translate(base.x, base.y); - * line(0, 0, vec.x, vec.y); - * rotate(vec.heading()); - * let arrowSize = 7; - * translate(vec.mag() - arrowSize, 0); - * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); - * pop(); - * } - * - *
      - */ - /** - * @method div - * @param {Number} x The number to divide with the x component of the vector - * @param {Number} y The number to divide with the y component of the vector - * @param {Number} [z] The number to divide with the z component of the vector - * @chainable - */ - /** - * @method div - * @param {Number[]} arr The array to divide the components of the vector by - * @chainable - */ - /** - * @method div - * @param {p5.Vector} v The vector to divide the components of the original vector by - * @chainable - */ - _main.default.Vector.prototype.div = function div(x, y, z) { - if (x instanceof _main.default.Vector) { - // new p5.Vector will check that values are valid upon construction but it's possible - // that someone could change the value of a component after creation, which is why we still - // perform this check - if (Number.isFinite(x.x) && Number.isFinite(x.y) && Number.isFinite(x.z) && typeof x.x === 'number' && typeof x.y === 'number' && typeof x.z === 'number') { - var isLikely2D = x.z === 0 && this.z === 0; - if (x.x === 0 || x.y === 0 || !isLikely2D && x.z === 0) { - console.warn('p5.Vector.prototype.div:', 'divide by 0'); - return this; - } - this.x /= x.x; - this.y /= x.y; - if (!isLikely2D) { - this.z /= x.z; + for (var key in defaults) { + if (typeof options[key] === 'undefined') { + options[key] = defaults[key]; } - } 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; + 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; } - 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'); + if (typeof collinear.tmpPoint1 === 'undefined') { + collinear.tmpPoint1 = [ + ]; + collinear.tmpPoint2 = [ + ]; } - return this; - }; - /** - * Calculates the magnitude (length) of the vector and returns the result as - * a float. (This is simply the equation `sqrt(x*x + y*y + z*z)`.) - * - * @method mag - * @return {Number} The magnitude of the vector - * @example - *
      - * - * 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(); - * } - * - *
      - *
      - * - * let v = createVector(20.0, 30.0, 40.0); - * let m = v.mag(); - * print(m); // Prints "53.85164807134504" - * - *
      - */ - _main.default.Vector.prototype.mag = function mag() { - return Math.sqrt(this.magSq()); - }; - /** - * Calculates the squared magnitude of the vector and returns the result - * as a float. (This is simply the equation `x*x + y*y + z*z`.) - * Faster if the real length is not required in the - * case of comparing vectors, etc. - * - * @method magSq - * @return {number} The squared magnitude of the vector - * @example - *
      - * - * // Static method - * let v1 = createVector(6, 4, 2); - * print(v1.magSq()); // Prints "56" - * - *
      - * - *
      - * - * 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(); - * } - * - *
      - */ - _main.default.Vector.prototype.magSq = function magSq() { - var x = this.x; - var y = this.y; - var z = this.z; - return x * x + y * y + z * z; - }; - /** - * Calculates the dot product of two vectors. The version of the method - * that computes the dot product of two independent vectors is a static - * method. See the examples for more context. - * - * @method dot - * @param {Number} x The x component of the vector - * @param {Number} [y] The y component of the vector - * @param {Number} [z] The z component of the vector - * @return {Number} The dot product - * - * @example - *
      - * - * let v1 = createVector(1, 2, 3); - * let v2 = createVector(2, 3, 4); - * - * print(v1.dot(v2)); // Prints "20" - * - *
      - * - *
      - * - * //Static method - * let v1 = createVector(1, 2, 3); - * let v2 = createVector(3, 2, 1); - * print(p5.Vector.dot(v1, v2)); // Prints "10" - * - *
      - */ - /** - * @method dot - * @param {p5.Vector} value value component of the vector or a p5.Vector - * @return {Number} - */ - _main.default.Vector.prototype.dot = function dot(x, y, z) { - if (x instanceof _main.default.Vector) { - return this.dot(x.x, x.y, x.z); + 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 this.x * (x || 0) + this.y * (y || 0) + this.z * (z || 0); - }; - /** - * Calculates and returns a vector composed of the cross product between - * two vectors. Both the static and non-static methods return a new p5.Vector. - * See the examples for more context. - * - * @method cross - * @param {p5.Vector} v p5.Vector to be crossed - * @return {p5.Vector} p5.Vector composed of cross product - * @example - *
      - * - * let v1 = createVector(1, 2, 3); - * let v2 = createVector(1, 2, 3); - * - * let v = v1.cross(v2); // v's components are [0, 0, 0] - * print(v); - * - *
      - * - *
      - * - * // 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); - * - *
      - */ - _main.default.Vector.prototype.cross = function cross(v) { - var x = this.y * v.z - this.z * v.y; - var y = this.z * v.x - this.x * v.z; - var z = this.x * v.y - this.y * v.x; - if (this.isPInst) { - return new _main.default.Vector(this._fromRadians, this._toRadians, x, y, z); - } else { - return new _main.default.Vector(x, y, z); + 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; } - }; - /** - * Calculates the Euclidean distance between two points (considering a - * point as a vector object). - * If you are looking to calculate distance between 2 points see dist() - * - * @method dist - * @param {p5.Vector} v The x, y, and z coordinates of a p5.Vector - * @return {Number} The distance - * @example - *
      - * - * let v1 = createVector(1, 0, 0); - * let v2 = createVector(0, 1, 0); - * - * let distance = v1.dist(v2); // distance is 1.4142... - * print(distance); - * - *
      - * - *
      - * - * // 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); - * - *
      - * - *
      - * - * 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(); - * } - * - *
      - */ - _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} The normalized p5.Vector - * @example - *
      - * - * 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] - * - *
      - * - *
      - * - * // Static method - * let v_initial = createVector(10, 20, 2); - * // v_initial has components [10.0, 20.0, 2.0] - * let v_normalized = p5.Vector.normalize(v_initial); - * print(v_normalized); - * // returns a new vector with components set to - * // [0.4454354, 0.8908708, 0.089087084] - * // v_initial remains unchanged - * - *
      - * - *
      - * - * 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(); - * } - * - *
      - */ - _main.default.Vector.prototype.normalize = function normalize() { - var len = this.mag(); // here we multiply by the reciprocal instead of calling 'div()' - // since div duplicates this zero check. - if (len !== 0) this.mult(1 / len); - return this; - }; - /** - * Limit the magnitude of this vector to the value used for the `max` - * parameter. - * - * @method limit - * @param {Number} max The maximum magnitude for the vector - * @chainable - * @example - *
      - * - * let v = createVector(10, 20, 2); - * // v has components [10.0, 20.0, 2.0] - * v.limit(5); - * // v's components are set to - * // [2.2271771, 4.4543543, 0.4454354] - * - *
      - *
      - * - * 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(); - * } - * - *
      - */ - _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); + 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 this; - }; - /** - * Set the magnitude of this vector to the value used for the `len` - * parameter. - * - * @method setMag - * @param {number} len The new length for this vector - * @chainable - * @example - *
      - * - * let v = createVector(3, 4, 0); - * // v has components [3.0, 4.0, 0.0] - * v.setMag(10); - * // v's components are set to [6.0, 8.0, 0.0] - * - *
      - * - *
      - * - * function draw() { - * background(240); - * - * let v0 = createVector(0, 0); - * let v1 = createVector(50, 50); - * - * drawArrow(v0, v1, 'red'); - * - * let length = map(mouseX, 0, width, 0, 141, true); - * v1.setMag(length); - * drawArrow(v0, v1, 'blue'); - * - * noStroke(); - * text('magnitude set to: ' + length.toFixed(2), 10, 70, 90, 30); - * } - * - * // draw an arrow for a vector at a given base position - * function drawArrow(base, vec, myColor) { - * push(); - * stroke(myColor); - * strokeWeight(3); - * fill(myColor); - * translate(base.x, base.y); - * line(0, 0, vec.x, vec.y); - * rotate(vec.heading()); - * let arrowSize = 7; - * translate(vec.mag() - arrowSize, 0); - * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); - * pop(); - * } - * - *
      - */ - _main.default.Vector.prototype.setMag = function setMag(n) { - return this.normalize().mult(n); - }; - /** - * Calculate the angle of rotation for this vector (only 2D vectors). - * p5.Vectors created using createVector() - * will take the current angleMode() into - * consideration, and give the angle in radians or degrees accordingly. - * - * @method heading - * @return {Number} The angle of rotation - * @example - *
      - * - * 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 - * } - * - *
      - * - *
      - * - * 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(); - * } - * - *
      - */ - _main.default.Vector.prototype.heading = function heading() { - var h = Math.atan2(this.y, this.x); - if (this.isPInst) return this._fromRadians(h); - return h; - }; - /** - * Rotate the vector to a specific angle (only 2D vectors); magnitude remains the - * same. - * - * @method setHeading - * @param {number} angle The angle of rotation - * @chainable - * @example - *
      - * - * let v = createVector(10.0, 20.0); - * // result of v.heading() is 1.1071487177940904 - * v.setHeading(Math.PI); - * // result of v.heading() is now 3.141592653589793 - * - *
      - */ - _main.default.Vector.prototype.setHeading = function setHeading(a) { - if (this.isPInst) a = this._toRadians(a); - var m = this.mag(); - this.x = m * Math.cos(a); - this.y = m * Math.sin(a); - return this; - }; - /** - * Rotate the vector by an angle (only 2D vectors); magnitude remains the - * same. - * - * @method rotate - * @param {number} angle The angle of rotation - * @chainable - * @example - *
      - * - * let v = createVector(10.0, 20.0); - * // v has components [10.0, 20.0, 0.0] - * v.rotate(HALF_PI); - * // v's components are set to [-20.0, 9.999999, 0.0] - * - *
      - * - *
      - * - * // static function implementation - * let v = createVector(10.0, 20.0); - * // v has components [10.0, 20.0, 0.0] - * let rotated_v = p5.Vector.rotate(v, HALF_PI); - * console.log(rotated_v); - * // rotated_v's components are set to [-20.0, 9.999999, 0.0] - * console.log(v); - * // v's components remains the same (i.e, [10.0, 20.0, 0.0]) - * - *
      - * - *
      - * - * let angle = 0; - * function draw() { - * background(240); - * - * let v0 = createVector(50, 50); - * let v1 = createVector(50, 0); - * - * drawArrow(v0, v1.rotate(angle), 'black'); - * angle += 0.01; - * } - * - * // draw an arrow for a vector at a given base position - * function drawArrow(base, vec, myColor) { - * push(); - * stroke(myColor); - * strokeWeight(3); - * fill(myColor); - * translate(base.x, base.y); - * line(0, 0, vec.x, vec.y); - * rotate(vec.heading()); - * let arrowSize = 7; - * translate(vec.mag() - arrowSize, 0); - * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); - * pop(); - * } - * - *
      - */ - _main.default.Vector.prototype.rotate = function rotate(a) { - var newHeading = this.heading() + a; - if (this.isPInst) newHeading = this._toRadians(newHeading); - var mag = this.mag(); - this.x = Math.cos(newHeading) * mag; - this.y = Math.sin(newHeading) * mag; - return this; - }; - /** - * Calculates and returns the angle between two vectors. This method will take - * the current angleMode into consideration, and - * give the angle in radians or degrees accordingly. - * - * @method angleBetween - * @param {p5.Vector} value The x, y, and z components of a p5.Vector - * @return {Number} The angle between - * @example - *
      - * - * let v1 = createVector(1, 0, 0); - * let v2 = createVector(0, 1, 0); - * - * let angle = v1.angleBetween(v2); - * // angle is PI/2 - * print(angle); - * - *
      - * - *
      - * - * 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(); - * } - * - *
      - */ - _main.default.Vector.prototype.angleBetween = function angleBetween(v) { - var dotmagmag = this.dot(v) / (this.mag() * v.mag()); // Mathematically speaking: the dotmagmag variable will be between -1 and 1 - // inclusive. Practically though it could be slightly outside this range due - // to floating-point rounding issues. This can make Math.acos return NaN. - // - // Solution: we'll clamp the value to the -1,1 range - var angle; - angle = Math.acos(Math.min(1, Math.max( - 1, dotmagmag))); - angle = angle * Math.sign(this.cross(v).z || 1); - if (this.isPInst) { - angle = this._fromRadians(angle); + return 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; } - return angle; - }; - /** - * Linear interpolate the vector to another vector. - * - * @method lerp - * @param {Number} x The x component - * @param {Number} y The y component - * @param {Number} z The z component - * @param {Number} amt The amount of interpolation; some value between 0.0 - * (old vector) and 1.0 (new vector). 0.9 is very near - * the new vector. 0.5 is halfway in between. - * @chainable - * - * @example - *
      - * - * let v = createVector(1, 1, 0); - * - * v.lerp(3, 3, 0, 0.5); // v now has components [2,2,0] - * - *
      - * - *
      - * - * 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); - * - *
      - * - *
      - * - * 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(); - * } - * - *
      - */ - /** - * @method lerp - * @param {p5.Vector} v The p5.Vector to lerp to - * @param {Number} amt - * @chainable - */ - _main.default.Vector.prototype.lerp = function lerp(x, y, z, amt) { - if (x instanceof _main.default.Vector) { - return this.lerp(x.x, x.y, x.z, y); + if (pathArray[0][0] === 'M') { + x = + pathArray[0][1]; + y = + pathArray[0][2]; + mx = x; + my = y; + start++; + res[0] = [ + 'M', + x, + y + ]; } - this.x += (x - this.x) * amt || 0; - this.y += (y - this.y) * amt || 0; - this.z += (z - this.z) * amt || 0; - return this; - }; - /** - * Reflect a vector about a normal to a line in 2D, or about a normal to a - * plane in 3D. - * - * @method reflect - * @param {p5.Vector} surfaceNormal the p5.Vector - * to reflect about. - * @chainable - * @example - *
      - * - * let v = createVector(4, 6); // incoming vector, this example vector is heading to the right and downward - * let n = createVector(0, -1); // surface normal to a plane (this example normal points directly upwards) - * v.reflect(n); // v is reflected about the surface normal n. v's components are now set to [4, -6] - * - *
      - * - *
      - * - * function draw() { - * background(240); - * - * let v0 = createVector(0, 0); - * let v1 = createVector(mouseX, mouseY); - * drawArrow(v0, v1, 'red'); - * - * let n = createVector(0, -30); - * drawArrow(v1, n, 'blue'); - * - * let r = v1.copy(); - * r.reflect(n); - * drawArrow(v1, r, 'purple'); - * } - * - * // draw an arrow for a vector at a given base position - * function drawArrow(base, vec, myColor) { - * push(); - * stroke(myColor); - * strokeWeight(3); - * fill(myColor); - * translate(base.x, base.y); - * line(0, 0, vec.x, vec.y); - * rotate(vec.heading()); - * let arrowSize = 7; - * translate(vec.mag() - arrowSize, 0); - * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); - * pop(); - * } - * - *
      - */ - _main.default.Vector.prototype.reflect = function reflect(surfaceNormal) { - surfaceNormal.normalize(); - return this.sub(surfaceNormal.mult(2 * this.dot(surfaceNormal))); - }; - /** - * Return a representation of this vector as a float array. This is only - * for temporary use. If used in any other fashion, the contents should be - * copied by using the p5.Vector.copy() - * method to copy into your own vector. - * - * @method array - * @return {Number[]} An Array with the 3 values - * @example - *
      - * - * function setup() { - * let v = createVector(20, 30); - * print(v.array()); // Prints : Array [20, 30, 0] - * } - * - *
      - * - *
      - * - * let v = createVector(10.0, 20.0, 30.0); - * let f = v.array(); - * print(f[0]); // Prints "10.0" - * print(f[1]); // Prints "20.0" - * print(f[2]); // Prints "30.0" - * - *
      - */ - _main.default.Vector.prototype.array = function array() { - return [this.x || 0, - this.y || 0, - this.z || 0]; - }; - /** - * Equality check against a p5.Vector. - * - * @method equals - * @param {Number} [x] The x component of the vector - * @param {Number} [y] The y component of the vector - * @param {Number} [z] The z component of the vector - * @return {Boolean} Whether the vectors are equal - * @example - *
      - * - * 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 - * - *
      - * - *
      - * - * 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 - * - *
      - */ - /** - * @method equals - * @param {p5.Vector|Array} value The vector to compare - * @return {Boolean} - */ - _main.default.Vector.prototype.equals = function equals(x, y, z) { - var a, - b, - c; - if (x instanceof _main.default.Vector) { - a = x.x || 0; - b = x.y || 0; - c = x.z || 0; - } else if (x instanceof Array) { - a = x[0] || 0; - b = x[1] || 0; - c = x[2] || 0; - } else { - a = x || 0; - b = y || 0; - c = z || 0; - } - return this.x === a && this.y === b && this.z === c; - }; // Static Methods - /** - * Make a new 2D vector from an angle. - * - * @method fromAngle - * @static - * @param {Number} angle The desired angle, in radians (unaffected by angleMode) - * @param {Number} [length] The length of the new vector (defaults to 1) - * @return {p5.Vector} The new p5.Vector object - * @example - *
      - * - * function draw() { - * background(200); - * - * // Create a variable, proportional to the mouseX, - * // varying from 0-360, to represent an angle in degrees. - * let myDegrees = map(mouseX, 0, width, 0, 360); - * - * // Display that variable in an onscreen text. - * // (Note the nfc() function to truncate additional decimal places, - * // and the "\xB0" character for the degree symbol.) - * let readout = 'angle = ' + nfc(myDegrees, 1) + '\xB0'; - * noStroke(); - * fill(0); - * text(readout, 5, 15); - * - * // Create a p5.Vector using the fromAngle function, - * // and extract its x and y components. - * let v = p5.Vector.fromAngle(radians(myDegrees), 30); - * let vx = v.x; - * let vy = v.y; - * - * push(); - * translate(width / 2, height / 2); - * noFill(); - * stroke(150); - * line(0, 0, 30, 0); - * stroke(0); - * line(0, 0, vx, vy); - * pop(); - * } - * - *
      - */ - _main.default.Vector.fromAngle = function fromAngle(angle, length) { - if (typeof length === 'undefined') { - length = 1; - } - return new _main.default.Vector(length * Math.cos(angle), length * Math.sin(angle), 0); - }; - /** - * Make a new 3D vector from a pair of ISO spherical angles. - * - * @method fromAngles - * @static - * @param {Number} theta The polar angle, in radians (zero is up) - * @param {Number} phi The azimuthal angle, in radians - * (zero is out of the screen) - * @param {Number} [length] The length of the new vector (defaults to 1) - * @return {p5.Vector} A new p5.Vector object - * @example - *
      - * - * function setup() { - * createCanvas(100, 100, WEBGL); - * fill(255); - * noStroke(); - * } - * function draw() { - * background(255); - * - * let t = millis() / 1000; - * - * // add three point lights - * pointLight(color('#f00'), p5.Vector.fromAngles(t * 1.0, t * 1.3, 100)); - * pointLight(color('#0f0'), p5.Vector.fromAngles(t * 1.1, t * 1.2, 100)); - * pointLight(color('#00f'), p5.Vector.fromAngles(t * 1.2, t * 1.1, 100)); - * - * sphere(35); - * } - * - *
      - */ - _main.default.Vector.fromAngles = function (theta, phi, length) { - if (typeof length === 'undefined') { - length = 1; - } - var cosPhi = Math.cos(phi); - var sinPhi = Math.sin(phi); - var cosTheta = Math.cos(theta); - var sinTheta = Math.sin(theta); - return new _main.default.Vector(length * sinTheta * sinPhi, - length * cosTheta, length * sinTheta * cosPhi); - }; - /** - * Make a new 2D unit vector from a random angle. - * - * @method random2D - * @static - * @return {p5.Vector} A new p5.Vector object - * @example - *
      - * - * let v = p5.Vector.random2D(); - * // May make v's attributes something like: - * // [0.61554617, -0.51195765, 0.0] or - * // [-0.4695841, -0.14366731, 0.0] or - * // [0.6091097, -0.22805278, 0.0] - * print(v); - * - *
      - * - *
      - * - * function setup() { - * frameRate(1); - * } - * - * function draw() { - * background(240); - * - * let v0 = createVector(50, 50); - * let v1 = p5.Vector.random2D(); - * drawArrow(v0, v1.mult(50), 'black'); - * } - * - * // draw an arrow for a vector at a given base position - * function drawArrow(base, vec, myColor) { - * push(); - * stroke(myColor); - * strokeWeight(3); - * fill(myColor); - * translate(base.x, base.y); - * line(0, 0, vec.x, vec.y); - * rotate(vec.heading()); - * let arrowSize = 7; - * translate(vec.mag() - arrowSize, 0); - * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); - * pop(); - * } - * - *
      - */ - _main.default.Vector.random2D = function random2D() { - return this.fromAngle(Math.random() * constants.TWO_PI); - }; - /** - * Make a new random 3D unit vector. - * - * @method random3D - * @static - * @return {p5.Vector} A new p5.Vector object - * @example - *
      - * - * let v = p5.Vector.random3D(); - * // May make v's attributes something like: - * // [0.61554617, -0.51195765, 0.599168] or - * // [-0.4695841, -0.14366731, -0.8711202] or - * // [0.6091097, -0.22805278, -0.7595902] - * print(v); - * - *
      - */ - _main.default.Vector.random3D = function random3D() { - var angle = Math.random() * constants.TWO_PI; - var vz = Math.random() * 2 - 1; - var vzBase = Math.sqrt(1 - vz * vz); - var vx = vzBase * Math.cos(angle); - var vy = vzBase * Math.sin(angle); - return new _main.default.Vector(vx, vy, vz); - }; // Returns a copy of a vector. - /** - * @method copy - * @static - * @param {p5.Vector} v the p5.Vector to create a copy of - * @return {p5.Vector} the copy of the p5.Vector object - */ - _main.default.Vector.copy = function copy(v) { - return v.copy(v); - }; // Adds two vectors together and returns a new one. - /** - * @method add - * @static - * @param {p5.Vector} v1 A p5.Vector to add - * @param {p5.Vector} v2 A p5.Vector to add - * @param {p5.Vector} [target] The vector to receive the result - * @return {p5.Vector} The resulting p5.Vector - */ - _main.default.Vector.add = function add(v1, v2, target) { - if (!target) { - target = v1.copy(); - if (arguments.length === 3) { - _main.default._friendlyError('The target parameter is undefined, it should be of type p5.Vector', 'p5.Vector.add'); + 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]; + } } - } else { - target.set(v1); - } - target.add(v2); - return target; - }; // Returns a vector remainder when it is divided by another vector - /** - * @method rem - * @static - * @param {p5.Vector} v1 The dividend p5.Vector - * @param {p5.Vector} v2 The divisor p5.Vector - */ - /** - * @method rem - * @static - * @param {p5.Vector} v1 - * @param {p5.Vector} v2 - * @return {p5.Vector} The resulting p5.Vector - */ - _main.default.Vector.rem = function rem(v1, v2) { - if (v1 instanceof _main.default.Vector && v2 instanceof _main.default.Vector) { - var target = v1.copy(); - target.rem(v2); - return target; - } - }; - /* - * Subtracts one p5.Vector from another and returns a new one. The second - * vector (`v2`) is subtracted from the first (`v1`), resulting in `v1-v2`. - */ - /** - * @method sub - * @static - * @param {p5.Vector} v1 A p5.Vector to subtract from - * @param {p5.Vector} v2 A p5.Vector to subtract - * @param {p5.Vector} [target] The vector to receive the result - * @return {p5.Vector} The resulting p5.Vector - */ - _main.default.Vector.sub = function sub(v1, v2, target) { - if (!target) { - target = v1.copy(); - if (arguments.length === 3) { - _main.default._friendlyError('The target parameter is undefined, it should be of type p5.Vector', 'p5.Vector.sub'); + 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]; } - } else { - target.set(v1); } - target.sub(v2); - return target; - }; - /** - * Multiplies a vector by a scalar and returns a new vector. - */ - /** - * @method mult - * @static - * @param {Number} x - * @param {Number} y - * @param {Number} [z] - * @return {p5.Vector} The resulting new p5.Vector - */ - /** - * @method mult - * @static - * @param {p5.Vector} v - * @param {Number} n - * @param {p5.Vector} [target] the vector to receive the result - */ - /** - * @method mult - * @static - * @param {p5.Vector} v0 - * @param {p5.Vector} v1 - * @param {p5.Vector} [target] - */ - /** - * @method mult - * @static - * @param {p5.Vector} v0 - * @param {Number[]} arr - * @param {p5.Vector} [target] - */ - _main.default.Vector.mult = function mult(v, n, target) { - if (!target) { - target = v.copy(); - if (arguments.length === 3) { - _main.default._friendlyError('The target parameter is undefined, it should be of type p5.Vector', 'p5.Vector.mult'); + 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]; } - } else { - target.set(v); - } - target.mult(n); - return target; - }; - /** - * Rotates the vector (only 2D vectors) by the given angle; magnitude remains the same. Returns a new vector. - */ - /** - * @method rotate - * @static - * @param {p5.Vector} v - * @param {Number} angle - * @param {p5.Vector} [target] The vector to receive the result - */ - _main.default.Vector.rotate = function rotate(v, a, target) { - if (arguments.length === 2) { - target = v.copy(); - } else { - if (!(target instanceof _main.default.Vector)) { - _main.default._friendlyError('The target parameter should be of type p5.Vector', 'p5.Vector.rotate'); + if (!(path[0] in tq)) { + d.qx = d.qy = null; } - target.set(v); - } - target.rotate(a); - return target; - }; - /** - * Divides a vector by a scalar and returns a new vector. - */ - /** - * @method div - * @static - * @param {Number} x - * @param {Number} y - * @param {Number} [z] - * @return {p5.Vector} The resulting new p5.Vector - */ - /** - * @method div - * @static - * @param {p5.Vector} v - * @param {Number} n - * @param {p5.Vector} [target] The vector to receive the result - */ - /** - * @method div - * @static - * @param {p5.Vector} v0 - * @param {p5.Vector} v1 - * @param {p5.Vector} [target] - */ - /** - * @method div - * @static - * @param {p5.Vector} v0 - * @param {Number[]} arr - * @param {p5.Vector} [target] - */ - _main.default.Vector.div = function div(v, n, target) { - if (!target) { - target = v.copy(); - if (arguments.length === 3) { - _main.default._friendlyError('The target parameter is undefined, it should be of type p5.Vector', 'p5.Vector.div'); + 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; } - } else { - target.set(v); - } - target.div(n); - return target; - }; - /** - * Calculates the dot product of two vectors. - */ - /** - * @method dot - * @static - * @param {p5.Vector} v1 The first p5.Vector - * @param {p5.Vector} v2 The second p5.Vector - * @return {Number} The dot product - */ - _main.default.Vector.dot = function dot(v1, v2) { - return v1.dot(v2); - }; - /** - * Calculates the cross product of two vectors. - */ - /** - * @method cross - * @static - * @param {p5.Vector} v1 The first p5.Vector - * @param {p5.Vector} v2 The second p5.Vector - * @return {Number} The cross product - */ - _main.default.Vector.cross = function cross(v1, v2) { - return v1.cross(v2); - }; - /** - * Calculates the Euclidean distance between two points (considering a - * point as a vector object). - */ - /** - * @method dist - * @static - * @param {p5.Vector} v1 The first p5.Vector - * @param {p5.Vector} v2 The second p5.Vector - * @return {Number} The distance - */ - _main.default.Vector.dist = function dist(v1, v2) { - return v1.dist(v2); - }; - /** - * Linear interpolate a vector to another vector and return the result as a - * new vector. - */ - /** - * @method lerp - * @static - * @param {p5.Vector} v1 - * @param {p5.Vector} v2 - * @param {Number} amt - * @param {p5.Vector} [target] The vector to receive the result - * @return {p5.Vector} The lerped value - */ - _main.default.Vector.lerp = function lerp(v1, v2, amt, target) { - if (!target) { - target = v1.copy(); - if (arguments.length === 4) { - _main.default._friendlyError('The target parameter is undefined, it should be of type p5.Vector', 'p5.Vector.lerp'); + 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); } - } else { - target.set(v1); - } - target.lerp(v2, amt); - return target; - }; - /** - * Calculates the magnitude (length) of the vector and returns the result as - * a float (this is simply the equation `sqrt(x*x + y*y + z*z)`.) - */ - /** - * @method mag - * @static - * @param {p5.Vector} vecT The vector to return the magnitude of - * @return {Number} The magnitude of vecT - */ - _main.default.Vector.mag = function mag(vecT) { - return vecT.mag(); - }; - /** - * Calculates the squared magnitude of the vector and returns the result - * as a float (this is simply the equation (x\*x + y\*y + z\*z).) - * Faster if the real length is not required in the - * case of comparing vectors, etc. - */ - /** - * @method magSq - * @static - * @param {p5.Vector} vecT the vector to return the squared magnitude of - * @return {Number} the squared magnitude of vecT - */ - _main.default.Vector.magSq = function magSq(vecT) { - return vecT.magSq(); - }; - /** - * Normalize the vector to length 1 (make it a unit vector). - */ - /** - * @method normalize - * @static - * @param {p5.Vector} v The vector to normalize - * @param {p5.Vector} [target] The vector to receive the result - * @return {p5.Vector} The vector v, normalized to a length of 1 - */ - _main.default.Vector.normalize = function normalize(v, target) { - if (arguments.length < 2) { - target = v.copy(); - } else { - if (!(target instanceof _main.default.Vector)) { - _main.default._friendlyError('The target parameter should be of type p5.Vector', 'p5.Vector.normalize'); + }, + 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); } - target.set(v); - } - return target.normalize(); - }; - /** - * Limit the magnitude of the vector to the value used for the max - * parameter. - */ - /** - * @method limit - * @static - * @param {p5.Vector} v the vector to limit - * @param {Number} max - * @param {p5.Vector} [target] the vector to receive the result (Optional) - * @return {p5.Vector} v with a magnitude limited to max - */ - _main.default.Vector.limit = function limit(v, max, target) { - if (arguments.length < 3) { - target = v.copy(); - } else { - if (!(target instanceof _main.default.Vector)) { - _main.default._friendlyError('The target parameter should be of type p5.Vector', 'p5.Vector.limit'); + }; + 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 + } - target.set(v); - } - return target.limit(max); - }; - /** - * Set the magnitude of the vector to the value used for the len - * parameter. - */ - /** - * @method setMag - * @static - * @param {p5.Vector} v the vector to set the magnitude of - * @param {number} len - * @param {p5.Vector} [target] the vector to receive the result (Optional) - * @return {p5.Vector} v with a magnitude set to len - */ - _main.default.Vector.setMag = function setMag(v, len, target) { - if (arguments.length < 3) { - target = v.copy(); - } else { - if (!(target instanceof _main.default.Vector)) { - _main.default._friendlyError('The target parameter should be of type p5.Vector', 'p5.Vector.setMag'); + p[i] = processPath(p[i], attrs, pcom); + if (pcoms1[i] !== 'A' && pfirst === 'C') { + pcoms1[i] = 'C'; } - target.set(v); - } - return target.setMag(len); - }; - /** - * Calculate the angle of rotation for this vector (only 2D vectors). - * p5.Vectors created using createVector() - * will take the current angleMode into - * consideration, and give the angle in radians or degrees accordingly. - */ - /** - * @method heading - * @static - * @param {p5.Vector} v the vector to find the angle of - * @return {Number} the angle of rotation - */ - _main.default.Vector.heading = function heading(v) { - return v.heading(); - }; - /** - * Calculates and returns the angle between two vectors. This function will take - * the angleMode on v1 into consideration, and - * give the angle in radians or degrees accordingly. - */ - /** - * @method angleBetween - * @static - * @param {p5.Vector} v1 the first vector - * @param {p5.Vector} v2 the second vector - * @return {Number} the angle between the two vectors - */ - _main.default.Vector.angleBetween = function angleBetween(v1, v2) { - return v1.angleBetween(v2); - }; - /** - * Reflect a vector about a normal to a line in 2D, or about a normal to a - * plane in 3D. - */ - /** - * @method reflect - * @static - * @param {p5.Vector} incidentVector vector to be reflected - * @param {p5.Vector} surfaceNormal - * @param {p5.Vector} [target] the vector to receive the result (Optional) - * @return {p5.Vector} the reflected vector - */ - _main.default.Vector.reflect = function reflect(incidentVector, surfaceNormal, target) { - if (arguments.length < 3) { - target = incidentVector.copy(); - } else { - if (!(target instanceof _main.default.Vector)) { - _main.default._friendlyError('The target parameter should be of type p5.Vector', 'p5.Vector.reflect'); + 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); } - target.set(incidentVector); - } - return target.reflect(surfaceNormal); - }; - /** - * Return a representation of this vector as a float array. This is only - * for temporary use. If used in any other fashion, the contents should be - * copied by using the p5.Vector.copy() - * method to copy into your own vector. - */ - /** - * @method array - * @static - * @param {p5.Vector} v the vector to convert to an array - * @return {Number[]} an Array with the 3 values - */ - _main.default.Vector.array = function array(v) { - return v.array(); - }; - /** - * Equality check against a p5.Vector - */ - /** - * @method equals - * @static - * @param {p5.Vector|Array} v1 the first vector to compare - * @param {p5.Vector|Array} v2 the second vector to compare - * @return {Boolean} - */ - _main.default.Vector.equals = function equals(v1, v2) { - var v; - if (v1 instanceof _main.default.Vector) { - v = v1; - } else if (v1 instanceof Array) { - v = new _main.default.Vector().set(v1); - } else { - _main.default._friendlyError('The v1 parameter should be of type Array or p5.Vector', 'p5.Vector.equals'); + 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 v.equals(v2); - }; - var _default = _main.default.Vector; - exports.default = _default; + return p2 ? [ + p, + p2 + ] : p; + } + function a2c(x1, y1, rx, ry, angle, lac, sweep_flag, x2, y2, recursive) { + // for more information of where this Math came from visit: + // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes + var PI = Math.PI; + var _120 = PI * 120 / 180; + var f1; + var f2; + var cx; + var cy; + var rad = PI / 180 * ( + angle || 0); + var res = [ + ]; + var xy; + var rotate = function rotate(x, y, rad) { + var X = x * Math.cos(rad) - y * Math.sin(rad), + Y = x * Math.sin(rad) + y * Math.cos(rad); + return { + x: X, + y: Y + }; + }; + if (!recursive) { + xy = rotate(x1, y1, - rad); + x1 = xy.x; + y1 = xy.y; + xy = rotate(x2, y2, - rad); + x2 = xy.x; + y2 = xy.y; + var x = (x1 - x2) / 2; + var y = (y1 - y2) / 2; + var h = x * x / (rx * rx) + y * y / (ry * ry); + if (h > 1) { + h = Math.sqrt(h); + rx = h * rx; + ry = h * ry; + } + var rx2 = rx * rx, + ry2 = ry * ry; + var k = (lac === sweep_flag ? - 1 : 1) * Math.sqrt(Math.abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))); + cx = k * rx * y / ry + (x1 + x2) / 2; + cy = k * - ry * x / rx + (y1 + y2) / 2; + f1 = Math.asin(((y1 - cy) / ry).toFixed(9)); + f2 = Math.asin(((y2 - cy) / ry).toFixed(9)); + f1 = x1 < cx ? PI - f1 : f1; + f2 = x2 < cx ? PI - f2 : f2; + if (f1 < 0) { + f1 = PI * 2 + f1; + } + if (f2 < 0) { + f2 = PI * 2 + f2; + } + if (sweep_flag && f1 > f2) { + f1 = f1 - PI * 2; + } + if (!sweep_flag && f2 > f1) { + f2 = f2 - PI * 2; + } + } else { + f1 = recursive[0]; + f2 = recursive[1]; + cx = recursive[2]; + cy = recursive[3]; + } + var df = f2 - f1; + if (Math.abs(df) > _120) { + var f2old = f2, + x2old = x2, + y2old = y2; + f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : - 1); + x2 = cx + rx * Math.cos(f2); + y2 = cy + ry * Math.sin(f2); + res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [ + f2, + f2old, + cx, + cy + ]); + } + df = f2 - f1; + var c1 = Math.cos(f1), + s1 = Math.sin(f1), + c2 = Math.cos(f2), + s2 = Math.sin(f2), + t = Math.tan(df / 4), + hx = 4 / 3 * rx * t, + hy = 4 / 3 * ry * t, + m1 = [ + x1, + y1 + ], + m2 = [ + x1 + hx * s1, + y1 - hy * c1 + ], + m3 = [ + x2 + hx * s2, + y2 - hy * c2 + ], + m4 = [ + x2, + y2 + ]; + m2[0] = 2 * m1[0] - m2[0]; + m2[1] = 2 * m1[1] - m2[1]; + if (recursive) { + return [m2, + m3, + m4].concat(res); + } else { + res = [ + m2, + m3, + m4 + ].concat(res).join().split(','); + var newres = [ + ]; + for (var i = 0, ii = res.length; i < ii; i++) { + newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x; + } + return newres; + } + } // http://schepers.cc/getting-to-the-point + + function catmullRom2bezier(crp, z) { + var d = [ + ]; + for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) { + var p = [ + { + x: + crp[i - 2], + y: + crp[i - 1] + }, + { + x: + crp[i], + y: + crp[i + 1] + }, + { + x: + crp[i + 2], + y: + crp[i + 3] + }, + { + x: + crp[i + 4], + y: + crp[i + 5] + } + ]; + if (z) { + if (!i) { + p[0] = { + x: + crp[iLen - 2], + y: + crp[iLen - 1] + }; + } else if (iLen - 4 === i) { + p[3] = { + x: + crp[0], + y: + crp[1] + }; + } else if (iLen - 2 === i) { + p[2] = { + x: + crp[0], + y: + crp[1] + }; + p[3] = { + x: + crp[2], + y: + crp[3] + }; + } + } else { + if (iLen - 4 === i) { + p[3] = p[2]; + } else if (!i) { + p[0] = { + x: + crp[i], + y: + crp[i + 1] + }; + } + } + d.push(['C', + ( - p[0].x + 6 * p[1].x + p[2].x) / 6, + ( - p[0].y + 6 * p[1].y + p[2].y) / 6, + (p[1].x + 6 * p[2].x - p[3].x) / 6, + (p[1].y + 6 * p[2].y - p[3].y) / 6, + p[2].x, + p[2].y]); + } + return d; + } + function l2c(x1, y1, x2, y2) { + return [x1, + y1, + x2, + y2, + x2, + y2]; + } + function q2c(x1, y1, ax, ay, x2, y2) { + var _13 = 1 / 3, + _23 = 2 / 3; + return [_13 * x1 + _23 * ax, + _13 * y1 + _23 * ay, + _13 * x2 + _23 * ax, + _13 * y2 + _23 * ay, + x2, + y2]; + } + function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) { + if (z == null) { + z = 1; + } + z = z > 1 ? 1 : z < 0 ? 0 : z; + var z2 = z / 2; + var n = 12; + var Tvalues = [ + - 0.1252, + 0.1252, + - 0.3678, + 0.3678, + - 0.5873, + 0.5873, + - 0.7699, + 0.7699, + - 0.9041, + 0.9041, + - 0.9816, + 0.9816 + ]; + var sum = 0; + var Cvalues = [ + 0.2491, + 0.2491, + 0.2335, + 0.2335, + 0.2032, + 0.2032, + 0.1601, + 0.1601, + 0.1069, + 0.1069, + 0.0472, + 0.0472 + ]; + for (var i = 0; i < n; i++) { + var ct = z2 * Tvalues[i] + z2, + xbase = base3(ct, x1, x2, x3, x4), + ybase = base3(ct, y1, y2, y3, y4), + comb = xbase * xbase + ybase * ybase; + sum += Cvalues[i] * Math.sqrt(comb); + } + return z2 * sum; + } + function getTatLen(x1, y1, x2, y2, x3, y3, x4, y4, ll) { + if (ll < 0 || bezlen(x1, y1, x2, y2, x3, y3, x4, y4) < ll) { + return; + } + var t = 1; + var step = t / 2; + var t2 = t - step; + var l; + var e = 0.01; + l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2); + while (Math.abs(l - ll) > e) { + step /= 2; + t2 += (l < ll ? 1 : - 1) * step; + l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2); + } + return t2; + } + function base3(t, p1, p2, p3, p4) { + var t1 = - 3 * p1 + 9 * p2 - 9 * p3 + 3 * p4, + t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3; + return t * t2 - 3 * p1 + 3 * p2; + } + function cacheKey() { + var hash = ''; + for (var i = arguments.length - 1; i >= 0; --i) { + hash += '?'.concat(i < 0 || arguments.length <= i ? undefined : arguments[i]); + } + return hash; + } + var _default = _main.default; + exports.default = _default; }, { - '../core/constants': 278, - '../core/main': 290, - 'core-js/modules/es.array.concat': 167, - 'core-js/modules/es.array.every': 169, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.array.some': 181, - 'core-js/modules/es.math.sign': 186, - 'core-js/modules/es.number.constructor': 187, - 'core-js/modules/es.number.is-finite': 188, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.to-string': 200, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.string.sub': 210, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + '../core/constants': 286, + '../core/main': 298, + 'core-js/modules/es.array.concat': 169, + 'core-js/modules/es.array.fill': 172, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.join': 180, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.array.splice': 185, + 'core-js/modules/es.function.name': 186, + 'core-js/modules/es.number.to-fixed': 193, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.string.replace': 214, + 'core-js/modules/es.string.split': 216, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 324: [ + 337: [ function (_dereq_, module, exports) { 'use strict'; + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.array-buffer.constructor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.array-buffer.constructor'); + _dereq_('core-js/modules/es.object.to-string'); Object.defineProperty(exports, '__esModule', { value: true }); @@ -89605,690 +100919,368 @@ obj }; } /** - * @module Math - * @submodule Random + * @module Data + * @submodule Array Functions * @for p5 * @requires core */ - // variables used for random number generators - - var randomStateProp = '_lcg_random_state'; // Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes - // m is basically chosen to be large (as it is the max period) - // and for its relationships to a and c - var m = 4294967296; // a - 1 should be divisible by m's prime factors - var a = 1664525; // c and m should be co-prime - var c = 1013904223; - var y2 = 0; // Linear Congruential Generator that stores its state at instance[stateProperty] - _main.default.prototype._lcg = function (stateProperty) { - // define the recurrence relationship - this[stateProperty] = (a * this[stateProperty] + c) % m; // return a float in [0, 1) - // we've just used % m, so / m is always < 1 - return this[stateProperty] / m; - }; - _main.default.prototype._lcgSetSeed = function (stateProperty, val) { - // pick a random seed if val is undefined or null - // the >>> 0 casts the seed to an unsigned 32-bit integer - this[stateProperty] = (val == null ? Math.random() * m : val) >>> 0; - }; /** - * Sets the seed value for random(). - * - * By default, random() produces different results each time the program - * is run. Set the seed parameter to a constant to return the same - * pseudo-random numbers each time the software is run. + * Adds a value to the end of an array. Extends the length of + * the array by one. Maps to Array.push(). * - * @method randomSeed - * @param {Number} seed the seed value + * @method append + * @deprecated Use array.push(value) instead. + * @param {Array} array Array to append + * @param {any} value to be added to the Array + * @return {Array} the array that was appended to * @example - *
      - * - * randomSeed(99); - * for (let i = 0; i < 100; i++) { - * let r = random(0, 255); - * stroke(r); - * line(i, 0, i, 100); + *
      + * function setup() { + * let myArray = ['Mango', 'Apple', 'Papaya']; + * print(myArray); // ['Mango', 'Apple', 'Papaya'] + * + * append(myArray, 'Peach'); + * print(myArray); // ['Mango', 'Apple', 'Papaya', 'Peach'] * } - * describe('many vertical lines drawn in white, black, or grey.'); - * - *
      + *
      */ - _main.default.prototype.randomSeed = function (seed) { - this._lcgSetSeed(randomStateProp, seed); - this._gaussian_previous = false; + + _main.default.prototype.append = function (array, value) { + array.push(value); + return array; }; /** - * Return a random floating-point number. + * Copies an array (or part of an array) to another array. The src array is + * copied to the dst array, beginning at the position specified by + * srcPosition and into the position specified by dstPosition. The number of + * elements to copy is determined by length. Note that copying values + * overwrites existing values in the destination array. To append values + * instead of overwriting them, use concat(). * - * Takes either 0, 1 or 2 arguments. + * 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). * - * If no argument is given, returns a random number from 0 - * up to (but not including) 1. + * Using this function is far more efficient for copying array data than + * iterating through a for() loop and copying each element individually. * - * If one argument is given and it is a number, returns a random number from 0 - * up to (but not including) the number. + * @method arrayCopy + * @deprecated Use arr1.copyWithin(arr2) instead. + * @param {Array} src the source Array + * @param {Integer} srcPosition starting position in the source Array + * @param {Array} dst the destination Array + * @param {Integer} dstPosition starting position in the destination Array + * @param {Integer} length number of Array elements to be copied * - * If one argument is given and it is an array, returns a random element from - * that array. + * @example + *
      + * let src = ['A', 'B', 'C']; + * let dst = [1, 2, 3]; + * let srcPosition = 1; + * let dstPosition = 0; + * let length = 2; * - * If two arguments are given, returns a random number from the - * first argument up to (but not including) the second argument. + * print(src); // ['A', 'B', 'C'] + * print(dst); // [ 1 , 2 , 3 ] * - * @method random - * @param {Number} [min] the lower bound (inclusive) - * @param {Number} [max] the upper bound (exclusive) - * @return {Number} the random number - * @example - *
      - * - * for (let i = 0; i < 100; i++) { - * let r = random(50); - * stroke(r * 5); - * line(50, i, 50 + r, i); - * } - * describe(`100 horizontal lines from center canvas to right. - * The size and fill change each time.`); - * - *
      - *
      - * - * for (let i = 0; i < 100; i++) { - * let r = random(-50, 50); - * line(50, i, 50 + r, i); - * } - * describe(`100 horizontal lines from center of canvas. - * The height & side change each render.`); - * - *
      - *
      - * - * // Get a random element from an array using the random(Array) syntax - * let words = ['apple', 'bear', 'cat', 'dog']; - * let word = random(words); // select random word - * text(word, 10, 50); // draw the word - * describe('word displayed at random. Either apple, bear, cat, or dog.'); - * - *
      + * arrayCopy(src, srcPosition, dst, dstPosition, length); + * print(dst); // ['B', 'C', 3] + *
      */ /** - * @method random - * @param {Array} choices the array to choose from - * @return {*} the random element from the array - * @example + * @method arrayCopy + * @deprecated Use arr1.copyWithin(arr2) instead. + * @param {Array} src + * @param {Array} dst + * @param {Integer} [length] */ - _main.default.prototype.random = function (min, max) { - _main.default._validateParameters('random', arguments); - var rand; - if (this[randomStateProp] != null) { - rand = this._lcg(randomStateProp); + _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 { - 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)]; + if (typeof dst !== 'undefined') { + // src, dst, length + // rename so we don't get confused + end = dst; + end = Math.min(end, src.length); } else { - return rand * min; - } - } else { - if (min > max) { - var tmp = min; - min = max; - max = tmp; + // src, dst + end = src.length; } - return rand * (max - min) + min; - } + 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. * - * Returns a random number fitting a Gaussian, or - * normal, distribution. There is theoretically no minimum or maximum - * value that randomGaussian() might return. Rather, there is - * just a very low probability that values far from the mean will be - * returned; and a higher probability that numbers near the mean will - * be returned. - * - * Takes either 0, 1 or 2 arguments.
      - * If no args, the mean is 0 and the standard deviation is 1.
      - * If one arg, that arg is the mean and the standard deviation is 1.
      - * If two args, the first arg is the mean and the second is the standard deviation. + * @method concat + * @deprecated Use arr1.concat(arr2) instead. + * @param {Array} a first Array to concatenate + * @param {Array} b second Array to concatenate + * @return {Array} concatenated array * - * @method randomGaussian - * @param {Number} [mean] the mean - * @param {Number} [sd] the standard deviation - * @return {Number} the random number * @example - *
      - * - * for (let y = 0; y < 100; y++) { - * let x = randomGaussian(50, 15); - * line(50, y, x, y); - * } - * describe(`100 horizontal lines from center of canvas. - * The height & side change each render.`); - * - *
      - *
      - * - * let distribution = new Array(360); - * + *
      * function setup() { - * createCanvas(100, 100); - * for (let i = 0; i < distribution.length; i++) { - * distribution[i] = floor(randomGaussian(0, 15)); - * } - * } - * - * function draw() { - * background(204); + * let arr1 = ['A', 'B', 'C']; + * let arr2 = [1, 2, 3]; * - * translate(width / 2, width / 2); + * print(arr1); // ['A','B','C'] + * print(arr2); // [1,2,3] * - * 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); - * } + * let arr3 = concat(arr1, arr2); * - * describe(`black lines radiate from center of canvas. - * The size changes each render.`); + * print(arr1); // ['A','B','C'] + * print(arr2); // [1, 2, 3] + * print(arr3); // ['A','B','C', 1, 2, 3] * } - * - *
      + *
      */ - _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; + _main.default.prototype.concat = function (list0, list1) { + return list0.concat(list1); }; - var _default = _main.default; - exports.default = _default; - }, - { - '../core/main': 290 - } - ], - 325: [ - function (_dereq_, module, exports) { - 'use strict'; - _dereq_('core-js/modules/es.symbol'); - _dereq_('core-js/modules/es.symbol.description'); - _dereq_('core-js/modules/es.symbol.iterator'); - _dereq_('core-js/modules/es.array.iterator'); - _dereq_('core-js/modules/es.object.get-own-property-descriptor'); - _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.string.iterator'); - _dereq_('core-js/modules/es.weak-map'); - _dereq_('core-js/modules/web.dom-collections.iterator'); - function _typeof2(obj) { - if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { - _typeof2 = function _typeof2(obj) { - return typeof obj; - }; - } else { - _typeof2 = function _typeof2(obj) { - return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; - }; - } - return _typeof2(obj); - } - function _typeof(obj) { - if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { - _typeof = function _typeof(obj) { - return _typeof2(obj); - }; - } else { - _typeof = function _typeof(obj) { - return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); - }; - } - return _typeof(obj); - } - Object.defineProperty(exports, '__esModule', { - value: true - }); - exports.default = void 0; - var _main = _interopRequireDefault(_dereq_('../core/main')); - var constants = _interopRequireWildcard(_dereq_('../core/constants')); - function _getRequireWildcardCache() { - if (typeof WeakMap !== 'function') return null; - var cache = new WeakMap(); - _getRequireWildcardCache = function _getRequireWildcardCache() { - return cache; - }; - return cache; - } - function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } - if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { - return { - default: - obj - }; - } - var cache = _getRequireWildcardCache(); - if (cache && cache.has(obj)) { - return cache.get(obj); - } - var newObj = { - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - newObj.default = obj; - if (cache) { - cache.set(obj, newObj); - } - return newObj; - } - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: - obj - }; - } /** - * @module Math - * @submodule Trigonometry - * @for p5 - * @requires core - * @requires constants - */ - /* - * all DEGREES/RADIANS conversion should be done in the p5 instance - * if possible, using the p5._toRadians(), p5._fromRadians() methods. - */ - - _main.default.prototype._angleMode = constants.RADIANS; /** - * The inverse of cos(), returns the arc cosine of a value. - * This function expects the values in the range of -1 to 1 and values are returned in - * the range 0 to PI (3.1415927) if the angleMode() is RADIANS - * or 0 to 180 if the angleMode() is DEGREES. - * - * @method acos - * @param {Number} value the value whose arc cosine is to be returned - * @return {Number} the arc cosine of the given value + * Reverses the order of an array, maps to Array.reverse() * + * @method reverse + * @deprecated Use array.reverse() instead. + * @param {Array} list Array to reverse + * @return {Array} the reversed list * @example - *
      - * - * let a = PI; - * let c = cos(a); - * let ac = acos(c); - * // Prints: "3.1415927 : -1.0 : 3.1415927" - * print(a + ' : ' + c + ' : ' + ac); - * - *
      + *
      + * function setup() { + * let myArray = ['A', 'B', 'C']; + * print(myArray); // ['A','B','C'] * - *
      - * - * 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); - * - *
      + * reverse(myArray); + * print(myArray); // ['C','B','A'] + * } + *
      */ - _main.default.prototype.acos = function (ratio) { - return this._fromRadians(Math.acos(ratio)); + _main.default.prototype.reverse = function (list) { + return list.reverse(); }; /** - * The inverse of sin(), returns the arc sine of a value. - * This function expects the values in the range of -1 to 1 and values are returned - * in the range -PI/2 to PI/2 if the angleMode is RADIANS or -90 to 90 if the angle - * mode is DEGREES. - * - * @method asin - * @param {Number} value the value whose arc sine is to be returned - * @return {Number} the arc sine of the given value + * Decreases an array by one element and returns the shortened array, + * maps to Array.pop(). * + * @method shorten + * @deprecated Use array.pop() instead. + * @param {Array} list Array to shorten + * @return {Array} shortened Array * @example - *
      - * - * let a = PI / 3.0; - * let s = sin(a); - * let as = asin(s); - * // Prints: "1.0471975 : 0.86602540 : 1.0471975" - * print(a + ' : ' + s + ' : ' + as); - * - *
      - * - *
      - * - * let a = PI + PI / 3.0; - * let s = sin(a); - * let as = asin(s); - * // Prints: "4.1887902 : -0.86602540 : -1.0471975" - * print(a + ' : ' + s + ' : ' + as); - * - *
      + *
      + * function setup() { + * let myArray = ['A', 'B', 'C']; + * print(myArray); // ['A', 'B', 'C'] + * let newArray = shorten(myArray); + * print(myArray); // ['A','B','C'] + * print(newArray); // ['A','B'] + * } + *
      */ - _main.default.prototype.asin = function (ratio) { - return this._fromRadians(Math.asin(ratio)); + _main.default.prototype.shorten = function (list) { + list.pop(); + return list; }; /** - * The inverse of tan(), returns the arc tangent of a value. - * This function expects the values in the range of -Infinity to Infinity (exclusive) and - * values are returned in the range -PI/2 to PI/2 if the angleMode is RADIANS or - * -90 to 90 if the angle mode is DEGREES. - * - * @method atan - * @param {Number} value the value whose arc tangent is to be returned - * @return {Number} the arc tangent of the given value + * Randomizes the order of the elements of an array. Implements + * + * Fisher-Yates Shuffle Algorithm. * + * @method shuffle + * @param {Array} array Array to shuffle + * @param {Boolean} [bool] modify passed array + * @return {Array} shuffled Array * @example - *
      - * - * let a = PI / 3.0; - * let t = tan(a); - * let at = atan(t); - * // Prints: "1.0471975 : 1.7320508 : 1.0471975" - * print(a + ' : ' + t + ' : ' + at); - * - *
      - * - *
      - * - * let a = PI + PI / 3.0; - * let t = tan(a); - * let at = atan(t); - * // Prints: "4.1887902 : 1.7320508 : 1.0471975" - * print(a + ' : ' + t + ' : ' + at); - * - *
      - */ - _main.default.prototype.atan = function (ratio) { - return this._fromRadians(Math.atan(ratio)); - }; - /** - * Calculates the angle (in radians) from a specified point to the coordinate - * origin as measured from the positive x-axis. Values are returned as a - * float in the range from PI to -PI if the angleMode() - * is RADIANS or 180 to -180 if the angleMode() is DEGREES. - * The atan2() function is most often used for orienting geometry - * to the position of the cursor. - * - * Note: The y-coordinate of the point is the first parameter, and the - * x-coordinate is the second parameter, due to the structure of calculating - * the tangent. - * - * @method atan2 - * @param {Number} y y-coordinate of the point - * @param {Number} x x-coordinate of the point - * @return {Number} the arc tangent of the given point + *
      + * function setup() { + * let regularArr = ['ABC', 'def', createVector(), TAU, Math.E]; + * print(regularArr); + * shuffle(regularArr, true); // force modifications to passed array + * print(regularArr); * - * @example - *
      - * - * function draw() { - * background(204); - * translate(width / 2, height / 2); - * let a = atan2(mouseY - height / 2, mouseX - width / 2); - * rotate(a); - * rect(-30, -5, 60, 10); - * describe('60×10 rect at center of canvas rotates with mouse movements'); + * // By default shuffle() returns a shuffled cloned array: + * let newArr = shuffle(regularArr); + * print(regularArr); + * print(newArr); * } - * - *
      + *
      */ - _main.default.prototype.atan2 = function (y, x) { - return this._fromRadians(Math.atan2(y, x)); + _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; }; /** - * Calculates the cosine of an angle. This function takes into account the - * current angleMode. Values are returned in the range -1 to 1. + * 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 cos - * @param {Number} angle the angle - * @return {Number} the cosine of the angle + * @method sort + * @deprecated Use array.sort() instead. + * @param {Array} list Array to sort + * @param {Integer} [count] number of elements to sort, starting from 0 + * @return {Array} the sorted list * * @example - *
      - * - * let a = 0.0; - * let inc = TWO_PI / 25.0; - * for (let i = 0; i < 25; i++) { - * line(i * 4, 50, i * 4, 50 + cos(a) * 40.0); - * a = a + inc; - * } - * describe(`vertical black lines form wave patterns, extend-down on - * left and right side`); - * - *
      - */ - _main.default.prototype.cos = function (angle) { - return Math.cos(this._toRadians(angle)); - }; - /** - * Calculates the sine of an angle. This function takes into account the - * current angleMode. Values are returned in the range -1 to 1. - * - * @method sin - * @param {Number} angle the angle - * @return {Number} the sine of the angle + *
      + * function setup() { + * let words = ['banana', 'apple', 'pear', 'lime']; + * print(words); // ['banana', 'apple', 'pear', 'lime'] + * let count = 4; // length of array * - * @example - *
      - * - * let a = 0.0; - * let inc = TWO_PI / 25.0; - * for (let i = 0; i < 25; i++) { - * line(i * 4, 50, i * 4, 50 + sin(a) * 40.0); - * a = a + inc; + * words = sort(words, count); + * print(words); // ['apple', 'banana', 'lime', 'pear'] * } - * describe(`vertical black lines extend down and up from center - * to form wave pattern.`); - * - *
      - */ - _main.default.prototype.sin = function (angle) { - return Math.sin(this._toRadians(angle)); - }; - /** - * Calculates the tangent of an angle. This function takes into account - * the current angleMode. Values are returned in the range of all real numbers. - * - * @method tan - * @param {Number} angle the angle - * @return {Number} the tangent of the angle + *
      + *
      + * 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 * - * @example - *
      - * - * let a = 0.0; - * let inc = TWO_PI / 50.0; - * for (let i = 0; i < 100; i = i + 2) { - * line(i, 50, i, 50 + tan(a) * 2.0); - * a = a + inc; + * numbers = sort(numbers, count); + * print(numbers); // [1,2,5,6,14,9,8,12] * } - * describe(`vertical black lines end down and up from center to - * form spike pattern.`); - * - */ - _main.default.prototype.tan = function (angle) { - return Math.tan(this._toRadians(angle)); - }; - /** - * Converts a radian measurement to its corresponding value in degrees. - * Radians and degrees are two ways of measuring the same thing. There are - * 360 degrees in a circle and 2*PI radians in a circle. For example, - * 90° = PI/2 = 1.5707964. This function does not take into account the - * current angleMode(). - * - * @method degrees - * @param {Number} radians the radians value to convert to degrees - * @return {Number} the converted angle - * - * @example - *
      - * - * let rad = PI / 4; - * let deg = degrees(rad); - * print(rad + ' radians is ' + deg + ' degrees'); - * // Prints: 0.7853981633974483 radians is 45 degrees - * - *
      + *
      */ - _main.default.prototype.degrees = function (angle) { - return angle * constants.RAD_TO_DEG; + _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); }; /** - * Converts a degree measurement to its corresponding value in radians. - * Radians and degrees are two ways of measuring the same thing. There are - * 360 degrees in a circle and 2*PI radians in a circle. For example, - * 90° = PI/2 = 1.5707964. This function does not take into account the - * current angleMode. + * 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 radians - * @param {Number} degrees the degree value to convert to radians - * @return {Number} the converted angle + * @method splice + * @deprecated Use array.splice() instead. + * @param {Array} list Array to splice into + * @param {any} value value to be spliced in + * @param {Integer} position in the array from which to insert data + * @return {Array} the list * * @example - *
      - * - * let deg = 45.0; - * let rad = radians(deg); - * print(deg + ' degrees is ' + rad + ' radians'); - * // Prints: 45 degrees is 0.7853981633974483 radians - * - *
      - */ - _main.default.prototype.radians = function (angle) { - return angle * constants.DEG_TO_RAD; - }; - /** - * Sets the current mode of p5 to the given mode. Default mode is RADIANS. + *
      + * 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'] * - * Calling angleMode() with no arguments returns current anglemode. - * @method angleMode - * @param {Constant} mode either RADIANS or DEGREES - * @example - *
      - * - * function draw() { - * background(204); - * angleMode(DEGREES); // Change the mode to DEGREES - * let a = atan2(mouseY - height / 2, mouseX - width / 2); - * translate(width / 2, height / 2); - * push(); - * rotate(a); - * rect(-20, -5, 40, 10); // Larger rectangle is rotating in degrees - * pop(); - * angleMode(RADIANS); // Change the mode to RADIANS - * rotate(a); // variable a stays the same - * rect(-40, -5, 20, 10); // Smaller rectangle is rotating in radians - * describe(`40×10 rect in center rotates with mouse moves. - * 20×10 rect moves faster.`); + * splice(myArray, insArray, 3); + * print(myArray); // [0,1,2,'A','B','C',3,4] * } - * - *
      - * - */ - /** - * @method angleMode - * @return {Constant} mode either RADIANS or DEGREES + *
      */ - _main.default.prototype.angleMode = function (mode) { - _main.default._validateParameters('angleMode', arguments); - if (typeof mode === 'undefined') { - return this._angleMode; - } else if (mode === constants.DEGREES || mode === constants.RADIANS) { - this._angleMode = mode; - } + _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; }; /** - * converts angles from the current angleMode to RADIANS + * 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 _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 subset + * @deprecated Use array.slice() instead. + * @param {Array} list Array to extract from + * @param {Integer} start position to begin + * @param {Integer} [count] number of values to extract + * @return {Array} Array of extracted elements * - * @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 + * @example + *
      + * function setup() { + * let myArray = [1, 2, 3, 4, 5]; + * print(myArray); // [1, 2, 3, 4, 5] * - * @method _fromRadians - * @private - * @param {Number} angle - * @returns {Number} + * let sub1 = subset(myArray, 0, 3); + * let sub2 = subset(myArray, 2, 2); + * print(sub1); // [1,2,3] + * print(sub2); // [3,4] + * } + *
      */ - _main.default.prototype._fromRadians = function (angle) { - if (this._angleMode === constants.DEGREES) { - return angle * constants.RAD_TO_DEG; + _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); } - return angle; }; var _default = _main.default; exports.default = _default; }, { - '../core/constants': 278, - '../core/main': 290, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + '../core/main': 298, + 'core-js/modules/es.array-buffer.constructor': 168, + 'core-js/modules/es.array.concat': 169, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.array.splice': 185, + 'core-js/modules/es.object.to-string': 200 } ], - 326: [ + 338: [ function (_dereq_, module, exports) { 'use strict'; + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.number.constructor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.repeat'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.number.constructor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.repeat'); Object.defineProperty(exports, '__esModule', { value: true }); @@ -90300,3681 +101292,3464 @@ obj }; } /** - * @module Typography - * @submodule Attributes + * @module Data + * @submodule Conversion * @for p5 * @requires core - * @requires constants */ /** - * Sets the current alignment for drawing text. Accepts two - * arguments: horizAlign (LEFT, CENTER, or RIGHT) and - * vertAlign (TOP, BOTTOM, CENTER, or BASELINE). - * - * The horizAlign parameter is in reference to the x value - * of the text() function, while the vertAlign parameter - * is in reference to the y value. + * 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. * - * So if you write textAlign(LEFT), you are aligning the left - * edge of your text to the x value you give in text(). - * If you write textAlign(RIGHT, TOP), you are aligning the right edge - * of your text to the x value and the top edge of the text - * to the y value. + * When an array of values is passed in, then an array of floats of the same + * length is returned. * - * @method textAlign - * @param {Constant} horizAlign horizontal alignment, either LEFT, - * CENTER, or RIGHT - * @param {Constant} [vertAlign] vertical alignment, either TOP, - * BOTTOM, CENTER, or BASELINE - * @chainable + * @method float + * @param {String} str float string to parse + * @return {Number} floating point representation of string * @example - *
      - * - * textSize(16); - * textAlign(RIGHT); - * text('ABCD', 50, 30); - * textAlign(CENTER); - * text('EFGH', 50, 50); - * textAlign(LEFT); - * text('IJKL', 50, 70); - * describe(`Letters ABCD displayed at top left, EFGH at center, and - * IJKL at bottom right.`); - * - *
      - * - *
      - * - * 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); - * - * describe(`The names of the four vertical alignments (TOP, CENTER, BASELINE, - * and BOTTOM) rendered each showing that alignment's placement relative to a - * horizontal line.`); - * - *
      - */ - /** - * @method textAlign - * @return {Object} + *
      + * let str = '20'; + * let diameter = float(str); + * ellipse(width / 2, height / 2, diameter, diameter); + * describe('20-by-20 white ellipse in the center of the canvas'); + *
      + *
      + * print(float('10.31')); // 10.31 + * print(float('Infinity')); // Infinity + * print(float('-Infinity')); // -Infinity + *
      */ - _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); + _main.default.prototype.float = function (str) { + if (str instanceof Array) { + return str.map(parseFloat); + } + return parseFloat(str); }; /** - * Sets/gets the spacing, in pixels, between lines of text. This setting will be - * used in all subsequent calls to the text() function. + * 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 textLeading - * @param {Number} leading the size in pixels for spacing between lines - * @chainable + * @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 - *
      - * - * let lines = 'L1\nL2\nL3'; // "\n" is a "new line" character - * textSize(12); - * - * textLeading(10); - * text(lines, 10, 25); - * - * textLeading(20); - * text(lines, 40, 25); - * - * textLeading(30); - * text(lines, 70, 25); - * - * describe(`A set of L1, L2, and L3, displayed vertically 3 times. - * Spacing increases for each set.`); - * - *
      + *
      + * 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 + *
      */ /** - * @method textLeading - * @return {Number} + * @method int + * @param {Array} ns values to parse + * @param {Integer} [radix] + * @return {Number[]} integer representation of values */ - _main.default.prototype.textLeading = function (theLeading) { - var _this$_renderer2; - _main.default._validateParameters('textLeading', arguments); - return (_this$_renderer2 = this._renderer).textLeading.apply(_this$_renderer2, arguments); + _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); + }); + } }; /** - * Sets/gets the current font size. This size will be used in all subsequent - * calls to the text() function. Font size is measured in pixels. - * - * @method textSize - * @param {Number} theSize the size of the letters in units of pixels - * @chainable + * 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 - *
      - * - * textSize(12); - * text('Font Size 12', 10, 30); - * textSize(14); - * text('Font Size 14', 10, 60); - * textSize(16); - * text('Font Size 16', 10, 90); - * - * describe(`'Font Size 12' displayed small, - * 'Font Size 14' medium, and - * 'Font Size 16' large`); - * - *
      + *
      + * 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" ] + *
      */ + _main.default.prototype.str = function (n) { + if (n instanceof Array) { + return n.map(_main.default.prototype.str); + } else { + return String(n); + } + }; /** - * @method textSize - * @return {Number} + * 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 + *
      + * print(boolean(0)); // false + * print(boolean(1)); // true + * print(boolean('true')); // true + * print(boolean('abcd')); // false + * print(boolean([0, 12, 'true'])); // [false, true, true] + *
      */ - _main.default.prototype.textSize = function (theSize) { - var _this$_renderer3; - _main.default._validateParameters('textSize', arguments); - return (_this$_renderer3 = this._renderer).textSize.apply(_this$_renderer3, arguments); + _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); + } }; /** - * 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. + * 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 * - * @method textStyle - * @param {Constant} theStyle styling for text, either NORMAL, - * ITALIC, BOLD or BOLDITALIC - * @chainable * @example - *
      - * - * 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); - * describe(`The words “Font Style Normal” displayed normally, - * “Font Style Italic” in italic, - * “Font Style Bold” in bold, and - * “Font Style Bold Italic” in bold italics.`); - * - *
      + *
      + * 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] + *
      */ /** - * @method textStyle - * @return {String} + * @method byte + * @param {Array} ns values to parse + * @return {Number[]} array of byte representation of values */ - _main.default.prototype.textStyle = function (theStyle) { - var _this$_renderer4; - _main.default._validateParameters('textStyle', arguments); - return (_this$_renderer4 = this._renderer).textStyle.apply(_this$_renderer4, arguments); + _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); + } }; /** - * Calculates and returns the width of any character or text string. - * - * @method textWidth - * @param {String} theText the String of characters to measure - * @return {Number} the calculated width - * @example - *
      - * - * textSize(28); - * - * let aChar = 'P'; - * let cWidth = textWidth(aChar); - * text(aChar, 0, 40); - * line(cWidth, 0, cWidth, 50); + * 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. * - * let aString = 'p5.js'; - * let sWidth = textWidth(aString); - * text(aString, 0, 85); - * line(sWidth, 50, sWidth, 100); + * @method char + * @param {String|Number} n value to parse + * @return {String} string representation of value * - * describe('Letter P and p5.js are displayed with vertical lines at end.'); - * - *
      + * @example + *
      + * print(char(65)); // "A" + * print(char('65')); // "A" + * print(char([65, 66, 67])); // [ "A", "B", "C" ] + * print(join(char([65, 66, 67]), '')); // "ABC" + *
      */ - _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; + /** + * @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)); } - return (_this$_renderer5 = this._renderer).textWidth.apply(_this$_renderer5, args); }; /** - * Returns the ascent of the current font at its current size. The ascent - * represents the distance, in pixels, of the tallest character above - * the baseline. - * @method textAscent - * @return {Number} - * @example - *
      - * - * let base = height * 0.75; - * let scalar = 0.8; // Different for each font + * 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. * - * 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 + * @method unchar + * @param {String} n value to parse + * @return {Number} integer representation of value * - * 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 - * - *
      + * @example + *
      + * print(unchar('A')); // 65 + * print(unchar(['A', 'B', 'C'])); // [ 65, 66, 67 ] + * print(unchar(split('ABC', ''))); // [ 65, 66, 67 ] + *
      */ - _main.default.prototype.textAscent = function () { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; + /** + * @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); } - _main.default._validateParameters('textAscent', args); - return this._renderer.textAscent(); }; /** - * Returns the descent of the current font at its current size. The descent - * represents the distance, in pixels, of the character with the longest - * descender below the baseline. - * @method textDescent - * @return {Number} - * @example - *
      - * - * let base = height * 0.75; - * let scalar = 0.8; // Different for each font + * 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. * - * textSize(32); // Set initial text size - * let desc = textDescent() * scalar; // Calc descent - * line(0, base + desc, width, base + desc); - * text('dp', 0, base); // Draw text on baseline + * @method hex + * @param {Number} n value to parse + * @param {Number} [digits] + * @return {String} hexadecimal string representation of value * - * textSize(64); // Increase text size - * desc = textDescent() * scalar; // Recalc descent - * line(40, base + desc, width, base + desc); - * text('dp', 40, base); // Draw text on baseline - * - *
      + * @example + *
      + * print(hex(255)); // "000000FF" + * print(hex(255, 6)); // "0000FF" + * print(hex([0, 127, 255], 6)); // [ "000000", "00007F", "0000FF" ] + * print(Infinity); // "FFFFFFFF" + * print(-Infinity); // "00000000" + *
      */ - _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. + * @method hex + * @param {Number[]} ns array of values to parse + * @param {Number} [digits] + * @return {String[]} hexadecimal string representation of values */ - _main.default.prototype._updateTextMetrics = function () { - return this._renderer._updateTextMetrics(); + _main.default.prototype.hex = function (n, digits) { + digits = digits === undefined || digits === null ? digits = 8 : digits; + if (n instanceof Array) { + return n.map(function (n) { + return _main.default.prototype.hex(n, digits); + }); + } else if (n === Infinity || n === - Infinity) { + var c = n === Infinity ? 'F' : '0'; + return c.repeat(digits); + } else if (typeof n === 'number') { + if (n < 0) { + n = 4294967295 + n + 1; + } + var hex = Number(n).toString(16).toUpperCase(); + while (hex.length < digits) { + hex = '0'.concat(hex); + } + if (hex.length >= digits) { + hex = hex.substring(hex.length - digits, hex.length); + } + return hex; + } }; /** - * Specifies how lines of text are wrapped within a text box. This requires a max-width set on the text area, specified in text() as parameter `x2`. - * - * WORD wrap style only breaks lines at spaces. A single string without spaces that exceeds the boundaries of the canvas or text area is not truncated, and will overflow the desired area, disappearing at the canvas edge. - * - * CHAR wrap style breaks lines wherever needed to stay within the text box. + * 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. * - * WORD is the default wrap style, and both styles will still break lines at any line breaks (`\n`) specified in the original text. The text area max-height parameter (`y2`) also still applies to wrapped text in both styles, lines of text that do not fit within the text area will not be drawn to the screen. + * @method unhex + * @param {String} n value to parse + * @return {Number} integer representation of hexadecimal value * - * @method textWrap - * @param {Constant} wrapStyle text wrapping style, either WORD or CHAR - * @return {String} wrapStyle * @example - *
      - * - * textSize(20); - * textWrap(WORD); - * text('Have a wonderful day', 0, 10, 100); - * - *
      - *
      - * - * textSize(20); - * textWrap(CHAR); - * text('Have a wonderful day', 0, 10, 100); - * - *
      - *
      - * - * textSize(20); - * textWrap(CHAR); - * text('祝你有美好的一天', 0, 10, 100); - * - *
      - *
      - * - * const scream = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; - * textSize(20); - * textWrap(WORD); - * text(scream, 0, 0, 100); - * fill(0, 0, 0, 75); - * text(scream, 0, 20, 100); - * fill(0, 0, 0, 50); - * text(scream, 0, 40, 100); - * fill(0, 0, 0, 25); - * text(scream, 0, 60, 100); - * strokeWeight(2); - * ellipseMode(CENTER); - * fill(255); - * ellipse(15, 50, 15, 15); - * fill(0); - * ellipse(11, 47, 1, 1); - * ellipse(19, 47, 1, 1); - * ellipse(15, 52, 5, 5); - * line(15, 60, 15, 70); - * line(15, 65, 5, 55); - * line(15, 65, 25, 55); - * line(15, 70, 10, 80); - * line(15, 70, 20, 80); - * - *
      + *
      + * print(unhex('A')); // 10 + * print(unhex('FF')); // 255 + * print(unhex(['FF', 'AA', '00'])); // [ 255, 170, 0 ] + *
      */ - _main.default.prototype.textWrap = function (wrapStyle) { - if (wrapStyle !== 'WORD' && wrapStyle !== 'CHAR') { - throw 'Error: textWrap accepts only WORD or CHAR'; + /** + * @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); } - return this._renderer.textWrap(wrapStyle); }; var _default = _main.default; exports.default = _default; }, { - '../core/main': 290 + '../core/main': 298, + 'core-js/modules/es.array.map': 182, + 'core-js/modules/es.number.constructor': 191, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.repeat': 213 } ], - 327: [ + 339: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); _dereq_('core-js/modules/es.symbol.description'); _dereq_('core-js/modules/es.symbol.iterator'); - _dereq_('core-js/modules/es.array.concat'); - _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.index-of'); _dereq_('core-js/modules/es.array.iterator'); - _dereq_('core-js/modules/es.array.last-index-of'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.map'); _dereq_('core-js/modules/es.array.slice'); - _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.number.to-fixed'); _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.constructor'); _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.match'); + _dereq_('core-js/modules/es.string.pad-start'); + _dereq_('core-js/modules/es.string.replace'); _dereq_('core-js/modules/es.string.split'); - _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/es.string.trim'); _dereq_('core-js/modules/web.dom-collections.iterator'); - function _typeof2(obj) { - if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { - _typeof2 = function _typeof2(obj) { - return typeof obj; - }; - } else { - _typeof2 = function _typeof2(obj) { - return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; - }; - } - return _typeof2(obj); - } - function _typeof(obj) { - if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { - _typeof = function _typeof(obj) { - return _typeof2(obj); - }; - } else { - _typeof = function _typeof(obj) { - return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); - }; - } - return _typeof(obj); - } - _dereq_('core-js/modules/es.array.concat'); - _dereq_('core-js/modules/es.array.includes'); - _dereq_('core-js/modules/es.array.last-index-of'); + _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.map'); _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.number.to-fixed'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.constructor'); _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.match'); + _dereq_('core-js/modules/es.string.pad-start'); + _dereq_('core-js/modules/es.string.replace'); _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.string.trim'); Object.defineProperty(exports, '__esModule', { value: true }); exports.default = void 0; var _main = _interopRequireDefault(_dereq_('../core/main')); - 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; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj }; - 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); + 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 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]; - } + 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; } } - newObj.default = obj; - if (cache) { - cache.set(obj, newObj); - } - return newObj; + return _arr; } - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: - obj - }; - } /** - * @module Typography - * @submodule Loading & Displaying - * @for p5 - * @requires core - */ + function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; + } /** + * @module Data + * @submodule String Functions + * @for p5 + * @requires core + */ + //return p5; //LM is this a mistake? /** - * Loads an opentype font file (.otf, .ttf) from a file or a URL, - * and returns a p5.Font object. This function - * 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. + * 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 nf() or + * nfs(). * - * @method loadFont - * @param {String} path name of the file or url to load - * @param {Function} [callback] function to be executed after - * loadFont() completes - * @param {Function} [onError] function to be executed if - * an error occurs - * @return {p5.Font} p5.Font object + * @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 - * - * Calling loadFont() inside preload() guarantees - * that the load operation will have completed before setup() - * and draw() are called. - * - *
      - * let myFont; - * function preload() { - * myFont = loadFont('assets/inconsolata.otf'); - * } - * - * function setup() { - * fill('#ED225D'); - * textFont(myFont); - * textSize(36); - * text('p5*js', 10, 50); - * } - *
      - * - * Outside of preload(), you may supply a - * callback function to handle the object: - * - *
      - * function setup() { - * loadFont('assets/inconsolata.otf', drawText); - * } - * - * function drawText(font) { - * fill('#ED225D'); - * textFont(font, 36); - * text('p5*js', 10, 50); - * } - *
      - * - * You can also use the font filename string (without the file extension) to - * style other HTML elements. - * - *
      - * function preload() { - * loadFont('assets/inconsolata.otf'); - * } - * - * function setup() { - * let myDiv = createDiv('hello there'); - * myDiv.style('font-family', 'Inconsolata'); - * } - *
      - * - * @alt - * p5*js in p5's theme dark pink - * p5*js in p5's theme dark pink + *
      + * + * let array = ['Hello', 'world!']; + * let separator = ' '; + * let message = join(array, separator); + * text(message, 5, 50); + * describe('“Hello world!” displayed middle left of canvas.'); + * + *
      */ - _main.default.prototype.loadFont = function (path, onSuccess, onError) { - _main.default._validateParameters('loadFont', arguments); - var p5Font = new _main.default.Font(this); - var self = this; - opentype.load(path, function (err, font) { - if (err) { - _main.default._friendlyFileLoadError(4, path); - if (typeof onError !== 'undefined') { - return onError(err); - } - console.error(err, path); - return; - } - p5Font.font = font; - if (typeof onSuccess !== 'undefined') { - onSuccess(p5Font); - } - self._decrementPreload(); // check that we have an acceptable font type - var validFontTypes = [ - 'ttf', - 'otf', - 'woff', - 'woff2' - ]; - var fileNoPath = path.split('\\').pop().split('/').pop(); - var lastDotIdx = fileNoPath.lastIndexOf('.'); - var fontFamily; - var newStyle; - var fileExt = lastDotIdx < 1 ? null : fileNoPath.slice(lastDotIdx + 1); // if so, add it to the DOM (name-only) for use with DOM module - if (validFontTypes.includes(fileExt)) { - fontFamily = fileNoPath.slice(0, lastDotIdx !== - 1 ? lastDotIdx : 0); - newStyle = document.createElement('style'); - newStyle.appendChild(document.createTextNode('\n@font-face {\nfont-family: '.concat(fontFamily, ';\nsrc: url(').concat(path, ');\n}\n'))); - document.head.appendChild(newStyle); - } - }); - return p5Font; + _main.default.prototype.join = function (list, separator) { + _main.default._validateParameters('join', arguments); + return list.join(separator); }; /** - * Draws text to the screen. Displays the information specified in the first - * parameter on the screen in the position specified by the additional - * parameters. A default font will be used unless a font is set with the - * textFont() function and a default size will be - * used unless a font is set with textSize(). Change - * the color of the text with the fill() function. Change - * the outline of the text with the stroke() and - * strokeWeight() functions. - * - * The text displays in relation to the textAlign() - * function, which gives the option to draw to the left, right, and center of the - * coordinates. - * - * The x2 and y2 parameters define a rectangular area to display within and - * may only be used with string data. When these parameters are specified, - * they are interpreted based on the current rectMode() - * setting. Text that does not fit completely within the rectangle specified will - * not be drawn to the screen. If x2 and y2 are not specified, the baseline - * alignment is the default, which means that the text will be drawn upwards - * from x and y. - * - * WEBGL: Only opentype/truetype fonts are supported. You must load a font - * using the loadFont() method (see the example above). - * stroke() currently has no effect in webgl mode. - * Learn more about working with text in webgl mode on the - * wiki. + * 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. * - * @method text - * @param {String|Object|Array|Number|Boolean} str the alphanumeric - * symbols to be displayed - * @param {Number} x x-coordinate of text - * @param {Number} y y-coordinate of text - * @param {Number} [x2] by default, the width of the text box, - * see rectMode() for more info - * @param {Number} [y2] by default, the height of the text box, - * see rectMode() for more info - * @chainable + * 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 *
      * - * textSize(32); - * text('word', 10, 30); - * fill(0, 102, 153); - * text('word', 10, 60); - * fill(0, 102, 153, 51); - * text('word', 10, 90); - * - *
      - *
      - * - * let s = 'The quick brown fox jumped over the lazy dog.'; - * fill(50); - * text(s, 10, 10, 70, 80); // Text wraps within text box + * let string = 'Hello p5js*!'; + * let regexp = 'p5js\\*'; + * let m = match(string, regexp); + * text(m, 5, 50); + * describe('“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 + *
      * - * 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); - * } + * let string = 'Hello p5js*! Hello world!'; + * let regexp = 'Hello'; + * matchAll(string, regexp); * *
      - * - * @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); + _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; }; /** - * Sets the current font that will be drawn with the text() function. - * If textFont() is called without any argument, it will return the current font if one has - * been set already. If not, it will return the name of the default font as a string. - * If textFont() is called with a font to use, it will return the p5 object. + * 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. * - * WEBGL: Only fonts loaded via loadFont() are supported. + * (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. * - * @method textFont - * @return {Object} the current font / p5 Object + * 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 *
      * - * fill(0); - * textSize(12); - * textFont('Georgia'); - * text('Georgia', 12, 30); - * textFont('Helvetica'); - * text('Helvetica', 12, 60); - * - *
      - *
      - * - * 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); + * background(200); + * let num1 = 321; + * let num2 = -1321; + * + * noStroke(); + * fill(0); + * textSize(16); + * + * text(nf(num1, 4, 2), 10, 30); + * text(nf(num2, 4, 2), 10, 80); + * // Draw dividing line + * stroke(120); + * line(0, 50, width, 50); + * + * describe('“0321.00” middle top, “-1321.00” middle bottom canvas'); * } * *
      - * - * @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 loadFont(), - * or a String representing a web safe font - * (a font that is generally available across all systems) - * @param {Number} [size] the font size to use - * @chainable + * @method nf + * @param {Array} nums the Numbers to format + * @param {Integer|String} [left] + * @param {Integer|String} [right] + * @return {String[]} formatted Strings */ - _main.default.prototype.textFont = function (theFont, theSize) { - _main.default._validateParameters('textFont', arguments); - if (arguments.length) { - if (!theFont) { - throw new Error('null font passed to textFont'); - } - this._renderer._setProperty('_textFont', theFont); - if (theSize) { - this._renderer._setProperty('_textSize', theSize); - if (!this._renderer._leadingSet) { - // only use a default value if not previously set (#5181) - this._renderer._setProperty('_textLeading', theSize * constants._DEFAULT_LEADMULT); - } - } - return this._renderer._applyTextProperties(); - } - return this._renderer._textFont; - }; - var _default = _main.default; - exports.default = _default; - }, - { - '../core/constants': 278, - '../core/friendly_errors/fes_core': 281, - '../core/friendly_errors/file_errors': 282, - '../core/friendly_errors/validate_params': 285, - '../core/main': 290, - 'core-js/modules/es.array.concat': 167, - 'core-js/modules/es.array.includes': 174, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.last-index-of': 178, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.exec': 199, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.string.split': 209, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248, - 'opentype.js': 263 - } - ], - 328: [ - function (_dereq_, module, exports) { - 'use strict'; - _dereq_('core-js/modules/es.symbol'); - _dereq_('core-js/modules/es.symbol.description'); - _dereq_('core-js/modules/es.symbol.iterator'); - _dereq_('core-js/modules/es.array.concat'); - _dereq_('core-js/modules/es.array.fill'); - _dereq_('core-js/modules/es.array.iterator'); - _dereq_('core-js/modules/es.array.join'); - _dereq_('core-js/modules/es.array.slice'); - _dereq_('core-js/modules/es.array.splice'); - _dereq_('core-js/modules/es.function.name'); - _dereq_('core-js/modules/es.number.to-fixed'); - _dereq_('core-js/modules/es.object.get-own-property-descriptor'); - _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.regexp.exec'); - _dereq_('core-js/modules/es.string.iterator'); - _dereq_('core-js/modules/es.string.split'); - _dereq_('core-js/modules/es.weak-map'); - _dereq_('core-js/modules/web.dom-collections.iterator'); - function _typeof2(obj) { - if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { - _typeof2 = function _typeof2(obj) { - return typeof obj; - }; + _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 { - _typeof2 = function _typeof2(obj) { - return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; - }; - } - return _typeof2(obj); - } - _dereq_('core-js/modules/es.symbol'); - _dereq_('core-js/modules/es.symbol.description'); - _dereq_('core-js/modules/es.symbol.iterator'); - _dereq_('core-js/modules/es.array.concat'); - _dereq_('core-js/modules/es.array.fill'); - _dereq_('core-js/modules/es.array.iterator'); - _dereq_('core-js/modules/es.array.join'); - _dereq_('core-js/modules/es.array.slice'); - _dereq_('core-js/modules/es.array.splice'); - _dereq_('core-js/modules/es.function.name'); - _dereq_('core-js/modules/es.number.to-fixed'); - _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.regexp.exec'); - _dereq_('core-js/modules/es.string.iterator'); - _dereq_('core-js/modules/es.string.split'); - _dereq_('core-js/modules/web.dom-collections.iterator'); - Object.defineProperty(exports, '__esModule', { - value: true - }); - exports.default = void 0; - var _main = _interopRequireDefault(_dereq_('../core/main')); - var constants = _interopRequireWildcard(_dereq_('../core/constants')); - function _getRequireWildcardCache() { - if (typeof WeakMap !== 'function') return null; - var cache = new WeakMap(); - _getRequireWildcardCache = function _getRequireWildcardCache() { - return cache; - }; - return cache; - } - function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } - if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { - return { - default: - obj - }; - } - var cache = _getRequireWildcardCache(); - if (cache && cache.has(obj)) { - return cache.get(obj); - } - var newObj = { - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); + 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 { - newObj[key] = obj[key]; + return this.nf(nums[0]); } + } else { + return doNf(nums, left, right); } } - newObj.default = obj; - if (cache) { - cache.set(obj, newObj); - } - return newObj; - } - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: - obj - }; - } - function _typeof(obj) { - if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { - _typeof = function _typeof(obj) { - return _typeof2(obj); - }; + }; + function doNf(num, left, right) { + var _num$toString$split = num.toString().split('.'), + _num$toString$split2 = _slicedToArray(_num$toString$split, 2), + leftPart = _num$toString$split2[0], + rightPart = _num$toString$split2[1]; + if (typeof right === 'undefined') { + leftPart = leftPart.padStart(left, '0'); + return rightPart ? leftPart + '.' + rightPart : leftPart; } else { - _typeof = function _typeof(obj) { - return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); - }; + var roundedOff = num.toFixed(right); + var _roundedOff$toString$ = roundedOff.toString().split('.'); + var _roundedOff$toString$2 = _slicedToArray(_roundedOff$toString$, 2); + leftPart = _roundedOff$toString$2[0]; + rightPart = _roundedOff$toString$2[1]; + leftPart = leftPart.padStart(left, '0'); + if (typeof rightPart === 'undefined') { + return leftPart; + } else { + return leftPart + '.' + rightPart; + } } - 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' + * 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. * - * @return {Object} a rectangle object with properties: x, y, w, h + * @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 *
      * - * let font; - * let textString = 'Lorem ipsum dolor sit amet.'; - * function preload() { - * font = loadFont('./assets/Regular.otf'); - * } * function setup() { - * background(210); + * background(200); + * let num = 11253106.115; + * let numArr = [1, 1, 2]; * - * 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); + * fill(0); * textSize(12); - * text(textString, 10, 30); * - * describe(`Words “Lorem ipsum dol” go off canvas and - * contained by white bounding box`); + * // 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); + * + * describe('“11,253,106.115” top middle and “1.00,1.00,2.00” displayed bottom mid'); * } * *
      */ - _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]; + /** + * @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); } - 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); + }; + 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'; } - }); - 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; + } else { + rem = rem.substring(0, right + 1); } } - 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: - * - *
      sampleFactor - the ratio of path-length to number of samples - * (default=.1); higher values yield more points and are therefore - * more precise + return n + rem; + } /** + * Utility function for formatting numbers into strings. Similar to nf() but + * puts a "+" in front of positive numbers and a "-" in front of negative + * numbers. There are two versions: one for formatting floats, and one for + * formatting ints. The values for left, and right parameters + * should always be positive integers. * - *
      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 + * @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 * - * @return {Array} an array of points, each with x, y, alpha (the path angle) * @example *
      * - * let font; - * function preload() { - * font = loadFont('assets/inconsolata.otf'); - * } - * - * let points; - * let bounds; * function setup() { - * createCanvas(100, 100); - * stroke(0); - * fill(255, 104, 204); + * background(200); + * let num1 = 11253106.115; + * let num2 = -11253106.115; * - * points = font.textToPoints('p5', 0, 0, 10, { - * sampleFactor: 5, - * simplifyThreshold: 0 - * }); - * bounds = font.textBounds(' p5 ', 0, 0, 10); - * } + * noStroke(); + * fill(0); + * textSize(12); * - * 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); + * // 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); + * + * describe('“+11253106.11” top middle and “-11253106.11” displayed bottom middle'); * } * *
      */ - _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) - ; + /** + * @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]; } - 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); + _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); } - return result; - }; // ----------------------------- End API ------------------------------ - /** - * Returns the set of opentype glyphs for the supplied string. + }; + function addNfp(num) { + return parseFloat(num) > 0 ? '+'.concat(num.toString()) : num.toString(); + } /** + * Utility function for formatting numbers into strings. Similar to nf() but + * puts an additional "_" (space) in front of positive numbers just in case to align it with negative + * numbers which includes "-" (minus) sign. * - * 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. + * 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. * - * @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. + * The values for the digits, left, and right parameters should always be positive integers. * - * @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 + * (IMP): The result on the canvas basically the expected alignment can vary based on the typeface you are using. + * + * (NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter + * if greater than the current length of the number. + * + * For example if number is 123.2 and left parameter passed is 4 which is greater than length of 123 + * (integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than + * the result will be 123.200. + * + * @method nfs + * @param {Number} num the Number to format + * @param {Integer} [left] number of digits to the left of the decimal + * point + * @param {Integer} [right] number of digits to the right of the + * decimal point + * @return {String} formatted String + * + * @example + *
      + * + * function setup() { + * background(200); + * let num1 = 321; + * let num2 = -1321; * - * @param {Object} path an opentype path, OR the following: + * noStroke(); + * fill(0); + * textSize(16); * - * @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 + * // 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); * - * @return {Object} this p5.Font object + * describe('“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.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; + _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); } - return line.toPathData(decimals); }; - /* - * Creates an SVG element, as a string, - * from the given opentype path or string/position - * - * @param {Object} path an opentype path, OR the following: + function addNfs(num) { + return parseFloat(num) >= 0 ? ' '.concat(num.toString()) : num.toString(); + } /** + * The split() function maps to String.split(), it breaks a String into + * pieces using a character or string as the delimiter. The delim parameter + * specifies the character or characters that mark the boundaries between + * each piece. A String[] array is returned that contains each of the pieces. * - * @param {String} line a line of text - * @param {Number} x x-position - * @param {Number} y y-position - * @param {Object} options opentype options (optional), set options.decimals - * to set the decimal precision of the path-data in the element, - * options.fill to set the fill color for the element, - * options.stroke to set the stroke color for the element, - * options.strokeWidth to set the strokeWidth for the element. + * The splitTokens() function works in a similar fashion, except that it + * splits using a range of characters instead of a specific character or + * sequence. * - * @return {Object} this p5.Font object + * @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 + *
      + * + * let names = 'Pat,Xio,Alex'; + * let splitString = split(names, ','); + * text(splitString[0], 5, 30); + * text(splitString[1], 5, 50); + * text(splitString[2], 5, 70); + * describe('“Pat” top left, “Xio” mid left, and “Alex” displayed bottom left'); + * + *
      */ - _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; + _main.default.prototype.split = function (str, delim) { + _main.default._validateParameters('split', arguments); + return str.split(delim); + }; + /** + * The splitTokens() function splits a String at one or many character + * delimiters or "tokens." The delim parameter specifies the character or + * characters to be used as a boundary. + * + * If no delim characters are specified, any whitespace character is used to + * split. Whitespace characters include tab (\t), line feed (\n), carriage + * return (\r), form feed (\f), and space. + * + * @method splitTokens + * @param {String} value the String to be split + * @param {String} [delim] list of individual Strings that will be used as + * separators + * @return {String[]} Array of Strings + * @example + *
      + * + * function setup() { + * let myStr = 'Mango, Banana, Lime'; + * let myStrArr = splitTokens(myStr, ','); + * + * print(myStrArr); // prints : ["Mango"," Banana"," Lime"] + * } + * + *
      + */ + _main.default.prototype.splitTokens = function (value, delims) { + _main.default._validateParameters('splitTokens', arguments); + var d; + if (typeof delims !== 'undefined') { + var str = delims; + var sqc = /\]/g.exec(str); + var sqo = /\[/g.exec(str); + if (sqo && sqc) { + str = str.slice(0, sqc.index) + str.slice(sqc.index + 1); + sqo = /\[/g.exec(str); + str = str.slice(0, sqo.index) + str.slice(sqo.index + 1); + d = new RegExp('[\\['.concat(str, '\\]]'), 'g'); + } else if (sqc) { + str = str.slice(0, sqc.index) + str.slice(sqc.index + 1); + d = new RegExp('['.concat(str, '\\]]'), 'g'); + } else if (sqo) { + str = str.slice(0, sqo.index) + str.slice(sqo.index + 1); + d = new RegExp('['.concat(str, '\\[]'), 'g'); + } else { + d = new RegExp('['.concat(str, ']'), 'g'); } + } else { + d = /\s/g; } - return line.toSVG(decimals); + return value.split(d).filter(function (n) { + return n; + }); }; - /* - * Renders an opentype path or string/position - * to the current graphics context - * - * @param {Object} path an opentype path, OR the following: + /** + * 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. * - * @param {String} line a line of text - * @param {Number} x x-position - * @param {Number} y y-position - * @param {Object} options opentype options (optional) + * @method trim + * @param {String} str a String to be trimmed + * @return {String} a trimmed String * - * @return {p5.Font} this p5.Font object + * @example + *
      + * + * let string = trim(' No new lines\n '); + * text(string + ' here', 2, 50); + * describe('“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.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; + _main.default.prototype.trim = function (str) { + _main.default._validateParameters('trim', arguments); + if (str instanceof Array) { + return str.map(this.trim); } else { - //pos = handleAlignment(p, ctx, line, x, y); - pdata = this._getPath(line, x, y, options).commands; + return str.trim(); } - 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 + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/friendly_errors/fes_core': 289, + '../core/friendly_errors/file_errors': 290, + '../core/friendly_errors/validate_params': 293, + '../core/main': 298, + 'core-js/modules/es.array.filter': 173, + 'core-js/modules/es.array.index-of': 178, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.join': 180, + 'core-js/modules/es.array.map': 182, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.number.to-fixed': 193, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.constructor': 204, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.string.match': 211, + 'core-js/modules/es.string.pad-start': 212, + 'core-js/modules/es.string.replace': 214, + 'core-js/modules/es.string.split': 216, + 'core-js/modules/es.string.trim': 219, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/web.dom-collections.iterator': 256 + } + ], + 340: [ + function (_dereq_, module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module IO + * @submodule Time & Date + * @for p5 + * @requires core + */ + /** + * p5.js communicates with the clock on your computer. The day() function + * returns the current day as a value from 1 - 31. + * + * @method day + * @return {Integer} the current day + * @example + *
      + * + * let d = day(); + * text('Current day: \n' + d, 5, 50); + * describe('Current day is displayed'); + * + *
      + */ - } 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.prototype.day = function () { + return new Date().getDate(); + }; + /** + * p5.js communicates with the clock on your computer. The hour() function + * returns the current hour as a value from 0 - 23. + * + * @method hour + * @return {Integer} the current hour + * @example + *
      + * + * let h = hour(); + * text('Current hour:\n' + h, 5, 50); + * describe('Current hour is displayed'); + * + *
      + */ + _main.default.prototype.hour = function () { + return new Date().getHours(); }; - _main.default.Font.prototype._textWidth = function (str, fontSize) { - return this.font.getAdvanceWidth(str, fontSize); + /** + * p5.js communicates with the clock on your computer. The minute() function + * returns the current minute as a value from 0 - 59. + * + * @method minute + * @return {Integer} the current minute + * @example + *
      + * + * let m = minute(); + * text('Current minute: \n' + m, 5, 50); + * describe('Current minute is displayed'); + * + *
      + */ + _main.default.prototype.minute = function () { + return new Date().getMinutes(); }; - _main.default.Font.prototype._textAscent = function (fontSize) { - return this.font.ascender * this._scale(fontSize); + /** + * 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 + *
      + * + * let millisecond = millis(); + * text('Milliseconds \nrunning: \n' + millisecond, 5, 40); + * describe('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; + } }; - _main.default.Font.prototype._textDescent = function (fontSize) { - return - this.font.descender * this._scale(fontSize); + /** + * p5.js communicates with the clock on your computer. The month() function + * returns the current month as a value from 1 - 12. + * + * @method month + * @return {Integer} the current month + * @example + *
      + * + * let m = month(); + * text('Current month: \n' + m, 5, 50); + * describe('Current month is displayed'); + * + *
      + */ + _main.default.prototype.month = function () { + //January is 0! + return new Date().getMonth() + 1; }; - _main.default.Font.prototype._scale = function (fontSize) { - return 1 / this.font.unitsPerEm * (fontSize || this.parent._renderer._textSize); + /** + * p5.js communicates with the clock on your computer. The second() function + * returns the current second as a value from 0 - 59. + * + * @method second + * @return {Integer} the current second + * @example + *
      + * + * let s = second(); + * text('Current second: \n' + s, 5, 50); + * describe('Current second is displayed'); + * + *
      + */ + _main.default.prototype.second = function () { + return new Date().getSeconds(); }; - _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; + /** + * p5.js communicates with the clock on your computer. The year() function + * returns the current year as an integer (2014, 2015, 2016, etc). + * + * @method year + * @return {Integer} the current year + * @example + *
      + * + * let y = year(); + * text('Current year: \n' + y, 5, 50); + * describe('Current year is displayed'); + * + *
      + */ + _main.default.prototype.year = function () { + return new Date().getFullYear(); + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 298 + } + ], + 341: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.math.hypot'); + _dereq_('core-js/modules/es.math.sign'); + _dereq_('core-js/modules/es.number.to-fixed'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; } - 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 _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; } - return { - x: x, - y: y + return _typeof(obj); + } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.math.hypot'); + _dereq_('core-js/modules/es.math.sign'); + _dereq_('core-js/modules/es.number.to-fixed'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + _dereq_('./p5.Geometry'); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; }; - }; // 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)); + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; } - if (opts.simplifyThreshold) { - simplify(pts, opts.simplifyThreshold); + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; } - 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++; - } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); } - 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); + 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]; } - current = [ - ]; } - current.push(cmdToArr(cmds[i])); } - paths.push(current); - return paths; + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; } - 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 */ } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Shape + * @submodule 3D Primitives + * @for p5 + * @requires core + * @requires p5.Geometry + */ + /** + * Starts creating a new p5.Geometry. Subsequent shapes drawn will be added + * to the geometry and then returned when + * endGeometry() is called. One can also use + * buildGeometry() to pass a function that + * draws shapes. + * + * If you need to draw complex shapes every frame which don't change over time, + * combining them upfront with `beginGeometry()` and `endGeometry()` and then + * drawing that will run faster than repeatedly drawing the individual pieces. + * + * @method beginGeometry + * + * @example + *
      + * + * let shapes; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * makeShapes(); + * } + * + * function makeShapes() { + * beginGeometry(); + * scale(0.18); + * + * push(); + * translate(100, -50); + * scale(0.5); + * rotateX(PI/4); + * cone(); + * pop(); + * cone(); + * + * beginShape(); + * vertex(-20, -50); + * quadraticVertex( + * -40, -70, + * 0, -60 + * ); + * endShape(); + * + * beginShape(TRIANGLE_STRIP); + * for (let y = 20; y <= 60; y += 10) { + * for (let x of [20, 60]) { + * vertex(x, y); + * } + * } + * endShape(); + * + * beginShape(); + * vertex(-100, -120); + * vertex(-120, -110); + * vertex(-105, -100); + * endShape(); + * + * shapes = endGeometry(); + * } + * + * function draw() { + * background(255); + * lights(); + * orbitControl(); + * model(shapes); + * } + * + *
      + * + * @alt + * A series of different flat, curved, and 3D shapes floating in space. + */ - 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]; - } - } + _main.default.prototype.beginGeometry = function () { + return this._renderer.beginGeometry(); + }; + /** + * Finishes creating a new p5.Geometry that was + * started using beginGeometry(). One can also + * use buildGeometry() to pass a function that + * draws shapes. + * + * @method endGeometry + * @returns {p5.Geometry} The model that was built. + */ + _main.default.prototype.endGeometry = function () { + return this._renderer.endGeometry(); + }; + /** + * Creates a new p5.Geometry that contains all + * the shapes drawn in a provided callback function. The returned combined shape + * can then be drawn all at once using model(). + * + * If you need to draw complex shapes every frame which don't change over time, + * combining them with `buildGeometry()` once and then drawing that will run + * faster than repeatedly drawing the individual pieces. + * + * One can also draw shapes directly between + * beginGeometry() and + * endGeometry() instead of using a callback + * function. + * + * @method buildGeometry + * @param {Function} callback A function that draws shapes. + * @returns {p5.Geometry} The model that was built from the callback function. + * + * @example + *
      + * + * let particles; + * let button; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * button = createButton('New'); + * button.mousePressed(makeParticles); + * makeParticles(); + * } + * + * function makeParticles() { + * if (particles) freeGeometry(particles); + * + * particles = buildGeometry(() => { + * for (let i = 0; i < 60; i++) { + * push(); + * translate( + * randomGaussian(0, 20), + * randomGaussian(0, 20), + * randomGaussian(0, 20) + * ); + * sphere(5); + * pop(); + * } + * }); + * } + * + * function draw() { + * background(255); + * noStroke(); + * lights(); + * orbitControl(); + * model(particles); + * } + * + *
      + * + * @alt + * A cluster of spheres. + */ + _main.default.prototype.buildGeometry = function (callback) { + return this._renderer.buildGeometry(callback); + }; + /** + * Clears the resources of a model to free up browser memory. A model whose + * resources have been cleared can still be drawn, but the first time it is + * drawn again, it might take longer. + * + * This method works on models generated with + * buildGeometry() as well as those loaded + * from loadModel(). + * + * @method freeGeometry + * @param {p5.Geometry} geometry The geometry whose resources should be freed + */ + _main.default.prototype.freeGeometry = function (geometry) { + this._renderer._freeBuffers(geometry.gid); + }; + /** + * Draw a plane with given a width and height + * @method plane + * @param {Number} [width] width of the plane + * @param {Number} [height] height of the plane + * @param {Integer} [detailX] Optional number of triangle + * subdivisions in x-dimension + * @param {Integer} [detailY] Optional number of triangle + * subdivisions in y-dimension + * @chainable + * @example + *
      + * + * // draw a plane + * // with width 50 and height 50 + * function setup() { + * createCanvas(100, 100, WEBGL); + * describe('a white plane with black wireframe lines'); + * } + * + * function draw() { + * background(200); + * plane(50, 50); + * } + * + *
      + * + * @alt + * Nothing displayed on canvas + * Rotating interior view of a box with sides that change color. + * 3d red and green gradient. + * Rotating interior view of a cylinder with sides that change color. + * Rotating view of a cylinder with sides that change color. + * 3d red and green gradient. + * rotating view of a multi-colored cylinder with concave sides. + */ + _main.default.prototype.plane = function (width, height, detailX, detailY) { + this._assert3d('plane'); + _main.default._validateParameters('plane', arguments); + if (typeof width === 'undefined') { + width = 50; } - 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 height === 'undefined') { + height = width; } - if (typeof collinear.tmpPoint1 === 'undefined') { - collinear.tmpPoint1 = [ - ]; - collinear.tmpPoint2 = [ - ]; + if (typeof detailX === 'undefined') { + detailX = 1; } - 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; + if (typeof detailY === 'undefined') { + detailY = 1; } - 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 - }; + 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); } } - len += l; - x = + p[5]; - y = + p[6]; + }; + 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'); } - sp += p.shift() + p; + this._renderer.createBuffers(gId, planeGeom); } - 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 - }; + this._renderer.drawBuffersScaled(gId, width, height, 1); + return this; + }; + /** + * Draw a box with given width, height and depth + * @method box + * @param {Number} [width] width of the box + * @param {Number} [height] height of the box + * @param {Number} [depth] depth of the box + * @param {Integer} [detailX] Optional number of triangle + * subdivisions in x-dimension + * @param {Integer} [detailY] Optional number of triangle + * subdivisions in y-dimension + * @chainable + * @example + *
      + * + * // draw a spinning box + * // with width, height and depth of 50 + * function setup() { + * createCanvas(100, 100, WEBGL); + * describe('a white box rotating in 3D space'); + * } + * + * function draw() { + * background(200); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * box(50); + * } + * + *
      + */ + _main.default.prototype.box = function (width, height, depth, detailX, detailY) { + this._assert3d('box'); + _main.default._validateParameters('box', arguments); + if (typeof width === 'undefined') { + width = 50; } - 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 (typeof height === 'undefined') { + height = width; } - if (pathArray[0][0] === 'M') { - x = + pathArray[0][1]; - y = + pathArray[0][2]; - mx = x; - my = y; - start++; - res[0] = [ - 'M', - x, - y - ]; + if (typeof depth === 'undefined') { + depth = height; } - 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]; - } + var perPixelLighting = this._renderer.attributes && this._renderer.attributes.perPixelLighting; + if (typeof detailX === 'undefined') { + detailX = perPixelLighting ? 1 : 4; } - 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'; + if (typeof detailY === 'undefined') { + detailY = perPixelLighting ? 1 : 4; + } + var gId = 'box|'.concat(detailX, '|').concat(detailY); + if (!this._renderer.geometryInHash(gId)) { + var _box = function _box() { + var _this = this; + var cubeIndices = [ + [0, + 4, + 2, + 6], + // -1, 0, 0],// -x + [ + 1, + 3, + 5, + 7 + ], + // +1, 0, 0],// +x + [ + 0, + 1, + 4, + 5 + ], + // 0, -1, 0],// -y + [ + 2, + 6, + 3, + 7 + ], + // 0, +1, 0],// +y + [ + 0, + 2, + 1, + 3 + ], + // 0, 0, -1],// -z + [ + 4, + 5, + 6, + 7 + ] // 0, 0, +1] // +z + ]; + //using custom edges + //to avoid diagonal stroke lines across face of box + this.edges = [ + [0, + 1], + [ + 1, + 3 + ], + [ + 3, + 2 + ], + [ + 6, + 7 + ], + [ + 8, + 9 + ], + [ + 9, + 11 + ], + [ + 14, + 15 + ], + [ + 16, + 17 + ], + [ + 17, + 19 + ], + [ + 18, + 19 + ], + [ + 20, + 21 + ], + [ + 22, + 23 + ] + ]; + cubeIndices.forEach(function (cubeIndex, i) { + var v = i * 4; + for (var j = 0; j < 4; j++) { + var d = cubeIndex[j]; + //inspired by lightgl: + //https://github.com/evanw/lightgl.js + //octants:https://en.wikipedia.org/wiki/Octant_(solid_geometry) + var octant = new _main.default.Vector(((d & 1) * 2 - 1) / 2, ((d & 2) - 1) / 2, ((d & 4) / 2 - 1) / 2); + _this.vertices.push(octant); + _this.uvs.push(j & 1, (j & 2) / 2); } - 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 + _this.faces.push([v, + v + 1, + v + 2]); + _this.faces.push([v + 2, + v + 1, + v + 3]); + }); + }; + var boxGeom = new _main.default.Geometry(detailX, detailY, _box); + boxGeom.computeNormals(); + if (detailX <= 4 && detailY <= 4) { + boxGeom._edgesToVertices(); + } else if (this._renderer._doStroke) { + console.log('Cannot draw stroke on box objects with more' + ' than 4 detailX or 4 detailY'); + } //initialize our geometry buffer with + //the key val pair: + //geometry Id, Geom object + this._renderer.createBuffers(gId, boxGeom); + } + this._renderer.drawBuffersScaled(gId, width, height, depth); + return this; + }; + /** + * Draw a sphere with given radius. + * + * DetailX and detailY determines the number of subdivisions in the x-dimension + * and the y-dimension of a sphere. More subdivisions make the sphere seem + * smoother. The recommended maximum values are both 24. Using a value greater + * than 24 may cause a warning or slow down the browser. + * @method sphere + * @param {Number} [radius] radius of circle + * @param {Integer} [detailX] optional number of subdivisions in x-dimension + * @param {Integer} [detailY] optional number of subdivisions in y-dimension + * + * @chainable + * @example + *
      + * + * // draw a sphere with radius 40 + * function setup() { + * createCanvas(100, 100, WEBGL); + * describe('a white sphere with black wireframe lines'); + * } + * + * function draw() { + * background(205, 102, 94); + * sphere(40); + * } + * + *
      + * + * @example + *
      + * + * let detailX; + * // slide to see how detailX works + * function setup() { + * createCanvas(100, 100, WEBGL); + * detailX = createSlider(3, 24, 3); + * detailX.position(10, height + 5); + * detailX.style('width', '80px'); + * describe( + * 'a white sphere with low detail on the x-axis, including a slider to adjust detailX' + * ); + * } + * + * function draw() { + * background(205, 105, 94); + * rotateY(millis() / 1000); + * sphere(40, detailX.value(), 16); + * } + * + *
      + * + * @example + *
      + * + * let detailY; + * // slide to see how detailY works + * function setup() { + * createCanvas(100, 100, WEBGL); + * detailY = createSlider(3, 16, 3); + * detailY.position(10, height + 5); + * detailY.style('width', '80px'); + * describe( + * 'a white sphere with low detail on the y-axis, including a slider to adjust detailY' + * ); + * } + * + * function draw() { + * background(205, 105, 94); + * rotateY(millis() / 1000); + * sphere(40, 16, detailY.value()); + * } + * + *
      + */ + _main.default.prototype.sphere = function (radius, detailX, detailY) { + this._assert3d('sphere'); + _main.default._validateParameters('sphere', arguments); + if (typeof radius === 'undefined') { + radius = 50; + } + if (typeof detailX === 'undefined') { + detailX = 24; + } + if (typeof detailY === 'undefined') { + detailY = 16; + } + this.ellipsoid(radius, radius, radius, detailX, detailY); + return this; + }; + /** + * @private + * Helper function for creating both cones and cylinders + * Will only generate well-defined geometry when bottomRadius, height > 0 + * and topRadius >= 0 + * If topRadius == 0, topCap should be false + */ + var _truncatedCone = function _truncatedCone(bottomRadius, topRadius, height, detailX, detailY, bottomCap, topCap) { + bottomRadius = bottomRadius <= 0 ? 1 : bottomRadius; + topRadius = topRadius < 0 ? 0 : topRadius; + height = height <= 0 ? bottomRadius : height; + detailX = detailX < 3 ? 3 : detailX; + detailY = detailY < 1 ? 1 : detailY; + bottomCap = bottomCap === undefined ? true : bottomCap; + topCap = topCap === undefined ? topRadius !== 0 : topCap; + var start = bottomCap ? - 2 : 0; + var end = detailY + (topCap ? 2 : 0); + //ensure constant slant for interior vertex normals + var slant = Math.atan2(bottomRadius - topRadius, height); + var sinSlant = Math.sin(slant); + var cosSlant = Math.cos(slant); + var yy, + ii, + jj; + for (yy = start; yy <= end; ++yy) { + var v = yy / detailY; + var y = height * v; + var ringRadius = void 0; + if (yy < 0) { + //for the bottomCap edge + y = 0; + v = 0; + ringRadius = bottomRadius; + } else if (yy > detailY) { + //for the topCap edge + y = height; + v = 1; + ringRadius = topRadius; + } else { + //for the middle + ringRadius = bottomRadius + (topRadius - bottomRadius) * v; } - p[i] = processPath(p[i], attrs, pcom); - if (pcoms1[i] !== 'A' && pfirst === 'C') { - pcoms1[i] = 'C'; + if (yy === - 2 || yy === detailY + 2) { + //center of bottom or top caps + ringRadius = 0; } - 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'; + 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); } - fixArc(p2, i); + this.vertexNormals.push(vertexNormal); + //UVs + this.uvs.push(u, v); } - 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; + 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]); } - if (!sweep_flag && f2 > f1) { - f2 = f2 - PI * 2; + 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]); } - } else { - f1 = recursive[0]; - f2 = recursive[1]; - cx = recursive[2]; - cy = recursive[3]; + startIndex += detailX; } - 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 - ]); + if (topCap) { + startIndex += detailX; + for (ii = 0; ii < detailX; ++ii) { + this.faces.push([startIndex + ii, + startIndex + (ii + 1) % detailX, + startIndex + detailX]); + } } - df = f2 - f1; - var c1 = Math.cos(f1), - s1 = Math.sin(f1), - c2 = Math.cos(f2), - s2 = Math.sin(f2), - t = Math.tan(df / 4), - hx = 4 / 3 * rx * t, - hy = 4 / 3 * ry * t, - m1 = [ - x1, - y1 - ], - m2 = [ - x1 + hx * s1, - y1 - hy * c1 - ], - m3 = [ - x2 + hx * s2, - y2 - hy * c2 - ], - m4 = [ - x2, - y2 - ]; - m2[0] = 2 * m1[0] - m2[0]; - m2[1] = 2 * m1[1] - m2[1]; - if (recursive) { - return [m2, - m3, - m4].concat(res); - } else { - res = [ - m2, - m3, - m4 - ].concat(res).join().split(','); - var newres = [ - ]; - for (var i = 0, ii = res.length; i < ii; i++) { - newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x; - } - return newres; - } - } // http://schepers.cc/getting-to-the-point - - function catmullRom2bezier(crp, z) { - var d = [ - ]; - for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) { - var p = [ - { - x: + crp[i - 2], - y: + crp[i - 1] - }, - { - x: + crp[i], - y: + crp[i + 1] - }, - { - x: + crp[i + 2], - y: + crp[i + 3] - }, - { - x: + crp[i + 4], - y: + crp[i + 5] - } - ]; - if (z) { - if (!i) { - p[0] = { - x: + crp[iLen - 2], - y: + crp[iLen - 1] - }; - } else if (iLen - 4 === i) { - p[3] = { - x: + crp[0], - y: + crp[1] - }; - } else if (iLen - 2 === i) { - p[2] = { - x: + crp[0], - y: + crp[1] - }; - p[3] = { - x: + crp[2], - y: + crp[3] - }; - } - } else { - if (iLen - 4 === i) { - p[3] = p[2]; - } else if (!i) { - p[0] = { - x: + crp[i], - y: + crp[i + 1] - }; - } - } - d.push(['C', - ( - p[0].x + 6 * p[1].x + p[2].x) / 6, - ( - p[0].y + 6 * p[1].y + p[2].y) / 6, - (p[1].x + 6 * p[2].x - p[3].x) / 6, - (p[1].y + 6 * p[2].y - p[3].y) / 6, - p[2].x, - p[2].y]); - } - return d; - } - function l2c(x1, y1, x2, y2) { - return [x1, - y1, - x2, - y2, - x2, - y2]; - } - function q2c(x1, y1, ax, ay, x2, y2) { - var _13 = 1 / 3, - _23 = 2 / 3; - return [_13 * x1 + _23 * ax, - _13 * y1 + _23 * ay, - _13 * x2 + _23 * ax, - _13 * y2 + _23 * ay, - x2, - y2]; - } - function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) { - if (z == null) { - z = 1; - } - z = z > 1 ? 1 : z < 0 ? 0 : z; - var z2 = z / 2; - var n = 12; - var Tvalues = [ - - 0.1252, - 0.1252, - - 0.3678, - 0.3678, - - 0.5873, - 0.5873, - - 0.7699, - 0.7699, - - 0.9041, - 0.9041, - - 0.9816, - 0.9816 - ]; - var sum = 0; - var Cvalues = [ - 0.2491, - 0.2491, - 0.2335, - 0.2335, - 0.2032, - 0.2032, - 0.1601, - 0.1601, - 0.1069, - 0.1069, - 0.0472, - 0.0472 - ]; - for (var i = 0; i < n; i++) { - var ct = z2 * Tvalues[i] + z2, - xbase = base3(ct, x1, x2, x3, x4), - ybase = base3(ct, y1, y2, y3, y4), - comb = xbase * xbase + ybase * ybase; - sum += Cvalues[i] * Math.sqrt(comb); - } - return z2 * sum; - } - function getTatLen(x1, y1, x2, y2, x3, y3, x4, y4, ll) { - if (ll < 0 || bezlen(x1, y1, x2, y2, x3, y3, x4, y4) < ll) { - return; - } - var t = 1; - var step = t / 2; - var t2 = t - step; - var l; - var e = 0.01; - l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2); - while (Math.abs(l - ll) > e) { - step /= 2; - t2 += (l < ll ? 1 : - 1) * step; - l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2); - } - return t2; - } - function base3(t, p1, p2, p3, p4) { - var t1 = - 3 * p1 + 9 * p2 - 9 * p3 + 3 * p4, - t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3; - return t * t2 - 3 * p1 + 3 * p2; - } - function cacheKey() { - var hash = ''; - for (var i = arguments.length - 1; i >= 0; --i) { - hash += '?'.concat(i < 0 || arguments.length <= i ? undefined : arguments[i]); - } - return hash; - } - var _default = _main.default; - exports.default = _default; - }, - { - '../core/constants': 278, - '../core/main': 290, - 'core-js/modules/es.array.concat': 167, - 'core-js/modules/es.array.fill': 170, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.join': 177, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.array.splice': 182, - 'core-js/modules/es.function.name': 183, - 'core-js/modules/es.number.to-fixed': 189, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.exec': 199, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.string.split': 209, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 - } - ], - 329: [ - function (_dereq_, module, exports) { - 'use strict'; - _dereq_('core-js/modules/es.array.concat'); - _dereq_('core-js/modules/es.array.slice'); - _dereq_('core-js/modules/es.array.splice'); - _dereq_('core-js/modules/es.array-buffer.constructor'); - _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.array.concat'); - _dereq_('core-js/modules/es.array.slice'); - _dereq_('core-js/modules/es.array.splice'); - _dereq_('core-js/modules/es.array-buffer.constructor'); - _dereq_('core-js/modules/es.object.to-string'); - Object.defineProperty(exports, '__esModule', { - value: true - }); - exports.default = void 0; - var _main = _interopRequireDefault(_dereq_('../core/main')); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: - obj - }; - } /** - * @module Data - * @submodule Array Functions - * @for p5 - * @requires core - */ + }; /** - * Adds a value to the end of an array. Extends the length of - * the array by one. Maps to Array.push(). + * Draw a cylinder with given radius and height * - * @method append - * @deprecated Use array.push(value) instead. - * @param {Array} array Array to append - * @param {any} value to be added to the Array - * @return {Array} the array that was appended to + * 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 - *
      + *
      + * + * // draw a spinning cylinder + * // with radius 20 and height 50 * function setup() { - * let myArray = ['Mango', 'Apple', 'Papaya']; - * print(myArray); // ['Mango', 'Apple', 'Papaya'] - * - * append(myArray, 'Peach'); - * print(myArray); // ['Mango', 'Apple', 'Papaya', 'Peach'] + * createCanvas(100, 100, WEBGL); + * describe('a rotating white cylinder'); * } - *
      - */ - - _main.default.prototype.append = function (array, value) { - array.push(value); - return array; - }; - /** - * Copies an array (or part of an array) to another array. The src array is - * copied to the dst array, beginning at the position specified by - * srcPosition and into the position specified by dstPosition. The number of - * elements to copy is determined by length. Note that copying values - * overwrites existing values in the destination array. To append values - * instead of overwriting them, use concat(). - * - * The simplified version with only two arguments, arrayCopy(src, dst), - * copies an entire array to another of the same size. It is equivalent to - * arrayCopy(src, 0, dst, 0, src.length). * - * Using this function is far more efficient for copying array data than - * iterating through a for() loop and copying each element individually. - * - * @method arrayCopy - * @deprecated Use arr1.copyWithin(arr2) instead. - * @param {Array} src the source Array - * @param {Integer} srcPosition starting position in the source Array - * @param {Array} dst the destination Array - * @param {Integer} dstPosition starting position in the destination Array - * @param {Integer} length number of Array elements to be copied + * function draw() { + * background(205, 105, 94); + * rotateX(frameCount * 0.01); + * rotateZ(frameCount * 0.01); + * cylinder(20, 50); + * } + *
      + *
      * * @example - *
      - * let src = ['A', 'B', 'C']; - * let dst = [1, 2, 3]; - * let srcPosition = 1; - * let dstPosition = 0; - * let length = 2; - * - * print(src); // ['A', 'B', 'C'] - * print(dst); // [ 1 , 2 , 3 ] - * - * arrayCopy(src, srcPosition, dst, dstPosition, length); - * print(dst); // ['B', 'C', 3] - *
      - */ - /** - * @method arrayCopy - * @deprecated Use arr1.copyWithin(arr2) instead. - * @param {Array} src - * @param {Array} dst - * @param {Integer} [length] - */ - _main.default.prototype.arrayCopy = function (src, srcPosition, dst, dstPosition, length) { - // the index to begin splicing from dst array - var start; - var end; - if (typeof length !== 'undefined') { - end = Math.min(length, src.length); - start = dstPosition; - src = src.slice(srcPosition, end + srcPosition); - } else { - if (typeof dst !== 'undefined') { - // src, dst, length - // rename so we don't get confused - end = dst; - end = Math.min(end, src.length); - } else { - // src, dst - end = src.length; - } - start = 0; // rename so we don't get confused - dst = srcPosition; - src = src.slice(0, end); - } // Since we are not returning the array and JavaScript is pass by reference - // we must modify the actual values of the array - // instead of reassigning arrays - - Array.prototype.splice.apply(dst, [ - start, - end - ].concat(src)); - }; - /** - * Concatenates two arrays, maps to Array.concat(). Does not modify the - * input arrays. + *
      + * + * // slide to see how detailX works + * let detailX; + * function setup() { + * createCanvas(100, 100, WEBGL); + * detailX = createSlider(3, 24, 3); + * detailX.position(10, height + 5); + * detailX.style('width', '80px'); + * describe( + * 'a rotating white cylinder with limited X detail, with a slider that adjusts detailX' + * ); + * } * - * @method concat - * @deprecated Use arr1.concat(arr2) instead. - * @param {Array} a first Array to concatenate - * @param {Array} b second Array to concatenate - * @return {Array} concatenated array + * function draw() { + * background(205, 105, 94); + * rotateY(millis() / 1000); + * cylinder(20, 75, detailX.value(), 1); + * } + * + *
      * * @example - *
      + *
      + * + * // slide to see how detailY works + * let detailY; * function setup() { - * 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); + * createCanvas(100, 100, WEBGL); + * detailY = createSlider(1, 16, 1); + * detailY.position(10, height + 5); + * detailY.style('width', '80px'); + * describe( + * 'a rotating white cylinder with limited Y detail, with a slider that adjusts detailY' + * ); + * } * - * print(arr1); // ['A','B','C'] - * print(arr2); // [1, 2, 3] - * print(arr3); // ['A','B','C', 1, 2, 3] + * function draw() { + * background(205, 105, 94); + * rotateY(millis() / 1000); + * cylinder(20, 75, 16, detailY.value()); * } - *
      + *
      + *
      */ - _main.default.prototype.concat = function (list0, list1) { - return list0.concat(list1); + _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; }; /** - * Reverses the order of an array, maps to Array.reverse() + * Draw a cone with given radius and height * - * @method reverse - * @deprecated Use array.reverse() instead. - * @param {Array} list Array to reverse - * @return {Array} the reversed list + * 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 - *
      + *
      + * + * // draw a spinning cone + * // with radius 40 and height 70 * function setup() { - * let myArray = ['A', 'B', 'C']; - * print(myArray); // ['A','B','C'] + * createCanvas(100, 100, WEBGL); + * describe('a rotating white cone'); + * } * - * reverse(myArray); - * print(myArray); // ['C','B','A'] + * function draw() { + * background(200); + * rotateX(frameCount * 0.01); + * rotateZ(frameCount * 0.01); + * cone(40, 70); * } - *
      - */ - _main.default.prototype.reverse = function (list) { - return list.reverse(); - }; - /** - * Decreases an array by one element and returns the shortened array, - * maps to Array.pop(). + *
      + *
      * - * @method shorten - * @deprecated Use array.pop() instead. - * @param {Array} list Array to shorten - * @return {Array} shortened Array * @example - *
      + *
      + * + * // slide to see how detailx works + * let detailX; * function setup() { - * let myArray = ['A', 'B', 'C']; - * print(myArray); // ['A', 'B', 'C'] - * let newArray = shorten(myArray); - * print(myArray); // ['A','B','C'] - * print(newArray); // ['A','B'] - * } - *
      - */ - _main.default.prototype.shorten = function (list) { - list.pop(); - return list; - }; - /** - * Randomizes the order of the elements of an array. Implements - * - * Fisher-Yates Shuffle Algorithm. + * createCanvas(100, 100, WEBGL); + * detailX = createSlider(3, 16, 3); + * detailX.position(10, height + 5); + * detailX.style('width', '80px'); + * describe( + * 'a rotating white cone with limited X detail, with a slider that adjusts detailX' + * ); + * } + * + * function draw() { + * background(205, 102, 94); + * rotateY(millis() / 1000); + * cone(30, 65, detailX.value(), 16); + * } + *
      + *
      * - * @method shuffle - * @param {Array} array Array to shuffle - * @param {Boolean} [bool] modify passed array - * @return {Array} shuffled Array * @example - *
      + *
      + * + * // slide to see how detailY works + * let detailY; * function setup() { - * let regularArr = ['ABC', 'def', createVector(), TAU, Math.E]; - * print(regularArr); - * shuffle(regularArr, true); // force modifications to passed array - * print(regularArr); + * createCanvas(100, 100, WEBGL); + * detailY = createSlider(3, 16, 3); + * detailY.position(10, height + 5); + * detailY.style('width', '80px'); + * describe( + * 'a rotating white cone with limited Y detail, with a slider that adjusts detailY' + * ); + * } * - * // By default shuffle() returns a shuffled cloned array: - * let newArr = shuffle(regularArr); - * print(regularArr); - * print(newArr); + * function draw() { + * background(205, 102, 94); + * rotateY(millis() / 1000); + * cone(30, 65, 16, detailY.value()); * } - *
      + *
      + *
      */ - _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; + _main.default.prototype.cone = function (radius, height, detailX, detailY, cap) { + this._assert3d('cone'); + _main.default._validateParameters('cone', arguments); + if (typeof radius === 'undefined') { + radius = 50; } - return arr; + 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; }; /** - * 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. + * Draw an ellipsoid with given radius * - * @method sort - * @deprecated Use array.sort() instead. - * @param {Array} list Array to sort - * @param {Integer} [count] number of elements to sort, starting from 0 - * @return {Array} the sorted list + * DetailX and detailY determine the number of subdivisions in the x-dimension and + * the y-dimension of a cone. More subdivisions make the ellipsoid appear to be smoother. + * Avoid detail number above 150, it may crash the browser. + * @method ellipsoid + * @param {Number} [radiusx] x-radius of ellipsoid + * @param {Number} [radiusy] y-radius of ellipsoid + * @param {Number} [radiusz] z-radius of ellipsoid + * @param {Integer} [detailX] number of segments, + * the more segments the smoother geometry + * default is 24. Avoid detail number above + * 150, it may crash the browser. + * @param {Integer} [detailY] number of segments, + * the more segments the smoother geometry + * default is 16. Avoid detail number above + * 150, it may crash the browser. + * @chainable + * @example + *
      + * + * // draw an ellipsoid + * // with radius 30, 40 and 40. + * function setup() { + * createCanvas(100, 100, WEBGL); + * describe('a white 3d ellipsoid'); + * } + * + * function draw() { + * background(205, 105, 94); + * ellipsoid(30, 40, 40); + * } + * + *
      * * @example - *
      + *
      + * + * // slide to see how detailX works + * let detailX; * function setup() { - * let words = ['banana', 'apple', 'pear', 'lime']; - * print(words); // ['banana', 'apple', 'pear', 'lime'] - * let count = 4; // length of array + * createCanvas(100, 100, WEBGL); + * detailX = createSlider(2, 24, 12); + * detailX.position(10, height + 5); + * detailX.style('width', '80px'); + * describe( + * 'a rotating white ellipsoid with limited X detail, with a slider that adjusts detailX' + * ); + * } * - * words = sort(words, count); - * print(words); // ['apple', 'banana', 'lime', 'pear'] + * function draw() { + * background(205, 105, 94); + * rotateY(millis() / 1000); + * ellipsoid(30, 40, 40, detailX.value(), 8); * } - *
      - *
      + * + *
      + * + * @example + *
      + * + * // slide to see how detailY works + * let detailY; * function setup() { - * 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 + * createCanvas(100, 100, WEBGL); + * detailY = createSlider(2, 24, 6); + * detailY.position(10, height + 5); + * detailY.style('width', '80px'); + * describe( + * 'a rotating white ellipsoid with limited Y detail, with a slider that adjusts detailY' + * ); + * } * - * numbers = sort(numbers, count); - * print(numbers); // [1,2,5,6,14,9,8,12] + * function draw() { + * background(205, 105, 9); + * rotateY(millis() / 1000); + * ellipsoid(30, 40, 40, 12, detailY.value()); * } - *
      + *
      + *
      */ - _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; - }); + _main.default.prototype.ellipsoid = function (radiusX, radiusY, radiusZ, detailX, detailY) { + this._assert3d('ellipsoid'); + _main.default._validateParameters('ellipsoid', arguments); + if (typeof radiusX === 'undefined') { + radiusX = 50; } - return arr.concat(rest); + 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; }; /** - * Inserts a value or an array of values into an existing array. The first - * parameter specifies the initial array to be modified, and the second - * parameter defines the data to be inserted. The third parameter is an index - * value which specifies the array position from which to insert data. - * (Remember that array index numbering starts at zero, so the first position - * is 0, the second position is 1, and so on.) - * - * @method splice - * @deprecated Use array.splice() instead. - * @param {Array} list Array to splice into - * @param {any} value value to be spliced in - * @param {Integer} position in the array from which to insert data - * @return {Array} the list + * 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 - *
      + *
      + * + * // draw a spinning torus + * // with ring radius 30 and tube radius 15 * 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] + * createCanvas(100, 100, WEBGL); + * describe('a rotating white torus'); * } - *
      - */ - _main.default.prototype.splice = function (list, value, index) { - // note that splice returns spliced elements and not an array - Array.prototype.splice.apply(list, [ - index, - 0 - ].concat(value)); - return list; - }; - /** - * Extracts an array of elements from an existing array. The list parameter - * defines the array from which the elements will be copied, and the start - * and count parameters specify which elements to extract. If no count is - * given, elements will be extracted from the start to the end of the array. - * When specifying the start, remember that the first array element is 0. - * This function does not change the source array. * - * @method subset - * @deprecated Use array.slice() instead. - * @param {Array} list Array to extract from - * @param {Integer} start position to begin - * @param {Integer} [count] number of values to extract - * @return {Array} Array of extracted elements + * function draw() { + * background(205, 102, 94); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * torus(30, 15); + * } + *
      + *
      * * @example - *
      + *
      + * + * // slide to see how detailX works + * let detailX; * 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] + * createCanvas(100, 100, WEBGL); + * detailX = createSlider(3, 24, 3); + * detailX.position(10, height + 5); + * detailX.style('width', '80px'); + * describe( + * 'a rotating white torus with limited X detail, with a slider that adjusts detailX' + * ); * } - *
      - */ - _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': 290, - 'core-js/modules/es.array-buffer.constructor': 166, - 'core-js/modules/es.array.concat': 167, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.array.splice': 182, - 'core-js/modules/es.object.to-string': 195 - } - ], - 330: [ - function (_dereq_, module, exports) { - 'use strict'; - _dereq_('core-js/modules/es.array.map'); - _dereq_('core-js/modules/es.number.constructor'); - _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.regexp.to-string'); - _dereq_('core-js/modules/es.string.repeat'); - _dereq_('core-js/modules/es.array.map'); - _dereq_('core-js/modules/es.number.constructor'); - _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.regexp.to-string'); - _dereq_('core-js/modules/es.string.repeat'); - Object.defineProperty(exports, '__esModule', { - value: true - }); - exports.default = void 0; - var _main = _interopRequireDefault(_dereq_('../core/main')); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: - obj - }; - } /** - * @module Data - * @submodule Conversion - * @for p5 - * @requires core - */ - /** - * Converts a string to 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. + * function draw() { + * background(205, 102, 94); + * rotateY(millis() / 1000); + * torus(30, 15, detailX.value(), 12); + * } + *
      + *
      * - * @method float - * @param {String} str float string to parse - * @return {Number} floating point representation of string * @example - *
      - * let str = '20'; - * let diameter = float(str); - * ellipse(width / 2, height / 2, diameter, diameter); - *
      - *
      - * print(float('10.31')); // 10.31 - * print(float('Infinity')); // Infinity - * print(float('-Infinity')); // -Infinity - *
      + *
      + * + * // slide to see how detailY works + * let detailY; + * function setup() { + * createCanvas(100, 100, WEBGL); + * detailY = createSlider(3, 16, 3); + * detailY.position(10, height + 5); + * detailY.style('width', '80px'); + * describe( + * 'a rotating white torus with limited Y detail, with a slider that adjusts detailY' + * ); + * } * - * @alt - * 20 by 20 white ellipse in the center of the canvas + * function draw() { + * background(205, 102, 94); + * rotateY(millis() / 1000); + * torus(30, 15, 16, detailY.value()); + * } + * + *
      */ - - _main.default.prototype.float = function (str) { - if (str instanceof Array) { - return str.map(parseFloat); + _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 } - return parseFloat(str); + if (typeof tubeRadius === 'undefined') { + tubeRadius = 10; + } else if (!tubeRadius) { + return; // nothing to draw + } + if (typeof detailX === 'undefined') { + detailX = 24; + } + if (typeof detailY === 'undefined') { + detailY = 16; + } + var tubeRatio = (tubeRadius / radius).toPrecision(4); + var gId = 'torus|'.concat(tubeRatio, '|').concat(detailX, '|').concat(detailY); + if (!this._renderer.geometryInHash(gId)) { + var _torus = function _torus() { + for (var i = 0; i <= this.detailY; i++) { + var v = i / this.detailY; + var phi = 2 * Math.PI * v; + var cosPhi = Math.cos(phi); + var sinPhi = Math.sin(phi); + var r = 1 + tubeRatio * cosPhi; + for (var j = 0; j <= this.detailX; j++) { + var u = j / this.detailX; + var theta = 2 * Math.PI * u; + var cosTheta = Math.cos(theta); + var sinTheta = Math.sin(theta); + var p = new _main.default.Vector(r * cosTheta, r * sinTheta, tubeRatio * sinPhi); + var n = new _main.default.Vector(cosPhi * cosTheta, cosPhi * sinTheta, sinPhi); + this.vertices.push(p); + this.vertexNormals.push(n); + this.uvs.push(u, v); + } + } + }; + var torusGeom = new _main.default.Geometry(detailX, detailY, _torus); + torusGeom.computeFaces(); + if (detailX <= 24 && detailY <= 16) { + torusGeom._makeTriangleEdges()._edgesToVertices(); + } else if (this._renderer._doStroke) { + console.log('Cannot draw strokes on torus object with more' + ' than 24 detailX or 16 detailY'); + } + this._renderer.createBuffers(gId, torusGeom); + } + this._renderer.drawBuffersScaled(gId, radius, radius, radius); + return this; }; + /////////////////////// + /// 2D primitives + ///////////////////////// + // + // Note: Documentation is not generated on the p5.js website for functions on + // the p5.RendererGL prototype. /** - * 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 - *
      - * 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 - *
      - */ - /** - * @method int - * @param {Array} ns values to parse - * @param {Integer} [radix] - * @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 + * 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 - *
      - * 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" ] - *
      - */ - _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. + *
      + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * } * - * @method boolean - * @param {String|Boolean|Number|Array} n value to parse - * @return {Boolean} boolean representation of value - * @example - *
      - * print(boolean(0)); // false - * print(boolean(1)); // true - * print(boolean('true')); // true - * print(boolean('abcd')); // false - * print(boolean([0, 12, 'true'])); // [false, true, true] - *
      + * function draw() { + * background(50); + * stroke(255); + * strokeWeight(4); + * point(25, 0); + * strokeWeight(3); + * point(-25, 0); + * strokeWeight(2); + * point(0, 25); + * strokeWeight(1); + * point(0, -25); + * } + *
      + *
      */ - _main.default.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); + _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; }; - /** - * 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 - *
      - * 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] - *
      - */ - /** - * @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); + _main.default.RendererGL.prototype.triangle = function (args) { + var x1 = args[0], + y1 = args[1]; + var x2 = args[2], + y2 = args[3]; + var x3 = args[4], + y3 = args[5]; + var gId = 'tri'; + if (!this.geometryInHash(gId)) { + var _triangle = function _triangle() { + var vertices = [ + ]; + vertices.push(new _main.default.Vector(0, 0, 0)); + vertices.push(new _main.default.Vector(1, 0, 0)); + vertices.push(new _main.default.Vector(0, 1, 0)); + this.edges = [ + [0, + 1], + [ + 1, + 2 + ], + [ + 2, + 0 + ] + ]; + this.vertices = vertices; + this.faces = [ + [0, + 1, + 2] + ]; + this.uvs = [ + 0, + 0, + 1, + 0, + 1, + 1 + ]; + }; + var triGeom = new _main.default.Geometry(1, 1, _triangle); + triGeom._edgesToVertices(); + triGeom.computeNormals(); + this.createBuffers(gId, triGeom); + } // only one triangle is cached, one point is at the origin, and the + // two adjacent sides are tne unit vectors along the X & Y axes. + // + // this matrix multiplication transforms those two unit vectors + // onto the required vector prior to rendering, and moves the + // origin appropriately. + + var uMVMatrix = this.uMVMatrix.copy(); + try { + // triangle orientation. + var orientation = Math.sign(x1 * y2 - x2 * y1 + x2 * y3 - x3 * y2 + x3 * y1 - x1 * y3); + var mult = new _main.default.Matrix([x2 - x1, + y2 - y1, + 0, + 0, + // the resulting unit X-axis + x3 - x1, + y3 - y1, + 0, + 0, + // the resulting unit Y-axis + 0, + 0, + orientation, + 0, + // the resulting unit Z-axis (Reflect the specified order of vertices) + x1, + y1, + 0, + 1 // the resulting origin + ]).mult(this.uMVMatrix); + this.uMVMatrix = mult; + this.drawBuffers(gId); + } finally { + this.uMVMatrix = uMVMatrix; } + return this; }; - /** - * 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 - *
      - * print(char(65)); // "A" - * print(char('65')); // "A" - * print(char([65, 66, 67])); // [ "A", "B", "C" ] - * print(join(char([65, 66, 67]), '')); // "ABC" - *
      - */ - /** - * @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)); - } + _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]); }; - /** - * 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 - *
      - * print(unchar('A')); // 65 - * print(unchar(['A', 'B', 'C'])); // [ 65, 66, 67 ] - * print(unchar(split('ABC', ''))); // [ 65, 66, 67 ] - *
      - */ - /** - * @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); + _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, '|'); } - }; - /** - * 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 - *
      - * print(hex(255)); // "000000FF" - * print(hex(255, 6)); // "0000FF" - * print(hex([0, 127, 255], 6)); // [ "000000", "00007F", "0000FF" ] - * print(Infinity); // "FFFFFFFF" - * print(-Infinity); // "00000000" - *
      - */ - /** - * @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 = 4294967295 + n + 1; - } - var hex = Number(n).toString(16).toUpperCase(); - while (hex.length < digits) { - hex = '0'.concat(hex); - } - if (hex.length >= digits) { - hex = hex.substring(hex.length - digits, hex.length); + if (!this.geometryInHash(gId)) { + var _arc = function _arc() { + // if the start and stop angles are not the same, push vertices to the array + if (start.toFixed(10) !== stop.toFixed(10)) { + // if the mode specified is PIE or null, push the mid point of the arc in vertices + if (mode === constants.PIE || typeof mode === 'undefined') { + this.vertices.push(new _main.default.Vector(0.5, 0.5, 0)); + this.uvs.push([0.5, + 0.5]); + } // vertices for the perimeter of the circle + + for (var i = 0; i <= detail; i++) { + var u = i / detail; + var theta = (stop - start) * u + start; + var _x = 0.5 + Math.cos(theta) / 2; + var _y = 0.5 + Math.sin(theta) / 2; + this.vertices.push(new _main.default.Vector(_x, _y, 0)); + this.uvs.push([_x, + _y]); + if (i < detail - 1) { + this.faces.push([0, + i + 1, + i + 2]); + this.edges.push([i + 1, + i + 2]); + } + } // check the mode specified in order to push vertices and faces, different for each mode + + switch (mode) { + case constants.PIE: + this.faces.push([0, + this.vertices.length - 2, + this.vertices.length - 1]); + this.edges.push([0, + 1]); + this.edges.push([this.vertices.length - 2, + this.vertices.length - 1]); + this.edges.push([0, + this.vertices.length - 1]); + break; + case constants.CHORD: + this.edges.push([0, + 1]); + this.edges.push([0, + this.vertices.length - 1]); + break; + case constants.OPEN: + this.edges.push([0, + 1]); + break; + default: + this.faces.push([0, + this.vertices.length - 2, + this.vertices.length - 1]); + this.edges.push([this.vertices.length - 2, + this.vertices.length - 1]); + } + } + }; + var arcGeom = new _main.default.Geometry(detail, 1, _arc); + arcGeom.computeNormals(); + if (detail <= 50) { + arcGeom._edgesToVertices(arcGeom); + } else if (this._doStroke) { + console.log('Cannot apply a stroke to an '.concat(shape, ' with more than 50 detail')); } - return hex; + this.createBuffers(gId, arcGeom); } - }; - /** - * 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 - *
      - * print(unhex('A')); // 10 - * print(unhex('FF')); // 255 - * print(unhex(['FF', 'AA', '00'])); // [ 255, 170, 0 ] - *
      - */ - /** - * @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 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; }; - var _default = _main.default; - exports.default = _default; - }, - { - '../core/main': 290, - 'core-js/modules/es.array.map': 179, - 'core-js/modules/es.number.constructor': 187, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.to-string': 200, - 'core-js/modules/es.string.repeat': 206 - } - ], - 331: [ - function (_dereq_, module, exports) { - 'use strict'; - _dereq_('core-js/modules/es.array.filter'); - _dereq_('core-js/modules/es.array.index-of'); - _dereq_('core-js/modules/es.array.join'); - _dereq_('core-js/modules/es.array.map'); - _dereq_('core-js/modules/es.array.slice'); - _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.regexp.constructor'); - _dereq_('core-js/modules/es.regexp.exec'); - _dereq_('core-js/modules/es.regexp.to-string'); - _dereq_('core-js/modules/es.string.match'); - _dereq_('core-js/modules/es.string.replace'); - _dereq_('core-js/modules/es.string.split'); - _dereq_('core-js/modules/es.string.trim'); - _dereq_('core-js/modules/es.array.filter'); - _dereq_('core-js/modules/es.array.index-of'); - _dereq_('core-js/modules/es.array.join'); - _dereq_('core-js/modules/es.array.map'); - _dereq_('core-js/modules/es.array.slice'); - _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.regexp.constructor'); - _dereq_('core-js/modules/es.regexp.exec'); - _dereq_('core-js/modules/es.regexp.to-string'); - _dereq_('core-js/modules/es.string.match'); - _dereq_('core-js/modules/es.string.replace'); - _dereq_('core-js/modules/es.string.split'); - _dereq_('core-js/modules/es.string.trim'); - Object.defineProperty(exports, '__esModule', { - value: true - }); - exports.default = void 0; - var _main = _interopRequireDefault(_dereq_('../core/main')); - _dereq_('../core/friendly_errors/validate_params'); - _dereq_('../core/friendly_errors/file_errors'); - _dereq_('../core/friendly_errors/fes_core'); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: - obj - }; - } /** - * @module Data - * @submodule String Functions - * @for p5 - * @requires core - */ - //return p5; //LM is this a mistake? - /** - * 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 nf() 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 - *
      - * - * let array = ['Hello', 'world!']; - * let separator = ' '; - * let message = join(array, separator); - * text(message, 5, 50); - * - *
      - * - * @alt - * "hello world!" displayed middle left of canvas. - */ + _main.default.RendererGL.prototype.rect = function (args) { + var x = args[0]; + var y = args[1]; + var width = args[2]; + var height = args[3]; + if (typeof args[4] === 'undefined') { + // Use the retained mode for drawing rectangle, + // if args for rounding rectangle is not provided by user. + var perPixelLighting = this._pInst._glAttributes.perPixelLighting; + var detailX = args[4] || (perPixelLighting ? 1 : 24); + var detailY = args[5] || (perPixelLighting ? 1 : 16); + var gId = 'rect|'.concat(detailX, '|').concat(detailY); + if (!this.geometryInHash(gId)) { + var _rect = function _rect() { + for (var i = 0; i <= this.detailY; i++) { + var v = i / this.detailY; + for (var j = 0; j <= this.detailX; j++) { + var u = j / this.detailX; + var p = new _main.default.Vector(u, v, 0); + this.vertices.push(p); + this.uvs.push(u, v); + } + } // using stroke indices to avoid stroke over face(s) of rectangle - _main.default.prototype.join = function (list, separator) { - _main.default._validateParameters('join', arguments); - return list.join(separator); - }; - /** - * This function is used to apply a regular expression to a piece of text, - * and return matching groups (elements found inside parentheses) as a - * String array. If there are no matches, a null value will be returned. - * If no groups are specified in the regular expression, but the sequence - * matches, an array of length 1 (with the matched text as the first element - * of the array) will be returned. - * - * To use the function, first check to see if the result is null. If the - * result is null, then the sequence did not match at all. If the sequence - * did match, an array is returned. - * - * If there are groups (specified by sets of parentheses) in the regular - * expression, then the contents of each will be returned in the array. - * Element [0] of a regular expression match returns the entire matching - * string, and the match groups start at element [1] (the first group is [1], - * the second [2], and so on). - * - * @method match - * @param {String} str the String to be searched - * @param {String} regexp the regexp to be used for matching - * @return {String[]} Array of Strings found - * @example - *
      - * - * let string = 'Hello p5js*!'; - * let regexp = 'p5js\\*'; - * let m = match(string, regexp); - * text(m, 5, 50); - * - *
      - * - * @alt - * "p5js*" displayed middle left of canvas. - */ - _main.default.prototype.match = function (str, reg) { - _main.default._validateParameters('match', arguments); - return str.match(reg); - }; - /** - * This function is used to apply a regular expression to a piece of text, - * and return a list of matching groups (elements found inside parentheses) - * as a two-dimensional String array. If there are no matches, a null value - * will be returned. If no groups are specified in the regular expression, - * but the sequence matches, a two dimensional array is still returned, but - * the second dimension is only of length one. - * - * To use the function, first check to see if the result is null. If the - * result is null, then the sequence did not match at all. If the sequence - * did match, a 2D array is returned. - * - * If there are groups (specified by sets of parentheses) in the regular - * expression, then the contents of each will be returned in the array. - * Assuming a loop with counter variable i, element [i][0] of a regular - * expression match returns the entire matching string, and the match groups - * start at element [i][1] (the first group is [i][1], the second [i][2], - * and so on). - * - * @method matchAll - * @param {String} str the String to be searched - * @param {String} regexp the regexp to be used for matching - * @return {String[]} 2d Array of Strings found - * @example - *
      - * - * let string = 'Hello p5js*! Hello world!'; - * let regexp = 'Hello'; - * matchAll(string, regexp); - * - *
      - */ - _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 - *
      - * - * function setup() { - * background(200); - * let num1 = 321; - * let num2 = -1321; - * - * noStroke(); - * fill(0); - * textSize(16); - * - * text(nf(num1, 4, 2), 10, 30); - * text(nf(num2, 4, 2), 10, 80); - * // Draw dividing line - * stroke(120); - * line(0, 50, width, 50); - * } - * - *
      - * - * @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); - }); + if (detailX > 0 && detailY > 0) { + this.edges = [ + [0, + detailX], + [ + detailX, + (detailX + 1) * (detailY + 1) - 1 + ], + [ + (detailX + 1) * (detailY + 1) - 1, + (detailX + 1) * detailY + ], + [ + (detailX + 1) * detailY, + 0 + ] + ]; + } + }; + var rectGeom = new _main.default.Geometry(detailX, detailY, _rect); + rectGeom.computeFaces().computeNormals()._edgesToVertices(); + this.createBuffers(gId, rectGeom); + } // only a single rectangle (of a given detail) is cached: a square with + // opposite corners at (0,0) & (1,1). + // + // before rendering, this square is scaled & moved to the required location. + + var uMVMatrix = this.uMVMatrix.copy(); + try { + this.uMVMatrix.translate([x, + y, + 0]); + this.uMVMatrix.scale(width, height, 1); + this.drawBuffers(gId); + } finally { + this.uMVMatrix = uMVMatrix; + } } else { - 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]); - } + // Use Immediate mode to round the rectangle corner, + // if args for rounding corners is provided by user + var tl = args[4]; + var tr = typeof args[5] === 'undefined' ? tl : args[5]; + var br = typeof args[6] === 'undefined' ? tr : args[6]; + var bl = typeof args[7] === 'undefined' ? br : args[7]; + var a = x; + var b = y; + var c = width; + var d = height; + c += a; + d += b; + if (a > c) { + var temp = a; + a = c; + c = temp; + } + if (b > d) { + var _temp = b; + b = d; + d = _temp; + } + var maxRounding = Math.min((c - a) / 2, (d - b) / 2); + if (tl > maxRounding) tl = maxRounding; + if (tr > maxRounding) tr = maxRounding; + if (br > maxRounding) br = maxRounding; + if (bl > maxRounding) bl = maxRounding; + var x1 = a; + var y1 = b; + var x2 = c; + var y2 = d; + this.beginShape(); + if (tr !== 0) { + this.vertex(x2 - tr, y1); + this.quadraticVertex(x2, y1, x2, y1 + tr); } else { - return doNf(nums, left, right); + this.vertex(x2, y1); + } + if (br !== 0) { + this.vertex(x2, y2 - br); + this.quadraticVertex(x2, y2, x2 - br, y2); + } else { + this.vertex(x2, y2); + } + if (bl !== 0) { + this.vertex(x1 + bl, y2); + this.quadraticVertex(x1, y2, x1, y2 - bl); + } else { + this.vertex(x1, y2); + } + if (tl !== 0) { + this.vertex(x1, y1 + tl); + this.quadraticVertex(x1, y1, x1 + tl, y1); + } else { + this.vertex(x1, y1); + } + this.immediateMode.geometry.uvs.length = 0; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = this.immediateMode.geometry.vertices[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var vert = _step.value; + var u = (vert.x - x1) / width; + var v = (vert.y - y1) / height; + this.immediateMode.geometry.uvs.push(u, v); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } } + this.endShape(constants.CLOSE); } + return this; }; - 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'; + /* eslint-disable max-len */ + _main.default.RendererGL.prototype.quad = function (x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4, detailX, detailY) { + /* eslint-enable max-len */ + if (typeof detailX === 'undefined') { + detailX = 2; + } + if (typeof detailY === 'undefined') { + detailY = 2; + } + var gId = 'quad|'.concat(x1, '|').concat(y1, '|').concat(z1, '|').concat(x2, '|').concat(y2, '|').concat(z2, '|').concat(x3, '|').concat(y3, '|').concat(z3, '|').concat(x4, '|').concat(y4, '|').concat(z4, '|').concat(detailX, '|').concat(detailY); + if (!this.geometryInHash(gId)) { + var quadGeom = new _main.default.Geometry(detailX, detailY, function () { + //algorithm adapted from c++ to js + //https://stackoverflow.com/questions/16989181/whats-the-correct-way-to-draw-a-distorted-plane-in-opengl/16993202#16993202 + var xRes = 1 / (this.detailX - 1); + var yRes = 1 / (this.detailY - 1); + for (var y = 0; y < this.detailY; y++) { + for (var x = 0; x < this.detailX; x++) { + var pctx = x * xRes; + var pcty = y * yRes; + var linePt0x = (1 - pcty) * x1 + pcty * x4; + var linePt0y = (1 - pcty) * y1 + pcty * y4; + var linePt0z = (1 - pcty) * z1 + pcty * z4; + var linePt1x = (1 - pcty) * x2 + pcty * x3; + var linePt1y = (1 - pcty) * y2 + pcty * y3; + var linePt1z = (1 - pcty) * z2 + pcty * z3; + var ptx = (1 - pctx) * linePt0x + pctx * linePt1x; + var pty = (1 - pctx) * linePt0y + pctx * linePt1y; + var ptz = (1 - pctx) * linePt0z + pctx * linePt1z; + this.vertices.push(new _main.default.Vector(ptx, pty, ptz)); + this.uvs.push([pctx, + pcty]); + } + } + }); + quadGeom.faces = [ + ]; + for (var y = 0; y < detailY - 1; y++) { + for (var x = 0; x < detailX - 1; x++) { + var pt0 = x + y * detailX; + var pt1 = x + 1 + y * detailX; + var pt2 = x + 1 + (y + 1) * detailX; + var pt3 = x + (y + 1) * detailX; + quadGeom.faces.push([pt0, + pt1, + pt2]); + quadGeom.faces.push([pt0, + pt2, + pt3]); + } } - return str; - } else { - for (var k = 0; k < Math.max(left - intPart.length, 0); k++) { - str += '0'; + quadGeom.computeNormals(); + quadGeom.edges.length = 0; + var vertexOrder = [ + 0, + 2, + 3, + 1 + ]; + for (var i = 0; i < vertexOrder.length; i++) { + var startVertex = vertexOrder[i]; + var endVertex = vertexOrder[(i + 1) % vertexOrder.length]; + quadGeom.edges.push([startVertex, + endVertex]); } - str += n; - return str; + quadGeom._edgesToVertices(); + this.createBuffers(gId, quadGeom); } - } /** - * 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 - * + this.drawBuffers(gId); + return this; + }; + //this implementation of bezier curve + //is based on Bernstein polynomial + // pretier-ignore + _main.default.RendererGL.prototype.bezier = function (x1, y1, z1, // x2 + x2, // y2 + y2, // x3 + z2, // y3 + x3, // x4 + y3, // y4 + z3, x4, y4, z4) { + if (arguments.length === 8) { + y4 = y3; + x4 = x3; + y3 = z2; + x3 = y2; + y2 = x2; + x2 = z1; + z1 = z2 = z3 = z4 = 0; + } + var bezierDetail = this._pInst._bezierDetail || 20; //value of Bezier detail + this.beginShape(); + for (var i = 0; i <= bezierDetail; i++) { + var c1 = Math.pow(1 - i / bezierDetail, 3); + var c2 = 3 * (i / bezierDetail) * Math.pow(1 - i / bezierDetail, 2); + var c3 = 3 * Math.pow(i / bezierDetail, 2) * (1 - i / bezierDetail); + var c4 = Math.pow(i / bezierDetail, 3); + this.vertex(x1 * c1 + x2 * c2 + x3 * c3 + x4 * c4, y1 * c1 + y2 * c2 + y3 * c3 + y4 * c4, z1 * c1 + z2 * c2 + z3 * c3 + z4 * c4); + } + this.endShape(); + return this; + }; + // pretier-ignore + _main.default.RendererGL.prototype.curve = function (x1, y1, z1, // x2 + x2, // y2 + y2, // x3 + z2, // y3 + x3, // x4 + y3, // y4 + z3, x4, y4, z4) { + if (arguments.length === 8) { + x4 = x3; + y4 = y3; + x3 = y2; + y3 = x2; + x2 = z1; + y2 = x2; + z1 = z2 = z3 = z4 = 0; + } + var curveDetail = this._pInst._curveDetail; + this.beginShape(); + for (var i = 0; i <= curveDetail; i++) { + var c1 = Math.pow(i / curveDetail, 3) * 0.5; + var c2 = Math.pow(i / curveDetail, 2) * 0.5; + var c3 = i / curveDetail * 0.5; + var c4 = 0.5; + var vx = c1 * ( - x1 + 3 * x2 - 3 * x3 + x4) + c2 * (2 * x1 - 5 * x2 + 4 * x3 - x4) + c3 * ( - x1 + x3) + c4 * (2 * x2); + var vy = c1 * ( - y1 + 3 * y2 - 3 * y3 + y4) + c2 * (2 * y1 - 5 * y2 + 4 * y3 - y4) + c3 * ( - y1 + y3) + c4 * (2 * y2); + var vz = c1 * ( - z1 + 3 * z2 - 3 * z3 + z4) + c2 * (2 * z1 - 5 * z2 + 4 * z3 - z4) + c3 * ( - z1 + z3) + c4 * (2 * z2); + this.vertex(vx, vy, vz); + } + this.endShape(); + return this; + }; + /** + * Draw a line given two points + * @private + * @param {Number} x0 x-coordinate of first vertex + * @param {Number} y0 y-coordinate of first vertex + * @param {Number} z0 z-coordinate of first vertex + * @param {Number} x1 x-coordinate of second vertex + * @param {Number} y1 y-coordinate of second vertex + * @param {Number} z1 z-coordinate of second vertex + * @chainable * @example *
      * + * //draw a line * function setup() { - * 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); + * createCanvas(100, 100, WEBGL); + * } * - * // Draw dividing line - * stroke(120); - * line(0, 50, width, 50); + * 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); * } * *
      - * - * @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); + _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; }; - function doNfc(num, right) { - num = num.toString(); - var dec = num.indexOf('.'); - var rem = dec !== - 1 ? num.substring(dec) : ''; - var n = dec !== - 1 ? num.substring(0, dec) : num; - n = n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); - if (right === 0) { - rem = ''; - } else if (typeof right !== 'undefined') { - if (right > rem.length) { - rem += dec === - 1 ? '.' : ''; - var len = right - rem.length + 1; - for (var i = 0; i < len; i++) { - rem += '0'; - } - } else { - rem = rem.substring(0, right + 1); - } - } - return n + rem; - } /** - * Utility function for formatting numbers into strings. Similar to nf() but - * puts a "+" in front of positive numbers and a "-" in front of negative - * numbers. There are two versions: one for formatting floats, and one for - * formatting ints. The values for left, and right parameters - * should always be positive integers. - * - * @method nfp - * @param {Number} num the Number to format - * @param {Integer} [left] number of digits to the left of the decimal - * point - * @param {Integer} [right] number of digits to the right of the - * decimal point - * @return {String} formatted String - * - * @example - *
      - * - * 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); - * } - * - *
      - * - * @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); + _main.default.RendererGL.prototype.bezierVertex = function () { + if (this.immediateMode._bezierVertex.length === 0) { + throw Error('vertex() must be used once before calling bezierVertex()'); } else { - return addNfp(nfRes); - } - }; - function addNfp(num) { - return parseFloat(num) > 0 ? '+'.concat(num.toString()) : num.toString(); - } /** - * Utility function for formatting numbers into strings. Similar to nf() but - * puts an additional "_" (space) in front of positive numbers just in case to align it with negative - * numbers which includes "-" (minus) sign. - * - * The main usecase of nfs() can be seen when one wants to align the digits (place values) of a non-negative - * number with some negative number (See the example to get a clear picture). - * There are two versions: one for formatting float, and one for formatting int. - * - * The values for the digits, left, and right parameters should always be positive integers. - * - * (IMP): The result on the canvas basically the expected alignment can vary based on the typeface you are using. - * - * (NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter - * if greater than the current length of the number. - * - * For example if number is 123.2 and left parameter passed is 4 which is greater than length of 123 - * (integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than - * the result will be 123.200. - * - * @method nfs - * @param {Number} num the Number to format - * @param {Integer} [left] number of digits to the left of the decimal - * point - * @param {Integer} [right] number of digits to the right of the - * decimal point - * @return {String} formatted String - * - * @example - *
      - * - * function setup() { - * background(200); - * let num1 = 321; - * let num2 = -1321; - * - * noStroke(); - * fill(0); - * textSize(16); - * - * // nfs() aligns num1 (positive number) with num2 (negative number) by - * // adding a blank space in front of the num1 (positive number) - * // [left = 4] in num1 add one 0 in front, to align the digits with num2 - * // [right = 2] in num1 and num2 adds two 0's after both numbers - * // To see the differences check the example of nf() too. - * text(nfs(num1, 4, 2), 10, 30); - * text(nfs(num2, 4, 2), 10, 80); - * // Draw dividing line - * stroke(120); - * line(0, 50, width, 50); - * } - * - *
      - * - * @alt - * "0321.00" top middle and "-1321.00" displayed bottom middle - */ - /** - * @method nfs - * @param {Array} nums the Numbers to format - * @param {Integer} [left] - * @param {Integer} [right] - * @return {String[]} formatted Strings - */ + var w_x = [ + ]; + var w_y = [ + ]; + var w_z = [ + ]; + var t, + _x, + _y, + _z, + i, + k, + m; + // variable i for bezierPoints, k for components, and m for anchor points. + var argLength = arguments.length; + t = 0; + if (this._lookUpTableBezier.length === 0 || this._lutBezierDetail !== this._pInst._curveDetail) { + this._lookUpTableBezier = [ + ]; + this._lutBezierDetail = this._pInst._curveDetail; + var step = 1 / this._lutBezierDetail; + var start = 0; + var end = 1; + var j = 0; + while (start < 1) { + t = parseFloat(start.toFixed(6)); + this._lookUpTableBezier[j] = this._bezierCoefficients(t); + if (end.toFixed(6) === step.toFixed(6)) { + t = parseFloat(end.toFixed(6)) + parseFloat(start.toFixed(6)); + ++j; + this._lookUpTableBezier[j] = this._bezierCoefficients(t); + break; + } + start += step; + end -= step; + ++j; + } + } + var LUTLength = this._lookUpTableBezier.length; + // fillColors[0]: start point color + // fillColors[1],[2]: control point color + // fillColors[3]: end point color + var fillColors = [ + ]; + for (m = 0; m < 4; m++) { + fillColors.push([]); + } + fillColors[0] = this.immediateMode.geometry.vertexColors.slice( - 4); + fillColors[3] = this.curFillColor.slice(); + // Do the same for strokeColor. + var strokeColors = [ + ]; + for (m = 0; m < 4; m++) { + strokeColors.push([]); + } + strokeColors[0] = this.immediateMode.geometry.vertexStrokeColors.slice( - 4); + strokeColors[3] = this.curStrokeColor.slice(); + if (argLength === 6) { + this.isBezier = true; + w_x = [ + this.immediateMode._bezierVertex[0], + arguments.length <= 0 ? undefined : arguments[0], + arguments.length <= 2 ? undefined : arguments[2], + arguments.length <= 4 ? undefined : arguments[4] + ]; + w_y = [ + this.immediateMode._bezierVertex[1], + arguments.length <= 1 ? undefined : arguments[1], + arguments.length <= 3 ? undefined : arguments[3], + arguments.length <= 5 ? undefined : arguments[5] + ]; + // The ratio of the distance between the start point, the two control- + // points, and the end point determines the intermediate color. + var d0 = Math.hypot(w_x[0] - w_x[1], w_y[0] - w_y[1]); + var d1 = Math.hypot(w_x[1] - w_x[2], w_y[1] - w_y[2]); + var d2 = Math.hypot(w_x[2] - w_x[3], w_y[2] - w_y[3]); + var totalLength = d0 + d1 + d2; + d0 /= totalLength; + d2 /= totalLength; + for (k = 0; k < 4; k++) { + fillColors[1].push(fillColors[0][k] * (1 - d0) + fillColors[3][k] * d0); + fillColors[2].push(fillColors[0][k] * d2 + fillColors[3][k] * (1 - d2)); + strokeColors[1].push(strokeColors[0][k] * (1 - d0) + strokeColors[3][k] * d0); + strokeColors[2].push(strokeColors[0][k] * d2 + strokeColors[3][k] * (1 - d2)); + } + for (i = 0; i < LUTLength; i++) { + // Interpolate colors using control points + this.curFillColor = [ + 0, + 0, + 0, + 0 + ]; + this.curStrokeColor = [ + 0, + 0, + 0, + 0 + ]; + _x = _y = 0; + for (m = 0; m < 4; m++) { + for (k = 0; k < 4; k++) { + this.curFillColor[k] += this._lookUpTableBezier[i][m] * fillColors[m][k]; + this.curStrokeColor[k] += this._lookUpTableBezier[i][m] * strokeColors[m][k]; + } + _x += w_x[m] * this._lookUpTableBezier[i][m]; + _y += w_y[m] * this._lookUpTableBezier[i][m]; + } + this.vertex(_x, _y); + } // so that we leave currentColor with the last value the user set it to - _main.default.prototype.nfs = function () { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - _main.default._validateParameters('nfs', args); - var nfRes = _main.default.prototype.nf.apply(this, args); - if (nfRes instanceof Array) { - return nfRes.map(addNfs); - } else { - return addNfs(nfRes); - } - }; - function addNfs(num) { - return parseFloat(num) >= 0 ? ' '.concat(num.toString()) : num.toString(); - } /** - * The split() function maps to String.split(), it breaks a String into - * pieces using a character or string as the delimiter. The delim parameter - * specifies the character or characters that mark the boundaries between - * each piece. A String[] array is returned that contains each of the pieces. - * - * The splitTokens() function works in a similar fashion, except that it - * splits using a range of characters instead of a specific character or - * sequence. - * - * @method split - * @param {String} value the String to be split - * @param {String} delim the String used to separate the data - * @return {String[]} Array of Strings - * @example - *
      - * - * let names = 'Pat,Xio,Alex'; - * let splitString = split(names, ','); - * text(splitString[0], 5, 30); - * text(splitString[1], 5, 50); - * text(splitString[2], 5, 70); - * - *
      - * - * @alt - * "pat" top left, "Xio" mid left and "Alex" displayed bottom left - */ + this.curFillColor = fillColors[3]; + this.curStrokeColor = strokeColors[3]; + this.immediateMode._bezierVertex[0] = arguments.length <= 4 ? undefined : arguments[4]; + this.immediateMode._bezierVertex[1] = arguments.length <= 5 ? undefined : arguments[5]; + } else if (argLength === 9) { + this.isBezier = true; + w_x = [ + this.immediateMode._bezierVertex[0], + arguments.length <= 0 ? undefined : arguments[0], + arguments.length <= 3 ? undefined : arguments[3], + arguments.length <= 6 ? undefined : arguments[6] + ]; + w_y = [ + this.immediateMode._bezierVertex[1], + arguments.length <= 1 ? undefined : arguments[1], + arguments.length <= 4 ? undefined : arguments[4], + arguments.length <= 7 ? undefined : arguments[7] + ]; + w_z = [ + this.immediateMode._bezierVertex[2], + arguments.length <= 2 ? undefined : arguments[2], + arguments.length <= 5 ? undefined : arguments[5], + arguments.length <= 8 ? undefined : arguments[8] + ]; + // The ratio of the distance between the start point, the two control- + // points, and the end point determines the intermediate color. + var _d = Math.hypot(w_x[0] - w_x[1], w_y[0] - w_y[1], w_z[0] - w_z[1]); + var _d2 = Math.hypot(w_x[1] - w_x[2], w_y[1] - w_y[2], w_z[1] - w_z[2]); + var _d3 = Math.hypot(w_x[2] - w_x[3], w_y[2] - w_y[3], w_z[2] - w_z[3]); + var _totalLength = _d + _d2 + _d3; + _d /= _totalLength; + _d3 /= _totalLength; + for (k = 0; k < 4; k++) { + fillColors[1].push(fillColors[0][k] * (1 - _d) + fillColors[3][k] * _d); + fillColors[2].push(fillColors[0][k] * _d3 + fillColors[3][k] * (1 - _d3)); + strokeColors[1].push(strokeColors[0][k] * (1 - _d) + strokeColors[3][k] * _d); + strokeColors[2].push(strokeColors[0][k] * _d3 + strokeColors[3][k] * (1 - _d3)); + } + for (i = 0; i < LUTLength; i++) { + // Interpolate colors using control points + this.curFillColor = [ + 0, + 0, + 0, + 0 + ]; + this.curStrokeColor = [ + 0, + 0, + 0, + 0 + ]; + _x = _y = _z = 0; + for (m = 0; m < 4; m++) { + for (k = 0; k < 4; k++) { + this.curFillColor[k] += this._lookUpTableBezier[i][m] * fillColors[m][k]; + this.curStrokeColor[k] += this._lookUpTableBezier[i][m] * strokeColors[m][k]; + } + _x += w_x[m] * this._lookUpTableBezier[i][m]; + _y += w_y[m] * this._lookUpTableBezier[i][m]; + _z += w_z[m] * this._lookUpTableBezier[i][m]; + } + this.vertex(_x, _y, _z); + } // so that we leave currentColor with the last value the user set it to - _main.default.prototype.split = function (str, delim) { - _main.default._validateParameters('split', arguments); - return str.split(delim); - }; - /** - * The splitTokens() function splits a String at one or many character - * delimiters or "tokens." The delim parameter specifies the character or - * characters to be used as a boundary. - * - * If no delim characters are specified, any whitespace character is used to - * split. Whitespace characters include tab (\t), line feed (\n), carriage - * return (\r), form feed (\f), and space. - * - * @method splitTokens - * @param {String} value the String to be split - * @param {String} [delim] list of individual Strings that will be used as - * separators - * @return {String[]} Array of Strings - * @example - *
      - * - * function setup() { - * let myStr = 'Mango, Banana, Lime'; - * let myStrArr = splitTokens(myStr, ','); - * - * print(myStrArr); // prints : ["Mango"," Banana"," Lime"] - * } - * - *
      - */ - _main.default.prototype.splitTokens = function (value, delims) { - _main.default._validateParameters('splitTokens', arguments); - var d; - if (typeof delims !== 'undefined') { - var str = delims; - var sqc = /\]/g.exec(str); - var sqo = /\[/g.exec(str); - if (sqo && sqc) { - str = str.slice(0, sqc.index) + str.slice(sqc.index + 1); - sqo = /\[/g.exec(str); - str = str.slice(0, sqo.index) + str.slice(sqo.index + 1); - d = new RegExp('[\\['.concat(str, '\\]]'), 'g'); - } else if (sqc) { - str = str.slice(0, sqc.index) + str.slice(sqc.index + 1); - d = new RegExp('['.concat(str, '\\]]'), 'g'); - } else if (sqo) { - str = str.slice(0, sqo.index) + str.slice(sqo.index + 1); - d = new RegExp('['.concat(str, '\\[]'), 'g'); - } else { - d = new RegExp('['.concat(str, ']'), 'g'); + this.curFillColor = fillColors[3]; + this.curStrokeColor = strokeColors[3]; + this.immediateMode._bezierVertex[0] = arguments.length <= 6 ? undefined : arguments[6]; + this.immediateMode._bezierVertex[1] = arguments.length <= 7 ? undefined : arguments[7]; + this.immediateMode._bezierVertex[2] = arguments.length <= 8 ? undefined : arguments[8]; } - } else { - d = /\s/g; } - return value.split(d).filter(function (n) { - return n; - }); }; - /** - * Removes whitespace characters from the beginning and end of a String. In - * addition to standard whitespace characters such as space, carriage return, - * and tab, this function also removes the Unicode "nbsp" character. - * - * @method trim - * @param {String} str a String to be trimmed - * @return {String} a trimmed String - * - * @example - *
      - * - * let string = trim(' No new lines\n '); - * text(string + ' here', 2, 50); - * - *
      - * - * @alt - * "No new lines here" displayed center canvas - */ - /** - * @method trim - * @param {Array} strs an Array of Strings to be trimmed - * @return {String[]} an Array of trimmed Strings - */ - _main.default.prototype.trim = function (str) { - _main.default._validateParameters('trim', arguments); - if (str instanceof Array) { - return str.map(this.trim); + _main.default.RendererGL.prototype.quadraticVertex = function () { + if (this.immediateMode._quadraticVertex.length === 0) { + throw Error('vertex() must be used once before calling quadraticVertex()'); } else { - return str.trim(); - } - }; - var _default = _main.default; - exports.default = _default; - }, - { - '../core/friendly_errors/fes_core': 281, - '../core/friendly_errors/file_errors': 282, - '../core/friendly_errors/validate_params': 285, - '../core/main': 290, - 'core-js/modules/es.array.filter': 171, - 'core-js/modules/es.array.index-of': 175, - 'core-js/modules/es.array.join': 177, - 'core-js/modules/es.array.map': 179, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.constructor': 198, - 'core-js/modules/es.regexp.exec': 199, - 'core-js/modules/es.regexp.to-string': 200, - 'core-js/modules/es.string.match': 205, - 'core-js/modules/es.string.replace': 207, - 'core-js/modules/es.string.split': 209, - 'core-js/modules/es.string.trim': 211 - } - ], - 332: [ - function (_dereq_, module, exports) { - 'use strict'; - Object.defineProperty(exports, '__esModule', { - value: true - }); - exports.default = void 0; - var _main = _interopRequireDefault(_dereq_('../core/main')); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: - obj - }; - } /** - * @module IO - * @submodule Time & Date - * @for p5 - * @requires core - */ - /** - * p5.js communicates with the clock on your computer. The day() function - * returns the current day as a value from 1 - 31. - * - * @method day - * @return {Integer} the current day - * @example - *
      - * - * let d = day(); - * text('Current day: \n' + d, 5, 50); - * - *
      - * - * @alt - * Current day is displayed - */ - - _main.default.prototype.day = function () { - return new Date().getDate(); - }; - /** - * p5.js communicates with the clock on your computer. The hour() function - * returns the current hour as a value from 0 - 23. - * - * @method hour - * @return {Integer} the current hour - * @example - *
      - * - * let h = hour(); - * text('Current hour:\n' + h, 5, 50); - * - *
      - * - * @alt - * Current hour is displayed - */ - _main.default.prototype.hour = function () { - return new Date().getHours(); - }; - /** - * p5.js communicates with the clock on your computer. The minute() function - * returns the current minute as a value from 0 - 59. - * - * @method minute - * @return {Integer} the current minute - * @example - *
      - * - * let m = minute(); - * text('Current minute: \n' + m, 5, 50); - * - *
      - * - * @alt - * Current minute is displayed - */ - _main.default.prototype.minute = function () { - return new Date().getMinutes(); - }; - /** - * Returns the number of milliseconds (thousandths of a second) since - * starting the sketch (when `setup()` is called). This information is often - * used for timing events and animation sequences. - * - * @method millis - * @return {Number} the number of milliseconds since starting the sketch - * @example - *
      - * - * let millisecond = millis(); - * text('Milliseconds \nrunning: \n' + millisecond, 5, 40); - * - *
      - * - * @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; + var w_x = [ + ]; + var w_y = [ + ]; + var w_z = [ + ]; + var t, + _x, + _y, + _z, + i, + k, + m; + // variable i for bezierPoints, k for components, and m for anchor points. + var argLength = arguments.length; + t = 0; + if (this._lookUpTableQuadratic.length === 0 || this._lutQuadraticDetail !== this._pInst._curveDetail) { + this._lookUpTableQuadratic = [ + ]; + this._lutQuadraticDetail = this._pInst._curveDetail; + var step = 1 / this._lutQuadraticDetail; + var start = 0; + var end = 1; + var j = 0; + while (start < 1) { + t = parseFloat(start.toFixed(6)); + this._lookUpTableQuadratic[j] = this._quadraticCoefficients(t); + if (end.toFixed(6) === step.toFixed(6)) { + t = parseFloat(end.toFixed(6)) + parseFloat(start.toFixed(6)); + ++j; + this._lookUpTableQuadratic[j] = this._quadraticCoefficients(t); + break; + } + start += step; + end -= step; + ++j; + } + } + var LUTLength = this._lookUpTableQuadratic.length; + // fillColors[0]: start point color + // fillColors[1]: control point color + // fillColors[2]: end point color + var fillColors = [ + ]; + for (m = 0; m < 3; m++) { + fillColors.push([]); + } + fillColors[0] = this.immediateMode.geometry.vertexColors.slice( - 4); + fillColors[2] = this.curFillColor.slice(); + // Do the same for strokeColor. + var strokeColors = [ + ]; + for (m = 0; m < 3; m++) { + strokeColors.push([]); + } + strokeColors[0] = this.immediateMode.geometry.vertexStrokeColors.slice( - 4); + strokeColors[2] = this.curStrokeColor.slice(); + if (argLength === 4) { + this.isQuadratic = true; + w_x = [ + this.immediateMode._quadraticVertex[0], + arguments.length <= 0 ? undefined : arguments[0], + arguments.length <= 2 ? undefined : arguments[2] + ]; + w_y = [ + this.immediateMode._quadraticVertex[1], + arguments.length <= 1 ? undefined : arguments[1], + arguments.length <= 3 ? undefined : arguments[3] + ]; + // The ratio of the distance between the start point, the control- + // point, and the end point determines the intermediate color. + var d0 = Math.hypot(w_x[0] - w_x[1], w_y[0] - w_y[1]); + var d1 = Math.hypot(w_x[1] - w_x[2], w_y[1] - w_y[2]); + var totalLength = d0 + d1; + d0 /= totalLength; + for (k = 0; k < 4; k++) { + fillColors[1].push(fillColors[0][k] * (1 - d0) + fillColors[2][k] * d0); + strokeColors[1].push(strokeColors[0][k] * (1 - d0) + strokeColors[2][k] * d0); + } + for (i = 0; i < LUTLength; i++) { + // Interpolate colors using control points + this.curFillColor = [ + 0, + 0, + 0, + 0 + ]; + this.curStrokeColor = [ + 0, + 0, + 0, + 0 + ]; + _x = _y = 0; + for (m = 0; m < 3; m++) { + for (k = 0; k < 4; k++) { + this.curFillColor[k] += this._lookUpTableQuadratic[i][m] * fillColors[m][k]; + this.curStrokeColor[k] += this._lookUpTableQuadratic[i][m] * strokeColors[m][k]; + } + _x += w_x[m] * this._lookUpTableQuadratic[i][m]; + _y += w_y[m] * this._lookUpTableQuadratic[i][m]; + } + this.vertex(_x, _y); + } // so that we leave currentColor with the last value the user set it to + + this.curFillColor = fillColors[2]; + this.curStrokeColor = strokeColors[2]; + this.immediateMode._quadraticVertex[0] = arguments.length <= 2 ? undefined : arguments[2]; + this.immediateMode._quadraticVertex[1] = arguments.length <= 3 ? undefined : arguments[3]; + } else if (argLength === 6) { + this.isQuadratic = true; + w_x = [ + this.immediateMode._quadraticVertex[0], + arguments.length <= 0 ? undefined : arguments[0], + arguments.length <= 3 ? undefined : arguments[3] + ]; + w_y = [ + this.immediateMode._quadraticVertex[1], + arguments.length <= 1 ? undefined : arguments[1], + arguments.length <= 4 ? undefined : arguments[4] + ]; + w_z = [ + this.immediateMode._quadraticVertex[2], + arguments.length <= 2 ? undefined : arguments[2], + arguments.length <= 5 ? undefined : arguments[5] + ]; + // The ratio of the distance between the start point, the control- + // point, and the end point determines the intermediate color. + var _d4 = Math.hypot(w_x[0] - w_x[1], w_y[0] - w_y[1], w_z[0] - w_z[1]); + var _d5 = Math.hypot(w_x[1] - w_x[2], w_y[1] - w_y[2], w_z[1] - w_z[2]); + var _totalLength2 = _d4 + _d5; + _d4 /= _totalLength2; + for (k = 0; k < 4; k++) { + fillColors[1].push(fillColors[0][k] * (1 - _d4) + fillColors[2][k] * _d4); + strokeColors[1].push(strokeColors[0][k] * (1 - _d4) + strokeColors[2][k] * _d4); + } + for (i = 0; i < LUTLength; i++) { + // Interpolate colors using control points + this.curFillColor = [ + 0, + 0, + 0, + 0 + ]; + this.curStrokeColor = [ + 0, + 0, + 0, + 0 + ]; + _x = _y = _z = 0; + for (m = 0; m < 3; m++) { + for (k = 0; k < 4; k++) { + this.curFillColor[k] += this._lookUpTableQuadratic[i][m] * fillColors[m][k]; + this.curStrokeColor[k] += this._lookUpTableQuadratic[i][m] * strokeColors[m][k]; + } + _x += w_x[m] * this._lookUpTableQuadratic[i][m]; + _y += w_y[m] * this._lookUpTableQuadratic[i][m]; + _z += w_z[m] * this._lookUpTableQuadratic[i][m]; + } + this.vertex(_x, _y, _z); + } // so that we leave currentColor with the last value the user set it to + + this.curFillColor = fillColors[2]; + this.curStrokeColor = strokeColors[2]; + this.immediateMode._quadraticVertex[0] = arguments.length <= 3 ? undefined : arguments[3]; + this.immediateMode._quadraticVertex[1] = arguments.length <= 4 ? undefined : arguments[4]; + this.immediateMode._quadraticVertex[2] = arguments.length <= 5 ? undefined : arguments[5]; + } } }; - /** - * p5.js communicates with the clock on your computer. The month() function - * returns the current month as a value from 1 - 12. - * - * @method month - * @return {Integer} the current month - * @example - *
      - * - * let m = month(); - * text('Current month: \n' + m, 5, 50); - * - *
      - * - * @alt - * Current month is displayed - */ - _main.default.prototype.month = function () { - //January is 0! - return new Date().getMonth() + 1; - }; - /** - * p5.js communicates with the clock on your computer. The second() function - * returns the current second as a value from 0 - 59. - * - * @method second - * @return {Integer} the current second - * @example - *
      - * - * let s = second(); - * text('Current second: \n' + s, 5, 50); - * - *
      - * - * @alt - * Current second is displayed - */ - _main.default.prototype.second = function () { - return new Date().getSeconds(); + _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(); + } + } + } }; - /** - * p5.js communicates with the clock on your computer. The year() function - * returns the current year as an integer (2014, 2015, 2016, etc). - * - * @method year - * @return {Integer} the current year - * @example - *
      - * - * let y = year(); - * text('Current year: \n' + y, 5, 50); - * - *
      - * - * @alt - * Current year is displayed - */ - _main.default.prototype.year = function () { - return new Date().getFullYear(); + _main.default.RendererGL.prototype.image = function (img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) { + if (this._isErasing) { + this.blendMode(this._cachedBlendMode); + } + this._pInst.push(); + this._pInst.noLights(); + this._pInst.noStroke(); + this._pInst.texture(img); + this._pInst.textureMode(constants.NORMAL); + var u0 = 0; + if (sx <= img.width) { + u0 = sx / img.width; + } + var u1 = 1; + if (sx + sWidth <= img.width) { + u1 = (sx + sWidth) / img.width; + } + var v0 = 0; + if (sy <= img.height) { + v0 = sy / img.height; + } + var v1 = 1; + if (sy + sHeight <= img.height) { + v1 = (sy + sHeight) / img.height; + } + this.beginShape(); + this.vertex(dx, dy, 0, u0, v0); + this.vertex(dx + dWidth, dy, 0, u1, v0); + this.vertex(dx + dWidth, dy + dHeight, 0, u1, v1); + this.vertex(dx, dy + dHeight, 0, u0, v1); + this.endShape(constants.CLOSE); + this._pInst.pop(); + if (this._isErasing) { + this.blendMode(constants.REMOVE); + } }; var _default = _main.default; exports.default = _default; }, { - '../core/main': 290 + '../core/constants': 286, + '../core/main': 298, + './p5.Geometry': 350, + 'core-js/modules/es.array.concat': 169, + 'core-js/modules/es.array.for-each': 175, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.math.hypot': 188, + 'core-js/modules/es.math.sign': 190, + 'core-js/modules/es.number.to-fixed': 193, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 333: [ + 342: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); _dereq_('core-js/modules/es.symbol.description'); _dereq_('core-js/modules/es.symbol.iterator'); - _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.every'); + _dereq_('core-js/modules/es.array.from'); _dereq_('core-js/modules/es.array.iterator'); - _dereq_('core-js/modules/es.array.slice'); - _dereq_('core-js/modules/es.math.hypot'); - _dereq_('core-js/modules/es.number.to-fixed'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.object.assign'); _dereq_('core-js/modules/es.object.get-own-property-descriptor'); _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.to-string'); _dereq_('core-js/modules/es.string.iterator'); _dereq_('core-js/modules/es.weak-map'); _dereq_('core-js/modules/web.dom-collections.iterator'); @@ -94002,23 +104777,14 @@ } return _typeof(obj); } - _dereq_('core-js/modules/es.symbol'); - _dereq_('core-js/modules/es.symbol.description'); - _dereq_('core-js/modules/es.symbol.iterator'); - _dereq_('core-js/modules/es.array.concat'); - _dereq_('core-js/modules/es.array.iterator'); - _dereq_('core-js/modules/es.array.slice'); - _dereq_('core-js/modules/es.math.hypot'); - _dereq_('core-js/modules/es.number.to-fixed'); - _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.string.iterator'); - _dereq_('core-js/modules/web.dom-collections.iterator'); + _dereq_('core-js/modules/es.array.every'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.object.assign'); Object.defineProperty(exports, '__esModule', { value: true }); exports.default = void 0; var _main = _interopRequireDefault(_dereq_('../core/main')); - _dereq_('./p5.Geometry'); var constants = _interopRequireWildcard(_dereq_('../core/constants')); function _getRequireWildcardCache() { if (typeof WeakMap !== 'function') return null; @@ -94066,2557 +104832,2714 @@ default: obj }; - } /** - * @module Shape - * @submodule 3D Primitives - * @for p5 - * @requires core - * @requires p5.Geometry - */ - /** - * Draw a plane with given a width and height - * @method plane - * @param {Number} [width] width of the plane - * @param {Number} [height] height of the plane - * @param {Integer} [detailX] Optional number of triangle - * subdivisions in x-dimension - * @param {Integer} [detailY] Optional number of triangle - * subdivisions in y-dimension - * @chainable - * @example - *
      - * - * // draw a plane - * // with width 50 and height 50 - * function setup() { - * createCanvas(100, 100, WEBGL); - * describe('a white plane with black wireframe lines'); - * } - * - * function draw() { - * background(200); - * plane(50, 50); - * } - * - *
      - * - * @alt - * Nothing displayed on canvas - * Rotating interior view of a box with sides that change color. - * 3d red and green gradient. - * Rotating interior view of a cylinder with sides that change color. - * Rotating view of a cylinder with sides that change color. - * 3d red and green gradient. - * rotating view of a multi-colored cylinder with concave sides. - */ - - _main.default.prototype.plane = function (width, height, detailX, detailY) { - this._assert3d('plane'); - _main.default._validateParameters('plane', arguments); - if (typeof width === 'undefined') { - width = 50; - } - if (typeof height === 'undefined') { - height = width; + } + 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; } - if (typeof detailX === 'undefined') { - detailX = 1; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); } - if (typeof detailY === 'undefined') { - detailY = 1; + } + 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); } - 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); + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } /** + * @private + * A class responsible for converting successive WebGL draw calls into a single + * `p5.Geometry` that can be reused and drawn with `model()`. + */ + + var GeometryBuilder = /*#__PURE__*/ function () { + function GeometryBuilder(renderer) { + _classCallCheck(this, GeometryBuilder); + this.renderer = renderer; + renderer._pInst.push(); + this.identityMatrix = new _main.default.Matrix(); + renderer.uMVMatrix = new _main.default.Matrix(); + this.geometry = new _main.default.Geometry(); + this.geometry.gid = '_p5_GeometryBuilder_'.concat(GeometryBuilder.nextGeometryId); + GeometryBuilder.nextGeometryId++; + this.hasTransform = false; + } /** + * @private + * Applies the current transformation matrix to each vertex. + */ + + _createClass(GeometryBuilder, [ + { + key: 'transformVertices', + value: function transformVertices(vertices) { + var _this = this; + if (!this.hasTransform) return vertices; + return vertices.map(function (v) { + return _this.renderer.uMVMatrix.multiplyPoint(v); + }); + } /** + * @private + * Applies the current normal matrix to each normal. + */ + + }, + { + key: 'transformNormals', + value: function transformNormals(normals) { + var _this2 = this; + if (!this.hasTransform) return normals; + return normals.map(function (v) { + return _this2.renderer.uNMatrix.multiplyVec3(v); + }); + } /** + * @private + * Adds a p5.Geometry to the builder's combined geometry, flattening + * transformations. + */ + + }, + { + key: 'addGeometry', + value: function addGeometry(input) { + var _this3 = this, + _this$geometry$vertic, + _this$geometry$vertex, + _this$geometry$uvs, + _this$geometry$vertex2; + this.hasTransform = !this.renderer.uMVMatrix.mat4.every(function (v, i) { + return v === _this3.identityMatrix.mat4[i]; + }); + if (this.hasTransform) { + this.renderer.uNMatrix.inverseTranspose(this.renderer.uMVMatrix); + } + var startIdx = this.geometry.vertices.length; + (_this$geometry$vertic = this.geometry.vertices).push.apply(_this$geometry$vertic, _toConsumableArray(this.transformVertices(input.vertices))); + (_this$geometry$vertex = this.geometry.vertexNormals).push.apply(_this$geometry$vertex, _toConsumableArray(this.transformNormals(input.vertexNormals))); + (_this$geometry$uvs = this.geometry.uvs).push.apply(_this$geometry$uvs, _toConsumableArray(input.uvs)); + if (this.renderer._doFill) { + var _this$geometry$faces; + (_this$geometry$faces = this.geometry.faces).push.apply(_this$geometry$faces, _toConsumableArray(input.faces.map(function (f) { + return f.map(function (idx) { + return idx + startIdx; + }); + }))); } - } - }; - 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; - }; + if (this.renderer._doStroke) { + var _this$geometry$edges; + (_this$geometry$edges = this.geometry.edges).push.apply(_this$geometry$edges, _toConsumableArray(input.edges.map(function (edge) { + return edge.map(function (idx) { + return idx + startIdx; + }); + }))); + } + var vertexColors = _toConsumableArray(input.vertexColors); + while (vertexColors.length < input.vertices.length * 4) { + vertexColors.push.apply(vertexColors, _toConsumableArray(this.renderer.curFillColor)); + }(_this$geometry$vertex2 = this.geometry.vertexColors).push.apply(_this$geometry$vertex2, _toConsumableArray(vertexColors)); + } /** + * Adds geometry from the renderer's immediate mode into the builder's + * combined geometry. + */ + + }, + { + key: 'addImmediate', + value: function addImmediate() { + var geometry = this.renderer.immediateMode.geometry; + var shapeMode = this.renderer.immediateMode.shapeMode; + var faces = [ + ]; + if (this.renderer._doFill) { + if (shapeMode === constants.TRIANGLE_STRIP || shapeMode === constants.QUAD_STRIP) { + for (var i = 2; i < geometry.vertices.length; i++) { + if (i % 2 === 0) { + faces.push([i, + i - 1, + i - 2]); + } else { + faces.push([i, + i - 2, + i - 1]); + } + } + } else if (shapeMode === constants.TRIANGLE_FAN) { + for (var _i = 2; _i < geometry.vertices.length; _i++) { + faces.push([0, + _i - 1, + _i]); + } + } else { + for (var _i2 = 0; _i2 < geometry.vertices.length; _i2 += 3) { + faces.push([_i2, + _i2 + 1, + _i2 + 2]); + } + } + } + this.addGeometry(Object.assign({ + }, geometry, { + faces: faces + })); + } /** + * Adds geometry from the renderer's retained mode into the builder's + * combined geometry. + */ + + }, + { + key: 'addRetained', + value: function addRetained(geometry) { + this.addGeometry(geometry.model); + } /** + * Cleans up the state of the renderer and returns the combined geometry that + * was built. + * @returns p5.Geometry The flattened, combined geometry + */ + + }, + { + key: 'finish', + value: function finish() { + this.renderer._pInst.pop(); + return this.geometry; + } + } + ]); + return GeometryBuilder; + }(); /** - * 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 + * Keeps track of how many custom geometry objects have been made so that each + * can be assigned a unique ID. + */ + GeometryBuilder.nextGeometryId = 0; + var _default = GeometryBuilder; + exports.default = _default; + }, + { + '../core/constants': 286, + '../core/main': 298, + 'core-js/modules/es.array.every': 171, + 'core-js/modules/es.array.from': 176, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.map': 182, + 'core-js/modules/es.object.assign': 194, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 + } + ], + 343: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.math.hypot'); + _dereq_('core-js/modules/es.math.sign'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.math.hypot'); + _dereq_('core-js/modules/es.math.sign'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } /** + * @module 3D + * @submodule Interaction + * @for p5 + * @requires core + */ + /** + * Allows movement around a 3D sketch using a mouse or trackpad or touch. + * Left-clicking and dragging or swipe motion will rotate the camera position + * about the center of the sketch, right-clicking and dragging or multi-swipe + * will pan the camera position without rotation, and using the mouse wheel + * (scrolling) or pinch in/out will move the camera further or closer + * from the center of the sketch. This function can be called with parameters + * dictating sensitivity to mouse/touch 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 + * @param {Object} [options] An optional object that can contain additional settings, + * disableTouchActions - Boolean, default value is true. + * Setting this to true makes mobile interactions smoother by preventing + * accidental interactions with the page while orbiting. But if you're already + * doing it via css or want the default touch actions, consider setting it to false. + * freeRotation - Boolean, default value is false. + * By default, horizontal movement of the mouse or touch pointer rotates the camera + * around the y-axis, and vertical movement rotates the camera around the x-axis. + * But if setting this option to true, the camera always rotates in the direction + * the pointer is moving. For zoom and move, the behavior is the same regardless of + * true/false. * @chainable * @example *
      * - * // draw a spinning box - * // with width, height and depth of 50 * function setup() { * createCanvas(100, 100, WEBGL); - * describe('a white box rotating in 3D space'); + * normalMaterial(); + * describe( + * 'Camera orbits around a box when mouse is hold-clicked & then moved.' + * ); * } - * * function draw() { * background(200); - * rotateX(frameCount * 0.01); - * rotateY(frameCount * 0.01); - * box(50); + * + * // If you execute the line commented out instead of next line, the direction of rotation + * // will be the direction the mouse or touch pointer moves, not around the X or Y axis. + * orbitControl(); + * // orbitControl(1, 1, 1, {freeRotation: true}); + * + * rotateY(0.5); + * box(30, 50); * } * *
      + * + * @alt + * Camera orbits around a box when mouse is hold-clicked & then moved. */ - _main.default.prototype.box = function (width, height, depth, detailX, detailY) { - this._assert3d('box'); - _main.default._validateParameters('box', arguments); - if (typeof width === 'undefined') { - width = 50; + // implementation based on three.js 'orbitControls': + // https://github.com/mrdoob/three.js/blob/6afb8595c0bf8b2e72818e42b64e6fe22707d896/examples/jsm/controls/OrbitControls.js#L22 + + _main.default.prototype.orbitControl = function (sensitivityX, sensitivityY, sensitivityZ, options) { + var _this = this; + this._assert3d('orbitControl'); + _main.default._validateParameters('orbitControl', arguments); + var cam = this._renderer._curCamera; + if (typeof sensitivityX === 'undefined') { + sensitivityX = 1; } - if (typeof height === 'undefined') { - height = width; + if (typeof sensitivityY === 'undefined') { + sensitivityY = sensitivityX; } - if (typeof depth === 'undefined') { - depth = height; + if (typeof sensitivityZ === 'undefined') { + sensitivityZ = 1; } - var perPixelLighting = this._renderer.attributes && this._renderer.attributes.perPixelLighting; - if (typeof detailX === 'undefined') { - detailX = perPixelLighting ? 1 : 4; + if (_typeof(options) !== 'object') { + options = { + }; + } // default right-mouse and mouse-wheel behaviors (context menu and scrolling, + // respectively) are disabled here to allow use of those events for panning and + // zooming. However, whether or not to disable touch actions is an option. + // disable context menu for canvas element and add 'contextMenuDisabled' + // flag to p5 instance + + if (this.contextMenuDisabled !== true) { + this.canvas.oncontextmenu = function () { + return false; + }; + this._setProperty('contextMenuDisabled', true); + } // disable default scrolling behavior on the canvas element and add + // 'wheelDefaultDisabled' flag to p5 instance + + if (this.wheelDefaultDisabled !== true) { + this.canvas.onwheel = function () { + return false; + }; + this._setProperty('wheelDefaultDisabled', true); + } // disable default touch behavior on the canvas element and add + // 'touchActionsDisabled' flag to p5 instance + + var _options = options, + _options$disableTouch = _options.disableTouchActions, + disableTouchActions = _options$disableTouch === void 0 ? true : _options$disableTouch; + if (this.touchActionsDisabled !== true && disableTouchActions) { + this.canvas.style['touch-action'] = 'none'; + this._setProperty('touchActionsDisabled', true); + } // If option.freeRotation is true, the camera always rotates freely in the direction + // the pointer moves. default value is false (normal behavior) + + var _options2 = options, + _options2$freeRotatio = _options2.freeRotation, + freeRotation = _options2$freeRotatio === void 0 ? false : _options2$freeRotatio; // get moved touches. + var movedTouches = [ + ]; + this.touches.forEach(function (curTouch) { + _this._renderer.prevTouches.forEach(function (prevTouch) { + if (curTouch.id === prevTouch.id) { + var movedTouch = { + x: curTouch.x, + y: curTouch.y, + px: prevTouch.x, + py: prevTouch.y + }; + movedTouches.push(movedTouch); + } + }); + }); + this._renderer.prevTouches = this.touches; + // The idea of using damping is based on the following website. thank you. + // https://github.com/freshfork/p5.EasyCam/blob/9782964680f6a5c4c9bee825c475d9f2021d5134/p5.easycam.js#L1124 + // variables for interaction + var deltaRadius = 0; + var deltaTheta = 0; + var deltaPhi = 0; + var moveDeltaX = 0; + var moveDeltaY = 0; + // constants for dampingProcess + var damping = 0.85; + var rotateAccelerationFactor = 0.6; + var moveAccelerationFactor = 0.15; + // For touches, the appropriate scale is different + // because the distance difference is multiplied. + var mouseZoomScaleFactor = 0.01; + var touchZoomScaleFactor = 0.0004; + var scaleFactor = this.height < this.width ? this.height : this.width; + // Flag whether the mouse or touch pointer is inside the canvas + var pointersInCanvas = false; + // calculate and determine flags and variables. + if (movedTouches.length > 0) { + /* for touch */ + // if length === 1, rotate + // if length > 1, zoom and move + // for touch, it is calculated based on one moved touch pointer position. + pointersInCanvas = movedTouches[0].x > 0 && movedTouches[0].x < this.width && movedTouches[0].y > 0 && movedTouches[0].y < this.height; + if (movedTouches.length === 1) { + var t = movedTouches[0]; + deltaTheta = - sensitivityX * (t.x - t.px) / scaleFactor; + deltaPhi = sensitivityY * (t.y - t.py) / scaleFactor; + } else { + var t0 = movedTouches[0]; + var t1 = movedTouches[1]; + var distWithTouches = Math.hypot(t0.x - t1.x, t0.y - t1.y); + var prevDistWithTouches = Math.hypot(t0.px - t1.px, t0.py - t1.py); + var changeDist = distWithTouches - prevDistWithTouches; + // move the camera farther when the distance between the two touch points + // decreases, move the camera closer when it increases. + deltaRadius = - changeDist * sensitivityZ * touchZoomScaleFactor; + // Move the center of the camera along with the movement of + // the center of gravity of the two touch points. + moveDeltaX = 0.5 * (t0.x + t1.x) - 0.5 * (t0.px + t1.px); + moveDeltaY = 0.5 * (t0.y + t1.y) - 0.5 * (t0.py + t1.py); + } + if (this.touches.length > 0) { + if (pointersInCanvas) { + // Initiate an interaction if touched in the canvas + this._renderer.executeRotateAndMove = true; + this._renderer.executeZoom = true; + } + } else { + // End an interaction when the touch is released + this._renderer.executeRotateAndMove = false; + this._renderer.executeZoom = false; + } + } else { + /* for mouse */ + // if wheelDeltaY !== 0, zoom + // if mouseLeftButton is down, rotate + // if mouseRightButton is down, move + // For mouse, it is calculated based on the mouse position. + pointersInCanvas = this.mouseX > 0 && this.mouseX < this.width && this.mouseY > 0 && this.mouseY < this.height; + if (this._mouseWheelDeltaY !== 0) { + // zoom the camera depending on the value of _mouseWheelDeltaY. + // move away if positive, move closer if negative + deltaRadius = Math.sign(this._mouseWheelDeltaY) * sensitivityZ; + deltaRadius *= mouseZoomScaleFactor; + this._mouseWheelDeltaY = 0; + // start zoom when the mouse is wheeled within the canvas. + if (pointersInCanvas) this._renderer.executeZoom = true; + } else { + // quit zoom when you stop wheeling. + this._renderer.zoomFlag = false; + } + if (this.mouseIsPressed) { + if (this.mouseButton === this.LEFT) { + deltaTheta = - sensitivityX * this.movedX / scaleFactor; + deltaPhi = sensitivityY * this.movedY / scaleFactor; + } else if (this.mouseButton === this.RIGHT) { + moveDeltaX = this.movedX; + moveDeltaY = this.movedY * cam.yScale; + } // start rotate and move when mouse is pressed within the canvas. + + if (pointersInCanvas) this._renderer.executeRotateAndMove = true; + } else { + // quit rotate and move if mouse is released. + this._renderer.executeRotateAndMove = false; + } + } // interactions + // zoom process + + if (deltaRadius !== 0 && this._renderer.executeZoom) { + // accelerate zoom velocity + this._renderer.zoomVelocity += deltaRadius; } - if (typeof detailY === 'undefined') { - detailY = perPixelLighting ? 1 : 4; + if (Math.abs(this._renderer.zoomVelocity) > 0.001) { + // if freeRotation is true, we use _orbitFree() instead of _orbit() + if (freeRotation) { + cam._orbitFree(0, 0, this._renderer.zoomVelocity); + } else { + cam._orbit(0, 0, this._renderer.zoomVelocity); + } // In orthogonal projection, the scale does not change even if + // the distance to the gaze point is changed, so the projection matrix + // needs to be modified. + + if (cam.projMatrix.mat4[15] !== 0) { + cam.projMatrix.mat4[0] *= Math.pow(10, - this._renderer.zoomVelocity); + cam.projMatrix.mat4[5] *= Math.pow(10, - this._renderer.zoomVelocity); + // modify uPMatrix + this._renderer.uPMatrix.mat4[0] = cam.projMatrix.mat4[0]; + this._renderer.uPMatrix.mat4[5] = cam.projMatrix.mat4[5]; + } // damping + + this._renderer.zoomVelocity *= damping; + } else { + this._renderer.zoomVelocity = 0; + } // rotate process + + if ((deltaTheta !== 0 || deltaPhi !== 0) && this._renderer.executeRotateAndMove) { + // accelerate rotate velocity + this._renderer.rotateVelocity.add(deltaTheta * rotateAccelerationFactor, deltaPhi * rotateAccelerationFactor); } - 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 + if (this._renderer.rotateVelocity.magSq() > 0.000001) { + // if freeRotation is true, the camera always rotates freely in the direction the pointer moves + if (freeRotation) { + cam._orbitFree( - this._renderer.rotateVelocity.x, this._renderer.rotateVelocity.y, 0); + } else { + cam._orbit(this._renderer.rotateVelocity.x, this._renderer.rotateVelocity.y, 0); + } // damping - this._renderer.createBuffers(gId, boxGeom); + this._renderer.rotateVelocity.mult(damping); + } else { + this._renderer.rotateVelocity.set(0, 0); + } // move process + + if ((moveDeltaX !== 0 || moveDeltaY !== 0) && this._renderer.executeRotateAndMove) { + // Normalize movement distance + var ndcX = moveDeltaX * 2 / this.width; + var ndcY = - moveDeltaY * 2 / this.height; + // accelerate move velocity + this._renderer.moveVelocity.add(ndcX * moveAccelerationFactor, ndcY * moveAccelerationFactor); + } + if (this._renderer.moveVelocity.magSq() > 0.000001) { + // Translate the camera so that the entire object moves + // perpendicular to the line of sight when the mouse is moved + // or when the centers of gravity of the two touch pointers move. + var local = cam._getLocalAxes(); + // Calculate the z coordinate in the view coordinates of + // the center, that is, the distance to the view point + var diffX = cam.eyeX - cam.centerX; + var diffY = cam.eyeY - cam.centerY; + var diffZ = cam.eyeZ - cam.centerZ; + var viewZ = Math.sqrt(diffX * diffX + diffY * diffY + diffZ * diffZ); + // position vector of the center. + var cv = new _main.default.Vector(cam.centerX, cam.centerY, cam.centerZ); + // Calculate the normalized device coordinates of the center. + cv = cam.cameraMatrix.multiplyPoint(cv); + cv = this._renderer.uPMatrix.multiplyAndNormalizePoint(cv); + // Move the center by this distance + // in the normalized device coordinate system. + cv.x -= this._renderer.moveVelocity.x; + cv.y -= this._renderer.moveVelocity.y; + // Calculate the translation vector + // in the direction perpendicular to the line of sight of center. + var dx, + dy; + var uP = this._renderer.uPMatrix.mat4; + if (uP[15] === 0) { + dx = (uP[8] + cv.x) / uP[0] * viewZ; + dy = (uP[9] + cv.y) / uP[5] * viewZ; + } else { + dx = (cv.x - uP[12]) / uP[0]; + dy = (cv.y - uP[13]) / uP[5]; + } // translate the camera. + + cam.setPosition(cam.eyeX + dx * local.x[0] + dy * local.y[0], cam.eyeY + dx * local.x[1] + dy * local.y[1], cam.eyeZ + dx * local.x[2] + dy * local.y[2]); + // damping + this._renderer.moveVelocity.mult(damping); + } else { + this._renderer.moveVelocity.set(0, 0); } - this._renderer.drawBuffersScaled(gId, width, height, depth); return this; }; /** - * Draw a sphere with given radius. + * 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. * - * 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 + * By default, the grid will run through the origin (0,0,0) of the sketch + * along the XZ plane + * and the axes icon will be offset from the origin. Both the grid and axes + * icon will be sized according to the current canvas size. Note that because the + * grid runs parallel to the default camera view, it is often helpful to use + * debugMode along with orbitControl to allow full view of the grid. + * @method debugMode + * @example + *
      + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * camera(0, -30, 100, 0, 0, 0, 0, 1, 0); + * normalMaterial(); + * debugMode(); + * describe( + * 'a 3D box is centered on a grid in a 3D sketch. an icon indicates the direction of each axis: a red line points +X, a green line +Y, and a blue line +Z. the grid and icon disappear when the spacebar is pressed.' + * ); + * } + * + * function draw() { + * background(200); + * orbitControl(); + * box(15, 30); + * // Press the spacebar to turn debugMode off! + * if (keyIsDown(32)) { + * noDebugMode(); + * } + * } + * + *
      + * @alt + * a 3D box is centered on a grid in a 3D sketch. an icon + * indicates the direction of each axis: a red line points +X, + * a green line +Y, and a blue line +Z. the grid and icon disappear when the + * spacebar is pressed. * - * @chainable * @example *
      * - * // draw a sphere with radius 40 * function setup() { * createCanvas(100, 100, WEBGL); - * describe('a white sphere with black wireframe lines'); + * camera(0, -30, 100, 0, 0, 0, 0, 1, 0); + * normalMaterial(); + * debugMode(GRID); + * describe('a 3D box is centered on a grid in a 3D sketch.'); * } * * function draw() { - * background(205, 102, 94); - * sphere(40); + * background(200); + * orbitControl(); + * box(15, 30); * } * *
      + * @alt + * a 3D box is centered on a grid in a 3D sketch. * * @example *
      * - * let detailX; - * // slide to see how detailX works * function setup() { * createCanvas(100, 100, WEBGL); - * detailX = createSlider(3, 24, 3); - * detailX.position(10, height + 5); - * detailX.style('width', '80px'); + * camera(0, -30, 100, 0, 0, 0, 0, 1, 0); + * normalMaterial(); + * debugMode(AXES); * describe( - * 'a white sphere with low detail on the x-axis, including a slider to adjust detailX' + * 'a 3D box is centered in a 3D sketch. an icon indicates the direction of each axis: a red line points +X, a green line +Y, and a blue line +Z.' * ); * } * * function draw() { - * background(205, 105, 94); - * rotateY(millis() / 1000); - * sphere(40, detailX.value(), 16); + * background(200); + * orbitControl(); + * box(15, 30); * } * *
      + * @alt + * a 3D box is centered in a 3D sketch. an icon + * indicates the direction of each axis: a red line points +X, + * a green line +Y, and a blue line +Z. * * @example *
      * - * 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'); + * camera(0, -30, 100, 0, 0, 0, 0, 1, 0); + * normalMaterial(); + * debugMode(GRID, 100, 10, 0, 0, 0); + * describe('a 3D box is centered on a grid in a 3D sketch'); + * } + * + * function draw() { + * background(200); + * orbitControl(); + * box(15, 30); + * } + * + *
      + * @alt + * a 3D box is centered on a grid in a 3D sketch + * + * @example + *
      + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * camera(0, -30, 100, 0, 0, 0, 0, 1, 0); + * normalMaterial(); + * debugMode(100, 10, 0, 0, 0, 20, 0, -40, 0); * describe( - * 'a white sphere with low detail on the y-axis, including a slider to adjust detailY' + * 'a 3D box is centered on a grid in a 3D sketch. an icon indicates the direction of each axis: a red line points +X, a green line +Y, and a blue line +Z.' * ); * } * * function draw() { - * background(205, 105, 94); - * rotateY(millis() / 1000); - * sphere(40, 16, detailY.value()); + * noStroke(); + * background(200); + * orbitControl(); + * box(15, 30); + * // set the stroke color and weight for the grid! + * stroke(255, 0, 150); + * strokeWeight(0.8); * } * *
      + * @alt + * a 3D box is centered on a grid in a 3D sketch. an icon + * indicates the direction of each axis: a red line points +X, + * a green line +Y, and a blue line +Z. */ - _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 + * @method debugMode + * @param {Constant} mode either GRID or AXES */ - 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; + /** + * @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]; } - if (topCap) { - startIndex += detailX; - for (ii = 0; ii < detailX; ++ii) { - this.faces.push([startIndex + ii, - startIndex + (ii + 1) % detailX, - startIndex + detailX]); + _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])); } }; /** - * 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 - *
      - * - * // draw a spinning cylinder - * // with radius 20 and height 50 - * function setup() { - * createCanvas(100, 100, WEBGL); - * describe('a rotating white cylinder'); - * } - * - * function draw() { - * background(205, 105, 94); - * rotateX(frameCount * 0.01); - * rotateZ(frameCount * 0.01); - * cylinder(20, 50); - * } - * - *
      - * - * @example - *
      - * - * // slide to see how detailX works - * let detailX; - * function setup() { - * createCanvas(100, 100, WEBGL); - * detailX = createSlider(3, 24, 3); - * detailX.position(10, height + 5); - * detailX.style('width', '80px'); - * describe( - * 'a rotating white cylinder with limited X detail, with a slider that adjusts detailX' - * ); - * } - * - * function draw() { - * background(205, 105, 94); - * rotateY(millis() / 1000); - * cylinder(20, 75, detailX.value(), 1); - * } - * - *
      - * + * Turns off debugMode() in a 3D sketch. + * @method noDebugMode * @example *
      * - * // slide to see how detailY works - * let detailY; * function setup() { * createCanvas(100, 100, WEBGL); - * detailY = createSlider(1, 16, 1); - * detailY.position(10, height + 5); - * detailY.style('width', '80px'); + * camera(0, -30, 100, 0, 0, 0, 0, 1, 0); + * normalMaterial(); + * debugMode(); * describe( - * 'a rotating white cylinder with limited Y detail, with a slider that adjusts detailY' + * 'a 3D box is centered on a grid in a 3D sketch. an icon indicates the direction of each axis: a red line points +X, a green line +Y, and a blue line +Z. the grid and icon disappear when the spacebar is pressed.' * ); * } * * function draw() { - * background(205, 105, 94); - * rotateY(millis() / 1000); - * cylinder(20, 75, 16, detailY.value()); + * background(200); + * orbitControl(); + * box(15, 30); + * // Press the spacebar to turn debugMode off! + * if (keyIsDown(32)) { + * noDebugMode(); + * } * } * *
      + * @alt + * a 3D box is centered on a grid in a 3D sketch. an icon + * indicates the direction of each axis: a red line points +X, + * a green line +Y, and a blue line +Z. the grid and icon disappear when the + * spacebar is pressed. */ - _main.default.prototype.cylinder = function (radius, height, detailX, detailY, bottomCap, topCap) { - this._assert3d('cylinder'); - _main.default._validateParameters('cylinder', arguments); - if (typeof radius === 'undefined') { - radius = 50; + _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); + } } - if (typeof height === 'undefined') { - height = radius; + }; + /** + * 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 detailX === 'undefined') { - detailX = 24; + if (typeof numDivs === 'undefined') { + // ensure at least 2 divisions + numDivs = Math.round(size / 30) < 4 ? 4 : Math.round(size / 30); } - if (typeof detailY === 'undefined') { - detailY = 1; + if (typeof xOff === 'undefined') { + xOff = 0; } - if (typeof topCap === 'undefined') { - topCap = true; + if (typeof yOff === 'undefined') { + yOff = 0; } - if (typeof bottomCap === 'undefined') { - bottomCap = true; + if (typeof zOff === 'undefined') { + zOff = 0; } - 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'); + 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._renderer.createBuffers(gId, cylinderGeom); + 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; } - this._renderer.drawBuffersScaled(gId, radius, height, radius); - return this; + 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': 286, + '../core/main': 298, + 'core-js/modules/es.array.for-each': 175, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.splice': 185, + 'core-js/modules/es.math.hypot': 188, + 'core-js/modules/es.math.sign': 190, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.for-each': 255, + 'core-js/modules/web.dom-collections.iterator': 256 + } + ], + 344: [ + function (_dereq_, module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module 3D + * @submodule Lights + * @for p5 + * @requires core + */ /** - * Draw a cone with given radius and height + * Creates an ambient light with the given color. * - * 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 + * Ambient light does not come from a specific direction. + * Objects are evenly lit from all sides. Ambient lights are + * almost always used in combination with other types of lights. + * + * Note: lights need to be called (whether directly or indirectly) + * within draw() to remain persistent in a looping program. + * Placing them in setup() will cause them to only have an effect + * the first time through the loop. + * + * @method ambientLight + * @param {Number} v1 red or hue value relative to + * the current color range + * @param {Number} v2 green or saturation value + * relative to the current color range + * @param {Number} v3 blue or brightness value + * relative to the current color range + * @param {Number} [alpha] alpha value relative to current + * color range (default is 0-255) * @chainable + * * @example *
      * - * // draw a spinning cone - * // with radius 40 and height 70 * function setup() { * createCanvas(100, 100, WEBGL); - * describe('a rotating white cone'); + * noStroke(); + * describe('sphere with coral color under black light'); * } - * * function draw() { - * background(200); - * rotateX(frameCount * 0.01); - * rotateZ(frameCount * 0.01); - * cone(40, 70); + * background(100); + * ambientLight(0); // black light (no light) + * ambientMaterial(255, 127, 80); // coral material + * sphere(40); * } * *
      + * @alt + * sphere with coral color under black light * * @example *
      * - * // slide to see how detailx works - * let detailX; * function setup() { * createCanvas(100, 100, WEBGL); - * detailX = createSlider(3, 16, 3); - * detailX.position(10, height + 5); - * detailX.style('width', '80px'); - * describe( - * 'a rotating white cone with limited X detail, with a slider that adjusts detailX' - * ); + * noStroke(); + * describe('sphere with coral color under white light'); * } - * * function draw() { - * background(205, 102, 94); - * rotateY(millis() / 1000); - * cone(30, 65, detailX.value(), 16); + * background(100); + * ambientLight(255); // white light + * ambientMaterial(255, 127, 80); // coral material + * sphere(40); * } * *
      + * @alt + * sphere with coral color under white light * * @example *
      * - * // slide to see how detailY works - * let detailY; * function setup() { - * createCanvas(100, 100, WEBGL); - * detailY = createSlider(3, 16, 3); - * detailY.position(10, height + 5); - * detailY.style('width', '80px'); - * describe( - * 'a rotating white cone with limited Y detail, with a slider that adjusts detailY' - * ); + * createCanvas(100,100,WEBGL); + * camera(0,-100,300); * } - * * function draw() { - * background(205, 102, 94); - * rotateY(millis() / 1000); - * cone(30, 65, 16, detailY.value()); + * background(230); + * ambientMaterial(237,34,93); //Pink Material + * ambientLight(mouseY); + * //As you move the mouse up to down it changes from no ambient light to full ambient light. + * rotateY(millis()/2000); + * box(100); * } * *
      + * @alt + * pink ambient material cube under the ambient light */ - _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); + /** + * @method ambientLight + * @param {Number} gray number specifying value between + * white and black + * @param {Number} [alpha] + * @chainable + */ + /** + * @method ambientLight + * @param {String} value a color string + * @chainable + */ + /** + * @method ambientLight + * @param {Number[]} values an array containing the red,green,blue & + * and alpha components of the color + * @chainable + */ + /** + * @method ambientLight + * @param {p5.Color} color color as a p5.Color + * @chainable + */ + + _main.default.prototype.ambientLight = function (v1, v2, v3, a) { + this._assert3d('ambientLight'); + _main.default._validateParameters('ambientLight', arguments); + var color = this.color.apply(this, arguments); + this._renderer.ambientLightColors.push(color._array[0], color._array[1], color._array[2]); + this._renderer._enableLighting = true; return this; }; /** - * Draw an ellipsoid with given radius + * Sets the color of the specular highlight of a non-ambient light + * (i.e. all lights except ambientLight()). * - * DetailX and detailY determine the number of subdivisions in the x-dimension and - * the y-dimension of a cone. More subdivisions make the ellipsoid appear to be smoother. - * Avoid detail number above 150, it may crash the browser. - * @method ellipsoid - * @param {Number} [radiusx] x-radius of ellipsoid - * @param {Number} [radiusy] y-radius of ellipsoid - * @param {Number} [radiusz] z-radius of ellipsoid - * @param {Integer} [detailX] number of segments, - * the more segments the smoother geometry - * default is 24. Avoid detail number above - * 150, it may crash the browser. - * @param {Integer} [detailY] number of segments, - * the more segments the smoother geometry - * default is 16. Avoid detail number above - * 150, it may crash the browser. - * @chainable - * @example - *
      - * - * // draw an ellipsoid - * // with radius 30, 40 and 40. - * function setup() { - * createCanvas(100, 100, WEBGL); - * describe('a white 3d ellipsoid'); - * } + * specularColor() affects only the lights which are created after + * it in the code. * - * function draw() { - * background(205, 105, 94); - * ellipsoid(30, 40, 40); - * } - * - *
      + * This function is used in combination with + * specularMaterial(). + * If a geometry does not use specularMaterial(), this function + * will have no effect. + * + * The default color is white (255, 255, 255), which is used if + * specularColor() is not explicitly called. + * + * Note: specularColor is equivalent to the Processing function + * lightSpecular. * + * @method specularColor + * @param {Number} v1 red or hue value relative to + * the current color range + * @param {Number} v2 green or saturation value + * relative to the current color range + * @param {Number} v3 blue or brightness value + * relative to the current color range + * @chainable * @example *
      * - * // slide to see how detailX works - * let detailX; + * let setRedSpecularColor = true; + * * function setup() { * createCanvas(100, 100, WEBGL); - * detailX = createSlider(2, 24, 12); - * detailX.position(10, height + 5); - * detailX.style('width', '80px'); + * noStroke(); * describe( - * 'a rotating white ellipsoid with limited X detail, with a slider that adjusts detailX' + * 'Sphere with specular highlight. Clicking the mouse toggles the specular highlight color between red and the default white.' * ); * } * * function draw() { - * background(205, 105, 94); - * rotateY(millis() / 1000); - * ellipsoid(30, 40, 40, detailX.value(), 8); + * background(0); + * + * ambientLight(60); + * + * // add a point light to showcase specular color + * // -- use mouse location to position the light + * let lightPosX = mouseX - width / 2; + * let lightPosY = mouseY - height / 2; + * // -- set the light's specular color + * if (setRedSpecularColor) { + * specularColor(255, 0, 0); // red specular highlight + * } + * // -- create the light + * pointLight(200, 200, 200, lightPosX, lightPosY, 50); // white light + * + * // use specular material with high shininess + * specularMaterial(150); + * shininess(50); + * + * sphere(30, 64, 64); + * } + * + * function mouseClicked() { + * setRedSpecularColor = !setRedSpecularColor; * } * *
      * + * @alt + * Sphere with specular highlight. Clicking the mouse toggles the + * specular highlight color between red and the default white. + */ + /** + * @method specularColor + * @param {Number} gray number specifying value between + * white and black + * @chainable + */ + /** + * @method specularColor + * @param {String} value color as a CSS string + * @chainable + */ + /** + * @method specularColor + * @param {Number[]} values color as an array containing the + * red, green, and blue components + * @chainable + */ + /** + * @method specularColor + * @param {p5.Color} color color as a p5.Color + * @chainable + */ + _main.default.prototype.specularColor = function (v1, v2, v3) { + this._assert3d('specularColor'); + _main.default._validateParameters('specularColor', arguments); + var color = this.color.apply(this, arguments); + this._renderer.specularColors = [ + color._array[0], + color._array[1], + color._array[2] + ]; + return this; + }; + /** + * Creates a directional light with the given color and direction. + * + * Directional light comes from one direction. + * The direction is specified as numbers inclusively between -1 and 1. + * For example, setting the direction as (0, -1, 0) will cause the + * geometry to be lit from below (since the light will be facing + * directly upwards). Similarly, setting the direction as (1, 0, 0) + * will cause the geometry to be lit from the left (since the light + * will be facing directly rightwards). + * + * Directional lights do not have a specific point of origin, and + * therefore cannot be positioned closer or farther away from a geometry. + * + * A maximum of **5** directional lights can be active at once. + * + * Note: lights need to be called (whether directly or indirectly) + * within draw() to remain persistent in a looping program. + * Placing them in setup() will cause them to only have an effect + * the first time through the loop. + * + * @method directionalLight + * @param {Number} v1 red or hue value relative to the current + * color range + * @param {Number} v2 green or saturation value relative to the + * current color range + * @param {Number} v3 blue or brightness value relative to the + * current color range + * @param {Number} x x component of direction (inclusive range of -1 to 1) + * @param {Number} y y component of direction (inclusive range of -1 to 1) + * @param {Number} z z component of direction (inclusive range of -1 to 1) + * @chainable * @example *
      * - * // slide to see how detailY works - * let detailY; * function setup() { * createCanvas(100, 100, WEBGL); - * detailY = createSlider(2, 24, 6); - * detailY.position(10, height + 5); - * detailY.style('width', '80px'); * describe( - * 'a rotating white ellipsoid with limited Y detail, with a slider that adjusts detailY' + * 'scene with sphere and directional light. The direction of the light is controlled with the mouse position.' * ); * } - * * function draw() { - * background(205, 105, 9); - * rotateY(millis() / 1000); - * ellipsoid(30, 40, 40, 12, detailY.value()); + * background(0); + * //move your mouse to change light direction + * let dirX = (mouseX / width - 0.5) * 2; + * let dirY = (mouseY / height - 0.5) * 2; + * directionalLight(250, 250, 250, -dirX, -dirY, -1); + * noStroke(); + * sphere(40); * } * *
      + * + * @alt + * scene with sphere and directional light. The direction of + * the light is controlled with the mouse position. */ - _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); + /** + * @method directionalLight + * @param {Number} v1 + * @param {Number} v2 + * @param {Number} v3 + * @param {p5.Vector} direction direction of light as a + * p5.Vector + * @chainable + */ + /** + * @method directionalLight + * @param {p5.Color|Number[]|String} color color as a p5.Color, + * as an array, or as a CSS string + * @param {Number} x + * @param {Number} y + * @param {Number} z + * @chainable + */ + /** + * @method directionalLight + * @param {p5.Color|Number[]|String} color + * @param {p5.Vector} direction + * @chainable + */ + _main.default.prototype.directionalLight = function (v1, v2, v3, x, y, z) { + this._assert3d('directionalLight'); + _main.default._validateParameters('directionalLight', arguments); + //@TODO: check parameters number + var color; + if (v1 instanceof _main.default.Color) { + color = v1; + } else { + color = this.color(v1, v2, v3); } - this._renderer.drawBuffersScaled(gId, radiusX, radiusY, radiusZ); + 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; }; /** - * Draw a torus with given radius and tube radius + * Creates a point light with the given color and position. * - * 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 + * A point light emits light from a single point in all directions. + * Because the light is emitted from a specific point (position), + * it has a different effect when it is positioned farther vs. nearer + * an object. + * + * A maximum of **5** point lights can be active at once. + * + * Note: lights need to be called (whether directly or indirectly) + * within draw() to remain persistent in a looping program. + * Placing them in setup() will cause them to only have an effect + * the first time through the loop. + * + * @method pointLight + * @param {Number} v1 red or hue value relative to the current + * color range + * @param {Number} v2 green or saturation value relative to the + * current color range + * @param {Number} v3 blue or brightness value relative to the + * current color range + * @param {Number} x x component of position + * @param {Number} y y component of position + * @param {Number} z z component of position * @chainable * @example *
      * - * // draw a spinning torus - * // with ring radius 30 and tube radius 15 * function setup() { * createCanvas(100, 100, WEBGL); - * describe('a rotating white torus'); + * describe( + * 'scene with sphere and point light. The position of the light is controlled with the mouse position.' + * ); * } - * * function draw() { - * background(205, 102, 94); - * rotateX(frameCount * 0.01); - * rotateY(frameCount * 0.01); - * torus(30, 15); + * background(0); + * // move your mouse to change light position + * let locX = mouseX - width / 2; + * let locY = mouseY - height / 2; + * // to set the light position, + * // think of the world's coordinate as: + * // -width/2,-height/2 ----------- width/2,-height/2 + * // | | + * // | 0,0 | + * // | | + * // -width/2,height/2 ----------- width/2,height/2 + * pointLight(250, 250, 250, locX, locY, 50); + * noStroke(); + * sphere(40); * } * *
      * + * @alt + * scene with sphere and point light. The position of + * the light is controlled with the mouse position. + */ + /** + * @method pointLight + * @param {Number} v1 + * @param {Number} v2 + * @param {Number} v3 + * @param {p5.Vector} position of light as a p5.Vector + * @chainable + */ + /** + * @method pointLight + * @param {p5.Color|Number[]|String} color color as a p5.Color, + * as an array, or as a CSS string + * @param {Number} x + * @param {Number} y + * @param {Number} z + * @chainable + */ + /** + * @method pointLight + * @param {p5.Color|Number[]|String} color + * @param {p5.Vector} position + * @chainable + */ + _main.default.prototype.pointLight = function (v1, v2, v3, x, y, z) { + this._assert3d('pointLight'); + _main.default._validateParameters('pointLight', arguments); + //@TODO: check parameters number + var color; + if (v1 instanceof _main.default.Color) { + color = v1; + } else { + color = this.color(v1, v2, v3); + } + var _x, + _y, + _z; + var v = arguments[arguments.length - 1]; + if (typeof v === 'number') { + _x = arguments[arguments.length - 3]; + _y = arguments[arguments.length - 2]; + _z = arguments[arguments.length - 1]; + } else { + _x = v.x; + _y = v.y; + _z = v.z; + } + this._renderer.pointLightPositions.push(_x, _y, _z); + this._renderer.pointLightDiffuseColors.push(color._array[0], color._array[1], color._array[2]); + Array.prototype.push.apply(this._renderer.pointLightSpecularColors, this._renderer.specularColors); + this._renderer._enableLighting = true; + return this; + }; + /** + * Creates an image light with the given image. + * + * The image light simulates light from all the directions. + * This is done by using the image as a texture for an infinitely + * large sphere light. This sphere contains + * or encapsulates the whole scene/drawing. + * It will have different effect for varying shininess of the + * object in the drawing. + * Under the hood it is mainly doing 2 types of calculations, + * the first one is creating an irradiance map the + * environment map of the input image. + * The second one is managing reflections based on the shininess + * or roughness of the material used in the scene. + * + * Note: The image's diffuse light will be affected by fill() + * and the specular reflections will be affected by specularMaterial() + * and shininess(). + * + * @method imageLight + * @param {p5.image} img image for the background * @example - *
      + *
      * - * // slide to see how detailX works - * let detailX; + * let img; + * function preload() { + * img = loadImage('assets/outdoor_image.jpg'); + * } * function setup() { * createCanvas(100, 100, WEBGL); - * detailX = createSlider(3, 24, 3); - * detailX.position(10, height + 5); - * detailX.style('width', '80px'); - * describe( - * 'a rotating white torus with limited X detail, with a slider that adjusts detailX' - * ); * } - * * function draw() { - * background(205, 102, 94); - * rotateY(millis() / 1000); - * torus(30, 15, detailX.value(), 12); + * background(220); + * imageMode(CENTER); + * push(); + * translate(0, 0, -200); + * scale(2); + * image(img, 0, 0, width, height); + * pop(); + * ambientLight(50); + * imageLight(img); + * specularMaterial(20); + * noStroke(); + * scale(2); + * rotateX(frameCount * 0.005); + * rotateY(frameCount * 0.005); + * box(25); * } * *
      - * + * @alt + * image light example * @example - *
      + *
      * - * // slide to see how detailY works - * let detailY; + * let img; + * let slider; + * function preload() { + * img = loadImage('assets/outdoor_spheremap.jpg'); + * } * function setup() { * createCanvas(100, 100, WEBGL); - * detailY = createSlider(3, 16, 3); - * detailY.position(10, height + 5); - * detailY.style('width', '80px'); - * describe( - * 'a rotating white torus with limited Y detail, with a slider that adjusts detailY' - * ); + * slider = createSlider(0, 400, 100, 1); + * slider.position(0, height); * } - * * function draw() { - * background(205, 102, 94); - * rotateY(millis() / 1000); - * torus(30, 15, 16, detailY.value()); + * background(220); + * imageMode(CENTER); + * push(); + * translate(0, 0, -200); + * scale(2); + * image(img, 0, 0, width, height); + * pop(); + * ambientLight(50); + * imageLight(img); + * specularMaterial(20); + * shininess(slider.value()); + * noStroke(); + * scale(2); + * sphere(15); * } * *
      + * @alt + * light with slider having a slider for varying roughness */ - _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 - ///////////////////////// + _main.default.prototype.imageLight = function (img) { + // activeImageLight property is checked by _setFillUniforms + // for sending uniforms to the fillshader + this._renderer.activeImageLight = img; + this._renderer._enableLighting = true; + }; /** - * 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 + * Places an ambient and directional light in the scene. + * The lights are set to ambientLight(128, 128, 128) and + * directionalLight(128, 128, 128, 0, 0, -1). + * + * Note: lights need to be called (whether directly or indirectly) + * within draw() to remain persistent in a looping program. + * Placing them in setup() will cause them to only have an effect + * the first time through the loop. + * + * @method lights * @chainable * @example *
      * * function setup() { * createCanvas(100, 100, WEBGL); + * describe('the light is partially ambient and partially directional'); * } - * * 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); + * background(0); + * lights(); + * rotateX(millis() / 1000); + * rotateY(millis() / 1000); + * rotateZ(millis() / 1000); + * box(); * } * *
      + * + * @alt + * the light is partially ambient and partially directional */ - _main.default.RendererGL.prototype.point = function (x, y, z) { - if (typeof z === 'undefined') { - z = 0; - } - var _vertex = [ - ]; - _vertex.push(new _main.default.Vector(x, y, z)); - this._drawPoints(_vertex, this.immediateMode.buffers.point); - return this; - }; - _main.default.RendererGL.prototype.triangle = function (args) { - var x1 = args[0], - y1 = args[1]; - var x2 = args[2], - y2 = args[3]; - var x3 = args[4], - y3 = args[5]; - var gId = 'tri'; - if (!this.geometryInHash(gId)) { - var _triangle = function _triangle() { - var vertices = [ - ]; - vertices.push(new _main.default.Vector(0, 0, 0)); - vertices.push(new _main.default.Vector(1, 0, 0)); - vertices.push(new _main.default.Vector(0, 1, 0)); - this.strokeIndices = [ - [0, - 1], - [ - 1, - 2 - ], - [ - 2, - 0 - ] - ]; - this.vertices = vertices; - this.faces = [ - [0, - 1, - 2] - ]; - this.uvs = [ - 0, - 0, - 1, - 0, - 1, - 1 - ]; - }; - var triGeom = new _main.default.Geometry(1, 1, _triangle); - triGeom._makeTriangleEdges()._edgesToVertices(); - triGeom.computeNormals(); - this.createBuffers(gId, triGeom); - } // only one triangle is cached, one point is at the origin, and the - // two adjacent sides are tne unit vectors along the X & Y axes. - // - // this matrix multiplication transforms those two unit vectors - // onto the required vector prior to rendering, and moves the - // origin appropriately. - - var uMVMatrix = this.uMVMatrix.copy(); - try { - var mult = new _main.default.Matrix([x2 - x1, - y2 - y1, - 0, - 0, // the resulting unit X-axis - x3 - x1, - y3 - y1, - 0, - 0, // the resulting unit Y-axis - 0, - 0, - 1, - 0, // the resulting unit Z-axis (unchanged) - x1, - y1, - 0, - 1 // the resulting origin - ]).mult(this.uMVMatrix); - this.uMVMatrix = mult; - this.drawBuffers(gId); - } finally { - this.uMVMatrix = uMVMatrix; - } - return this; - }; - _main.default.RendererGL.prototype.ellipse = function (args) { - this.arc(args[0], args[1], args[2], args[3], 0, constants.TWO_PI, constants.OPEN, args[4]); - }; - _main.default.RendererGL.prototype.arc = function (args) { - var x = arguments[0]; - var y = arguments[1]; - var width = arguments[2]; - var height = arguments[3]; - var start = arguments[4]; - var stop = arguments[5]; - var mode = arguments[6]; - var detail = arguments[7] || 25; - var shape; - var gId; // check if it is an ellipse or an arc - if (Math.abs(stop - start) >= constants.TWO_PI) { - shape = 'ellipse'; - gId = ''.concat(shape, '|').concat(detail, '|'); - } else { - shape = 'arc'; - gId = ''.concat(shape, '|').concat(start, '|').concat(stop, '|').concat(mode, '|').concat(detail, '|'); - } - if (!this.geometryInHash(gId)) { - var _arc = function _arc() { - this.strokeIndices = [ - ]; // if the start and stop angles are not the same, push vertices to the array - if (start.toFixed(10) !== stop.toFixed(10)) { - // if the mode specified is PIE or null, push the mid point of the arc in vertices - if (mode === constants.PIE || typeof mode === 'undefined') { - this.vertices.push(new _main.default.Vector(0.5, 0.5, 0)); - this.uvs.push([0.5, - 0.5]); - } // vertices for the perimeter of the circle - - for (var i = 0; i <= detail; i++) { - var u = i / detail; - var theta = (stop - start) * u + start; - var _x = 0.5 + Math.cos(theta) / 2; - var _y = 0.5 + Math.sin(theta) / 2; - this.vertices.push(new _main.default.Vector(_x, _y, 0)); - this.uvs.push([_x, - _y]); - if (i < detail - 1) { - this.faces.push([0, - i + 1, - i + 2]); - this.strokeIndices.push([i + 1, - i + 2]); - } - } // check the mode specified in order to push vertices and faces, different for each mode - - switch (mode) { - case constants.PIE: - this.faces.push([0, - this.vertices.length - 2, - this.vertices.length - 1]); - this.strokeIndices.push([0, - 1]); - this.strokeIndices.push([this.vertices.length - 2, - this.vertices.length - 1]); - this.strokeIndices.push([0, - this.vertices.length - 1]); - break; - case constants.CHORD: - this.strokeIndices.push([0, - 1]); - this.strokeIndices.push([0, - this.vertices.length - 1]); - break; - case constants.OPEN: - this.strokeIndices.push([0, - 1]); - break; - default: - this.faces.push([0, - this.vertices.length - 2, - this.vertices.length - 1]); - this.strokeIndices.push([this.vertices.length - 2, - this.vertices.length - 1]); - } - } - }; - var arcGeom = new _main.default.Geometry(detail, 1, _arc); - arcGeom.computeNormals(); - if (detail <= 50) { - arcGeom._makeTriangleEdges()._edgesToVertices(arcGeom); - } else if (this._doStroke) { - console.log('Cannot apply a stroke to an '.concat(shape, ' with more than 50 detail')); - } - this.createBuffers(gId, arcGeom); - } - var uMVMatrix = this.uMVMatrix.copy(); - try { - this.uMVMatrix.translate([x, - y, - 0]); - this.uMVMatrix.scale(width, height, 1); - this.drawBuffers(gId); - } finally { - this.uMVMatrix = uMVMatrix; - } - return this; - }; - _main.default.RendererGL.prototype.rect = function (args) { - var x = args[0]; - var y = args[1]; - var width = args[2]; - var height = args[3]; - if (typeof args[4] === 'undefined') { - // Use the retained mode for drawing rectangle, - // if args for rounding rectangle is not provided by user. - var perPixelLighting = this._pInst._glAttributes.perPixelLighting; - var detailX = args[4] || (perPixelLighting ? 1 : 24); - var detailY = args[5] || (perPixelLighting ? 1 : 16); - var gId = 'rect|'.concat(detailX, '|').concat(detailY); - if (!this.geometryInHash(gId)) { - var _rect = function _rect() { - for (var i = 0; i <= this.detailY; i++) { - var v = i / this.detailY; - for (var j = 0; j <= this.detailX; j++) { - var u = j / this.detailX; - var p = new _main.default.Vector(u, v, 0); - this.vertices.push(p); - this.uvs.push(u, v); - } - } // using stroke indices to avoid stroke over face(s) of rectangle - - if (detailX > 0 && detailY > 0) { - this.strokeIndices = [ - [0, - detailX], - [ - detailX, - (detailX + 1) * (detailY + 1) - 1 - ], - [ - (detailX + 1) * (detailY + 1) - 1, - (detailX + 1) * detailY - ], - [ - (detailX + 1) * detailY, - 0 - ] - ]; - } - }; - var rectGeom = new _main.default.Geometry(detailX, detailY, _rect); - rectGeom.computeFaces().computeNormals()._makeTriangleEdges()._edgesToVertices(); - this.createBuffers(gId, rectGeom); - } // only a single rectangle (of a given detail) is cached: a square with - // opposite corners at (0,0) & (1,1). - // - // before rendering, this square is scaled & moved to the required location. - - var uMVMatrix = this.uMVMatrix.copy(); - try { - this.uMVMatrix.translate([x, - y, - 0]); - this.uMVMatrix.scale(width, height, 1); - this.drawBuffers(gId); - } finally { - this.uMVMatrix = uMVMatrix; - } - } else { - // Use Immediate mode to round the rectangle corner, - // if args for rounding corners is provided by user - var tl = args[4]; - var tr = typeof args[5] === 'undefined' ? tl : args[5]; - var br = typeof args[6] === 'undefined' ? tr : args[6]; - var bl = typeof args[7] === 'undefined' ? br : args[7]; - var a = x; - var b = y; - var c = width; - var d = height; - c += a; - d += b; - if (a > c) { - var temp = a; - a = c; - c = temp; - } - if (b > d) { - var _temp = b; - b = d; - d = _temp; - } - var maxRounding = Math.min((c - a) / 2, (d - b) / 2); - if (tl > maxRounding) tl = maxRounding; - if (tr > maxRounding) tr = maxRounding; - if (br > maxRounding) br = maxRounding; - if (bl > maxRounding) bl = maxRounding; - var x1 = a; - var y1 = b; - var x2 = c; - var y2 = d; - this.beginShape(); - if (tr !== 0) { - this.vertex(x2 - tr, y1); - this.quadraticVertex(x2, y1, x2, y1 + tr); - } else { - this.vertex(x2, y1); - } - if (br !== 0) { - this.vertex(x2, y2 - br); - this.quadraticVertex(x2, y2, x2 - br, y2); - } else { - this.vertex(x2, y2); - } - if (bl !== 0) { - this.vertex(x1 + bl, y2); - this.quadraticVertex(x1, y2, x1, y2 - bl); - } else { - this.vertex(x1, y2); - } - if (tl !== 0) { - this.vertex(x1, y1 + tl); - this.quadraticVertex(x1, y1, x1 + tl, y1); - } else { - this.vertex(x1, y1); - } - this.immediateMode.geometry.uvs.length = 0; - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - try { - for (var _iterator = this.immediateMode.geometry.vertices[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var vert = _step.value; - var u = (vert.x - x1) / width; - var v = (vert.y - y1) / height; - this.immediateMode.geometry.uvs.push(u, v); - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return != null) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - this.endShape(constants.CLOSE); - } - return this; - }; - /* eslint-disable max-len */ - _main.default.RendererGL.prototype.quad = function (x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4, detailX, detailY) { - /* eslint-enable max-len */ - if (typeof detailX === 'undefined') { - detailX = 2; - } - if (typeof detailY === 'undefined') { - detailY = 2; - } - var gId = 'quad|'.concat(x1, '|').concat(y1, '|').concat(z1, '|').concat(x2, '|').concat(y2, '|').concat(z2, '|').concat(x3, '|').concat(y3, '|').concat(z3, '|').concat(x4, '|').concat(y4, '|').concat(z4, '|').concat(detailX, '|').concat(detailY); - if (!this.geometryInHash(gId)) { - var quadGeom = new _main.default.Geometry(detailX, detailY, function () { - //algorithm adapted from c++ to js - //https://stackoverflow.com/questions/16989181/whats-the-correct-way-to-draw-a-distorted-plane-in-opengl/16993202#16993202 - var xRes = 1 / (this.detailX - 1); - var yRes = 1 / (this.detailY - 1); - for (var y = 0; y < this.detailY; y++) { - for (var x = 0; x < this.detailX; x++) { - var pctx = x * xRes; - var pcty = y * yRes; - var linePt0x = (1 - pcty) * x1 + pcty * x4; - var linePt0y = (1 - pcty) * y1 + pcty * y4; - var linePt0z = (1 - pcty) * z1 + pcty * z4; - var linePt1x = (1 - pcty) * x2 + pcty * x3; - var linePt1y = (1 - pcty) * y2 + pcty * y3; - var linePt1z = (1 - pcty) * z2 + pcty * z3; - var ptx = (1 - pctx) * linePt0x + pctx * linePt1x; - var pty = (1 - pctx) * linePt0y + pctx * linePt1y; - var ptz = (1 - pctx) * linePt0z + pctx * linePt1z; - this.vertices.push(new _main.default.Vector(ptx, pty, ptz)); - this.uvs.push([pctx, - pcty]); - } - } - }); - quadGeom.faces = [ - ]; - for (var y = 0; y < detailY - 1; y++) { - for (var x = 0; x < detailX - 1; x++) { - var pt0 = x + y * detailX; - var pt1 = x + 1 + y * detailX; - var pt2 = x + 1 + (y + 1) * detailX; - var pt3 = x + (y + 1) * detailX; - quadGeom.faces.push([pt0, - pt1, - pt2]); - quadGeom.faces.push([pt0, - pt2, - pt3]); - } - } - quadGeom.computeNormals()._makeTriangleEdges()._edgesToVertices(); - this.createBuffers(gId, quadGeom); - } - this.drawBuffers(gId); - return this; - }; //this implementation of bezier curve - //is based on Bernstein polynomial - // pretier-ignore - _main.default.RendererGL.prototype.bezier = function (x1, y1, z1, // x2 - x2, // y2 - y2, // x3 - z2, // y3 - x3, // x4 - y3, // y4 - z3, x4, y4, z4) { - if (arguments.length === 8) { - y4 = y3; - x4 = x3; - y3 = z2; - x3 = y2; - y2 = x2; - x2 = z1; - z1 = z2 = z3 = z4 = 0; - } - var bezierDetail = this._pInst._bezierDetail || 20; //value of Bezier detail - this.beginShape(); - for (var i = 0; i <= bezierDetail; i++) { - var c1 = Math.pow(1 - i / bezierDetail, 3); - var c2 = 3 * (i / bezierDetail) * Math.pow(1 - i / bezierDetail, 2); - var c3 = 3 * Math.pow(i / bezierDetail, 2) * (1 - i / bezierDetail); - var c4 = Math.pow(i / bezierDetail, 3); - this.vertex(x1 * c1 + x2 * c2 + x3 * c3 + x4 * c4, y1 * c1 + y2 * c2 + y3 * c3 + y4 * c4, z1 * c1 + z2 * c2 + z3 * c3 + z4 * c4); - } - this.endShape(); - return this; - }; // pretier-ignore - _main.default.RendererGL.prototype.curve = function (x1, y1, z1, // x2 - x2, // y2 - y2, // x3 - z2, // y3 - x3, // x4 - y3, // y4 - z3, x4, y4, z4) { - if (arguments.length === 8) { - x4 = x3; - y4 = y3; - x3 = y2; - y3 = x2; - x2 = z1; - y2 = x2; - z1 = z2 = z3 = z4 = 0; - } - var curveDetail = this._pInst._curveDetail; - this.beginShape(); - for (var i = 0; i <= curveDetail; i++) { - var c1 = Math.pow(i / curveDetail, 3) * 0.5; - var c2 = Math.pow(i / curveDetail, 2) * 0.5; - var c3 = i / curveDetail * 0.5; - var c4 = 0.5; - var vx = c1 * ( - x1 + 3 * x2 - 3 * x3 + x4) + c2 * (2 * x1 - 5 * x2 + 4 * x3 - x4) + c3 * ( - x1 + x3) + c4 * (2 * x2); - var vy = c1 * ( - y1 + 3 * y2 - 3 * y3 + y4) + c2 * (2 * y1 - 5 * y2 + 4 * y3 - y4) + c3 * ( - y1 + y3) + c4 * (2 * y2); - var vz = c1 * ( - z1 + 3 * z2 - 3 * z3 + z4) + c2 * (2 * z1 - 5 * z2 + 4 * z3 - z4) + c3 * ( - z1 + z3) + c4 * (2 * z2); - this.vertex(vx, vy, vz); - } - this.endShape(); + _main.default.prototype.lights = function () { + this._assert3d('lights'); + // Both specify gray by default. + var grayColor = this.color('rgb(128,128,128)'); + this.ambientLight(grayColor); + this.directionalLight(grayColor, 0, 0, - 1); return this; }; /** - * 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 + * Sets the falloff rate for pointLight() + * and spotLight(). + * + * lightFalloff() affects only the lights which are created after it + * in the code. + * + * The `constant`, `linear`, an `quadratic` parameters are used to calculate falloff as follows: + * + * d = distance from light position to vertex position + * + * falloff = 1 / (CONSTANT + d \* LINEAR + (d \* d) \* QUADRATIC) + * + * @method lightFalloff + * @param {Number} constant CONSTANT value for determining falloff + * @param {Number} linear LINEAR value for determining falloff + * @param {Number} quadratic QUADRATIC value for determining falloff * @chainable * @example *
      * - * //draw a line * function setup() { * createCanvas(100, 100, WEBGL); + * noStroke(); + * describe( + * 'Two spheres with different falloff values show different intensity of light' + * ); * } - * * 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); + * ortho(); + * background(0); + * + * let locX = mouseX - width / 2; + * let locY = mouseY - height / 2; + * locX /= 2; // half scale + * + * lightFalloff(1, 0, 0); + * push(); + * translate(-25, 0, 0); + * pointLight(250, 250, 250, locX - 25, locY, 50); + * sphere(20); + * pop(); + * + * lightFalloff(0.97, 0.03, 0); + * push(); + * translate(25, 0, 0); + * pointLight(250, 250, 250, locX + 25, locY, 50); + * sphere(20); + * pop(); * } * *
      + * + * @alt + * Two spheres with different falloff values show different intensity of light */ - _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(); + _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.'); } - return this; - }; - _main.default.RendererGL.prototype.bezierVertex = function () { - if (this.immediateMode._bezierVertex.length === 0) { - throw Error('vertex() must be used once before calling bezierVertex()'); - } else { - var w_x = [ - ]; - var w_y = [ - ]; - var w_z = [ - ]; - var t, - _x, - _y, - _z, - i, - k, - m; // variable i for bezierPoints, k for components, and m for anchor points. - var argLength = arguments.length; - t = 0; - if (this._lookUpTableBezier.length === 0 || this._lutBezierDetail !== this._pInst._curveDetail) { - this._lookUpTableBezier = [ - ]; - this._lutBezierDetail = this._pInst._curveDetail; - var step = 1 / this._lutBezierDetail; - var start = 0; - var end = 1; - var j = 0; - while (start < 1) { - t = parseFloat(start.toFixed(6)); - this._lookUpTableBezier[j] = this._bezierCoefficients(t); - if (end.toFixed(6) === step.toFixed(6)) { - t = parseFloat(end.toFixed(6)) + parseFloat(start.toFixed(6)); - ++j; - this._lookUpTableBezier[j] = this._bezierCoefficients(t); - break; - } - start += step; - end -= step; - ++j; + if (linearAttenuation < 0) { + linearAttenuation = 0; + console.warn('Value of linear argument in lightFalloff() should be never be negative. Set to 0.'); + } + if (quadraticAttenuation < 0) { + quadraticAttenuation = 0; + console.warn('Value of quadratic argument in lightFalloff() should be never be negative. Set to 0.'); + } + if (constantAttenuation === 0 && linearAttenuation === 0 && quadraticAttenuation === 0) { + constantAttenuation = 1; + console.warn('Either one of the three arguments in lightFalloff() should be greater than zero. Set constant argument to 1.'); + } + this._renderer.constantAttenuation = constantAttenuation; + this._renderer.linearAttenuation = linearAttenuation; + this._renderer.quadraticAttenuation = quadraticAttenuation; + return this; + }; + /** + * Creates a spot light with the given color, position, + * light direction, angle, and concentration. + * + * Like a pointLight(), a spotLight() + * emits light from a specific point (position). It has a different effect + * when it is positioned farther vs. nearer an object. + * + * However, unlike a pointLight(), the light is emitted in **one direction** + * along a conical shape. The shape of the cone can be controlled using + * the `angle` and `concentration` parameters. + * + * The `angle` parameter is used to + * determine the radius of the cone. And the `concentration` + * parameter is used to focus the light towards the center of + * the cone. Both parameters are optional, however if you want + * to specify `concentration`, you must also specify `angle`. + * The minimum concentration value is 1. + * + * A maximum of **5** spot lights can be active at once. + * + * Note: lights need to be called (whether directly or indirectly) + * within draw() to remain persistent in a looping program. + * Placing them in setup() will cause them to only have an effect + * the first time through the loop. + * + * @method spotLight + * @param {Number} v1 red or hue value relative to the current color range + * @param {Number} v2 green or saturation value relative to the current color range + * @param {Number} v3 blue or brightness value relative to the current color range + * @param {Number} x x component of position + * @param {Number} y y component of position + * @param {Number} z z component of position + * @param {Number} rx x component of light direction (inclusive range of -1 to 1) + * @param {Number} ry y component of light direction (inclusive range of -1 to 1) + * @param {Number} rz z component of light direction (inclusive range of -1 to 1) + * @param {Number} [angle] angle of cone. Defaults to PI/3 + * @param {Number} [concentration] concentration of cone. Defaults to 100 + * @chainable + * + * @example + *
      + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * describe( + * 'scene with sphere and spot light. The position of the light is controlled with the mouse position.' + * ); + * } + * function draw() { + * background(0); + * // move your mouse to change light position + * let locX = mouseX - width / 2; + * let locY = mouseY - height / 2; + * // to set the light position, + * // think of the world's coordinate as: + * // -width/2,-height/2 ----------- width/2,-height/2 + * // | | + * // | 0,0 | + * // | | + * // -width/2,height/2 ----------- width/2,height/2 + * ambientLight(50); + * spotLight(0, 250, 0, locX, locY, 100, 0, 0, -1, Math.PI / 16); + * noStroke(); + * sphere(40); + * } + * + *
      + * + * @alt + * scene with sphere and spot light. The position of + * the light is controlled with the mouse position. + */ + /** + * @method spotLight + * @param {p5.Color|Number[]|String} color color as a p5.Color, + * as an array, or as a CSS string + * @param {p5.Vector} position position of light as a p5.Vector + * @param {p5.Vector} direction direction of light as a p5.Vector + * @param {Number} [angle] + * @param {Number} [concentration] + */ + /** + * @method spotLight + * @param {Number} v1 + * @param {Number} v2 + * @param {Number} v3 + * @param {p5.Vector} position + * @param {p5.Vector} direction + * @param {Number} [angle] + * @param {Number} [concentration] + */ + /** + * @method spotLight + * @param {p5.Color|Number[]|String} color + * @param {Number} x + * @param {Number} y + * @param {Number} z + * @param {p5.Vector} direction + * @param {Number} [angle] + * @param {Number} [concentration] + */ + /** + * @method spotLight + * @param {p5.Color|Number[]|String} color + * @param {p5.Vector} position + * @param {Number} rx + * @param {Number} ry + * @param {Number} rz + * @param {Number} [angle] + * @param {Number} [concentration] + */ + /** + * @method spotLight + * @param {Number} v1 + * @param {Number} v2 + * @param {Number} v3 + * @param {Number} x + * @param {Number} y + * @param {Number} z + * @param {p5.Vector} direction + * @param {Number} [angle] + * @param {Number} [concentration] + */ + /** + * @method spotLight + * @param {Number} v1 + * @param {Number} v2 + * @param {Number} v3 + * @param {p5.Vector} position + * @param {Number} rx + * @param {Number} ry + * @param {Number} rz + * @param {Number} [angle] + * @param {Number} [concentration] + */ + /** + * @method spotLight + * @param {p5.Color|Number[]|String} color + * @param {Number} x + * @param {Number} y + * @param {Number} z + * @param {Number} rx + * @param {Number} ry + * @param {Number} rz + * @param {Number} [angle] + * @param {Number} [concentration] + */ + _main.default.prototype.spotLight = function (v1, v2, v3, x, y, z, nx, ny, nz, angle, concentration) { + this._assert3d('spotLight'); + _main.default._validateParameters('spotLight', arguments); + var color, + position, + direction; + var length = arguments.length; + switch (length) { + case 11: + case 10: + color = this.color(v1, v2, v3); + position = new _main.default.Vector(x, y, z); + direction = new _main.default.Vector(nx, ny, nz); + break; + case 9: + if (v1 instanceof _main.default.Color) { + color = v1; + position = new _main.default.Vector(v2, v3, x); + direction = new _main.default.Vector(y, z, nx); + angle = ny; + concentration = nz; + } else if (x instanceof _main.default.Vector) { + color = this.color(v1, v2, v3); + position = x; + direction = new _main.default.Vector(y, z, nx); + angle = ny; + concentration = nz; + } else if (nx instanceof _main.default.Vector) { + color = this.color(v1, v2, v3); + position = new _main.default.Vector(x, y, z); + direction = nx; + angle = ny; + concentration = nz; + } else { + color = this.color(v1, v2, v3); + position = new _main.default.Vector(x, y, z); + direction = new _main.default.Vector(nx, ny, nz); } - } - var LUTLength = this._lookUpTableBezier.length; // fillColors[0]: start point color - // fillColors[1],[2]: control point color - // fillColors[3]: end point color - var fillColors = [ - ]; - for (m = 0; m < 4; m++) { - fillColors.push([]); - } - fillColors[0] = this.immediateMode.geometry.vertexColors.slice( - 4); - fillColors[3] = this.curFillColor.slice(); // Do the same for strokeColor. - var strokeColors = [ - ]; - for (m = 0; m < 4; m++) { - strokeColors.push([]); - } - strokeColors[0] = this.immediateMode.geometry.vertexStrokeColors.slice( - 4); - strokeColors[3] = this.curStrokeColor.slice(); - if (argLength === 6) { - this.isBezier = true; - w_x = [ - this.immediateMode._bezierVertex[0], - arguments.length <= 0 ? undefined : arguments[0], - arguments.length <= 2 ? undefined : arguments[2], - arguments.length <= 4 ? undefined : arguments[4] - ]; - w_y = [ - this.immediateMode._bezierVertex[1], - arguments.length <= 1 ? undefined : arguments[1], - arguments.length <= 3 ? undefined : arguments[3], - arguments.length <= 5 ? undefined : arguments[5] - ]; // The ratio of the distance between the start point, the two control- - // points, and the end point determines the intermediate color. - var d0 = Math.hypot(w_x[0] - w_x[1], w_y[0] - w_y[1]); - var d1 = Math.hypot(w_x[1] - w_x[2], w_y[1] - w_y[2]); - var d2 = Math.hypot(w_x[2] - w_x[3], w_y[2] - w_y[3]); - var totalLength = d0 + d1 + d2; - d0 /= totalLength; - d2 /= totalLength; - for (k = 0; k < 4; k++) { - fillColors[1].push(fillColors[0][k] * (1 - d0) + fillColors[3][k] * d0); - fillColors[2].push(fillColors[0][k] * d2 + fillColors[3][k] * (1 - d2)); - strokeColors[1].push(strokeColors[0][k] * (1 - d0) + strokeColors[3][k] * d0); - strokeColors[2].push(strokeColors[0][k] * d2 + strokeColors[3][k] * (1 - d2)); + 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; } - for (i = 0; i < LUTLength; i++) { - // Interpolate colors using control points - this.curFillColor = [ - 0, - 0, - 0, - 0 - ]; - this.curStrokeColor = [ - 0, - 0, - 0, - 0 - ]; - _x = _y = 0; - for (m = 0; m < 4; m++) { - for (k = 0; k < 4; k++) { - this.curFillColor[k] += this._lookUpTableBezier[i][m] * fillColors[m][k]; - this.curStrokeColor[k] += this._lookUpTableBezier[i][m] * strokeColors[m][k]; - } - _x += w_x[m] * this._lookUpTableBezier[i][m]; - _y += w_y[m] * this._lookUpTableBezier[i][m]; - } - this.vertex(_x, _y); - } // so that we leave currentColor with the last value the user set it to - - this.curFillColor = fillColors[3]; - this.curStrokeColor = strokeColors[3]; - this.immediateMode._bezierVertex[0] = arguments.length <= 4 ? undefined : arguments[4]; - this.immediateMode._bezierVertex[1] = arguments.length <= 5 ? undefined : arguments[5]; - } else if (argLength === 9) { - this.isBezier = true; - w_x = [ - this.immediateMode._bezierVertex[0], - arguments.length <= 0 ? undefined : arguments[0], - arguments.length <= 3 ? undefined : arguments[3], - arguments.length <= 6 ? undefined : arguments[6] - ]; - w_y = [ - this.immediateMode._bezierVertex[1], - arguments.length <= 1 ? undefined : arguments[1], - arguments.length <= 4 ? undefined : arguments[4], - arguments.length <= 7 ? undefined : arguments[7] - ]; - w_z = [ - this.immediateMode._bezierVertex[2], - arguments.length <= 2 ? undefined : arguments[2], - arguments.length <= 5 ? undefined : arguments[5], - arguments.length <= 8 ? undefined : arguments[8] - ]; // The ratio of the distance between the start point, the two control- - // points, and the end point determines the intermediate color. - var _d = Math.hypot(w_x[0] - w_x[1], w_y[0] - w_y[1], w_z[0] - w_z[1]); - var _d2 = Math.hypot(w_x[1] - w_x[2], w_y[1] - w_y[2], w_z[1] - w_z[2]); - var _d3 = Math.hypot(w_x[2] - w_x[3], w_y[2] - w_y[3], w_z[2] - w_z[3]); - var _totalLength = _d + _d2 + _d3; - _d /= _totalLength; - _d3 /= _totalLength; - for (k = 0; k < 4; k++) { - fillColors[1].push(fillColors[0][k] * (1 - _d) + fillColors[3][k] * _d); - fillColors[2].push(fillColors[0][k] * _d3 + fillColors[3][k] * (1 - _d3)); - strokeColors[1].push(strokeColors[0][k] * (1 - _d) + strokeColors[3][k] * _d); - strokeColors[2].push(strokeColors[0][k] * _d3 + strokeColors[3][k] * (1 - _d3)); + 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; } - for (i = 0; i < LUTLength; i++) { - // Interpolate colors using control points - this.curFillColor = [ - 0, - 0, - 0, - 0 - ]; - this.curStrokeColor = [ - 0, - 0, - 0, - 0 - ]; - _x = _y = _z = 0; - for (m = 0; m < 4; m++) { - for (k = 0; k < 4; k++) { - this.curFillColor[k] += this._lookUpTableBezier[i][m] * fillColors[m][k]; - this.curStrokeColor[k] += this._lookUpTableBezier[i][m] * strokeColors[m][k]; - } - _x += w_x[m] * this._lookUpTableBezier[i][m]; - _y += w_y[m] * this._lookUpTableBezier[i][m]; - _z += w_z[m] * this._lookUpTableBezier[i][m]; - } - this.vertex(_x, _y, _z); - } // so that we leave currentColor with the last value the user set it to - - this.curFillColor = fillColors[3]; - this.curStrokeColor = strokeColors[3]; - this.immediateMode._bezierVertex[0] = arguments.length <= 6 ? undefined : arguments[6]; - this.immediateMode._bezierVertex[1] = arguments.length <= 7 ? undefined : arguments[7]; - this.immediateMode._bezierVertex[2] = arguments.length <= 8 ? undefined : arguments[8]; - } + 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; }; - _main.default.RendererGL.prototype.quadraticVertex = function () { - if (this.immediateMode._quadraticVertex.length === 0) { - throw Error('vertex() must be used once before calling quadraticVertex()'); - } else { - var w_x = [ - ]; - var w_y = [ - ]; - var w_z = [ - ]; - var t, - _x, - _y, - _z, - i, - k, - m; // variable i for bezierPoints, k for components, and m for anchor points. - var argLength = arguments.length; - t = 0; - if (this._lookUpTableQuadratic.length === 0 || this._lutQuadraticDetail !== this._pInst._curveDetail) { - this._lookUpTableQuadratic = [ - ]; - this._lutQuadraticDetail = this._pInst._curveDetail; - var step = 1 / this._lutQuadraticDetail; - var start = 0; - var end = 1; - var j = 0; - while (start < 1) { - t = parseFloat(start.toFixed(6)); - this._lookUpTableQuadratic[j] = this._quadraticCoefficients(t); - if (end.toFixed(6) === step.toFixed(6)) { - t = parseFloat(end.toFixed(6)) + parseFloat(start.toFixed(6)); - ++j; - this._lookUpTableQuadratic[j] = this._quadraticCoefficients(t); - break; - } - start += step; - end -= step; - ++j; - } - } - var LUTLength = this._lookUpTableQuadratic.length; // fillColors[0]: start point color - // fillColors[1]: control point color - // fillColors[2]: end point color - var fillColors = [ - ]; - for (m = 0; m < 3; m++) { - fillColors.push([]); - } - fillColors[0] = this.immediateMode.geometry.vertexColors.slice( - 4); - fillColors[2] = this.curFillColor.slice(); // Do the same for strokeColor. - var strokeColors = [ - ]; - for (m = 0; m < 3; m++) { - strokeColors.push([]); - } - strokeColors[0] = this.immediateMode.geometry.vertexStrokeColors.slice( - 4); - strokeColors[2] = this.curStrokeColor.slice(); - if (argLength === 4) { - this.isQuadratic = true; - w_x = [ - this.immediateMode._quadraticVertex[0], - arguments.length <= 0 ? undefined : arguments[0], - arguments.length <= 2 ? undefined : arguments[2] - ]; - w_y = [ - this.immediateMode._quadraticVertex[1], - arguments.length <= 1 ? undefined : arguments[1], - arguments.length <= 3 ? undefined : arguments[3] - ]; // The ratio of the distance between the start point, the control- - // point, and the end point determines the intermediate color. - var d0 = Math.hypot(w_x[0] - w_x[1], w_y[0] - w_y[1]); - var d1 = Math.hypot(w_x[1] - w_x[2], w_y[1] - w_y[2]); - var totalLength = d0 + d1; - d0 /= totalLength; - for (k = 0; k < 4; k++) { - fillColors[1].push(fillColors[0][k] * (1 - d0) + fillColors[2][k] * d0); - strokeColors[1].push(strokeColors[0][k] * (1 - d0) + strokeColors[2][k] * d0); - } - for (i = 0; i < LUTLength; i++) { - // Interpolate colors using control points - this.curFillColor = [ - 0, - 0, - 0, - 0 - ]; - this.curStrokeColor = [ - 0, - 0, - 0, - 0 - ]; - _x = _y = 0; - for (m = 0; m < 3; m++) { - for (k = 0; k < 4; k++) { - this.curFillColor[k] += this._lookUpTableQuadratic[i][m] * fillColors[m][k]; - this.curStrokeColor[k] += this._lookUpTableQuadratic[i][m] * strokeColors[m][k]; - } - _x += w_x[m] * this._lookUpTableQuadratic[i][m]; - _y += w_y[m] * this._lookUpTableQuadratic[i][m]; - } - this.vertex(_x, _y); - } // so that we leave currentColor with the last value the user set it to - - this.curFillColor = fillColors[2]; - this.curStrokeColor = strokeColors[2]; - this.immediateMode._quadraticVertex[0] = arguments.length <= 2 ? undefined : arguments[2]; - this.immediateMode._quadraticVertex[1] = arguments.length <= 3 ? undefined : arguments[3]; - } else if (argLength === 6) { - this.isQuadratic = true; - w_x = [ - this.immediateMode._quadraticVertex[0], - arguments.length <= 0 ? undefined : arguments[0], - arguments.length <= 3 ? undefined : arguments[3] - ]; - w_y = [ - this.immediateMode._quadraticVertex[1], - arguments.length <= 1 ? undefined : arguments[1], - arguments.length <= 4 ? undefined : arguments[4] - ]; - w_z = [ - this.immediateMode._quadraticVertex[2], - arguments.length <= 2 ? undefined : arguments[2], - arguments.length <= 5 ? undefined : arguments[5] - ]; // The ratio of the distance between the start point, the control- - // point, and the end point determines the intermediate color. - var _d4 = Math.hypot(w_x[0] - w_x[1], w_y[0] - w_y[1], w_z[0] - w_z[1]); - var _d5 = Math.hypot(w_x[1] - w_x[2], w_y[1] - w_y[2], w_z[1] - w_z[2]); - var _totalLength2 = _d4 + _d5; - _d4 /= _totalLength2; - for (k = 0; k < 4; k++) { - fillColors[1].push(fillColors[0][k] * (1 - _d4) + fillColors[2][k] * _d4); - strokeColors[1].push(strokeColors[0][k] * (1 - _d4) + strokeColors[2][k] * _d4); - } - for (i = 0; i < LUTLength; i++) { - // Interpolate colors using control points - this.curFillColor = [ - 0, - 0, - 0, - 0 - ]; - this.curStrokeColor = [ - 0, - 0, - 0, - 0 - ]; - _x = _y = _z = 0; - for (m = 0; m < 3; m++) { - for (k = 0; k < 4; k++) { - this.curFillColor[k] += this._lookUpTableQuadratic[i][m] * fillColors[m][k]; - this.curStrokeColor[k] += this._lookUpTableQuadratic[i][m] * strokeColors[m][k]; - } - _x += w_x[m] * this._lookUpTableQuadratic[i][m]; - _y += w_y[m] * this._lookUpTableQuadratic[i][m]; - _z += w_z[m] * this._lookUpTableQuadratic[i][m]; - } - this.vertex(_x, _y, _z); - } // so that we leave currentColor with the last value the user set it to - - this.curFillColor = fillColors[2]; - this.curStrokeColor = strokeColors[2]; - this.immediateMode._quadraticVertex[0] = arguments.length <= 3 ? undefined : arguments[3]; - this.immediateMode._quadraticVertex[1] = arguments.length <= 4 ? undefined : arguments[4]; - this.immediateMode._quadraticVertex[2] = arguments.length <= 5 ? undefined : arguments[5]; - } + /** + * Removes all lights present in a sketch. + * + * All subsequent geometry is rendered without lighting (until a new + * light is created with a call to one of the lighting functions + * (lights(), + * ambientLight(), + * directionalLight(), + * pointLight(), + * spotLight()). + * + * @method noLights + * @chainable + * @example + *
      + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * describe( + * 'Three white spheres. Each appears as a different color due to lighting.' + * ); + * } + * function draw() { + * background(200); + * noStroke(); + * + * ambientLight(255, 0, 0); + * translate(-30, 0, 0); + * ambientMaterial(255); + * sphere(13); + * + * noLights(); + * translate(30, 0, 0); + * ambientMaterial(255); + * sphere(13); + * + * ambientLight(0, 255, 0); + * translate(30, 0, 0); + * ambientMaterial(255); + * sphere(13); + * } + * + *
      + * + * @alt + * Three white spheres. Each appears as a different + * color due to lighting. + */ + _main.default.prototype.noLights = function () { + this._assert3d('noLights'); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; } - }; - _main.default.RendererGL.prototype.curveVertex = function () { - var w_x = [ - ]; - var w_y = [ - ]; - var w_z = [ + _main.default._validateParameters('noLights', args); + this._renderer._enableLighting = false; + this._renderer.ambientLightColors.length = 0; + this._renderer.specularColors = [ + 1, + 1, + 1 ]; - var t, - _x, - _y, - _z, - i; - t = 0; - var argLength = arguments.length; - if (this._lookUpTableBezier.length === 0 || this._lutBezierDetail !== this._pInst._curveDetail) { - this._lookUpTableBezier = [ - ]; - this._lutBezierDetail = this._pInst._curveDetail; - var step = 1 / this._lutBezierDetail; - var start = 0; - var end = 1; - var j = 0; - while (start < 1) { - t = parseFloat(start.toFixed(6)); - this._lookUpTableBezier[j] = this._bezierCoefficients(t); - if (end.toFixed(6) === step.toFixed(6)) { - t = parseFloat(end.toFixed(6)) + parseFloat(start.toFixed(6)); - ++j; - this._lookUpTableBezier[j] = this._bezierCoefficients(t); - break; - } - start += step; - end -= step; - ++j; - } - } - var LUTLength = this._lookUpTableBezier.length; - if (argLength === 2) { - this.immediateMode._curveVertex.push(arguments.length <= 0 ? undefined : arguments[0]); - this.immediateMode._curveVertex.push(arguments.length <= 1 ? undefined : arguments[1]); - if (this.immediateMode._curveVertex.length === 8) { - this.isCurve = true; - w_x = this._bezierToCatmull([this.immediateMode._curveVertex[0], - this.immediateMode._curveVertex[2], - this.immediateMode._curveVertex[4], - this.immediateMode._curveVertex[6]]); - w_y = this._bezierToCatmull([this.immediateMode._curveVertex[1], - this.immediateMode._curveVertex[3], - this.immediateMode._curveVertex[5], - this.immediateMode._curveVertex[7]]); - for (i = 0; i < LUTLength; i++) { - _x = w_x[0] * this._lookUpTableBezier[i][0] + w_x[1] * this._lookUpTableBezier[i][1] + w_x[2] * this._lookUpTableBezier[i][2] + w_x[3] * this._lookUpTableBezier[i][3]; - _y = w_y[0] * this._lookUpTableBezier[i][0] + w_y[1] * this._lookUpTableBezier[i][1] + w_y[2] * this._lookUpTableBezier[i][2] + w_y[3] * this._lookUpTableBezier[i][3]; - this.vertex(_x, _y); - } - for (i = 0; i < argLength; i++) { - this.immediateMode._curveVertex.shift(); - } - } - } else if (argLength === 3) { - this.immediateMode._curveVertex.push(arguments.length <= 0 ? undefined : arguments[0]); - this.immediateMode._curveVertex.push(arguments.length <= 1 ? undefined : arguments[1]); - this.immediateMode._curveVertex.push(arguments.length <= 2 ? undefined : arguments[2]); - if (this.immediateMode._curveVertex.length === 12) { - this.isCurve = true; - w_x = this._bezierToCatmull([this.immediateMode._curveVertex[0], - this.immediateMode._curveVertex[3], - this.immediateMode._curveVertex[6], - this.immediateMode._curveVertex[9]]); - w_y = this._bezierToCatmull([this.immediateMode._curveVertex[1], - this.immediateMode._curveVertex[4], - this.immediateMode._curveVertex[7], - this.immediateMode._curveVertex[10]]); - w_z = this._bezierToCatmull([this.immediateMode._curveVertex[2], - this.immediateMode._curveVertex[5], - this.immediateMode._curveVertex[8], - this.immediateMode._curveVertex[11]]); - for (i = 0; i < LUTLength; i++) { - _x = w_x[0] * this._lookUpTableBezier[i][0] + w_x[1] * this._lookUpTableBezier[i][1] + w_x[2] * this._lookUpTableBezier[i][2] + w_x[3] * this._lookUpTableBezier[i][3]; - _y = w_y[0] * this._lookUpTableBezier[i][0] + w_y[1] * this._lookUpTableBezier[i][1] + w_y[2] * this._lookUpTableBezier[i][2] + w_y[3] * this._lookUpTableBezier[i][3]; - _z = w_z[0] * this._lookUpTableBezier[i][0] + w_z[1] * this._lookUpTableBezier[i][1] + w_z[2] * this._lookUpTableBezier[i][2] + w_z[3] * this._lookUpTableBezier[i][3]; - this.vertex(_x, _y, _z); - } - for (i = 0; i < argLength; i++) { - this.immediateMode._curveVertex.shift(); - } - } - } - }; - _main.default.RendererGL.prototype.image = function (img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) { - if (this._isErasing) { - this.blendMode(this._cachedBlendMode); - } - this._pInst.push(); - this._pInst.noLights(); - this._pInst.noStroke(); - this._pInst.texture(img); - this._pInst.textureMode(constants.NORMAL); - var u0 = 0; - if (sx <= img.width) { - u0 = sx / img.width; - } - var u1 = 1; - if (sx + sWidth <= img.width) { - u1 = (sx + sWidth) / img.width; - } - var v0 = 0; - if (sy <= img.height) { - v0 = sy / img.height; - } - var v1 = 1; - if (sy + sHeight <= img.height) { - v1 = (sy + sHeight) / img.height; - } - this.beginShape(); - this.vertex(dx, dy, 0, u0, v0); - this.vertex(dx + dWidth, dy, 0, u1, v0); - this.vertex(dx + dWidth, dy + dHeight, 0, u1, v1); - this.vertex(dx, dy + dHeight, 0, u0, v1); - this.endShape(constants.CLOSE); - this._pInst.pop(); - if (this._isErasing) { - this.blendMode(constants.REMOVE); - } + this._renderer.directionalLightDirections.length = 0; + this._renderer.directionalLightDiffuseColors.length = 0; + this._renderer.directionalLightSpecularColors.length = 0; + this._renderer.pointLightPositions.length = 0; + this._renderer.pointLightDiffuseColors.length = 0; + this._renderer.pointLightSpecularColors.length = 0; + this._renderer.spotLightPositions.length = 0; + this._renderer.spotLightDirections.length = 0; + this._renderer.spotLightDiffuseColors.length = 0; + this._renderer.spotLightSpecularColors.length = 0; + this._renderer.spotLightAngle.length = 0; + this._renderer.spotLightConc.length = 0; + this._renderer.constantAttenuation = 1; + this._renderer.linearAttenuation = 0; + this._renderer.quadraticAttenuation = 0; + this._renderer._useShininess = 1; + return this; }; var _default = _main.default; exports.default = _default; }, { - '../core/constants': 278, - '../core/main': 290, - './p5.Geometry': 339, - 'core-js/modules/es.array.concat': 167, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.math.hypot': 185, - 'core-js/modules/es.number.to-fixed': 189, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + '../core/main': 298 } ], - 334: [ + 345: [ function (_dereq_, module, exports) { 'use strict'; - _dereq_('core-js/modules/es.symbol'); - _dereq_('core-js/modules/es.symbol.description'); - _dereq_('core-js/modules/es.symbol.iterator'); - _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.slice'); _dereq_('core-js/modules/es.array.splice'); - _dereq_('core-js/modules/es.object.get-own-property-descriptor'); _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.regexp.to-string'); - _dereq_('core-js/modules/es.string.iterator'); - _dereq_('core-js/modules/es.weak-map'); - _dereq_('core-js/modules/web.dom-collections.iterator'); - function _typeof2(obj) { - if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { - _typeof2 = function _typeof2(obj) { - return typeof obj; - }; - } else { - _typeof2 = function _typeof2(obj) { - return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; - }; - } - return _typeof2(obj); - } - function _typeof(obj) { - if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { - _typeof = function _typeof(obj) { - return _typeof2(obj); - }; - } else { - _typeof = function _typeof(obj) { - return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); - }; - } - return _typeof(obj); - } + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.match'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.string.trim'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.slice'); _dereq_('core-js/modules/es.array.splice'); _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.match'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.string.trim'); Object.defineProperty(exports, '__esModule', { value: true }); exports.default = void 0; var _main = _interopRequireDefault(_dereq_('../core/main')); - 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; - } + _dereq_('./p5.Geometry'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** - * @module 3D - * @submodule Interaction + * @module Shape + * @submodule 3D Models * @for p5 * @requires core + * @requires p5.Geometry */ /** - * 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 + * Load a 3d model from an OBJ or STL file. + * + * loadModel() should be placed inside of preload(). + * This allows the model to load fully before the rest of your code is run. + * + * One of the limitations of the OBJ and STL format is that it doesn't have a built-in + * sense of scale. This means that models exported from different programs might + * be very different sizes. If your model isn't displaying, try calling + * loadModel() with the normalized parameter set to true. This will resize the + * model to a scale appropriate for p5. You can also make additional changes to + * the final size of your model with the scale() function. + * + * Also, the support for colored STL files is not present. STL files with color will be + * rendered without color properties. + * + * @method loadModel + * @param {String} path Path of the model to be loaded + * @param {Boolean} normalize If true, scale the model to a + * standardized size when loading + * @param {function(p5.Geometry)} [successCallback] Function to be called + * once the model is loaded. Will be passed + * the 3D model object. + * @param {function(Event)} [failureCallback] called with event error if + * the model fails to load. + * @param {String} [fileType] The file extension of the model + * (.stl, .obj). + * @return {p5.Geometry} the p5.Geometry object + * * @example *
      * + * //draw a spinning octahedron + * let octahedron; + * + * function preload() { + * octahedron = loadModel('assets/octahedron.obj'); + * } + * * function setup() { * createCanvas(100, 100, WEBGL); - * normalMaterial(); - * describe( - * 'Camera orbits around a box when mouse is hold-clicked & then moved.' - * ); + * describe('Vertically rotating 3-d octahedron.'); * } + * * function draw() { * background(200); - * orbitControl(); - * rotateY(0.5); - * box(30, 50); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * model(octahedron); * } * *
      * * @alt - * Camera orbits around a box when mouse is hold-clicked & then moved. - */ - // implementation based on three.js 'orbitControls': - // https://github.com/mrdoob/three.js/blob/dev/examples/js/controls/OrbitControls.js - - _main.default.prototype.orbitControl = function (sensitivityX, sensitivityY, sensitivityZ) { - this._assert3d('orbitControl'); - _main.default._validateParameters('orbitControl', arguments); // If the mouse is not in bounds of the canvas, disable all behaviors: - var mouseInCanvas = this.mouseX < this.width && this.mouseX > 0 && this.mouseY < this.height && this.mouseY > 0; - if (!mouseInCanvas) return; - var cam = this._renderer._curCamera; - if (typeof sensitivityX === 'undefined') { - sensitivityX = 1; - } - if (typeof sensitivityY === 'undefined') { - sensitivityY = sensitivityX; - } - if (typeof sensitivityZ === 'undefined') { - sensitivityZ = 0.5; - } // default right-mouse and mouse-wheel behaviors (context menu and scrolling, - // respectively) are disabled here to allow use of those events for panning and - // zooming - // disable context menu for canvas element and add 'contextMenuDisabled' - // flag to p5 instance - - if (this.contextMenuDisabled !== true) { - this.canvas.oncontextmenu = function () { - return false; - }; - this._setProperty('contextMenuDisabled', true); - } // disable default scrolling behavior on the canvas element and add - // 'wheelDefaultDisabled' flag to p5 instance - - if (this.wheelDefaultDisabled !== true) { - this.canvas.onwheel = function () { - return false; - }; - this._setProperty('wheelDefaultDisabled', true); - } - var scaleFactor = this.height < this.width ? this.height : this.width; // ZOOM if there is a change in mouseWheelDelta - if (this._mouseWheelDeltaY !== this._pmouseWheelDeltaY) { - // zoom according to direction of mouseWheelDeltaY rather than value - if (this._mouseWheelDeltaY > 0) { - this._renderer._curCamera._orbit(0, 0, sensitivityZ * scaleFactor); - } else { - this._renderer._curCamera._orbit(0, 0, - sensitivityZ * scaleFactor); - } - } - if (this.mouseIsPressed) { - // ORBIT BEHAVIOR - if (this.mouseButton === this.LEFT) { - var deltaTheta = - sensitivityX * (this.mouseX - this.pmouseX) / scaleFactor; - var deltaPhi = sensitivityY * (this.mouseY - this.pmouseY) / scaleFactor; - this._renderer._curCamera._orbit(deltaTheta, deltaPhi, 0); - } else if (this.mouseButton === this.RIGHT) { - // PANNING BEHAVIOR along X/Z camera axes and restricted to X/Z plane - // in world space - var local = cam._getLocalAxes(); // normalize portions along X/Z axes - var xmag = Math.sqrt(local.x[0] * local.x[0] + local.x[2] * local.x[2]); - if (xmag !== 0) { - local.x[0] /= xmag; - local.x[2] /= xmag; - } // normalize portions along X/Z axes - - var ymag = Math.sqrt(local.y[0] * local.y[0] + local.y[2] * local.y[2]); - if (ymag !== 0) { - local.y[0] /= ymag; - local.y[2] /= ymag; - } // move along those vectors by amount controlled by mouseX, pmouseY - - var dx = - 1 * sensitivityX * (this.mouseX - this.pmouseX); - var dz = - 1 * sensitivityY * (this.mouseY - this.pmouseY); // restrict movement to XZ plane in world space - cam.setPosition(cam.eyeX + dx * local.x[0] + dz * local.z[0], cam.eyeY, cam.eyeZ + dx * local.x[2] + dz * local.z[2]); - } - } - return this; - }; - /** - * debugMode() helps visualize 3D space by adding a grid to indicate where the - * ‘ground’ is in a sketch and an axes icon which indicates the +X, +Y, and +Z - * directions. This function can be called without parameters to create a - * default grid and axes icon, or it can be called according to the examples - * above to customize the size and position of the grid and/or axes icon. The - * grid is drawn using the most recently set stroke color and weight. To - * specify these parameters, add a call to stroke() and strokeWeight() - * just before the end of the draw() loop. - * - * By default, the grid will run through the origin (0,0,0) of the sketch - * along the XZ plane - * and the axes icon will be offset from the origin. Both the grid and axes - * icon will be sized according to the current canvas size. Note that because the - * grid runs parallel to the default camera view, it is often helpful to use - * debugMode along with orbitControl to allow full view of the grid. - * @method debugMode - * @example - *
      - * - * function setup() { - * createCanvas(100, 100, WEBGL); - * camera(0, -30, 100, 0, 0, 0, 0, 1, 0); - * normalMaterial(); - * debugMode(); - * describe( - * 'a 3D box is centered on a grid in a 3D sketch. an icon indicates the direction of each axis: a red line points +X, a green line +Y, and a blue line +Z. the grid and icon disappear when the spacebar is pressed.' - * ); - * } - * - * function draw() { - * background(200); - * orbitControl(); - * box(15, 30); - * // Press the spacebar to turn debugMode off! - * if (keyIsDown(32)) { - * noDebugMode(); - * } - * } - * - *
      - * @alt - * a 3D box is centered on a grid in a 3D sketch. an icon - * indicates the direction of each axis: a red line points +X, - * a green line +Y, and a blue line +Z. the grid and icon disappear when the - * spacebar is pressed. - * - * @example - *
      - * - * function setup() { - * createCanvas(100, 100, WEBGL); - * camera(0, -30, 100, 0, 0, 0, 0, 1, 0); - * normalMaterial(); - * debugMode(GRID); - * describe('a 3D box is centered on a grid in a 3D sketch.'); - * } - * - * function draw() { - * background(200); - * orbitControl(); - * box(15, 30); - * } - * - *
      - * @alt - * a 3D box is centered on a grid in a 3D sketch. + * Vertically rotating 3-d octahedron. * * @example *
      * - * function setup() { - * createCanvas(100, 100, WEBGL); - * camera(0, -30, 100, 0, 0, 0, 0, 1, 0); - * normalMaterial(); - * debugMode(AXES); - * describe( - * 'a 3D box is centered in a 3D sketch. an icon indicates the direction of each axis: a red line points +X, a green line +Y, and a blue line +Z.' - * ); - * } + * //draw a spinning teapot + * let teapot; * - * function draw() { - * background(200); - * orbitControl(); - * box(15, 30); + * function preload() { + * // Load model with normalise parameter set to true + * teapot = loadModel('assets/teapot.obj', true); * } - * - *
      - * @alt - * a 3D box is centered in a 3D sketch. an icon - * indicates the direction of each axis: a red line points +X, - * a green line +Y, and a blue line +Z. * - * @example - *
      - * * function setup() { * createCanvas(100, 100, WEBGL); - * camera(0, -30, 100, 0, 0, 0, 0, 1, 0); - * normalMaterial(); - * debugMode(GRID, 100, 10, 0, 0, 0); - * describe('a 3D box is centered on a grid in a 3D sketch'); + * describe('Vertically rotating 3-d teapot with red, green and blue gradient.'); * } * * function draw() { * background(200); - * orbitControl(); - * box(15, 30); + * scale(0.4); // Scaled to make model fit into canvas + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * normalMaterial(); // For effect + * model(teapot); * } * *
      - * @alt - * a 3D box is centered on a grid in a 3D sketch - * - * @example - *
      - * - * function setup() { - * createCanvas(100, 100, WEBGL); - * camera(0, -30, 100, 0, 0, 0, 0, 1, 0); - * normalMaterial(); - * debugMode(100, 10, 0, 0, 0, 20, 0, -40, 0); - * describe( - * 'a 3D box is centered on a grid in a 3D sketch. an icon indicates the direction of each axis: a red line points +X, a green line +Y, and a blue line +Z.' - * ); - * } * - * function draw() { - * noStroke(); - * background(200); - * orbitControl(); - * box(15, 30); - * // set the stroke color and weight for the grid! - * stroke(255, 0, 150); - * strokeWeight(0.8); - * } - * - *
      * @alt - * a 3D box is centered on a grid in a 3D sketch. an icon - * indicates the direction of each axis: a red line points +X, - * a green line +Y, and a blue line +Z. - */ - /** - * @method debugMode - * @param {Constant} mode either GRID or AXES - */ - /** - * @method debugMode - * @param {Constant} mode - * @param {Number} [gridSize] size of one side of the grid - * @param {Number} [gridDivisions] number of divisions in the grid - * @param {Number} [xOff] X axis offset from origin (0,0,0) - * @param {Number} [yOff] Y axis offset from origin (0,0,0) - * @param {Number} [zOff] Z axis offset from origin (0,0,0) - */ - /** - * @method debugMode - * @param {Constant} mode - * @param {Number} [axesSize] size of axes icon - * @param {Number} [xOff] - * @param {Number} [yOff] - * @param {Number} [zOff] + * Vertically rotating 3-d teapot with red, green and blue gradient. */ /** - * @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] + * @method loadModel + * @param {String} path + * @param {function(p5.Geometry)} [successCallback] + * @param {function(Event)} [failureCallback] + * @param {String} [fileType] + * @return {p5.Geometry} the p5.Geometry object */ - _main.default.prototype.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])); + _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 { - 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])); + 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 { + _main.default._friendlyError('Sorry, the file type is invalid. Only OBJ and STL files are supported.'); + } } + return model; }; /** - * Turns off debugMode() in a 3D sketch. - * @method noDebugMode - * @example - *
      - * - * function setup() { - * createCanvas(100, 100, WEBGL); - * camera(0, -30, 100, 0, 0, 0, 0, 1, 0); - * normalMaterial(); - * debugMode(); - * describe( - * 'a 3D box is centered on a grid in a 3D sketch. an icon indicates the direction of each axis: a red line points +X, a green line +Y, and a blue line +Z. the grid and icon disappear when the spacebar is pressed.' - * ); - * } + * Parse OBJ lines into model. For reference, this is what a simple model of a + * square might look like: * - * function draw() { - * background(200); - * orbitControl(); - * box(15, 30); - * // Press the spacebar to turn debugMode off! - * if (keyIsDown(32)) { - * noDebugMode(); - * } - * } - * - *
      - * @alt - * a 3D box is centered on a grid in a 3D sketch. an icon - * indicates the direction of each axis: a red line points +X, - * a green line +Y, and a blue line +Z. the grid and icon disappear when the - * spacebar is pressed. + * 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 */ - _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); + function parseObj(model, lines) { + // OBJ allows a face to specify an index for a vertex (in the above example), + // but it also allows you to specify a custom combination of vertex, UV + // coordinate, and vertex normal. So, "3/4/3" would mean, "use vertex 3 with + // UV coordinate 4 and vertex normal 3". In WebGL, every vertex with different + // parameters must be a different vertex, so loadedVerts is used to + // temporarily store the parsed vertices, normals, etc., and indexedVerts is + // used to map a specific combination (keyed on, for example, the string + // "3/4/3"), to the actual index of the newly created vertex in the final + // object. + var loadedVerts = { + v: [ + ], + vt: [ + ], + vn: [ + ] + }; + var indexedVerts = { + }; + for (var line = 0; line < lines.length; ++line) { + // Each line is a separate object (vertex, face, vertex normal, etc) + // For each line, split it into tokens on whitespace. The first token + // describes the type. + var tokens = lines[line].trim().split(/\b\s+/); + if (tokens.length > 0) { + if (tokens[0] === 'v' || tokens[0] === 'vn') { + // Check if this line describes a vertex or vertex normal. + // It will have three numeric parameters. + var vertex = new _main.default.Vector(parseFloat(tokens[1]), parseFloat(tokens[2]), parseFloat(tokens[3])); + loadedVerts[tokens[0]].push(vertex); + } else if (tokens[0] === 'vt') { + // Check if this line describes a texture coordinate. + // It will have two numeric parameters U and V (W is omitted). + // Because of WebGL texture coordinates rendering behaviour, the V + // coordinate is inversed. + var texVertex = [ + parseFloat(tokens[1]), + 1 - parseFloat(tokens[2]) + ]; + loadedVerts[tokens[0]].push(texVertex); + } else if (tokens[0] === 'f') { + // Check if this line describes a face. + // OBJ faces can have more than three points. Triangulate points. + for (var tri = 3; tri < tokens.length; ++tri) { + var face = [ + ]; + var vertexTokens = [ + 1, + tri - 1, + tri + ]; + for (var tokenInd = 0; tokenInd < vertexTokens.length; ++tokenInd) { + // Now, convert the given token into an index + var vertString = tokens[vertexTokens[tokenInd]]; + var vertIndex = 0; + // TODO: Faces can technically use negative numbers to refer to the + // previous nth vertex. I haven't seen this used in practice, but + // it might be good to implement this in the future. + if (indexedVerts[vertString] !== undefined) { + vertIndex = indexedVerts[vertString]; + } else { + var vertParts = vertString.split('/'); + for (var i = 0; i < vertParts.length; i++) { + vertParts[i] = parseInt(vertParts[i]) - 1; + } + vertIndex = indexedVerts[vertString] = model.vertices.length; + model.vertices.push(loadedVerts.v[vertParts[0]].copy()); + if (loadedVerts.vt[vertParts[1]]) { + model.uvs.push(loadedVerts.vt[vertParts[1]].slice()); + } else { + model.uvs.push([0, + 0]); + } + if (loadedVerts.vn[vertParts[2]]) { + model.vertexNormals.push(loadedVerts.vn[vertParts[2]].copy()); + } + } + face.push(vertIndex); + } + if (face[0] !== face[1] && face[0] !== face[2] && face[1] !== face[2]) { + model.faces.push(face); + } + } + } } + } // If the model doesn't have normals, compute the normals + + if (model.vertexNormals.length === 0) { + model.computeNormals(); } - }; - /** - * 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 + 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. */ - _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(); + 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; } - 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; + var decoder = new TextDecoder('utf-8'); + var lines = decoder.decode(reader); + var lineArray = lines.split('\n'); + parseASCIISTL(model, lineArray); } - if (typeof zOff === 'undefined') { - zOff = xOff; + return model; + } /** + * This function checks if the file is in ASCII format or in Binary format + * + * It is done by searching keyword `solid` at the start of the file. + * + * An ASCII STL data must begin with `solid` as the first six bytes. + * However, ASCII STLs lacking the SPACE after the `d` are known to be + * plentiful. So, check the first 5 bytes for `solid`. + * + * Several encodings, such as UTF-8, precede the text with up to 5 bytes: + * https://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding + * Search for `solid` to start anywhere after those prefixes. + */ + + function isBinary(data) { + var reader = new DataView(data); + // US-ASCII ordinal values for `s`, `o`, `l`, `i`, `d` + var solid = [ + 115, + 111, + 108, + 105, + 100 + ]; + for (var off = 0; off < 5; off++) { + // If "solid" text is matched to the current offset, declare it to be an ASCII STL. + if (matchDataViewAt(solid, reader, off)) return false; + } // Couldn't find "solid" text at the beginning; it is binary STL. + + return true; + } /** + * This function matches the `query` at the provided `offset` + */ + + function matchDataViewAt(query, reader, offset) { + // Check if each byte in query matches the corresponding byte from the current offset + for (var i = 0, il = query.length; i < il; i++) { + if (query[i] !== reader.getUint8(offset + i, false)) return false; + } + return true; + } /** + * This function parses the Binary STL files. + * https://en.wikipedia.org/wiki/STL_%28file_format%29#Binary_STL + * + * Currently there is no support for the colors provided in STL files. + */ + + function parseBinarySTL(model, buffer) { + var reader = new DataView(buffer); + // Number of faces is present following the header + var faces = reader.getUint32(80, true); + var r, + g, + b, + hasColors = false, + colors; + var defaultR, + defaultG, + defaultB; + // Binary files contain 80-byte header, which is generally ignored. + for (var index = 0; index < 80 - 10; index++) { + // Check for `COLOR=` + if (reader.getUint32(index, false) === 1129270351 /*COLO*/ && reader.getUint8(index + 4) === 82 /*'R'*/ && reader.getUint8(index + 5) === 61 /*'='*/ ) { + hasColors = true; + colors = [ + ]; + defaultR = reader.getUint8(index + 6) / 255; + defaultG = reader.getUint8(index + 7) / 255; + defaultB = reader.getUint8(index + 8) / 255; + // To be used when color support is added + // alpha = reader.getUint8(index + 9) / 255; + } + } + var dataOffset = 84; + var faceLength = 12 * 4 + 2; + // Iterate the faces + for (var face = 0; face < faces; face++) { + var start = dataOffset + face * faceLength; + var normalX = reader.getFloat32(start, true); + var normalY = reader.getFloat32(start + 4, true); + var normalZ = reader.getFloat32(start + 8, true); + if (hasColors) { + var packedColor = reader.getUint16(start + 48, true); + if ((packedColor & 32768) === 0) { + // facet has its own unique color + r = (packedColor & 31) / 31; + g = (packedColor >> 5 & 31) / 31; + b = (packedColor >> 10 & 31) / 31; + } else { + r = defaultR; + g = defaultG; + b = defaultB; + } + } + var newNormal = new _main.default.Vector(normalX, normalY, normalZ); + for (var i = 1; i <= 3; i++) { + var vertexstart = start + i * 12; + var newVertex = new _main.default.Vector(reader.getFloat32(vertexstart, true), reader.getFloat32(vertexstart + 4, true), reader.getFloat32(vertexstart + 8, true)); + model.vertices.push(newVertex); + model.vertexNormals.push(newNormal); + if (hasColors) { + colors.push(r, g, b); + } + } + model.faces.push([3 * face, + 3 * face + 1, + 3 * face + 2]); + model.uvs.push([0, + 0], [ + 0, + 0 + ], [ + 0, + 0 + ]); + } + if (hasColors) { + // add support for colors here. + } + return model; + } /** + * ASCII STL file starts with `solid 'nameOfFile'` + * Then contain the normal of the face, starting with `facet normal` + * Next contain a keyword indicating the start of face vertex, `outer loop` + * Next comes the three vertex, starting with `vertex x y z` + * Vertices ends with `endloop` + * Face ends with `endfacet` + * Next face starts with `facet normal` + * The end of the file is indicated by `endsolid` + */ + + function parseASCIISTL(model, lines) { + var state = ''; + var curVertexIndex = [ + ]; + var newNormal, + newVertex; + for (var iterator = 0; iterator < lines.length; ++iterator) { + var line = lines[iterator].trim(); + var parts = line.split(' '); + for (var partsiterator = 0; partsiterator < parts.length; ++partsiterator) { + if (parts[partsiterator] === '') { + // Ignoring multiple whitespaces + parts.splice(partsiterator, 1); + } + } + if (parts.length === 0) { + // Remove newline + continue; + } + switch (state) { + case '': + // First run + if (parts[0] !== 'solid') { + // Invalid state + console.error(line); + console.error('Invalid state "'.concat(parts[0], '", should be "solid"')); + return; + } else { + state = 'solid'; + } + break; + case 'solid': + // First face + if (parts[0] !== 'facet' || parts[1] !== 'normal') { + // Invalid state + console.error(line); + console.error('Invalid state "'.concat(parts[0], '", should be "facet normal"')); + return; + } else { + // Push normal for first face + newNormal = new _main.default.Vector(parseFloat(parts[2]), parseFloat(parts[3]), parseFloat(parts[4])); + model.vertexNormals.push(newNormal, newNormal, newNormal); + state = 'facet normal'; + } + break; + case 'facet normal': + // After normal is defined + if (parts[0] !== 'outer' || parts[1] !== 'loop') { + // Invalid State + console.error(line); + console.error('Invalid state "'.concat(parts[0], '", should be "outer loop"')); + return; + } else { + // Next should be vertices + state = 'vertex'; + } + break; + case 'vertex': + if (parts[0] === 'vertex') { + //Vertex of triangle + newVertex = new _main.default.Vector(parseFloat(parts[1]), parseFloat(parts[2]), parseFloat(parts[3])); + model.vertices.push(newVertex); + model.uvs.push([0, + 0]); + curVertexIndex.push(model.vertices.indexOf(newVertex)); + } else if (parts[0] === 'endloop') { + // End of vertices + model.faces.push(curVertexIndex); + curVertexIndex = [ + ]; + state = 'endloop'; + } else { + // Invalid State + console.error(line); + console.error('Invalid state "'.concat(parts[0], '", should be "vertex" or "endloop"')); + return; + } + break; + case 'endloop': + if (parts[0] !== 'endfacet') { + // End of face + console.error(line); + console.error('Invalid state "'.concat(parts[0], '", should be "endfacet"')); + return; + } else { + state = 'endfacet'; + } + break; + case 'endfacet': + if (parts[0] === 'endsolid') { + // End of solid + } else if (parts[0] === 'facet' && parts[1] === 'normal') { + // Next face + newNormal = new _main.default.Vector(parseFloat(parts[2]), parseFloat(parts[3]), parseFloat(parts[4])); + model.vertexNormals.push(newNormal, newNormal, newNormal); + state = 'facet normal'; + } else { + // Invalid State + console.error(line); + console.error('Invalid state "'.concat(parts[0], '", should be "endsolid" or "facet normal"')); + return; + } + break; + default: + console.error('Invalid state "'.concat(state, '"')); + break; + } + } + return model; + } /** + * Render a 3d model to the screen. + * + * @method model + * @param {p5.Geometry} model Loaded 3d model to be rendered + * @example + *
      + * + * //draw a spinning octahedron + * let octahedron; + * + * function preload() { + * octahedron = loadModel('assets/octahedron.obj'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * describe('Vertically rotating 3-d octahedron.'); + * } + * + * function draw() { + * background(200); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * model(octahedron); + * } + * + *
      + * + * @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)) { + if (model.edges.length === 0) { + model._makeTriangleEdges(); + } + model._edgesToVertices(); + this._renderer.createBuffers(model.gid, model); + } + this._renderer.drawBuffers(model.gid); } - return function () { - this.push(); - this._renderer.uMVMatrix.set(this._renderer._curCamera.cameraMatrix.mat4[0], this._renderer._curCamera.cameraMatrix.mat4[1], this._renderer._curCamera.cameraMatrix.mat4[2], this._renderer._curCamera.cameraMatrix.mat4[3], this._renderer._curCamera.cameraMatrix.mat4[4], this._renderer._curCamera.cameraMatrix.mat4[5], this._renderer._curCamera.cameraMatrix.mat4[6], this._renderer._curCamera.cameraMatrix.mat4[7], this._renderer._curCamera.cameraMatrix.mat4[8], this._renderer._curCamera.cameraMatrix.mat4[9], this._renderer._curCamera.cameraMatrix.mat4[10], this._renderer._curCamera.cameraMatrix.mat4[11], this._renderer._curCamera.cameraMatrix.mat4[12], this._renderer._curCamera.cameraMatrix.mat4[13], this._renderer._curCamera.cameraMatrix.mat4[14], this._renderer._curCamera.cameraMatrix.mat4[15]); // X axis - this.strokeWeight(2); - this.stroke(255, 0, 0); - this.beginShape(this.LINES); - this.vertex(xOff, yOff, zOff); - this.vertex(xOff + size, yOff, zOff); - this.endShape(); // Y axis - this.stroke(0, 255, 0); - this.beginShape(this.LINES); - this.vertex(xOff, yOff, zOff); - this.vertex(xOff, yOff + size, zOff); - this.endShape(); // Z axis - this.stroke(0, 0, 255); - this.beginShape(this.LINES); - this.vertex(xOff, yOff, zOff); - this.vertex(xOff, yOff, zOff + size); - this.endShape(); - this.pop(); - }; }; var _default = _main.default; exports.default = _default; }, { - '../core/constants': 278, - '../core/main': 290, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.splice': 182, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.to-string': 200, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + '../core/main': 298, + './p5.Geometry': 350, + 'core-js/modules/es.array.concat': 169, + 'core-js/modules/es.array.index-of': 178, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.array.splice': 185, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.string.match': 211, + 'core-js/modules/es.string.split': 216, + 'core-js/modules/es.string.trim': 219 } ], - 335: [ + 346: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); _dereq_('core-js/modules/es.symbol.description'); _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.includes'); _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.join'); _dereq_('core-js/modules/es.object.get-own-property-descriptor'); _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.includes'); _dereq_('core-js/modules/es.string.iterator'); _dereq_('core-js/modules/es.weak-map'); _dereq_('core-js/modules/web.dom-collections.iterator'); @@ -96644,12 +107567,23 @@ } return _typeof(obj); } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.iterator'); Object.defineProperty(exports, '__esModule', { value: true }); exports.default = void 0; var _main = _interopRequireDefault(_dereq_('../core/main')); var constants = _interopRequireWildcard(_dereq_('../core/constants')); + _dereq_('./p5.Texture'); function _getRequireWildcardCache() { if (typeof WeakMap !== 'function') return null; var cache = new WeakMap(); @@ -96698,4420 +107632,5418 @@ }; } /** * @module 3D - * @submodule Lights + * @submodule Material * @for p5 * @requires core */ /** - * Creates an ambient light with the given color. + * Creates a new p5.Shader object + * from the provided vertex and fragment shader files. * - * Ambient light does not come from a specific direction. - * Objects are evenly lit from all sides. Ambient lights are - * almost always used in combination with other types of lights. + * The shader files are loaded asynchronously in the + * background, so this method should be used in preload(). * - * Note: lights need to be called (whether directly or indirectly) - * within draw() to remain persistent in a looping program. - * Placing them in setup() will cause them to only have an effect - * the first time through the loop. + * Shaders can alter the positioning of shapes drawn with them. + * To ensure consistency in rendering, it's recommended to use the vertex shader in the createShader example. * - * @method ambientLight - * @param {Number} v1 red or hue value relative to - * the current color range - * @param {Number} v2 green or saturation value - * relative to the current color range - * @param {Number} v3 blue or brightness value - * relative to the current color range - * @param {Number} [alpha] alpha value relative to current - * color range (default is 0-255) - * @chainable + * Note, shaders can only be used in WEBGL mode. + * + * @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 p5.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 - *
      + *
      * + * 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(); - * describe('sphere with coral color under black light'); + * mandel.setUniform('p', [-0.74364388703, 0.13182590421]); + * describe('zooming Mandelbrot set. a colorful, infinitely detailed fractal.'); * } + * * function draw() { - * background(100); - * ambientLight(0); // black light (no light) - * ambientMaterial(255, 127, 80); // coral material - * sphere(40); + * mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000)))); + * quad(-1, -1, 1, -1, 1, 1, -1, 1); * } * *
      + * * @alt - * sphere with coral color under black light + * zooming Mandelbrot set. a colorful, infinitely detailed fractal. + */ + + _main.default.prototype.loadShader = function (vertFilename, fragFilename, callback, errorCallback) { + _main.default._validateParameters('loadShader', arguments); + if (!errorCallback) { + errorCallback = console.error; + } + var loadedShader = new _main.default.Shader(); + var self = this; + var loadedFrag = false; + var loadedVert = false; + var onLoad = function onLoad() { + self._decrementPreload(); + if (callback) { + callback(loadedShader); + } + }; + this.loadStrings(vertFilename, function (result) { + loadedShader._vertSrc = result.join('\n'); + loadedVert = true; + if (loadedFrag) { + onLoad(); + } + }, errorCallback); + this.loadStrings(fragFilename, function (result) { + loadedShader._fragSrc = result.join('\n'); + loadedFrag = true; + if (loadedVert) { + onLoad(); + } + }, errorCallback); + return loadedShader; + }; + /** + * Creates a new p5.Shader object + * from the provided vertex and fragment shader code. + * + * Note, shaders can only be used in WEBGL mode. + * + * Shaders can alter the positioning of shapes drawn with them. + * To ensure consistency in rendering, it's recommended to use the vertex shader shown in the example below. + * + * @method createShader + * @param {String} vertSrc source code for the vertex shader + * @param {String} fragSrc source code for the fragment shader + * @returns {p5.Shader} a shader object created from the provided + * vertex and fragment shaders. * * @example - *
      + *
      * + * + * // the vertex shader is called for each vertex + * let vs = ` + * precision highp float; + * uniform mat4 uModelViewMatrix; + * uniform mat4 uProjectionMatrix; + * + * attribute vec3 aPosition; + * attribute vec2 aTexCoord; + * varying vec2 vTexCoord; + * + * void main() { + * vTexCoord = aTexCoord; + * vec4 positionVec4 = vec4(aPosition, 1.0); + * gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; + * } + * `; + * + * + * // the fragment shader is called for each pixel + * let fs = ` + * precision highp float; + * uniform vec2 p; + * uniform float r; + * const int I = 500; + * varying vec2 vTexCoord; + * void main() { + * vec2 c = p + gl_FragCoord.xy * 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(); - * describe('sphere with coral color under white light'); + * + * // 'p' is the center point of the Mandelbrot image + * mandel.setUniform('p', [-0.74364388703, 0.13182590421]); + * describe('zooming Mandelbrot set. a colorful, infinitely detailed fractal.'); * } + * * function draw() { - * background(100); - * ambientLight(255); // white light - * ambientMaterial(255, 127, 80); // coral material - * sphere(40); + * // 'r' is the size of the image in Mandelbrot-space + * mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000)))); + * plane(width, height); * } * *
      + * * @alt - * sphere with coral color under white light - */ - /** - * @method ambientLight - * @param {Number} gray number specifying value between - * white and black - * @param {Number} [alpha] - * @chainable - */ - /** - * @method ambientLight - * @param {String} value a color string - * @chainable - */ - /** - * @method ambientLight - * @param {Number[]} values an array containing the red,green,blue & - * and alpha components of the color - * @chainable - */ - /** - * @method ambientLight - * @param {p5.Color} color color as a p5.Color - * @chainable + * zooming Mandelbrot set. a colorful, infinitely detailed fractal. */ - - _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; + _main.default.prototype.createShader = function (vertSrc, fragSrc) { + _main.default._validateParameters('createShader', arguments); + return new _main.default.Shader(this._renderer, vertSrc, fragSrc); }; /** - * Sets the color of the specular highlight of a non-ambient light - * (i.e. all lights except ambientLight()). - * - * specularColor() affects only the lights which are created after - * it in the code. + * Creates a new p5.Shader using only a fragment shader, as a convenience method for creating image effects. + * It's like createShader() but with a default vertex shader included. * - * This function is used in combination with - * specularMaterial(). - * If a geometry does not use specularMaterial(), this function - * will have no effect. + * createFilterShader() is intended to be used along with filter() for filtering the contents of a canvas. + * A filter shader will not be applied to any geometries. * - * The default color is white (255, 255, 255), which is used if - * specularColor() is not explicitly called. + * The fragment shader receives some uniforms: + * - `sampler2D tex0`, which contains the canvas contents as a texture +* - `vec2 canvasSize`, which is the p5 width and height of the canvas (not including pixel density) + * - `vec2 texelSize`, which is the size of a physical pixel including pixel density (`1.0/(width*density)`, `1.0/(height*density)`) * - * Note: specularColor is equivalent to the Processing function - * lightSpecular. + * For more info about filters and shaders, see Adam Ferriss' repo of shader examples + * or the introduction to shaders page. * - * @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 + * @method createFilterShader + * @param {String} fragSrc source code for the fragment shader + * @returns {p5.Shader} a shader object created from the provided + * fragment shader. * @example - *
      + *
      * - * let setRedSpecularColor = true; - * * function setup() { + * let fragSrc = `precision highp float; + * void main() { + * gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0); + * }`; + * * createCanvas(100, 100, WEBGL); - * noStroke(); - * describe( - * 'Sphere with specular highlight. Clicking the mouse toggles the specular highlight color between red and the default white.' - * ); + * let s = createFilterShader(fragSrc); + * filter(s); + * describe('a yellow canvas'); * } + * + *
      * - * function draw() { - * background(0); - * - * ambientLight(60); - * - * // add a point light to showcase specular color - * // -- use mouse location to position the light - * let lightPosX = mouseX - width / 2; - * let lightPosY = mouseY - height / 2; - * // -- set the light's specular color - * if (setRedSpecularColor) { - * specularColor(255, 0, 0); // red specular highlight - * } - * // -- create the light - * pointLight(200, 200, 200, lightPosX, lightPosY, 50); // white light - * - * // use specular material with high shininess - * specularMaterial(150); - * shininess(50); - * - * sphere(30, 64, 64); + *
      + * + * let img, s; + * function preload() { + * img = loadImage('assets/bricks.jpg'); * } + * function setup() { + * let fragSrc = `precision highp float; + * + * // x,y coordinates, given from the vertex shader + * varying vec2 vTexCoord; + * + * // the canvas contents, given from filter() + * uniform sampler2D tex0; + * // other useful information from the canvas + * uniform vec2 texelSize; + * uniform vec2 canvasSize; + * // a custom variable from this sketch + * uniform float darkness; + * + * void main() { + * // get the color at current pixel + * vec4 color = texture2D(tex0, vTexCoord); + * // set the output color + * color.b = 1.0; + * color *= darkness; + * gl_FragColor = vec4(color.rgb, 1.0); + * }`; * - * function mouseClicked() { - * setRedSpecularColor = !setRedSpecularColor; + * createCanvas(100, 100, WEBGL); + * s = createFilterShader(fragSrc); + * } + * function draw() { + * image(img, -50, -50); + * s.setUniform('darkness', 0.5); + * filter(s); + * describe('a image of bricks tinted dark blue'); * } * *
      - * - * @alt - * Sphere with specular highlight. Clicking the mouse toggles the - * specular highlight color between red and the default white. */ + _main.default.prototype.createFilterShader = function (fragSrc) { + _main.default._validateParameters('createFilterShader', arguments); + var defaultVertV1 = '\n uniform mat4 uModelViewMatrix;\n uniform mat4 uProjectionMatrix;\n\n attribute vec3 aPosition;\n // texcoords only come from p5 to vertex shader\n // so pass texcoords on to the fragment shader in a varying variable\n attribute vec2 aTexCoord;\n varying vec2 vTexCoord;\n\n void main() {\n // transferring texcoords for the frag shader\n vTexCoord = aTexCoord;\n\n // copy position with a fourth coordinate for projection (1.0 is normal)\n vec4 positionVec4 = vec4(aPosition, 1.0);\n\n // project to 3D space\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n }\n '; + var defaultVertV2 = '#version 300 es\n uniform mat4 uModelViewMatrix;\n uniform mat4 uProjectionMatrix;\n\n in vec3 aPosition;\n in vec2 aTexCoord;\n out vec2 vTexCoord;\n\n void main() {\n // transferring texcoords for the frag shader\n vTexCoord = aTexCoord;\n\n // copy position with a fourth coordinate for projection (1.0 is normal)\n vec4 positionVec4 = vec4(aPosition, 1.0);\n\n // project to 3D space\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n }\n '; + var vertSrc = fragSrc.includes('#version 300 es') ? defaultVertV2 : defaultVertV1; + var shader = new _main.default.Shader(this._renderer, vertSrc, fragSrc); + if (this._renderer.GL) { + shader.ensureCompiledOnContext(this); + } else { + shader.ensureCompiledOnContext(this._renderer.getFilterGraphicsLayer()); + } + return shader; + }; /** - * @method specularColor - * @param {Number} gray number specifying value between - * white and black + * Sets the p5.Shader object to + * be used to render subsequent shapes. + * + * Shaders can alter the positioning of shapes drawn with them. + * To ensure consistency in rendering, it's recommended to use the vertex shader in the createShader example. + * + * Custom shaders can be created using the + * createShader() and + * loadShader() functions. + * + * Use resetShader() to + * restore the default shaders. + * + * Note, shaders can only be used in WEBGL mode. + * + * @method shader * @chainable - */ - /** - * @method specularColor - * @param {String} value color as a CSS string - * @chainable - */ - /** - * @method specularColor - * @param {Number[]} values color as an array containing the - * red, green, and blue components - * @chainable - */ - /** - * @method specularColor - * @param {p5.Color} color color as a p5.Color - * @chainable - */ - _main.default.prototype.specularColor = function (v1, v2, v3) { - this._assert3d('specularColor'); - _main.default._validateParameters('specularColor', arguments); - var color = this.color.apply(this, arguments); - this._renderer.specularColors = [ - color._array[0], - color._array[1], - color._array[2] - ]; - return this; - }; - /** - * Creates a directional light with the given color and direction. - * - * Directional light comes from one direction. - * The direction is specified as numbers inclusively between -1 and 1. - * For example, setting the direction as (0, -1, 0) will cause the - * geometry to be lit from below (since the light will be facing - * directly upwards). Similarly, setting the direction as (1, 0, 0) - * will cause the geometry to be lit from the left (since the light - * will be facing directly rightwards). + * @param {p5.Shader} s the p5.Shader object + * to use for rendering shapes. * - * Directional lights do not have a specific point of origin, and - * therefore cannot be positioned closer or farther away from a geometry. + * @example + *
      + * + * // Click within the image to toggle + * // the shader used by the quad shape + * // Note: for an alternative approach to the same example, + * // involving changing uniforms please refer to: + * // https://p5js.org/reference/#/p5.Shader/setUniform * - * A maximum of **5** directional lights can be active at once. + * let redGreen; + * let orangeBlue; + * let showRedGreen = false; * - * Note: lights need to be called (whether directly or indirectly) - * within draw() to remain persistent in a looping program. - * Placing them in setup() will cause them to only have an effect - * the first time through the loop. + * 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'); + * } * - * @method directionalLight - * @param {Number} v1 red or hue value relative to the current - * color range - * @param {Number} v2 green or saturation value relative to the - * current color range - * @param {Number} v3 blue or brightness value relative to the - * current color range - * @param {Number} x x component of direction (inclusive range of -1 to 1) - * @param {Number} y y component of direction (inclusive range of -1 to 1) - * @param {Number} z z component of direction (inclusive range of -1 to 1) - * @chainable - * @example - *
      - * * function setup() { * createCanvas(100, 100, WEBGL); + * + * // initialize the colors for redGreen shader + * shader(redGreen); + * redGreen.setUniform('colorCenter', [1.0, 0.0, 0.0]); + * redGreen.setUniform('colorBackground', [0.0, 1.0, 0.0]); + * + * // initialize the colors for orangeBlue shader + * shader(orangeBlue); + * orangeBlue.setUniform('colorCenter', [1.0, 0.5, 0.0]); + * orangeBlue.setUniform('colorBackground', [0.226, 0.0, 0.615]); + * + * noStroke(); + * * describe( - * 'scene with sphere and directional light. The direction of the light is controlled with the mouse position.' + * 'canvas toggles between a circular gradient of orange and blue vertically. and a circular gradient of red and green moving horizontally when mouse is clicked/pressed.' * ); * } + * * function draw() { - * 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); + * // update the offset values for each shader, + * // moving orangeBlue in vertical and redGreen + * // in horizontal direction + * orangeBlue.setUniform('offset', [0, sin(millis() / 2000) + 1]); + * redGreen.setUniform('offset', [sin(millis() / 2000), 1]); + * + * if (showRedGreen === true) { + * shader(redGreen); + * } else { + * shader(orangeBlue); + * } + * quad(-1, -1, 1, -1, 1, 1, -1, 1); + * } + * + * function mouseClicked() { + * showRedGreen = !showRedGreen; * } * *
      * * @alt - * scene with sphere and directional light. The direction of - * the light is controlled with the mouse position. - */ - /** - * @method directionalLight - * @param {Number} v1 - * @param {Number} v2 - * @param {Number} v3 - * @param {p5.Vector} direction direction of light as a - * p5.Vector - * @chainable - */ - /** - * @method directionalLight - * @param {p5.Color|Number[]|String} color color as a p5.Color, - * as an array, or as a CSS string - * @param {Number} x - * @param {Number} y - * @param {Number} z - * @chainable - */ - /** - * @method directionalLight - * @param {p5.Color|Number[]|String} color - * @param {p5.Vector} direction - * @chainable + * 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.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; + _main.default.prototype.shader = function (s) { + this._assert3d('shader'); + _main.default._validateParameters('shader', arguments); + s.ensureCompiledOnContext(this); + if (s.isStrokeShader()) { + this._renderer.userStrokeShader = s; } else { - color = this.color(v1, v2, v3); + this._renderer.userFillShader = s; + this._renderer._useNormalMaterial = false; } - var _x, - _y, - _z; - var v = arguments[arguments.length - 1]; - if (typeof v === 'number') { - _x = arguments[arguments.length - 3]; - _y = arguments[arguments.length - 2]; - _z = arguments[arguments.length - 1]; - } else { - _x = v.x; - _y = v.y; - _z = v.z; - } // normalize direction - - var l = Math.sqrt(_x * _x + _y * _y + _z * _z); - this._renderer.directionalLightDirections.push(_x / l, _y / l, _z / l); - this._renderer.directionalLightDiffuseColors.push(color._array[0], color._array[1], color._array[2]); - Array.prototype.push.apply(this._renderer.directionalLightSpecularColors, this._renderer.specularColors); - this._renderer._enableLighting = true; return this; }; /** - * Creates a point light with the given color and position. - * - * A point light emits light from a single point in all directions. - * Because the light is emitted from a specific point (position), - * it has a different effect when it is positioned farther vs. nearer - * an object. - * - * A maximum of **5** point lights can be active at once. - * - * Note: lights need to be called (whether directly or indirectly) - * within draw() to remain persistent in a looping program. - * Placing them in setup() will cause them to only have an effect - * the first time through the loop. + * Restores the default shaders. Code that runs after resetShader() + * will not be affected by the shader previously set by + * shader() * - * @method pointLight - * @param {Number} v1 red or hue value relative to the current - * color range - * @param {Number} v2 green or saturation value relative to the - * current color range - * @param {Number} v3 blue or brightness value relative to the - * current color range - * @param {Number} x x component of position - * @param {Number} y y component of position - * @param {Number} z z component of position + * @method resetShader * @chainable * @example *
      * + * // This variable will hold our shader object + * let shaderProgram; + * + * // This variable will hold our vertex shader source code + * let vertSrc = ` + * attribute vec3 aPosition; + * attribute vec2 aTexCoord; + * uniform mat4 uProjectionMatrix; + * uniform mat4 uModelViewMatrix; + * varying vec2 vTexCoord; + * + * void main() { + * vTexCoord = aTexCoord; + * vec4 position = vec4(aPosition, 1.0); + * gl_Position = uProjectionMatrix * uModelViewMatrix * position; + * } + * `; + * + * // This variable will hold our fragment shader source code + * let fragSrc = ` + * precision mediump float; + * + * varying vec2 vTexCoord; + * + * void main() { + * vec2 uv = vTexCoord; + * vec3 color = vec3(uv.x, uv.y, min(uv.x + uv.y, 1.0)); + * gl_FragColor = vec4(color, 1.0); + * } + * `; + * * function setup() { + * // Shaders require WEBGL mode to work * createCanvas(100, 100, WEBGL); + * + * // Create our shader + * shaderProgram = createShader(vertSrc, fragSrc); + * * describe( - * 'scene with sphere and point light. The position of the light is controlled with the mouse position.' + * 'Two rotating cubes. The left one is painted using a custom (user-defined) shader, while the right one is painted using the default fill shader.' * ); * } + * * function draw() { - * 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); + * // Clear the scene + * background(200); + * + * // Draw a box using our shader + * // shader() sets the active shader with our shader + * shader(shaderProgram); + * push(); + * translate(-width / 4, 0, 0); + * rotateX(millis() * 0.00025); + * rotateY(millis() * 0.0005); + * box(width / 4); + * pop(); + * + * // Draw a box using the default fill shader + * // resetShader() restores the default fill shader + * resetShader(); + * fill(255, 0, 0); + * push(); + * translate(width / 4, 0, 0); + * rotateX(millis() * 0.00025); + * rotateY(millis() * 0.0005); + * box(width / 4); + * pop(); * } * *
      - * * @alt - * scene with sphere and point light. The position of - * the light is controlled with the mouse position. - */ - /** - * @method pointLight - * @param {Number} v1 - * @param {Number} v2 - * @param {Number} v3 - * @param {p5.Vector} position of light as a p5.Vector - * @chainable - */ - /** - * @method pointLight - * @param {p5.Color|Number[]|String} color color as a p5.Color, - * as an array, or as a CSS string - * @param {Number} x - * @param {Number} y - * @param {Number} z - * @chainable - */ - /** - * @method pointLight - * @param {p5.Color|Number[]|String} color - * @param {p5.Vector} position - * @chainable + * Two rotating cubes. The left one is painted using a custom (user-defined) shader, + * while the right one is painted using the default fill shader. */ - _main.default.prototype.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; + _main.default.prototype.resetShader = function () { + this._renderer.userFillShader = this._renderer.userStrokeShader = null; return this; }; /** - * Places an ambient and directional light in the scene. - * The lights are set to ambientLight(128, 128, 128) and - * directionalLight(128, 128, 128, 0, 0, -1). + * Sets the texture that will be used to render subsequent shapes. * - * Note: lights need to be called (whether directly or indirectly) - * within draw() to remain persistent in a looping program. - * Placing them in setup() will cause them to only have an effect - * the first time through the loop. + * A texture is like a "skin" that wraps around a 3D geometry. Currently + * supported textures are images, video, and offscreen renders. * - * @method lights + * To texture a geometry created with beginShape(), + * you will need to specify uv coordinates in vertex(). + * + * Note, texture() can only be used in WEBGL mode. + * + * You can view more materials in this + * example. + * + * @method texture + * @param {p5.Image|p5.MediaElement|p5.Graphics|p5.Texture|p5.Framebuffer|p5.FramebufferTexture} tex image to use as texture * @chainable * @example *
      * + * let img; + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * * function setup() { * createCanvas(100, 100, WEBGL); - * describe('the light is partially ambient and partially directional'); + * describe('spinning cube with a texture from an image'); * } + * * function draw() { * background(0); - * lights(); - * rotateX(millis() / 1000); - * rotateY(millis() / 1000); - * rotateZ(millis() / 1000); - * box(); + * rotateZ(frameCount * 0.01); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * //pass image as texture + * texture(img); + * box(width / 2); * } * *
      - * * @alt - * the light is partially ambient and partially directional - */ - _main.default.prototype.lights = function () { - this._assert3d('lights'); // only restore the colorMode to default if it is not in default already - if (this._colorMode === constants.RGB) { - this.ambientLight(128, 128, 128); - this.directionalLight(128, 128, 128, 0, 0, - 1); - } else { - var maxBright = this._colorMaxes[this._colorMode][2]; - this.ambientLight(0, 0, maxBright); - this.directionalLight(0, 0, maxBright, 0, 0, - 1); - } - return this; - }; - /** - * Sets the falloff rate for pointLight() - * and spotLight(). - * - * lightFalloff() affects only the lights which are created after it - * in the code. + * spinning cube with a texture from an image * - * The `constant`, `linear`, an `quadratic` parameters are used to calculate falloff as follows: + * @example + *
      + * + * let pg; * - * d = distance from light position to vertex position + * function setup() { + * createCanvas(100, 100, WEBGL); + * pg = createGraphics(200, 200); + * pg.textSize(75); + * describe('plane with a texture from an image created by createGraphics()'); + * } * - * falloff = 1 / (CONSTANT + d \* LINEAR + (d \* d) \* QUADRATIC) + * function draw() { + * background(0); + * pg.background(255); + * pg.text('hello!', 0, 100); + * //pass image as texture + * texture(pg); + * rotateX(0.5); + * noStroke(); + * plane(50); + * } + * + *
      + * @alt + * plane with a texture from an image created by createGraphics() * - * @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 *
      * + * let vid; + * function preload() { + * vid = createVideo('assets/fingers.mov'); + * vid.hide(); + * } * function setup() { * createCanvas(100, 100, WEBGL); - * noStroke(); - * describe( - * 'Two spheres with different falloff values show different intensity of light' - * ); + * describe('rectangle with video as texture'); * } + * * function draw() { - * ortho(); * background(0); + * //pass video frame as texture + * texture(vid); + * rect(-40, -40, 80, 80); + * } * - * let locX = mouseX - width / 2; - * let locY = mouseY - height / 2; - * locX /= 2; // half scale + * function mousePressed() { + * vid.loop(); + * } + * + *
      * - * lightFalloff(1, 0, 0); - * push(); - * translate(-25, 0, 0); - * pointLight(250, 250, 250, locX - 25, locY, 50); - * sphere(20); - * pop(); + * @alt + * rectangle with video as texture * - * lightFalloff(0.97, 0.03, 0); - * push(); - * translate(25, 0, 0); - * pointLight(250, 250, 250, locX + 25, locY, 50); - * sphere(20); - * pop(); + * @example + *
      + * + * let img; + * + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * describe('quad with a texture, mapped using normalized coordinates'); + * } + * + * function draw() { + * background(0); + * texture(img); + * textureMode(NORMAL); + * beginShape(); + * vertex(-40, -40, 0, 0); + * vertex(40, -40, 1, 0); + * vertex(40, 40, 1, 1); + * vertex(-40, 40, 0, 1); + * endShape(); * } * *
      - * * @alt - * Two spheres with different falloff values show different intensity of light + * quad with a texture, mapped using normalized coordinates */ - _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.'); + _main.default.prototype.texture = function (tex) { + this._assert3d('texture'); + _main.default._validateParameters('texture', arguments); + if (tex.gifProperties) { + tex._animateGif(this); } - this._renderer.constantAttenuation = constantAttenuation; - this._renderer.linearAttenuation = linearAttenuation; - this._renderer.quadraticAttenuation = quadraticAttenuation; + this._renderer.drawMode = constants.TEXTURE; + this._renderer._useNormalMaterial = false; + this._renderer._tex = tex; + this._renderer._setProperty('_doFill', true); return this; }; /** - * Creates a spot light with the given color, position, - * light direction, angle, and concentration. + * 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. * - * Like a pointLight(), a spotLight() - * emits light from a specific point (position). It has a different effect - * when it is positioned farther vs. nearer an object. + * With IMAGE, if an image is 100×200 pixels, mapping the image onto the entire + * size of a quad would require the points (0,0) (100, 0) (100,200) (0,200). + * The same mapping in NORMAL is (0,0) (1,0) (1,1) (0,1). + * @method textureMode + * @param {Constant} mode either IMAGE or NORMAL + * @example + *
      + * + * let img; * - * However, unlike a pointLight(), the light is emitted in **one direction** - * along a conical shape. The shape of the cone can be controlled using - * the `angle` and `concentration` parameters. + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } * - * The `angle` parameter is used to - * determine the radius of the cone. And the `concentration` - * parameter is used to focus the light towards the center of - * the cone. Both parameters are optional, however if you want - * to specify `concentration`, you must also specify `angle`. - * The minimum concentration value is 1. + * function setup() { + * createCanvas(100, 100, WEBGL); + * describe('quad with a texture, mapped using normalized coordinates'); + * } * - * A maximum of **5** spot lights can be active at once. + * 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(); + * } + * + *
      + * @alt + * quad with a texture, mapped using normalized coordinates * - * Note: lights need to be called (whether directly or indirectly) - * within draw() to remain persistent in a looping program. - * Placing them in setup() will cause them to only have an effect - * the first time through the loop. + * @example + *
      + * + * let img; * - * @method spotLight - * @param {Number} v1 red or hue value relative to the current color range - * @param {Number} v2 green or saturation value relative to the current color range - * @param {Number} v3 blue or brightness value relative to the current color range - * @param {Number} x x component of position - * @param {Number} y y component of position - * @param {Number} z z component of position - * @param {Number} rx x component of light direction (inclusive range of -1 to 1) - * @param {Number} ry y component of light direction (inclusive range of -1 to 1) - * @param {Number} rz z component of light direction (inclusive range of -1 to 1) - * @param {Number} [angle] angle of cone. Defaults to PI/3 - * @param {Number} [concentration] concentration of cone. Defaults to 100 - * @chainable + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * describe('quad with a texture, mapped using image coordinates'); + * } + * + * function draw() { + * texture(img); + * textureMode(IMAGE); + * 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(); + * } + * + *
      + * @alt + * quad with a texture, mapped using image coordinates + */ + _main.default.prototype.textureMode = function (mode) { + if (mode !== constants.IMAGE && mode !== constants.NORMAL) { + console.warn('You tried to set '.concat(mode, ' textureMode only supports IMAGE & NORMAL ')); + } else { + this._renderer.textureMode = mode; + } + }; + /** + * Sets the global texture wrapping mode. This controls how textures behave + * when their uv's go outside of the 0 to 1 range. There are three options: + * CLAMP, REPEAT, and MIRROR. + * + * CLAMP causes the pixels at the edge of the texture to extend to the bounds. + * REPEAT causes the texture to tile repeatedly until reaching the bounds. + * MIRROR works similarly to REPEAT but it flips the texture with every new tile. + * + * REPEAT & MIRROR are only available if the texture + * is a power of two size (128, 256, 512, 1024, etc.). + * + * This method will affect all textures in your sketch until a subsequent + * textureWrap() call is made. * + * If only one argument is provided, it will be applied to both the + * horizontal and vertical axes. + * @method textureWrap + * @param {Constant} wrapX either CLAMP, REPEAT, or MIRROR + * @param {Constant} [wrapY] either CLAMP, REPEAT, or MIRROR * @example *
      * + * let img; + * function preload() { + * img = loadImage('assets/rockies128.jpg'); + * } + * * function setup() { * createCanvas(100, 100, WEBGL); - * describe( - * 'scene with sphere and spot light. The position of the light is controlled with the mouse position.' - * ); + * textureWrap(MIRROR); + * describe('an image of the rocky mountains repeated in mirrored tiles'); * } + * * 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); + * + * let dX = mouseX; + * let dY = mouseY; + * + * let u = lerp(1.0, 2.0, dX); + * let v = lerp(1.0, 2.0, dY); + * + * scale(width / 2); + * + * texture(img); + * + * beginShape(TRIANGLES); + * vertex(-1, -1, 0, 0, 0); + * vertex(1, -1, 0, u, 0); + * vertex(1, 1, 0, u, v); + * + * vertex(1, 1, 0, u, v); + * vertex(-1, 1, 0, 0, v); + * vertex(-1, -1, 0, 0, 0); + * endShape(); * } * *
      * * @alt - * scene with sphere and spot light. The position of - * the light is controlled with the mouse position. - */ - /** - * @method spotLight - * @param {p5.Color|Number[]|String} color color as a p5.Color, - * as an array, or as a CSS string - * @param {p5.Vector} position position of light as a p5.Vector - * @param {p5.Vector} direction direction of light as a p5.Vector - * @param {Number} [angle] - * @param {Number} [concentration] - */ - /** - * @method spotLight - * @param {Number} v1 - * @param {Number} v2 - * @param {Number} v3 - * @param {p5.Vector} position - * @param {p5.Vector} direction - * @param {Number} [angle] - * @param {Number} [concentration] - */ - /** - * @method spotLight - * @param {p5.Color|Number[]|String} color - * @param {Number} x - * @param {Number} y - * @param {Number} z - * @param {p5.Vector} direction - * @param {Number} [angle] - * @param {Number} [concentration] - */ - /** - * @method spotLight - * @param {p5.Color|Number[]|String} color - * @param {p5.Vector} position - * @param {Number} rx - * @param {Number} ry - * @param {Number} rz - * @param {Number} [angle] - * @param {Number} [concentration] - */ - /** - * @method spotLight - * @param {Number} v1 - * @param {Number} v2 - * @param {Number} v3 - * @param {Number} x - * @param {Number} y - * @param {Number} z - * @param {p5.Vector} direction - * @param {Number} [angle] - * @param {Number} [concentration] - */ - /** - * @method spotLight - * @param {Number} v1 - * @param {Number} v2 - * @param {Number} v3 - * @param {p5.Vector} position - * @param {Number} rx - * @param {Number} ry - * @param {Number} rz - * @param {Number} [angle] - * @param {Number} [concentration] - */ - /** - * @method spotLight - * @param {p5.Color|Number[]|String} color - * @param {Number} x - * @param {Number} y - * @param {Number} z - * @param {Number} rx - * @param {Number} ry - * @param {Number} rz - * @param {Number} [angle] - * @param {Number} [concentration] + * an image of the rocky mountains repeated in mirrored tiles */ - _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; + _main.default.prototype.textureWrap = function (wrapX) { + var wrapY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : wrapX; + this._renderer.textureWrapX = wrapX; + this._renderer.textureWrapY = wrapY; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = this._renderer.textures.values() [Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var texture = _step.value; + texture.setWrapMode(wrapX, wrapY); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); } - 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); + } finally { + if (_didIteratorError) { + throw _iteratorError; } - break; - case 4: - color = v1; - position = v2; - direction = v3; - angle = x; - break; - case 3: - color = v1; - position = v2; - direction = v3; - break; - default: - console.warn('Sorry, input for spotlight() is not in prescribed format. Too '.concat(length < 3 ? 'few' : 'many', ' arguments were provided')); - return this; - } - this._renderer.spotLightDiffuseColors.push(color._array[0], color._array[1], color._array[2]); - Array.prototype.push.apply(this._renderer.spotLightSpecularColors, this._renderer.specularColors); - this._renderer.spotLightPositions.push(position.x, position.y, position.z); - direction.normalize(); - this._renderer.spotLightDirections.push(direction.x, direction.y, direction.z); - if (angle === undefined) { - angle = Math.PI / 3; - } - if (concentration !== undefined && concentration < 1) { - concentration = 1; - console.warn('Value of concentration needs to be greater than 1. Setting it to 1'); - } else if (concentration === undefined) { - concentration = 100; + } } - angle = this._renderer._pInst._toRadians(angle); - this._renderer.spotLightAngle.push(Math.cos(angle)); - this._renderer.spotLightConc.push(concentration); - this._renderer._enableLighting = true; - return this; }; /** - * Removes all lights present in a sketch. + * Sets the current material as a normal material. * - * All subsequent geometry is rendered without lighting (until a new - * light is created with a call to one of the lighting functions - * (lights(), - * ambientLight(), - * directionalLight(), - * pointLight(), - * spotLight()). + * A normal material is not affected by light. It is often used as + * a placeholder material when debugging. * - * @method noLights + * Surfaces facing the X-axis become red, those facing the Y-axis + * become green, and those facing the Z-axis become blue. + * + * You can view more materials in this + * example. + * + * @method normalMaterial * @chainable * @example *
      * * function setup() { * createCanvas(100, 100, WEBGL); - * describe( - * 'Three white spheres. Each appears as a different color due to lighting.' - * ); + * describe('Sphere with normal material'); * } + * * function draw() { * background(200); - * noStroke(); - * - * ambientLight(255, 0, 0); - * translate(-30, 0, 0); - * ambientMaterial(255); - * sphere(13); - * - * noLights(); - * translate(30, 0, 0); - * ambientMaterial(255); - * sphere(13); - * - * ambientLight(0, 255, 0); - * translate(30, 0, 0); - * ambientMaterial(255); - * sphere(13); + * normalMaterial(); + * sphere(40); * } * *
      - * * @alt - * Three white spheres. Each appears as a different - * color due to lighting. + * Sphere with normal material */ - _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 = [ + _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.directionalLightDirections.length = 0; - this._renderer.directionalLightDiffuseColors.length = 0; - this._renderer.directionalLightSpecularColors.length = 0; - this._renderer.pointLightPositions.length = 0; - this._renderer.pointLightDiffuseColors.length = 0; - this._renderer.pointLightSpecularColors.length = 0; - this._renderer.spotLightPositions.length = 0; - this._renderer.spotLightDirections.length = 0; - this._renderer.spotLightDiffuseColors.length = 0; - this._renderer.spotLightSpecularColors.length = 0; - this._renderer.spotLightAngle.length = 0; - this._renderer.spotLightConc.length = 0; - this._renderer.constantAttenuation = 1; - this._renderer.linearAttenuation = 0; - this._renderer.quadraticAttenuation = 0; - this._renderer._useShininess = 1; + this._renderer._setProperty('_doFill', true); + this.noStroke(); return this; }; - var _default = _main.default; - exports.default = _default; - }, - { - '../core/constants': 278, - '../core/main': 290, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 - } - ], - 336: [ - function (_dereq_, module, exports) { - 'use strict'; - _dereq_('core-js/modules/es.array.concat'); - _dereq_('core-js/modules/es.array.index-of'); - _dereq_('core-js/modules/es.array.slice'); - _dereq_('core-js/modules/es.array.splice'); - _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.regexp.exec'); - _dereq_('core-js/modules/es.string.match'); - _dereq_('core-js/modules/es.string.split'); - _dereq_('core-js/modules/es.string.trim'); - _dereq_('core-js/modules/es.array.concat'); - _dereq_('core-js/modules/es.array.index-of'); - _dereq_('core-js/modules/es.array.slice'); - _dereq_('core-js/modules/es.array.splice'); - _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.regexp.exec'); - _dereq_('core-js/modules/es.string.match'); - _dereq_('core-js/modules/es.string.split'); - _dereq_('core-js/modules/es.string.trim'); - Object.defineProperty(exports, '__esModule', { - value: true - }); - exports.default = void 0; - var _main = _interopRequireDefault(_dereq_('../core/main')); - _dereq_('./p5.Geometry'); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: - obj - }; - } /** - * @module Shape - * @submodule 3D Models - * @for p5 - * @requires core - * @requires p5.Geometry - */ /** - * Load a 3d model from an OBJ or STL file. - * - * loadModel() should be placed inside of preload(). - * This allows the model to load fully before the rest of your code is run. + * Sets the ambient color of the material. * - * One of the limitations of the OBJ and STL format is that it doesn't have a built-in - * sense of scale. This means that models exported from different programs might - * be very different sizes. If your model isn't displaying, try calling - * loadModel() with the normalized parameter set to true. This will resize the - * model to a scale appropriate for p5. You can also make additional changes to - * the final size of your model with the scale() function. + * The ambientMaterial() color represents the components + * of the **ambientLight()** color that the object reflects. * - * Also, the support for colored STL files is not present. STL files with color will be - * rendered without color properties. + * Consider an ambientMaterial() with the color yellow (255, 255, 0). + * If the ambientLight() emits the color white (255, 255, 255), then the object + * will appear yellow as it will reflect the red and green components + * of the light. If the ambientLight() emits the color red (255, 0, 0), then + * the object will appear red as it will reflect the red component + * of the light. If the ambientLight() emits the color blue (0, 0, 255), + * then the object will appear black, as there is no component of + * the light that it can reflect. * - * @method loadModel - * @param {String} path Path of the model to be loaded - * @param {Boolean} normalize If true, scale the model to a - * standardized size when loading - * @param {function(p5.Geometry)} [successCallback] Function to be called - * once the model is loaded. Will be passed - * the 3D model object. - * @param {function(Event)} [failureCallback] called with event error if - * the model fails to load. - * @param {String} [fileType] The file extension of the model - * (.stl, .obj). - * @return {p5.Geometry} the p5.Geometry object + * You can view more materials in this + * example. * + * @method ambientMaterial + * @param {Number} v1 red or hue value relative to the current + * color range + * @param {Number} v2 green or saturation value relative to the + * current color range + * @param {Number} v3 blue or brightness value relative to the + * current color range + * @chainable * @example *
      * - * //draw a spinning octahedron - * let octahedron; - * - * function preload() { - * octahedron = loadModel('assets/octahedron.obj'); + * function setup() { + * createCanvas(100, 100, WEBGL); + * describe('sphere reflecting red, blue, and green light'); + * } + * function draw() { + * background(0); + * noStroke(); + * ambientLight(255); + * ambientMaterial(70, 130, 230); + * sphere(40); * } + * + *
      + * @alt + * sphere reflecting red, blue, and green light * + * @example + *
      + * + * // ambientLight is both red and blue (magenta), + * // so object only reflects it's red and blue components * function setup() { * createCanvas(100, 100, WEBGL); - * describe('Vertically rotating 3-d octahedron.'); + * describe('box reflecting only red and blue light'); * } - * * function draw() { - * background(200); - * rotateX(frameCount * 0.01); - * rotateY(frameCount * 0.01); - * model(octahedron); + * background(70); + * ambientLight(255, 0, 255); // magenta light + * ambientMaterial(255); // white material + * box(30); * } * *
      - * * @alt - * Vertically rotating 3-d octahedron. + * box reflecting only red and blue light * * @example *
      * - * //draw a spinning teapot - * let teapot; - * - * function preload() { - * // Load model with normalise parameter set to true - * teapot = loadModel('assets/teapot.obj', true); + * // ambientLight is green. Since object does not contain + * // green, it does not reflect any light + * function setup() { + * createCanvas(100, 100, WEBGL); + * describe('box reflecting no light'); + * } + * function draw() { + * background(70); + * ambientLight(0, 255, 0); // green light + * ambientMaterial(255, 0, 255); // magenta material + * box(30); * } + * + *
      + * @alt + * box reflecting no light + */ + /** + * @method ambientMaterial + * @param {Number} gray number specifying value between + * white and black + * @chainable + */ + /** + * @method ambientMaterial + * @param {p5.Color|Number[]|String} color + * color as a p5.Color, + * as an array, or as a CSS string + * @chainable + */ + _main.default.prototype.ambientMaterial = function (v1, v2, v3) { + this._assert3d('ambientMaterial'); + _main.default._validateParameters('ambientMaterial', arguments); + var color = _main.default.prototype.color.apply(this, arguments); + this._renderer._hasSetAmbient = true; + this._renderer.curAmbientColor = color._array; + this._renderer._useNormalMaterial = false; + this._renderer._enableLighting = true; + this._renderer._setProperty('_doFill', true); + return this; + }; + /** + * Sets the emissive color of the material. + * + * An emissive material will display the emissive color at + * full strength regardless of lighting. This can give the + * appearance that the object is glowing. + * + * Note, "emissive" is a misnomer in the sense that the material + * does not actually emit light that will affect surrounding objects. + * + * You can view more materials in this + * example. * + * @method emissiveMaterial + * @param {Number} v1 red or hue value relative to the current + * color range + * @param {Number} v2 green or saturation value relative to the + * current color range + * @param {Number} v3 blue or brightness value relative to the + * current color range + * @param {Number} [alpha] alpha value relative to current color + * range (default is 0-255) + * @chainable + * @example + *
      + * * function setup() { * createCanvas(100, 100, WEBGL); - * describe('Vertically rotating 3-d teapot with red, green and blue gradient.'); + * describe('sphere with green emissive material'); * } - * * 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); + * background(0); + * noStroke(); + * ambientLight(0); + * emissiveMaterial(130, 230, 0); + * sphere(40); * } * *
      * * @alt - * Vertically rotating 3-d teapot with red, green and blue gradient. + * sphere with green emissive material */ /** - * @method loadModel - * @param {String} path - * @param {function(p5.Geometry)} [successCallback] - * @param {function(Event)} [failureCallback] - * @param {String} [fileType] - * @return {p5.Geometry} the p5.Geometry object + * @method emissiveMaterial + * @param {Number} gray number specifying value between + * white and black + * @chainable */ - - _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; + /** + * @method emissiveMaterial + * @param {p5.Color|Number[]|String} color + * color as a p5.Color, + * as an array, or as a CSS string + * @chainable + */ + _main.default.prototype.emissiveMaterial = function (v1, v2, v3, a) { + this._assert3d('emissiveMaterial'); + _main.default._validateParameters('emissiveMaterial', arguments); + var color = _main.default.prototype.color.apply(this, arguments); + this._renderer.curEmissiveColor = color._array; + this._renderer._useEmissiveMaterial = true; + this._renderer._useNormalMaterial = false; + this._renderer._enableLighting = true; + return this; }; /** - * Parse OBJ lines into model. For reference, this is what a simple model of a - * square might look like: + * Sets the specular color of the material. * - * 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 + * A specular material is reflective (shiny). The shininess can be + * controlled by the shininess() function. * - * f 4 3 2 1 - */ - function parseObj(model, lines) { - // OBJ allows a face to specify an index for a vertex (in the above example), - // but it also allows you to specify a custom combination of vertex, UV - // coordinate, and vertex normal. So, "3/4/3" would mean, "use vertex 3 with - // UV coordinate 4 and vertex normal 3". In WebGL, every vertex with different - // parameters must be a different vertex, so loadedVerts is used to - // temporarily store the parsed vertices, normals, etc., and indexedVerts is - // used to map a specific combination (keyed on, for example, the string - // "3/4/3"), to the actual index of the newly created vertex in the final - // object. - var loadedVerts = { - v: [ - ], - vt: [ - ], - vn: [ - ] - }; - var indexedVerts = { - }; - for (var line = 0; line < lines.length; ++line) { - // Each line is a separate object (vertex, face, vertex normal, etc) - // For each line, split it into tokens on whitespace. The first token - // describes the type. - var tokens = lines[line].trim().split(/\b\s+/); - if (tokens.length > 0) { - if (tokens[0] === 'v' || tokens[0] === 'vn') { - // Check if this line describes a vertex or vertex normal. - // It will have three numeric parameters. - var vertex = new _main.default.Vector(parseFloat(tokens[1]), parseFloat(tokens[2]), parseFloat(tokens[3])); - loadedVerts[tokens[0]].push(vertex); - } else if (tokens[0] === 'vt') { - // Check if this line describes a texture coordinate. - // It will have two numeric parameters U and V (W is omitted). - // Because of WebGL texture coordinates rendering behaviour, the V - // coordinate is inversed. - var texVertex = [ - parseFloat(tokens[1]), - 1 - parseFloat(tokens[2]) - ]; - loadedVerts[tokens[0]].push(texVertex); - } else if (tokens[0] === 'f') { - // Check if this line describes a face. - // OBJ faces can have more than three points. Triangulate points. - for (var tri = 3; tri < tokens.length; ++tri) { - var face = [ - ]; - var vertexTokens = [ - 1, - tri - 1, - tri - ]; - for (var tokenInd = 0; tokenInd < vertexTokens.length; ++tokenInd) { - // Now, convert the given token into an index - var vertString = tokens[vertexTokens[tokenInd]]; - var vertIndex = 0; // TODO: Faces can technically use negative numbers to refer to the - // previous nth vertex. I haven't seen this used in practice, but - // it might be good to implement this in the future. - if (indexedVerts[vertString] !== undefined) { - vertIndex = indexedVerts[vertString]; - } else { - var vertParts = vertString.split('/'); - for (var i = 0; i < vertParts.length; i++) { - vertParts[i] = parseInt(vertParts[i]) - 1; - } - vertIndex = indexedVerts[vertString] = model.vertices.length; - model.vertices.push(loadedVerts.v[vertParts[0]].copy()); - if (loadedVerts.vt[vertParts[1]]) { - model.uvs.push(loadedVerts.vt[vertParts[1]].slice()); - } else { - model.uvs.push([0, - 0]); - } - if (loadedVerts.vn[vertParts[2]]) { - model.vertexNormals.push(loadedVerts.vn[vertParts[2]].copy()); - } - } - face.push(vertIndex); - } - if (face[0] !== face[1] && face[0] !== face[2] && face[1] !== face[2]) { - model.faces.push(face); - } - } - } - } - } // If the model doesn't have normals, compute the normals - - if (model.vertexNormals.length === 0) { - model.computeNormals(); - } - return model; - } /** - * STL files can be of two types, ASCII and Binary, + * Like ambientMaterial(), + * the specularMaterial() color is the color the object will reflect + * under ambientLight(). + * However unlike ambientMaterial(), for all other types of lights + * (directionalLight(), + * pointLight(), + * spotLight()), + * a specular material will reflect the **color of the light source**. + * This is what gives it its "shiny" appearance. * - * 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 + * You can view more materials in this + * example. * - * It is done by searching keyword `solid` at the start of the file. + * @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 * - * 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`. + * @example + *
      + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * noStroke(); + * describe('torus with specular material'); + * } * - * 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 draw() { + * background(0); + * + * ambientLight(60); + * + * // add point light to showcase specular material + * let locX = mouseX - width / 2; + * let locY = mouseY - height / 2; + * pointLight(255, 255, 255, locX, locY, 50); + * + * specularMaterial(250); + * shininess(50); + * torus(30, 10, 64, 64); + * } + * + *
      + * @alt + * torus with specular material */ - - 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` + /** + * @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 */ - - 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. + /** + * @method specularMaterial + * @param {p5.Color|Number[]|String} color + * color as a p5.Color, + * as an array, or as a CSS string + * @chainable */ - - function parseBinarySTL(model, buffer) { - var reader = new DataView(buffer); // Number of faces is present following the header - var faces = reader.getUint32(80, true); - var r, - g, - b, - hasColors = false, - colors; - var defaultR, - defaultG, - defaultB; // Binary files contain 80-byte header, which is generally ignored. - for (var index = 0; index < 80 - 10; index++) { - // Check for `COLOR=` - if (reader.getUint32(index, false) === 1129270351 /*COLO*/ - && reader.getUint8(index + 4) === 82 /*'R'*/ - && reader.getUint8(index + 5) === 61 /*'='*/ - ) { - hasColors = true; - colors = [ - ]; - defaultR = reader.getUint8(index + 6) / 255; - defaultG = reader.getUint8(index + 7) / 255; - defaultB = reader.getUint8(index + 8) / 255; // To be used when color support is added - // alpha = reader.getUint8(index + 9) / 255; - } - } - var dataOffset = 84; - var faceLength = 12 * 4 + 2; // Iterate the faces - for (var face = 0; face < faces; face++) { - var start = dataOffset + face * faceLength; - var normalX = reader.getFloat32(start, true); - var normalY = reader.getFloat32(start + 4, true); - var normalZ = reader.getFloat32(start + 8, true); - if (hasColors) { - var packedColor = reader.getUint16(start + 48, true); - if ((packedColor & 32768) === 0) { - // facet has its own unique color - r = (packedColor & 31) / 31; - g = (packedColor >> 5 & 31) / 31; - b = (packedColor >> 10 & 31) / 31; - } else { - r = defaultR; - g = defaultG; - b = defaultB; - } - } - var newNormal = new _main.default.Vector(normalX, normalY, normalZ); - for (var i = 1; i <= 3; i++) { - var vertexstart = start + i * 12; - var newVertex = new _main.default.Vector(reader.getFloat32(vertexstart, true), reader.getFloat32(vertexstart + 4, true), reader.getFloat32(vertexstart + 8, true)); - model.vertices.push(newVertex); - model.vertexNormals.push(newNormal); - if (hasColors) { - colors.push(r, g, b); - } - } - model.faces.push([3 * face, - 3 * face + 1, - 3 * face + 2]); - model.uvs.push([0, - 0], [ - 0, - 0 - ], [ - 0, - 0 - ]); - } - if (hasColors) { // add support for colors here. - } - return model; - } /** - * ASCII STL file starts with `solid 'nameOfFile'` - * Then contain the normal of the face, starting with `facet normal` - * Next contain a keyword indicating the start of face vertex, `outer loop` - * Next comes the three vertex, starting with `vertex x y z` - * Vertices ends with `endloop` - * Face ends with `endfacet` - * Next face starts with `facet normal` - * The end of the file is indicated by `endsolid` - */ - - function parseASCIISTL(model, lines) { - var state = ''; - var curVertexIndex = [ - ]; - var newNormal, - newVertex; - for (var iterator = 0; iterator < lines.length; ++iterator) { - var line = lines[iterator].trim(); - var parts = line.split(' '); - for (var partsiterator = 0; partsiterator < parts.length; ++partsiterator) { - if (parts[partsiterator] === '') { - // Ignoring multiple whitespaces - parts.splice(partsiterator, 1); - } - } - if (parts.length === 0) { - // Remove newline - continue; - } - switch (state) { - case '': - // First run - if (parts[0] !== 'solid') { - // Invalid state - console.error(line); - console.error('Invalid state "'.concat(parts[0], '", should be "solid"')); - return; - } else { - state = 'solid'; - } - break; - case 'solid': - // First face - if (parts[0] !== 'facet' || parts[1] !== 'normal') { - // Invalid state - console.error(line); - console.error('Invalid state "'.concat(parts[0], '", should be "facet normal"')); - return; - } else { - // Push normal for first face - newNormal = new _main.default.Vector(parseFloat(parts[2]), parseFloat(parts[3]), parseFloat(parts[4])); - model.vertexNormals.push(newNormal, newNormal, newNormal); - state = 'facet normal'; - } - break; - case 'facet normal': - // After normal is defined - if (parts[0] !== 'outer' || parts[1] !== 'loop') { - // Invalid State - console.error(line); - console.error('Invalid state "'.concat(parts[0], '", should be "outer loop"')); - return; - } else { - // Next should be vertices - state = 'vertex'; - } - break; - case 'vertex': - if (parts[0] === 'vertex') { - //Vertex of triangle - newVertex = new _main.default.Vector(parseFloat(parts[1]), parseFloat(parts[2]), parseFloat(parts[3])); - model.vertices.push(newVertex); - model.uvs.push([0, - 0]); - curVertexIndex.push(model.vertices.indexOf(newVertex)); - } else if (parts[0] === 'endloop') { - // End of vertices - model.faces.push(curVertexIndex); - curVertexIndex = [ - ]; - state = 'endloop'; - } else { - // Invalid State - console.error(line); - console.error('Invalid state "'.concat(parts[0], '", should be "vertex" or "endloop"')); - return; - } - break; - case 'endloop': - if (parts[0] !== 'endfacet') { - // End of face - console.error(line); - console.error('Invalid state "'.concat(parts[0], '", should be "endfacet"')); - return; - } else { - state = 'endfacet'; - } - break; - case 'endfacet': - if (parts[0] === 'endsolid') { // End of solid - } else if (parts[0] === 'facet' && parts[1] === 'normal') { - // Next face - newNormal = new _main.default.Vector(parseFloat(parts[2]), parseFloat(parts[3]), parseFloat(parts[4])); - model.vertexNormals.push(newNormal, newNormal, newNormal); - state = 'facet normal'; - } else { - // Invalid State - console.error(line); - console.error('Invalid state "'.concat(parts[0], '", should be "endsolid" or "facet normal"')); - return; - } - break; - default: - console.error('Invalid state "'.concat(state, '"')); - break; - } - } - return model; - } /** - * Render a 3d model to the screen. + _main.default.prototype.specularMaterial = function (v1, v2, v3, alpha) { + this._assert3d('specularMaterial'); + _main.default._validateParameters('specularMaterial', arguments); + var color = _main.default.prototype.color.apply(this, arguments); + this._renderer.curSpecularColor = color._array; + this._renderer._useSpecularMaterial = true; + this._renderer._useNormalMaterial = false; + this._renderer._enableLighting = true; + return this; + }; + /** + * Sets the amount of gloss ("shininess") of a + * specularMaterial(). * - * @method model - * @param {p5.Geometry} model Loaded 3d model to be rendered + * The default and minimum value is 1. + * + * @method shininess + * @param {Number} shine degree of shininess + * @chainable * @example *
      * - * //draw a spinning octahedron - * let octahedron; - * - * function preload() { - * octahedron = loadModel('assets/octahedron.obj'); - * } - * * function setup() { * createCanvas(100, 100, WEBGL); - * describe('Vertically rotating 3-d octahedron.'); + * describe('two spheres, one more shiny than the other'); * } - * * function draw() { - * background(200); - * rotateX(frameCount * 0.01); - * rotateY(frameCount * 0.01); - * model(octahedron); + * 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); * } * *
      - * * @alt - * Vertically rotating 3-d octahedron. + * two spheres, one more shiny than the other */ - - _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); + _main.default.prototype.shininess = function (shine) { + this._assert3d('shininess'); + _main.default._validateParameters('shininess', arguments); + if (shine < 1) { + shine = 1; + } + this._renderer._useShininess = shine; + return this; + }; + /** + * @private blends colors according to color components. + * If alpha value is less than 1, or non-standard blendMode + * we need to enable blending on our gl context. + * @param {Number[]} color [description] + * @return {Number[]]} Normalized numbers array + */ + _main.default.RendererGL.prototype._applyColorBlend = function (colors) { + var gl = this.GL; + var isTexture = this.drawMode === constants.TEXTURE; + var doBlend = this.userFillShader || this.userStrokeShader || this.userPointShader || isTexture || this.curBlendMode !== constants.BLEND || colors[colors.length - 1] < 1 || this._isErasing; + if (doBlend !== this._isBlending) { + if (doBlend || this.curBlendMode !== constants.BLEND && this.curBlendMode !== constants.ADD) { + gl.enable(gl.BLEND); + } else { + gl.disable(gl.BLEND); } - this._renderer.drawBuffers(model.gid); + gl.depthMask(true); + this._isBlending = doBlend; + } + this._applyBlendMode(); + return colors; + }; + /** + * @private sets blending in gl context to curBlendMode + * @param {Number[]} color [description] + * @return {Number[]]} Normalized numbers array + */ + _main.default.RendererGL.prototype._applyBlendMode = function () { + if (this._cachedBlendMode === this.curBlendMode) { + return; + } + var gl = this.GL; + switch (this.curBlendMode) { + case constants.BLEND: + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case constants.ADD: + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ONE); + break; + case constants.REMOVE: + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_ALPHA); + break; + case constants.MULTIPLY: + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA); + break; + case constants.SCREEN: + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_COLOR); + break; + case constants.EXCLUSION: + gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); + gl.blendFuncSeparate(gl.ONE_MINUS_DST_COLOR, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE); + break; + case constants.REPLACE: + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ZERO); + break; + case constants.SUBTRACT: + gl.blendEquationSeparate(gl.FUNC_REVERSE_SUBTRACT, gl.FUNC_ADD); + gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case constants.DARKEST: + if (this.blendExt) { + gl.blendEquationSeparate(this.blendExt.MIN || this.blendExt.MIN_EXT, gl.FUNC_ADD); + gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE); + } else { + console.warn('blendMode(DARKEST) does not work in your browser in WEBGL mode.'); + } + break; + case constants.LIGHTEST: + if (this.blendExt) { + gl.blendEquationSeparate(this.blendExt.MAX || this.blendExt.MAX_EXT, gl.FUNC_ADD); + gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE); + } else { + console.warn('blendMode(LIGHTEST) does not work in your browser in WEBGL mode.'); + } + break; + default: + console.error('Oops! Somehow RendererGL set curBlendMode to an unsupported mode.'); + break; + } + if (!this._isErasing) { + this._cachedBlendMode = this.curBlendMode; } }; var _default = _main.default; exports.default = _default; }, { - '../core/main': 290, - './p5.Geometry': 339, - 'core-js/modules/es.array.concat': 167, - 'core-js/modules/es.array.index-of': 175, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.array.splice': 182, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.exec': 199, - 'core-js/modules/es.string.match': 205, - 'core-js/modules/es.string.split': 209, - 'core-js/modules/es.string.trim': 211 + '../core/constants': 286, + '../core/main': 298, + './p5.Texture': 357, + 'core-js/modules/es.array.includes': 177, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.join': 180, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.string.includes': 209, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 337: [ + 347: [ function (_dereq_, module, exports) { 'use strict'; - _dereq_('core-js/modules/es.symbol'); - _dereq_('core-js/modules/es.symbol.description'); - _dereq_('core-js/modules/es.symbol.iterator'); - _dereq_('core-js/modules/es.array.iterator'); - _dereq_('core-js/modules/es.array.join'); - _dereq_('core-js/modules/es.object.get-own-property-descriptor'); - _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.string.iterator'); - _dereq_('core-js/modules/es.weak-map'); - _dereq_('core-js/modules/web.dom-collections.iterator'); - function _typeof2(obj) { - if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { - _typeof2 = function _typeof2(obj) { - return typeof obj; - }; - } else { - _typeof2 = function _typeof2(obj) { - return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; - }; - } - return _typeof2(obj); - } - function _typeof(obj) { - if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { - _typeof = function _typeof(obj) { - return _typeof2(obj); - }; - } else { - _typeof = function _typeof(obj) { - return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); - }; - } - return _typeof(obj); - } - _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.math.hypot'); + _dereq_('core-js/modules/es.string.sub'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.math.hypot'); + _dereq_('core-js/modules/es.string.sub'); Object.defineProperty(exports, '__esModule', { value: true }); exports.default = void 0; var _main = _interopRequireDefault(_dereq_('../core/main')); - var constants = _interopRequireWildcard(_dereq_('../core/constants')); - _dereq_('./p5.Texture'); - function _getRequireWildcardCache() { - if (typeof WeakMap !== 'function') return null; - var cache = new WeakMap(); - _getRequireWildcardCache = function _getRequireWildcardCache() { - return cache; - }; - return cache; - } - function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } - if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { - return { - default: - obj - }; - } - var cache = _getRequireWildcardCache(); - if (cache && cache.has(obj)) { - return cache.get(obj); - } - var newObj = { - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - newObj.default = obj; - if (cache) { - cache.set(obj, newObj); - } - return newObj; - } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; - } /** - * @module 3D - * @submodule Material - * @for p5 - * @requires core - */ + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } /** + * @module 3D + * @submodule Camera + * @requires core + */ + //////////////////////////////////////////////////////////////////////////////// + // p5.Prototype Methods + //////////////////////////////////////////////////////////////////////////////// /** - * Creates a new p5.Shader object - * from the provided vertex and fragment shader files. - * - * The shader files are loaded asynchronously in the - * background, so this method should be used in preload(). + * Sets the position of the current camera in a 3D sketch. + * Parameters for this function define the camera's position, + * the center of the sketch (where the camera is pointing), + * and an up direction (the orientation of the camera). * - * Note, shaders can only be used in WEBGL mode. + * This function simulates the movements of the camera, allowing objects to be + * viewed from various angles. Remember, it does not move the objects themselves + * but the camera instead. For example when the centerX value is positive, + * and the camera is rotating to the right side of the sketch, + * the object will seem like it's moving to the left. * - * @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 p5.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. + * See this example + * to view the position of your camera. * + * If no parameters are given, the following default is used: + * camera(0, 0, (height/2) / tan(PI/6), 0, 0, 0, 0, 1, 0) + * @method camera + * @constructor + * @for p5 + * @param {Number} [x] camera position value on x axis + * @param {Number} [y] camera position value on y axis + * @param {Number} [z] camera position value on z axis + * @param {Number} [centerX] x coordinate representing center of the sketch + * @param {Number} [centerY] y coordinate representing center of the sketch + * @param {Number} [centerZ] z coordinate representing center of the sketch + * @param {Number} [upX] x component of direction 'up' from camera + * @param {Number} [upY] y component of direction 'up' from camera + * @param {Number} [upZ] z component of direction 'up' from camera + * @chainable * @example - *
      + *
      * - * 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]); - * describe('zooming Mandelbrot set. a colorful, infinitely detailed fractal.'); + * describe('a square moving closer and then away from the camera.'); * } - * * function draw() { - * mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000)))); - * quad(-1, -1, 1, -1, 1, 1, -1, 1); + * 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); * } * *
      * - * @alt - * zooming Mandelbrot set. a colorful, infinitely detailed fractal. - */ - - _main.default.prototype.loadShader = function (vertFilename, fragFilename, callback, errorCallback) { - _main.default._validateParameters('loadShader', arguments); - if (!errorCallback) { - errorCallback = console.error; - } - var loadedShader = new _main.default.Shader(); - var self = this; - var loadedFrag = false; - var loadedVert = false; - var onLoad = function onLoad() { - self._decrementPreload(); - if (callback) { - callback(loadedShader); - } - }; - this.loadStrings(vertFilename, function (result) { - loadedShader._vertSrc = result.join('\n'); - loadedVert = true; - if (loadedFrag) { - onLoad(); - } - }, errorCallback); - this.loadStrings(fragFilename, function (result) { - loadedShader._fragSrc = result.join('\n'); - loadedFrag = true; - if (loadedVert) { - onLoad(); - } - }, errorCallback); - return loadedShader; - }; - /** - * Creates a new p5.Shader object - * from the provided vertex and fragment shader code. - * - * Note, shaders can only be used in WEBGL mode. - * - * @method createShader - * @param {String} vertSrc source code for the vertex shader - * @param {String} fragSrc source code for the fragment shader - * @returns {p5.Shader} a shader object created from the provided - * vertex and fragment shaders. - * * @example - *
      + *
      * - * // the 'varying's are shared between both vertex & fragment shaders - * let varying = 'precision highp float; varying vec2 vPos;'; - * - * // the vertex shader is called for each vertex - * let vs = - * varying + - * 'attribute vec3 aPosition;' + - * 'void main() { vPos = (gl_Position = vec4(aPosition,1.0)).xy; }'; - * - * // the fragment shader is called for each pixel - * let fs = - * varying + - * 'uniform vec2 p;' + - * 'uniform float r;' + - * 'const int I = 500;' + - * 'void main() {' + - * ' vec2 c = p + vPos * r, z = c;' + - * ' float n = 0.0;' + - * ' for (int i = I; i > 0; i --) {' + - * ' if(z.x*z.x+z.y*z.y > 4.0) {' + - * ' n = float(i)/float(I);' + - * ' break;' + - * ' }' + - * ' z = vec2(z.x*z.x-z.y*z.y, 2.0*z.x*z.y) + c;' + - * ' }' + - * ' gl_FragColor = vec4(0.5-cos(n*17.0)/2.0,0.5-cos(n*13.0)/2.0,0.5-cos(n*23.0)/2.0,1.0);' + - * '}'; + * //move slider to see changes! + * //sliders control the first 6 parameters of camera() + * let sliderGroup = []; + * let X; + * let Y; + * let Z; + * let centerX; + * let centerY; + * let centerZ; + * let h = 20; * - * let mandel; * function setup() { * createCanvas(100, 100, WEBGL); - * - * // create and initialize the shader - * mandel = createShader(vs, fs); - * shader(mandel); - * noStroke(); - * - * // 'p' is the center point of the Mandelbrot image - * mandel.setUniform('p', [-0.74364388703, 0.13182590421]); - * describe('zooming Mandelbrot set. a colorful, infinitely detailed fractal.'); + * //create sliders + * for (var i = 0; i < 6; i++) { + * if (i === 2) { + * sliderGroup[i] = createSlider(10, 400, 200); + * } else { + * sliderGroup[i] = createSlider(-400, 400, 0); + * } + * h = map(i, 0, 6, 5, 85); + * sliderGroup[i].position(10, height + h); + * sliderGroup[i].style('width', '80px'); + * } + * describe( + * 'White square repeatedly grows to fill canvas and then shrinks. An interactive example of a red cube with 3 sliders for moving it across x, y, z axis and 3 sliders for shifting its center.' + * ); * } * * function draw() { - * // '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); + * background(60); + * // assigning sliders' value to each parameters + * X = sliderGroup[0].value(); + * Y = sliderGroup[1].value(); + * Z = sliderGroup[2].value(); + * centerX = sliderGroup[3].value(); + * centerY = sliderGroup[4].value(); + * centerZ = sliderGroup[5].value(); + * camera(X, Y, Z, centerX, centerY, centerZ, 0, 1, 0); + * stroke(255); + * fill(255, 102, 94); + * box(85); * } * *
      - * * @alt - * zooming Mandelbrot set. a colorful, infinitely detailed fractal. + * White square repeatedly grows to fill canvas and then shrinks. + * An interactive example of a red cube with 3 sliders for moving it across x, y, + * z axis and 3 sliders for shifting its center. */ - _main.default.prototype.createShader = function (vertSrc, fragSrc) { - this._assert3d('createShader'); - _main.default._validateParameters('createShader', arguments); - return new _main.default.Shader(this._renderer, vertSrc, fragSrc); + + _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 the p5.Shader object to - * be used to render subsequent shapes. + * Sets a perspective projection for the current camera in a 3D sketch. + * This projection represents depth through foreshortening: objects + * that are close to the camera appear their actual size while those + * that are further away from the camera appear smaller. * - * Custom shaders can be created using the - * createShader() and - * loadShader() functions. + * 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. * - * Use resetShader() to - * restore the default shaders. + * If no parameters are given, the default values are used as: * - * Note, shaders can only be used in WEBGL mode. + * - `fov` : The default field of view for the camera is such that the full height of renderer is visible when it is positioned at a default distance of 800 units from the camera. + * - `aspect` : The default aspect ratio is the ratio of renderer's width to renderer's height. + * - `near` : The default value for the near clipping plane is 80, which is 0.1 times the default distance from the camera to its subject. + * - `far` : The default value for the far clipping plane is 8000, which is 10 times the default distance from the camera to its subject. * - * @method shader - * @chainable - * @param {p5.Shader} s the p5.Shader object - * to use for rendering shapes. + * If you prefer a fixed field of view, follow these steps: + * 1. Choose your desired field of view angle (`fovy`). This is how wide the camera can see. + * 2. To ensure that you can see the entire width across horizontally and height across vertically, place the camera a distance of `(height / 2) / tan(fovy / 2)` back from its subject. + * 3. Call perspective with the chosen field of view, canvas aspect ratio, and near/far values: + * `perspective(fovy, width / height, cameraDistance / 10, cameraDistance * 10);` * + * @method perspective + * @for p5 + * @param {Number} [fovy] camera frustum vertical field of view, + * from bottom to top of view, in angleMode units + * @param {Number} [aspect] camera frustum aspect ratio + * @param {Number} [near] frustum near plane length + * @param {Number} [far] frustum far plane length + * @chainable * @example - *
      + *
      * - * // 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'); - * } - * + * //drag the mouse to look around! * 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(); - * + * perspective(PI / 3.0, width / height, 0.1, 500); * describe( - * 'canvas toggles between a circular gradient of orange and blue vertically. and a circular gradient of red and green moving horizontally when mouse is clicked/pressed.' + * 'two colored 3D boxes move back and forth, rotating as mouse is dragged.' * ); * } - * * 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]); + * background(200); + * orbitControl(); + * normalMaterial(); * - * if (showRedGreen === true) { - * shader(redGreen); - * } else { - * shader(orangeBlue); - * } - * quad(-1, -1, 1, -1, 1, 1, -1, 1); - * } + * translate(0, 0, 550); + * rotateX(-0.3); + * rotateY(-0.2); * - * function mouseClicked() { - * showRedGreen = !showRedGreen; + * push(); + * translate(-15, 0, sin(frameCount / 30) * 95); + * box(30); + * pop(); + * push(); + * translate(15, 0, sin(frameCount / 30 + PI) * 95); + * box(30); + * pop(); * } * *
      * * @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. + * two colored 3D boxes move back and forth, rotating as mouse is dragged. */ - _main.default.prototype.shader = function (s) { - this._assert3d('shader'); - _main.default._validateParameters('shader', arguments); - if (s._renderer === undefined) { - s._renderer = this._renderer; - } - s.init(); - if (s.isStrokeShader()) { - this._renderer.userStrokeShader = s; - } else { - this._renderer.userFillShader = s; - this._renderer._useNormalMaterial = false; + _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; }; /** - * Restores the default shaders. Code that runs after resetShader() - * will not be affected by the shader previously set by - * shader() + * Sets an orthographic projection for the current camera in a 3D sketch + * and defines a box-shaped viewing frustum within which objects are seen. + * In this projection, all objects with the same dimension appear the same + * size, regardless of whether they are near or far from the camera. * - * @method resetShader + * The parameters to this function specify the viewing frustum where + * left and right are the minimum and maximum x values, top and bottom are + * the minimum and maximum y values, and near and far are the minimum and + * maximum z values. + * + * If no parameters are given, the following default is used: + * ortho(-width/2, width/2, -height/2, height/2). + * @method ortho + * @for p5 + * @param {Number} [left] camera frustum left plane + * @param {Number} [right] camera frustum right plane + * @param {Number} [bottom] camera frustum bottom plane + * @param {Number} [top] camera frustum top plane + * @param {Number} [near] camera frustum near plane + * @param {Number} [far] camera frustum far plane * @chainable * @example *
      * - * // This variable will hold our shader object - * let shaderProgram; - * - * // This variable will hold our vertex shader source code - * let vertSrc = ` - * attribute vec3 aPosition; - * attribute vec2 aTexCoord; - * uniform mat4 uProjectionMatrix; - * uniform mat4 uModelViewMatrix; - * varying vec2 vTexCoord; - * - * void main() { - * vTexCoord = aTexCoord; - * vec4 position = vec4(aPosition, 1.0); - * gl_Position = uProjectionMatrix * uModelViewMatrix * position; - * } - * `; - * - * // This variable will hold our fragment shader source code - * let fragSrc = ` - * precision mediump float; - * - * varying vec2 vTexCoord; - * - * void main() { - * vec2 uv = vTexCoord; - * vec3 color = vec3(uv.x, uv.y, min(uv.x + uv.y, 1.0)); - * gl_FragColor = vec4(color, 1.0); - * } - * `; - * + * //drag the mouse to look around! + * //there's no vanishing point * function setup() { - * // Shaders require WEBGL mode to work * createCanvas(100, 100, WEBGL); - * - * // Create our shader - * shaderProgram = createShader(vertSrc, fragSrc); - * + * ortho(-width / 2, width / 2, height / 2, -height / 2, 0, 500); * describe( - * 'Two rotating cubes. The left one is painted using a custom (user-defined) shader, while the right one is painted using the default fill shader.' + * 'two 3D boxes move back and forth along same plane, rotating as mouse is dragged.' * ); * } - * * function draw() { - * // Clear the scene * background(200); + * orbitControl(); + * normalMaterial(); * - * // Draw a box using our shader - * // shader() sets the active shader with our shader - * shader(shaderProgram); + * translate(0,0,500); + * rotateX(0.2); + * rotateY(-0.2); * push(); - * translate(-width / 4, 0, 0); - * rotateX(millis() * 0.00025); - * rotateY(millis() * 0.0005); - * box(width / 4); + * translate(-15, 0, sin(frameCount / 30) * 65); + * box(30); * pop(); - * - * // Draw a box using the default fill shader - * // resetShader() restores the default fill shader - * resetShader(); - * fill(255, 0, 0); * push(); - * translate(width / 4, 0, 0); - * rotateX(millis() * 0.00025); - * rotateY(millis() * 0.0005); - * box(width / 4); + * translate(15, 0, sin(frameCount / 30 + PI) * 65); + * box(30); * pop(); * } * *
      + * * @alt - * Two rotating cubes. The left one is painted using a custom (user-defined) shader, - * while the right one is painted using the default fill shader. + * two 3D boxes move back and forth along same plane, rotating as mouse is dragged. */ - _main.default.prototype.resetShader = function () { - this._renderer.userFillShader = this._renderer.userStrokeShader = null; + _main.default.prototype.ortho = function () { + var _this$_renderer$_curC3; + this._assert3d('ortho'); + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + _main.default._validateParameters('ortho', args); + (_this$_renderer$_curC3 = this._renderer._curCamera).ortho.apply(_this$_renderer$_curC3, args); return this; }; /** - * Sets the texture that will be used to render subsequent shapes. - * - * A texture is like a "skin" that wraps around a 3D geometry. Currently - * supported textures are images, video, and offscreen renders. - * - * To texture a geometry created with beginShape(), - * you will need to specify uv coordinates in vertex(). + * Sets the frustum of the current camera as defined by + * the parameters. * - * Note, texture() can only be used in WEBGL mode. + * 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. * - * You can view more materials in this - * example. + * Setting the frustum changes the perspective of the scene being rendered. + * This can be achieved more simply in many cases by using + * perspective(). * - * @method texture - * @param {p5.Image|p5.MediaElement|p5.Graphics|p5.Texture} tex image to use as texture + * If no parameters are given, the following default is used: + * frustum(-width/20, width/20, height/20, -height/20, eyeZ/10, eyeZ*10), + * where eyeZ is equal to ((height/2) / tan(PI/6)). + * @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 *
      * - * let img; - * function preload() { - * img = loadImage('assets/laDefense.jpg'); - * } - * * function setup() { * createCanvas(100, 100, WEBGL); - * describe('spinning cube with a texture from an image'); + * setAttributes('antialias', true); + * frustum(-0.1, 0.1, -0.1, 0.1, 0.1, 200); + * describe( + * 'two 3D boxes move back and forth along same plane, rotating as mouse is dragged.' + * ); * } - * * function draw() { - * background(0); - * rotateZ(frameCount * 0.01); - * rotateX(frameCount * 0.01); - * rotateY(frameCount * 0.01); - * //pass image as texture - * texture(img); - * box(width / 2); + * background(200); + * orbitControl(); + * normalMaterial(); + * translate(0,0,700); + * 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(); * } * *
      + * * @alt - * spinning cube with a texture from an image + * two 3D boxes move back and forth along same plane, rotating as mouse is dragged. + */ + _main.default.prototype.frustum = function () { + var _this$_renderer$_curC4; + this._assert3d('frustum'); + for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + _main.default._validateParameters('frustum', args); + (_this$_renderer$_curC4 = this._renderer._curCamera).frustum.apply(_this$_renderer$_curC4, args); + return this; + }; + //////////////////////////////////////////////////////////////////////////////// + // p5.Camera + //////////////////////////////////////////////////////////////////////////////// + /** + * Creates a new p5.Camera object and sets it + * as the current (active) camera. * - * @example - *
      - * - * let pg; + * The new camera is initialized with a default position + * (see camera()) + * and a default perspective projection + * (see perspective()). + * Its properties can be controlled with the p5.Camera + * methods. * + * Note: Every 3D sketch starts with a default camera initialized. + * This camera can be controlled with the global methods + * camera(), + * perspective(), ortho(), + * and frustum() if it is the only camera + * in the scene. + * @method createCamera + * @return {p5.Camera} The newly created camera object. + * @for p5 + * @example + *
      + * // Creates a camera object and animates it around a box. + * let camera; * function setup() { * createCanvas(100, 100, WEBGL); - * pg = createGraphics(200, 200); - * pg.textSize(75); - * describe('plane with a texture from an image created by createGraphics()'); + * background(0); + * camera = createCamera(); + * describe('An example that creates a camera and moves it around the box.'); * } * * function draw() { * background(0); - * pg.background(255); - * pg.text('hello!', 0, 100); - * //pass image as texture - * texture(pg); - * rotateX(0.5); - * noStroke(); - * plane(50); + * // The camera will automatically + * // rotate to look at [0, 0, 0]. + * camera.lookAt(0, 0, 0); + * + * // The camera will move on the + * // x axis. + * camera.setPosition(sin(frameCount / 60) * 200, 0, 100); + * box(20); + * + * // A 'ground' box to give the viewer + * // a better idea of where the camera + * // is looking. + * translate(0, 50, 0); + * rotateX(HALF_PI); + * box(150, 150, 20); * } - * - *
      + *
      + * * @alt - * plane with a texture from an image created by createGraphics() + * An example that creates a camera and moves it around the box. + */ + _main.default.prototype.createCamera = function () { + this._assert3d('createCamera'); + var _cam = new _main.default.Camera(this._renderer); + // compute default camera settings, then set a default camera + _cam._computeCameraDefaultSettings(); + _cam._setDefaultCamera(); + // set renderer current camera to the new camera + this._renderer._curCamera = _cam; + return _cam; + }; + /** + * This class describes a camera for use in p5's + * + * WebGL mode. It contains camera position, orientation, and projection + * information necessary for rendering a 3D scene. + * + * New p5.Camera objects can be made through the + * createCamera() function and controlled through + * the methods described below. A camera created in this way will use a default + * position in the scene and a default perspective projection until these + * properties are changed through the various methods available. It is possible + * to create multiple cameras, in which case the current camera + * can be set through the setCamera() method. + * + * Note: + * The methods below operate in two coordinate systems: the 'world' coordinate + * system describe positions in terms of their relationship to the origin along + * the X, Y and Z axes whereas the camera's 'local' coordinate system + * describes positions from the camera's point of view: left-right, up-down, + * and forward-backward. The move() method, + * for instance, moves the camera along its own axes, whereas the + * setPosition() + * method sets the camera's position in world-space. + * + * The camera object propreties + * eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ + * which describes camera position, orientation, and projection + * are also accessible via the camera object generated using + * createCamera() * + * @class p5.Camera + * @param {rendererGL} rendererGL instance of WebGL renderer * @example *
      * - * let vid; - * function preload() { - * vid = createVideo('assets/fingers.mov'); - * vid.hide(); - * } + * let cam; + * let delta = 0.01; + * * function setup() { * createCanvas(100, 100, WEBGL); - * describe('rectangle with video as texture'); - * } - * - * function draw() { - * background(0); - * //pass video frame as texture - * texture(vid); - * rect(-40, -40, 80, 80); - * } - * - * function mousePressed() { - * vid.loop(); + * normalMaterial(); + * cam = createCamera(); + * // set initial pan angle + * cam.pan(-0.8); + * describe( + * 'camera view pans left and right across a series of rotating 3D boxes.' + * ); * } - * - *
      - * - * @alt - * rectangle with video as texture * - * @example - *
      - * - * let img; + * function draw() { + * background(200); * - * function preload() { - * img = loadImage('assets/laDefense.jpg'); - * } + * // pan camera according to angle 'delta' + * cam.pan(delta); * - * function setup() { - * createCanvas(100, 100, WEBGL); - * describe('quad with a texture, mapped using normalized coordinates'); - * } + * // every 160 frames, switch direction + * if (frameCount % 160 === 0) { + * delta *= -1; + * } * - * function draw() { - * background(0); - * texture(img); - * textureMode(NORMAL); - * beginShape(); - * vertex(-40, -40, 0, 0); - * vertex(40, -40, 1, 0); - * vertex(40, 40, 1, 1); - * vertex(-40, 40, 0, 1); - * endShape(); + * rotateX(frameCount * 0.01); + * translate(-100, 0, 0); + * box(20); + * translate(35, 0, 0); + * box(20); + * translate(35, 0, 0); + * box(20); + * translate(35, 0, 0); + * box(20); + * translate(35, 0, 0); + * box(20); + * translate(35, 0, 0); + * box(20); + * translate(35, 0, 0); + * box(20); * } * *
      + * * @alt - * quad with a texture, mapped using normalized coordinates + * camera view pans left and right across a series of rotating 3D boxes. */ - _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; - }; + _main.default.Camera = /*#__PURE__*/ function () { + function Camera(renderer) { + _classCallCheck(this, Camera); + this._renderer = renderer; + this.cameraType = 'default'; + this.cameraMatrix = new _main.default.Matrix(); + this.projMatrix = new _main.default.Matrix(); + this.yScale = 1; + } /** + * camera position value on x axis + * @property {Number} eyeX + * @readonly + * @example + * + *
      + * let cam, div; + * function setup() { + * createCanvas(100, 100, WEBGL); + * background(0); + * cam = createCamera(); + * div = createDiv(); + * div.position(0, 0); + * describe('An example showing the use of camera object properties'); + * } + * + * function draw() { + * orbitControl(); + * box(10); + * div.html('eyeX = ' + cam.eyeX); + * } + *
      + * + * @alt + * An example showing the use of camera object properties + * + */ + /** + * camera position value on y axis + * @property {Number} eyeY + * @readonly + * @example + *
      + * let cam, div; + * function setup() { + * createCanvas(100, 100, WEBGL); + * background(0); + * cam = createCamera(); + * div = createDiv(); + * div.position(0, 0); + * describe('An example showing the use of camera object properties'); + * } + * + * function draw() { + * orbitControl(); + * box(10); + * div.html('eyeY = ' + cam.eyeY); + * } + *
      + * + * @alt + * An example showing the use of camera object properties + * + */ + /** + * camera position value on z axis + * @property {Number} eyeZ + * @readonly + * @example + *
      + * let cam, div; + * function setup() { + * createCanvas(100, 100, WEBGL); + * background(0); + * cam = createCamera(); + * div = createDiv(); + * div.position(0, 0); + * describe('An example showing the use of camera object properties'); + * } + * + * function draw() { + * orbitControl(); + * box(10); + * div.html('eyeZ = ' + cam.eyeZ); + * } + *
      + * + * @alt + * An example showing the use of camera object properties + * + */ + /** + * x coordinate representing center of the sketch + * @property {Number} centerX + * @readonly + * @example + *
      + * let cam, div; + * function setup() { + * createCanvas(100, 100, WEBGL); + * background(255); + * cam = createCamera(); + * cam.lookAt(1, 0, 0); + * div = createDiv('centerX = ' + cam.centerX); + * div.position(0, 0); + * div.style('color', 'white'); + * describe('An example showing the use of camera object properties'); + * } + * + * function draw() { + * orbitControl(); + * box(10); + * } + *
      + * + * @alt + * An example showing the use of camera object properties + * + */ + /** + * y coordinate representing center of the sketch + * @property {Number} centerY + * @readonly + * @example + *
      + * let cam, div; + * function setup() { + * createCanvas(100, 100, WEBGL); + * background(255); + * cam = createCamera(); + * cam.lookAt(0, 1, 0); + * div = createDiv('centerY = ' + cam.centerY); + * div.position(0, 0); + * div.style('color', 'white'); + * describe('An example showing the use of camera object properties'); + * } + * + * function draw() { + * orbitControl(); + * box(10); + * } + *
      + * + * @alt + * An example showing the use of camera object properties + * + */ + /** + * z coordinate representing center of the sketch + * @property {Number} centerZ + * @readonly + * @example + *
      + * let cam, div; + * function setup() { + * createCanvas(100, 100, WEBGL); + * background(255); + * cam = createCamera(); + * cam.lookAt(0, 0, 1); + * div = createDiv('centerZ = ' + cam.centerZ); + * div.position(0, 0); + * div.style('color', 'white'); + * describe('An example showing the use of camera object properties'); + * } + * + * function draw() { + * orbitControl(); + * box(10); + * } + *
      + * + * @alt + * An example showing the use of camera object properties + * + */ + /** + * x component of direction 'up' from camera + * @property {Number} upX + * @readonly + * @example + *
      + * let cam, div; + * function setup() { + * createCanvas(100, 100, WEBGL); + * background(255); + * cam = createCamera(); + * div = createDiv('upX = ' + cam.upX); + * div.position(0, 0); + * div.style('color', 'blue'); + * div.style('font-size', '18px'); + * describe('An example showing the use of camera object properties'); + * } + *
      + * + * @alt + * An example showing the use of camera object properties + * + */ + /** + * y component of direction 'up' from camera + * @property {Number} upY + * @readonly + * @example + *
      + * let cam, div; + * function setup() { + * createCanvas(100, 100, WEBGL); + * background(255); + * cam = createCamera(); + * div = createDiv('upY = ' + cam.upY); + * div.position(0, 0); + * div.style('color', 'blue'); + * div.style('font-size', '18px'); + * describe('An example showing the use of camera object properties'); + * } + *
      + * + * @alt + * An example showing the use of camera object properties + * + */ + /** + * z component of direction 'up' from camera + * @property {Number} upZ + * @readonly + * @example + *
      + * let cam, div; + * function setup() { + * createCanvas(100, 100, WEBGL); + * background(255); + * cam = createCamera(); + * div = createDiv('upZ = ' + cam.upZ); + * div.position(0, 0); + * div.style('color', 'blue'); + * div.style('font-size', '18px'); + * describe('An example showing the use of camera object properties'); + * } + *
      + * + * @alt + * An example showing the use of camera object properties + * + */ + //////////////////////////////////////////////////////////////////////////////// + // Camera Projection Methods + //////////////////////////////////////////////////////////////////////////////// + /** + * Sets a perspective projection. + * Accepts the same parameters as the global + * perspective(). + * More information on this function can be found there. + * @method perspective + * @for p5.Camera + * @example + *
      + * + * // drag the mouse to look around! + * + * let cam; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * // create a camera + * cam = createCamera(); + * // give it a perspective projection + * cam.perspective(PI / 3.0, width / height, 0.1, 500); + * } + * + * function draw() { + * background(200); + * orbitControl(); + * normalMaterial(); + * + * translate(0, 0, 550); + * rotateX(-0.3); + * rotateY(-0.2); + * + * push(); + * translate(-15, 0, sin(frameCount / 30) * 95); + * box(30); + * pop(); + * push(); + * translate(15, 0, sin(frameCount / 30 + PI) * 95); + * box(30); + * pop(); + * } + * + *
      + * @alt + * two colored 3D boxes move back and forth, rotating as mouse is dragged. + */ + + _createClass(Camera, [ + { + key: 'perspective', + value: function perspective(fovy, aspect, near, far) { + this.cameraType = arguments.length > 0 ? 'custom' : 'default'; + if (typeof fovy === 'undefined') { + fovy = this.defaultCameraFOV; + // this avoids issue where setting angleMode(DEGREES) before calling + // perspective leads to a smaller than expected FOV (because + // _computeCameraDefaultSettings computes in radians) + this.cameraFOV = fovy; + } else { + this.cameraFOV = this._renderer._pInst._toRadians(fovy); + } + if (typeof aspect === 'undefined') { + aspect = this.defaultAspectRatio; + } + if (typeof near === 'undefined') { + near = this.defaultCameraNear; + } + if (typeof far === 'undefined') { + far = this.defaultCameraFar; + } + if (near <= 0.0001) { + near = 0.01; + console.log('Avoid perspective near plane values close to or below 0. ' + 'Setting value to 0.01.'); + } + if (far < near) { + console.log('Perspective far plane value is less than near plane value. ' + 'Nothing will be shown.'); + } + this.aspectRatio = aspect; + this.cameraNear = near; + this.cameraFar = far; + this.projMatrix = _main.default.Matrix.identity(); + var f = 1 / Math.tan(this.cameraFOV / 2); + var nf = 1 / (this.cameraNear - this.cameraFar); + /* eslint-disable indent */ + this.projMatrix.set(f / aspect, 0, 0, 0, 0, - f * this.yScale, 0, 0, 0, 0, (far + near) * nf, - 1, 0, 0, 2 * far * near * nf, 0); + /* eslint-enable indent */ + if (this._isActive()) { + this._renderer.uPMatrix.set(this.projMatrix.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. + * Accepts the same parameters as the global + * ortho(). + * More information on this function can be found there. + * @method ortho + * @for p5.Camera + * @example + *
      + * + * // drag the mouse to look around! + * // there's no vanishing point + * + * let cam; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * // create a camera + * cam = createCamera(); + * // give it an orthographic projection + * cam.ortho(-width / 2, width / 2, height / 2, -height / 2, 0, 500); + * } + * function draw() { + * background(200); + * orbitControl(); + * normalMaterial(); + * translate(0,0,500); + * 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(); + * } + * + *
      + * @alt + * two 3D boxes move back and forth along same plane, rotating as mouse is dragged. + */ + + }, + { + key: 'ortho', + value: function ortho(left, right, bottom, top, near, far) { + if (left === undefined) left = - this._renderer.width / 2; + if (right === undefined) right = + this._renderer.width / 2; + if (bottom === undefined) bottom = - this._renderer.height / 2; + if (top === undefined) top = + this._renderer.height / 2; + if (near === undefined) near = 0; + if (far === undefined) far = Math.max(this._renderer.width, this._renderer.height); + this.cameraNear = near; + this.cameraFar = far; + var w = right - left; + var h = top - bottom; + var d = far - near; + var x = + 2 / w; + var y = + 2 / h * this.yScale; + var z = - 2 / d; + var tx = - (right + left) / w; + var ty = - (top + bottom) / h; + var tz = - (far + near) / d; + this.projMatrix = _main.default.Matrix.identity(); + /* eslint-disable indent */ + this.projMatrix.set(x, 0, 0, 0, 0, - y, 0, 0, 0, 0, z, 0, tx, ty, tz, 1); + /* eslint-enable indent */ + if (this._isActive()) { + this._renderer.uPMatrix.set(this.projMatrix.mat4[0], this.projMatrix.mat4[1], this.projMatrix.mat4[2], this.projMatrix.mat4[3], this.projMatrix.mat4[4], this.projMatrix.mat4[5], this.projMatrix.mat4[6], this.projMatrix.mat4[7], this.projMatrix.mat4[8], this.projMatrix.mat4[9], this.projMatrix.mat4[10], this.projMatrix.mat4[11], this.projMatrix.mat4[12], this.projMatrix.mat4[13], this.projMatrix.mat4[14], this.projMatrix.mat4[15]); + } + this.cameraType = 'custom'; + } /** + * Sets the camera's frustum. + * Accepts the same parameters as the global + * frustum(). + * More information on this function can be found there. + * @method frustum + * @for p5.Camera + * @example + *
      + * + * let cam; + * + * function setup() { + * x = createCanvas(100, 100, WEBGL); + * setAttributes('antialias', true); + * // create a camera + * cam = createCamera(); + * // set its frustum + * cam.frustum(-0.1, 0.1, -0.1, 0.1, 0.1, 200); + * } + * + * function draw() { + * background(200); + * orbitControl(); + * normalMaterial(); + * translate(0,0,700); + * 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(); + * } + * + *
      + * @alt + * two 3D boxes move back and forth along same plane, rotating as mouse is dragged. + */ + + }, + { + key: 'frustum', + value: function frustum(left, right, bottom, top, near, far) { + if (left === undefined) left = - this._renderer.width * 0.05; + if (right === undefined) right = + this._renderer.width * 0.05; + if (bottom === undefined) bottom = + this._renderer.height * 0.05; + if (top === undefined) top = - this._renderer.height * 0.05; + if (near === undefined) near = this.defaultCameraNear; + if (far === undefined) far = this.defaultCameraFar; + this.cameraNear = near; + this.cameraFar = far; + var w = right - left; + var h = top - bottom; + var d = far - near; + var x = + (2 * near) / w; + var y = + (2 * near) / h * this.yScale; + var z = - (2 * far * near) / d; + var tx = (right + left) / w; + var ty = (top + bottom) / h; + var tz = - (far + near) / d; + this.projMatrix = _main.default.Matrix.identity(); + /* eslint-disable indent */ + this.projMatrix.set(x, 0, 0, 0, 0, - y, 0, 0, tx, ty, tz, - 1, 0, 0, z, 0); + /* eslint-enable indent */ + if (this._isActive()) { + this._renderer.uPMatrix.set(this.projMatrix.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 + */ + + }, + { + key: '_rotateView', + value: function _rotateView(a, x, y, z) { + var centerX = this.centerX; + var centerY = this.centerY; + var centerZ = this.centerZ; + // move center by eye position such that rotation happens around eye position + centerX -= this.eyeX; + centerY -= this.eyeY; + centerZ -= this.eyeZ; + var rotation = _main.default.Matrix.identity(this._renderer._pInst); + rotation.rotate(this._renderer._pInst._toRadians(a), x, y, z); + /* eslint-disable max-len */ + var rotatedCenter = [ + centerX * rotation.mat4[0] + centerY * rotation.mat4[4] + centerZ * rotation.mat4[8], + centerX * rotation.mat4[1] + centerY * rotation.mat4[5] + centerZ * rotation.mat4[9], + centerX * rotation.mat4[2] + centerY * rotation.mat4[6] + centerZ * rotation.mat4[10] + ]; + /* eslint-enable max-len */ + // add eye position back into center + rotatedCenter[0] += this.eyeX; + rotatedCenter[1] += this.eyeY; + rotatedCenter[2] += this.eyeZ; + this.camera(this.eyeX, this.eyeY, this.eyeZ, rotatedCenter[0], rotatedCenter[1], rotatedCenter[2], this.upX, this.upY, this.upZ); + } /** + * Panning rotates the camera view to the left and right. + * @method pan + * @param {Number} angle amount to rotate camera in current + * angleMode units. + * Greater than 0 values rotate counterclockwise (to the left). + * @example + *
      + * + * 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); + * } + * + *
      + * + * @alt + * camera view pans left and right across a series of rotating 3D boxes. + */ + + }, + { + key: 'pan', + value: function pan(amount) { + var local = this._getLocalAxes(); + this._rotateView(amount, local.y[0], local.y[1], local.y[2]); + } /** + * Tilting rotates the camera view up and down. + * @method tilt + * @param {Number} angle amount to rotate camera in current + * angleMode units. + * Greater than 0 values rotate counterclockwise (to the left). + * @example + *
      + * + * 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); + * } + * + *
      + * + * @alt + * camera view tilts up and down across a series of rotating 3D boxes. + */ + + }, + { + key: 'tilt', + value: function tilt(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 + *
      + * + * 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); + * } + * + *
      + * + * @alt + * camera view of rotating 3D cubes changes to look at a new random + * point every second . + */ + + }, + { + key: 'lookAt', + value: function lookAt(x, y, z) { + this.camera(this.eyeX, this.eyeY, this.eyeZ, x, y, z, this.upX, this.upY, this.upZ); + } //////////////////////////////////////////////////////////////////////////////// + // Camera Position Methods + //////////////////////////////////////////////////////////////////////////////// + /** + * Sets the camera's position and orientation. + * Accepts the same parameters as the global + * camera(). + * More information on this function can be found there. + * @method camera + * @for p5.Camera + * @example + *
      + * + * let cam; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * // Create a camera. + * // createCamera() sets the newly created camera as + * // the current (active) camera. + * cam = createCamera(); + * } + * + * function draw() { + * background(204); + * // Move the camera away from the plane by a sin wave + * cam.camera(0, 0, 20 + sin(frameCount * 0.01) * 10, 0, 0, 0, 0, 1, 0); + * plane(10, 10); + * } + * + *
      + * @alt + * White square repeatedly grows to fill canvas and then shrinks. + * + * @example + *
      + * + * // move slider to see changes! + * // sliders control the first 6 parameters of camera() + * + * let sliderGroup = []; + * let X; + * let Y; + * let Z; + * let centerX; + * let centerY; + * let centerZ; + * let h = 20; + * let cam; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * // create a camera + * cam = createCamera(); + * // create sliders + * for (var i = 0; i < 6; i++) { + * if (i === 2) { + * sliderGroup[i] = createSlider(10, 400, 200); + * } else { + * sliderGroup[i] = createSlider(-400, 400, 0); + * } + * h = map(i, 0, 6, 5, 85); + * sliderGroup[i].position(10, height + h); + * sliderGroup[i].style('width', '80px'); + * } + * } + * + * function draw() { + * background(60); + * // assigning sliders' value to each parameters + * X = sliderGroup[0].value(); + * Y = sliderGroup[1].value(); + * Z = sliderGroup[2].value(); + * centerX = sliderGroup[3].value(); + * centerY = sliderGroup[4].value(); + * centerZ = sliderGroup[5].value(); + * cam.camera(X, Y, Z, centerX, centerY, centerZ, 0, 1, 0); + * stroke(255); + * fill(255, 102, 94); + * box(85); + * } + * + *
      + * @alt + * An interactive example of a red cube with 3 sliders for moving it across x, y, + * z axis and 3 sliders for shifting its center. + */ + + }, + { + key: 'camera', + value: function camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ) { + if (typeof eyeX === 'undefined') { + eyeX = this.defaultEyeX; + eyeY = this.defaultEyeY; + eyeZ = this.defaultEyeZ; + centerX = eyeX; + centerY = eyeY; + centerZ = 0; + upX = 0; + upY = 1; + upZ = 0; + } + this.eyeX = eyeX; + this.eyeY = eyeY; + this.eyeZ = eyeZ; + if (typeof centerX !== 'undefined') { + this.centerX = centerX; + this.centerY = centerY; + this.centerZ = centerZ; + } + if (typeof upX !== 'undefined') { + this.upX = upX; + this.upY = upY; + this.upZ = upZ; + } + var local = this._getLocalAxes(); + // the camera affects the model view matrix, insofar as it + // inverse translates the world to the eye position of the camera + // and rotates it. + /* eslint-disable indent */ + this.cameraMatrix.set(local.x[0], local.y[0], local.z[0], 0, local.x[1], local.y[1], local.z[1], 0, local.x[2], local.y[2], local.z[2], 0, 0, 0, 0, 1); + /* eslint-enable indent */ + var tx = - eyeX; + var ty = - eyeY; + var tz = - eyeZ; + this.cameraMatrix.translate([tx, + ty, + tz]); + if (this._isActive()) { + this._renderer.uMVMatrix.set(this.cameraMatrix.mat4[0], this.cameraMatrix.mat4[1], this.cameraMatrix.mat4[2], this.cameraMatrix.mat4[3], this.cameraMatrix.mat4[4], this.cameraMatrix.mat4[5], this.cameraMatrix.mat4[6], this.cameraMatrix.mat4[7], this.cameraMatrix.mat4[8], this.cameraMatrix.mat4[9], this.cameraMatrix.mat4[10], this.cameraMatrix.mat4[11], this.cameraMatrix.mat4[12], this.cameraMatrix.mat4[13], this.cameraMatrix.mat4[14], this.cameraMatrix.mat4[15]); + } + return this; + } /** + * Move camera along its local axes while maintaining current camera orientation. + * @method move + * @param {Number} x amount to move along camera's left-right axis + * @param {Number} y amount to move along camera's up-down axis + * @param {Number} z amount to move along camera's forward-backward axis + * @example + *
      + * + * // see the camera move along its own axes while maintaining its orientation + * let cam; + * let delta = 0.5; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * normalMaterial(); + * cam = createCamera(); + * } + * + * function draw() { + * background(200); + * + * // move the camera along its local axes + * cam.move(delta, delta, 0); + * + * // every 100 frames, switch direction + * if (frameCount % 150 === 0) { + * delta *= -1; + * } + * + * translate(-10, -10, 0); + * box(50, 8, 50); + * translate(15, 15, 0); + * box(50, 8, 50); + * translate(15, 15, 0); + * box(50, 8, 50); + * translate(15, 15, 0); + * box(50, 8, 50); + * translate(15, 15, 0); + * box(50, 8, 50); + * translate(15, 15, 0); + * box(50, 8, 50); + * } + * + *
      + * + * @alt + * camera view moves along a series of 3D boxes, maintaining the same + * orientation throughout the move + */ + + }, + { + key: 'move', + value: function move(x, y, z) { + var local = this._getLocalAxes(); + // scale local axes by movement amounts + // based on http://learnwebgl.brown37.net/07_cameras/camera_linear_motion.html + var dx = [ + local.x[0] * x, + local.x[1] * x, + local.x[2] * x + ]; + var dy = [ + local.y[0] * y, + local.y[1] * y, + local.y[2] * y + ]; + var dz = [ + local.z[0] * z, + local.z[1] * z, + local.z[2] * z + ]; + this.camera(this.eyeX + dx[0] + dy[0] + dz[0], this.eyeY + dx[1] + dy[1] + dz[1], this.eyeZ + dx[2] + dy[2] + dz[2], this.centerX + dx[0] + dy[0] + dz[0], this.centerY + dx[1] + dy[1] + dz[1], this.centerZ + dx[2] + dy[2] + dz[2], this.upX, this.upY, this.upZ); + } /** + * 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 + *
      + * + * // 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); + * } + * + *
      + * + * @alt + * camera position changes as the user presses keys, altering view of a 3D box + */ + + }, + { + key: 'setPosition', + value: function setPosition(x, y, z) { + var diffX = x - this.eyeX; + var diffY = y - this.eyeY; + var diffZ = z - this.eyeZ; + this.camera(x, y, z, this.centerX + diffX, this.centerY + diffY, this.centerZ + diffZ, this.upX, this.upY, this.upZ); + } /** + * Copies information about the argument camera's view and projection to + * the target camera. If the target camera is active, it will be reflected + * on the screen. + * + * @method set + * @param {p5.Camera} cam source camera + * + * @example + *
      + * + * let cam, initialCam; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * strokeWeight(3); + * + * // Set the initial state to initialCamera and set it to the camera + * // used for drawing. Then set cam to be the active camera. + * cam = createCamera(); + * initialCam = createCamera(); + * initialCam.camera(100, 100, 100, 0, 0, 0, 0, 0, -1); + * cam.set(initialCam); + * + * setCamera(cam); + * } + * + * function draw() { + * orbitControl(); + * background(255); + * box(50); + * translate(0, 0, -25); + * plane(100); + * } + * + * function doubleClicked(){ + * // Double-click to return the camera to its initial position. + * cam.set(initialCam); + * } + * + *
      + * @alt + * Prepare two cameras. One is the camera that sets the initial state, + * and the other is the camera that moves with interaction. + * Draw a plane and a box on top of it, operate the camera using orbitControl(). + * Double-click to set the camera in the initial state and return to + * the initial state. + */ + + }, + { + key: 'set', + value: function set(cam) { + var keyNamesOfThePropToCopy = [ + 'eyeX', + 'eyeY', + 'eyeZ', + 'centerX', + 'centerY', + 'centerZ', + 'upX', + 'upY', + 'upZ', + 'cameraFOV', + 'aspectRatio', + 'cameraNear', + 'cameraFar', + 'cameraType', + 'yScale' + ]; + for (var _i = 0, _keyNamesOfThePropToC = keyNamesOfThePropToCopy; _i < _keyNamesOfThePropToC.length; _i++) { + var keyName = _keyNamesOfThePropToC[_i]; + this[keyName] = cam[keyName]; + } + this.cameraMatrix = cam.cameraMatrix.copy(); + this.projMatrix = cam.projMatrix.copy(); + // If the target camera is active, update uMVMatrix and uPMatrix. + if (this._isActive()) { + this._renderer.uMVMatrix.mat4 = this.cameraMatrix.mat4.slice(); + this._renderer.uPMatrix.mat4 = this.projMatrix.mat4.slice(); + } + } /** + * For the cameras cam0 and cam1 with the given arguments, their view are combined + * with the parameter amt that represents the quantity, and the obtained view is applied. + * For example, if cam0 is looking straight ahead and cam1 is looking straight + * to the right and amt is 0.5, the applied camera will look to the halfway + * between front and right. + * If the applied camera is active, the applied result will be reflected on the screen. + * When applying this function, all cameras involved must have exactly the same projection + * settings. For example, if one is perspective, ortho, frustum, the other two must also be + * perspective, ortho, frustum respectively. However, if all cameras have ortho settings, + * interpolation is possible if the ratios of left, right, top and bottom are equal to each other. + * For example, when it is changed by orbitControl(). + * + * @method slerp + * @param {p5.Camera} cam0 first p5.Camera + * @param {p5.Camera} cam1 second p5.Camera + * @param {Number} amt amount to use for interpolation during slerp + * + * @example + *
      + * + * let cam0, cam1, cam; + * function setup() { + * createCanvas(100, 100, WEBGL); + * strokeWeight(3); + * + * // camera for slerp. + * cam = createCamera(); + * // cam0 is looking at the cube from the front. + * // cam1 is pointing straight to the right in the cube + * // at the same position as cam0 by doing a pan(-PI/2). + * cam0 = createCamera(); + * cam1 = createCamera(); + * cam1.pan(-PI/2); + * + * // we only use cam. + * setCamera(cam); + * } + * + * function draw() { + * // calculate amount. + * const amt = 0.5 - 0.5 * cos(frameCount * TAU / 120); + * // slerp cam0 and cam1 with amt, set to cam. + * // When amt moves from 0 to 1, cam moves from cam0 to cam1, + * // shaking the camera to the right. + * cam.slerp(cam0, cam1, amt); + * + * background(255); + * // Every time the camera turns right, the cube drifts left. + * box(40); + * } + * + *
      + * @alt + * Prepare two cameras. One camera is facing straight ahead to the cube and the other + * camera is in the same position and looking straight to the right. + * If you use a camera which interpolates these with slerp(), the facing direction + * of the camera will change smoothly between the front and the right. + * + * @example + *
      + * + * let cam, lastCam, initialCam; + * let countForReset = 30; + * // This sample uses orbitControl() to move the camera. + * // Double-clicking the canvas restores the camera to its initial state. + * function setup() { + * createCanvas(100, 100, WEBGL); + * strokeWeight(3); + * + * cam = createCamera(); // main camera + * lastCam = createCamera(); // Camera for recording loc info before reset + * initialCam = createCamera(); // Camera for recording the initial state + * + * setCamera(cam); // set main camera + * } + * + * function draw() { + * if (countForReset < 30) { + * // if the reset count is less than 30, + * // it will move closer to the original camera as it increases. + * countForReset++; + * cam.slerp(lastCam, initialCam, countForReset / 30); + * } else { + * // if the count is 30, + * // you can freely move the main camera with orbitControl(). + * orbitControl(); + * } + * + * background(255); + * box(40); + * } + * // A double-click sets countForReset to 0 and initiates a reset. + * function doubleClicked() { + * if (countForReset === 30) { + * countForReset = 0; + * lastCam.set(cam); + * } + * } + * + *
      + * @alt + * There is a camera, drawing a cube. The camera can be moved freely with + * orbitControl(). Double-click to smoothly return the camera to its initial state. + * The camera cannot be moved during that time. + */ + + }, + { + key: 'slerp', + value: function slerp(cam0, cam1, amt) { + // If t is 0 or 1, do not interpolate and set the argument camera. + if (amt === 0) { + this.set(cam0); + return; + } else if (amt === 1) { + this.set(cam1); + return; + } // For this cameras is ortho, assume that cam0 and cam1 are also ortho + // and interpolate the elements of the projection matrix. + // Use logarithmic interpolation for interpolation. + + if (this.projMatrix.mat4[15] !== 0) { + this.projMatrix.mat4[0] = cam0.projMatrix.mat4[0] * Math.pow(cam1.projMatrix.mat4[0] / cam0.projMatrix.mat4[0], amt); + this.projMatrix.mat4[5] = cam0.projMatrix.mat4[5] * Math.pow(cam1.projMatrix.mat4[5] / cam0.projMatrix.mat4[5], amt); + // If the camera is active, make uPMatrix reflect changes in projMatrix. + if (this._isActive()) { + this._renderer.uPMatrix.mat4 = this.projMatrix.mat4.slice(); + } + } // prepare eye vector and center vector of argument cameras. + + var eye0 = new _main.default.Vector(cam0.eyeX, cam0.eyeY, cam0.eyeZ); + var eye1 = new _main.default.Vector(cam1.eyeX, cam1.eyeY, cam1.eyeZ); + var center0 = new _main.default.Vector(cam0.centerX, cam0.centerY, cam0.centerZ); + var center1 = new _main.default.Vector(cam1.centerX, cam1.centerY, cam1.centerZ); + // Calculate the distance between eye and center for each camera. + // Logarithmically interpolate these with amt. + var dist0 = _main.default.Vector.dist(eye0, center0); + var dist1 = _main.default.Vector.dist(eye1, center1); + var lerpedDist = dist0 * Math.pow(dist1 / dist0, amt); + // Next, calculate the ratio to interpolate the eye and center by a constant + // ratio for each camera. This ratio is the same for both. Also, with this ratio + // of points, the distance is the minimum distance of the two points of + // the same ratio. + // With this method, if the viewpoint is fixed, linear interpolation is performed + // at the viewpoint, and if the center is fixed, linear interpolation is performed + // at the center, resulting in reasonable interpolation. If both move, the point + // halfway between them is taken. + var eyeDiff = _main.default.Vector.sub(eye0, eye1); + var diffDiff = eye0.copy().sub(eye1).sub(center0).add(center1); + // Suppose there are two line segments. Consider the distance between the points + // above them as if they were taken in the same ratio. This calculation figures out + // a ratio that minimizes this. + // Each line segment is, a line segment connecting the viewpoint and the center + // for each camera. + var divider = diffDiff.magSq(); + var ratio = 1; // default. + if (divider > 0.000001) { + ratio = _main.default.Vector.dot(eyeDiff, diffDiff) / divider; + ratio = Math.max(0, Math.min(ratio, 1)); + } // Take the appropriate proportions and work out the points + // that are between the new viewpoint and the new center position. + + var lerpedMedium = _main.default.Vector.lerp(_main.default.Vector.lerp(eye0, center0, ratio), _main.default.Vector.lerp(eye1, center1, ratio), amt); + // Prepare each of rotation matrix from their camera matrix + var rotMat0 = cam0.cameraMatrix.createSubMatrix3x3(); + var rotMat1 = cam1.cameraMatrix.createSubMatrix3x3(); + // get front and up vector from local-coordinate-system. + var front0 = rotMat0.row(2); + var front1 = rotMat1.row(2); + var up0 = rotMat0.row(1); + var up1 = rotMat1.row(1); + // prepare new vectors. + var newFront = new _main.default.Vector(); + var newUp = new _main.default.Vector(); + var newEye = new _main.default.Vector(); + var newCenter = new _main.default.Vector(); + // Create the inverse matrix of mat0 by transposing mat0, + // and multiply it to mat1 from the right. + // This matrix represents the difference between the two. + // 'deltaRot' means 'difference of rotation matrices'. + var deltaRot = rotMat1.mult3x3(rotMat0.copy().transpose3x3()); + // Calculate the trace and from it the cos value of the angle. + // An orthogonal matrix is just an orthonormal basis. If this is not the identity + // matrix, it is a centered orthonormal basis plus some angle of rotation about + // some axis. That's the angle. Letting this be theta, trace becomes 1+2cos(theta). + // reference: https://en.wikipedia.org/wiki/Rotation_matrix#Determining_the_angle + var diag = deltaRot.diagonal(); + var cosTheta = 0.5 * (diag[0] + diag[1] + diag[2] - 1); + // If the angle is close to 0, the two matrices are very close, + // so in that case we execute linearly interpolate. + if (1 - cosTheta < 1e-7) { + // Obtain the front vector and up vector by linear interpolation + // and normalize them. + // calculate newEye, newCenter with newFront vector. + newFront.set(_main.default.Vector.lerp(front0, front1, amt)).normalize(); + newEye.set(newFront).mult(ratio * lerpedDist).add(lerpedMedium); + newCenter.set(newFront).mult((ratio - 1) * lerpedDist).add(lerpedMedium); + newUp.set(_main.default.Vector.lerp(up0, up1, amt)).normalize(); + // set the camera + this.camera(newEye.x, newEye.y, newEye.z, newCenter.x, newCenter.y, newCenter.z, newUp.x, newUp.y, newUp.z); + return; + } // Calculates the axis vector and the angle of the difference orthogonal matrix. + // The axis vector is what I explained earlier in the comments. + // similar calculation is here: + // https://github.com/mrdoob/three.js/blob/883249620049d1632e8791732808fefd1a98c871/src/math/Quaternion.js#L294 + + var a, + b, + c, + sinTheta; + var invOneMinusCosTheta = 1 / (1 - cosTheta); + var maxDiag = Math.max(diag[0], diag[1], diag[2]); + var offDiagSum13 = deltaRot.mat3[1] + deltaRot.mat3[3]; + var offDiagSum26 = deltaRot.mat3[2] + deltaRot.mat3[6]; + var offDiagSum57 = deltaRot.mat3[5] + deltaRot.mat3[7]; + if (maxDiag === diag[0]) { + a = Math.sqrt((diag[0] - cosTheta) * invOneMinusCosTheta); // not zero. + invOneMinusCosTheta /= a; + b = 0.5 * offDiagSum13 * invOneMinusCosTheta; + c = 0.5 * offDiagSum26 * invOneMinusCosTheta; + sinTheta = 0.5 * (deltaRot.mat3[7] - deltaRot.mat3[5]) / a; + } else if (maxDiag === diag[1]) { + b = Math.sqrt((diag[1] - cosTheta) * invOneMinusCosTheta); // not zero. + invOneMinusCosTheta /= b; + c = 0.5 * offDiagSum57 * invOneMinusCosTheta; + a = 0.5 * offDiagSum13 * invOneMinusCosTheta; + sinTheta = 0.5 * (deltaRot.mat3[2] - deltaRot.mat3[6]) / b; + } else { + c = Math.sqrt((diag[2] - cosTheta) * invOneMinusCosTheta); // not zero. + invOneMinusCosTheta /= c; + a = 0.5 * offDiagSum26 * invOneMinusCosTheta; + b = 0.5 * offDiagSum57 * invOneMinusCosTheta; + sinTheta = 0.5 * (deltaRot.mat3[3] - deltaRot.mat3[1]) / c; + } // Constructs a new matrix after interpolating the angles. + // Multiplying mat0 by the first matrix yields mat1, but by creating a state + // in the middle of that matrix, you can obtain a matrix that is + // an intermediate state between mat0 and mat1. + + var angle = amt * Math.atan2(sinTheta, cosTheta); + var cosAngle = Math.cos(angle); + var sinAngle = Math.sin(angle); + var oneMinusCosAngle = 1 - cosAngle; + var ab = a * b; + var bc = b * c; + var ca = c * a; + var lerpedRotMat = new _main.default.Matrix('mat3', [ + cosAngle + oneMinusCosAngle * a * a, + oneMinusCosAngle * ab + sinAngle * c, + oneMinusCosAngle * ca - sinAngle * b, + oneMinusCosAngle * ab - sinAngle * c, + cosAngle + oneMinusCosAngle * b * b, + oneMinusCosAngle * bc + sinAngle * a, + oneMinusCosAngle * ca + sinAngle * b, + oneMinusCosAngle * bc - sinAngle * a, + cosAngle + oneMinusCosAngle * c * c + ]); + // Multiply this to mat0 from left to get the interpolated front vector. + // calculate newEye, newCenter with newFront vector. + lerpedRotMat.multiplyVec3(front0, newFront); + newEye.set(newFront).mult(ratio * lerpedDist).add(lerpedMedium); + newCenter.set(newFront).mult((ratio - 1) * lerpedDist).add(lerpedMedium); + lerpedRotMat.multiplyVec3(up0, newUp); + // We also get the up vector in the same way and set the camera. + // The eye position and center position are calculated based on the front vector. + this.camera(newEye.x, newEye.y, newEye.z, newCenter.x, newCenter.y, newCenter.z, newUp.x, newUp.y, newUp.z); + } //////////////////////////////////////////////////////////////////////////////// + // Camera Helper Methods + //////////////////////////////////////////////////////////////////////////////// + // @TODO: combine this function with _setDefaultCamera to compute these values + // as-needed + + }, + { + key: '_computeCameraDefaultSettings', + value: function _computeCameraDefaultSettings() { + this.defaultAspectRatio = this._renderer.width / this._renderer.height; + this.defaultEyeX = 0; + this.defaultEyeY = 0; + this.defaultEyeZ = 800; + this.defaultCameraFOV = 2 * Math.atan(this._renderer.height / 2 / this.defaultEyeZ); + this.defaultCenterX = 0; + this.defaultCenterY = 0; + this.defaultCenterZ = 0; + this.defaultCameraNear = this.defaultEyeZ * 0.1; + this.defaultCameraFar = this.defaultEyeZ * 10; + } //detect if user didn't set the camera + //then call this function below + + }, + { + key: '_setDefaultCamera', + value: function _setDefaultCamera() { + this.cameraFOV = this.defaultCameraFOV; + this.aspectRatio = this.defaultAspectRatio; + this.eyeX = this.defaultEyeX; + this.eyeY = this.defaultEyeY; + this.eyeZ = this.defaultEyeZ; + this.centerX = this.defaultCenterX; + this.centerY = this.defaultCenterY; + this.centerZ = this.defaultCenterZ; + this.upX = 0; + this.upY = 1; + this.upZ = 0; + this.cameraNear = this.defaultCameraNear; + this.cameraFar = this.defaultCameraFar; + this.perspective(); + this.camera(); + this.cameraType = 'default'; + } + }, + { + key: '_resize', + value: function _resize() { + // If we're using the default camera, update the aspect ratio + if (this.cameraType === 'default') { + this._computeCameraDefaultSettings(); + this.cameraFOV = this.defaultCameraFOV; + this.aspectRatio = this.defaultAspectRatio; + this.perspective(); + } + } /** + * Returns a copy of a camera. + * @method copy + * @private + */ + + }, + { + key: 'copy', + value: function copy() { + var _cam = new _main.default.Camera(this._renderer); + _cam.cameraFOV = this.cameraFOV; + _cam.aspectRatio = this.aspectRatio; + _cam.eyeX = this.eyeX; + _cam.eyeY = this.eyeY; + _cam.eyeZ = this.eyeZ; + _cam.centerX = this.centerX; + _cam.centerY = this.centerY; + _cam.centerZ = this.centerZ; + _cam.upX = this.upX; + _cam.upY = this.upY; + _cam.upZ = this.upZ; + _cam.cameraNear = this.cameraNear; + _cam.cameraFar = this.cameraFar; + _cam.cameraType = this.cameraType; + _cam.cameraMatrix = this.cameraMatrix.copy(); + _cam.projMatrix = this.projMatrix.copy(); + _cam.yScale = this.yScale; + return _cam; + } /** + * Returns a camera's local axes: left-right, up-down, and forward-backward, + * as defined by vectors in world-space. + * @method _getLocalAxes + * @private + */ + + }, + { + key: '_getLocalAxes', + value: function _getLocalAxes() { + // calculate camera local Z vector + var z0 = this.eyeX - this.centerX; + var z1 = this.eyeY - this.centerY; + var z2 = this.eyeZ - this.centerZ; + // normalize camera local Z vector + var eyeDist = Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); + if (eyeDist !== 0) { + z0 /= eyeDist; + z1 /= eyeDist; + z2 /= eyeDist; + } // calculate camera Y vector + + var y0 = this.upX; + var y1 = this.upY; + var y2 = this.upZ; + // compute camera local X vector as up vector (local Y) cross local Z + var x0 = y1 * z2 - y2 * z1; + var x1 = - y0 * z2 + y2 * z0; + var x2 = y0 * z1 - y1 * z0; + // recompute y = z cross x + y0 = z1 * x2 - z2 * x1; + y1 = - z0 * x2 + z2 * x0; + y2 = z0 * x1 - z1 * x0; + // cross product gives area of parallelogram, which is < 1.0 for + // non-perpendicular unit-length vectors; so normalize x, y here: + var xmag = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); + if (xmag !== 0) { + x0 /= xmag; + x1 /= xmag; + x2 /= xmag; + } + var ymag = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); + if (ymag !== 0) { + y0 /= ymag; + y1 /= ymag; + y2 /= ymag; + } + return { + x: [ + x0, + x1, + x2 + ], + y: [ + y0, + y1, + y2 + ], + z: [ + z0, + z1, + z2 + ] + }; + } /** + * Orbits the camera about center point. For use with orbitControl(). + * @method _orbit + * @private + * @param {Number} dTheta change in spherical coordinate theta + * @param {Number} dPhi change in spherical coordinate phi + * @param {Number} dRadius change in radius + */ + + }, + { + key: '_orbit', + value: function _orbit(dTheta, dPhi, dRadius) { + // Calculate the vector and its magnitude from the center to the viewpoint + var diffX = this.eyeX - this.centerX; + var diffY = this.eyeY - this.centerY; + var diffZ = this.eyeZ - this.centerZ; + var camRadius = Math.hypot(diffX, diffY, diffZ); + // front vector. unit vector from center to eye. + var front = new _main.default.Vector(diffX, diffY, diffZ).normalize(); + // up vector. normalized camera's up vector. + var up = new _main.default.Vector(this.upX, this.upY, this.upZ).normalize(); // y-axis + // side vector. Right when viewed from the front + var side = new _main.default.Vector.cross(up, front).normalize(); // x-axis + // vertical vector. normalized vector of projection of front vector. + var vertical = new _main.default.Vector.cross(side, up); // z-axis + // update camRadius + camRadius *= Math.pow(10, dRadius); + // prevent zooming through the center: + if (camRadius < this.cameraNear) { + camRadius = this.cameraNear; + } + if (camRadius > this.cameraFar) { + camRadius = this.cameraFar; + } // calculate updated camera angle + // Find the angle between the "up" and the "front", add dPhi to that. + // angleBetween() may return negative value. Since this specification is subject to change + // due to version updates, it cannot be adopted, so here we calculate using a method + // that directly obtains the absolute value. + + var camPhi = Math.acos(Math.max( - 1, Math.min(1, _main.default.Vector.dot(front, up)))) + dPhi; + // Rotate by dTheta in the shortest direction from "vertical" to "side" + var camTheta = dTheta; + // Invert camera's upX, upY, upZ if dPhi is below 0 or above PI + if (camPhi <= 0 || camPhi >= Math.PI) { + this.upX *= - 1; + this.upY *= - 1; + this.upZ *= - 1; + } // update eye vector by calculate new front vector + + up.mult(Math.cos(camPhi)); + vertical.mult(Math.cos(camTheta) * Math.sin(camPhi)); + side.mult(Math.sin(camTheta) * Math.sin(camPhi)); + front.set(up).add(vertical).add(side); + this.eyeX = camRadius * front.x + this.centerX; + this.eyeY = camRadius * front.y + this.centerY; + this.eyeZ = camRadius * front.z + this.centerZ; + // update camera + this.camera(this.eyeX, this.eyeY, this.eyeZ, this.centerX, this.centerY, this.centerZ, this.upX, this.upY, this.upZ); + } /** + * Orbits the camera about center point. For use with orbitControl(). + * Unlike _orbit(), the direction of rotation always matches the direction of pointer movement. + * @method _orbitFree + * @private + * @param {Number} dx the x component of the rotation vector. + * @param {Number} dy the y component of the rotation vector. + * @param {Number} dRadius change in radius + */ + + }, + { + key: '_orbitFree', + value: function _orbitFree(dx, dy, dRadius) { + // Calculate the vector and its magnitude from the center to the viewpoint + var diffX = this.eyeX - this.centerX; + var diffY = this.eyeY - this.centerY; + var diffZ = this.eyeZ - this.centerZ; + var camRadius = Math.hypot(diffX, diffY, diffZ); + // front vector. unit vector from center to eye. + var front = new _main.default.Vector(diffX, diffY, diffZ).normalize(); + // up vector. camera's up vector. + var up = new _main.default.Vector(this.upX, this.upY, this.upZ); + // side vector. Right when viewed from the front. (like x-axis) + var side = new _main.default.Vector.cross(up, front).normalize(); + // down vector. Bottom when viewed from the front. (like y-axis) + var down = new _main.default.Vector.cross(front, side); + // side vector and down vector are no longer used as-is. + // Create a vector representing the direction of rotation + // in the form cos(direction)*side + sin(direction)*down. + // Make the current side vector into this. + var directionAngle = Math.atan2(dy, dx); + down.mult(Math.sin(directionAngle)); + side.mult(Math.cos(directionAngle)).add(down); + // The amount of rotation is the size of the vector (dx, dy). + var rotAngle = Math.sqrt(dx * dx + dy * dy); + // The vector that is orthogonal to both the front vector and + // the rotation direction vector is the rotation axis vector. + var axis = new _main.default.Vector.cross(front, side); + // update camRadius + camRadius *= Math.pow(10, dRadius); + // prevent zooming through the center: + if (camRadius < this.cameraNear) { + camRadius = this.cameraNear; + } + if (camRadius > this.cameraFar) { + camRadius = this.cameraFar; + } // If the axis vector is likened to the z-axis, the front vector is + // the x-axis and the side vector is the y-axis. Rotate the up and front + // vectors respectively by thinking of them as rotations around the z-axis. + // Calculate the components by taking the dot product and + // calculate a rotation based on that. + + var c = Math.cos(rotAngle); + var s = Math.sin(rotAngle); + var dotFront = up.dot(front); + var dotSide = up.dot(side); + var ux = dotFront * c + dotSide * s; + var uy = - dotFront * s + dotSide * c; + var uz = up.dot(axis); + up.x = ux * front.x + uy * side.x + uz * axis.x; + up.y = ux * front.y + uy * side.y + uz * axis.y; + up.z = ux * front.z + uy * side.z + uz * axis.z; + // We won't be using the side vector and the front vector anymore, + // so let's make the front vector into the vector from the center to the new eye. + side.mult( - s); + front.mult(c).add(side).mult(camRadius); + // it's complete. let's update camera. + this.camera(front.x + this.centerX, front.y + this.centerY, front.z + this.centerZ, this.centerX, this.centerY, this.centerZ, up.x, up.y, up.z); + } /** + * Returns true if camera is currently attached to renderer. + * @method _isActive + * @private + */ + + }, + { + key: '_isActive', + value: function _isActive() { + return this === this._renderer._curCamera; + } + } + ]); + return Camera; + }(); /** - * Sets the coordinate space for texture mapping. The default mode is IMAGE - * which refers to the actual coordinates of the image. - * NORMAL refers to a normalized space of values ranging from 0 to 1. - * - * With IMAGE, if an image is 100×200 pixels, mapping the image onto the entire - * size of a quad would require the points (0,0) (100, 0) (100,200) (0,200). - * The same mapping in NORMAL is (0,0) (1,0) (1,1) (0,1). - * @method textureMode - * @param {Constant} mode either IMAGE or NORMAL + * Sets the current (active) camera of a 3D sketch. + * Allows for switching between multiple cameras. + * @method setCamera + * @param {p5.Camera} cam p5.Camera object + * @for p5 * @example *
      * - * let img; - * - * function preload() { - * img = loadImage('assets/laDefense.jpg'); - * } + * let cam1, cam2; + * let currentCamera; * * function setup() { * createCanvas(100, 100, WEBGL); - * describe('quad with a texture, mapped using normalized coordinates'); + * 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; + * + * describe( + * 'Canvas switches between two camera views, each showing a series of spinning 3D boxes.' + * ); * } * * 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(); - * } - * - *
      - * @alt - * quad with a texture, mapped using normalized coordinates + * background(200); * - * @example - *
      - * - * let img; + * // camera 1: + * cam1.lookAt(0, 0, 0); + * cam1.setPosition(sin(frameCount / 60) * 200, 0, 100); * - * function preload() { - * img = loadImage('assets/laDefense.jpg'); - * } + * // every 100 frames, switch between the two cameras + * if (frameCount % 100 === 0) { + * if (currentCamera === 1) { + * setCamera(cam1); + * currentCamera = 0; + * } else { + * setCamera(cam2); + * currentCamera = 1; + * } + * } * - * function setup() { - * createCanvas(100, 100, WEBGL); - * describe('quad with a texture, mapped using image coordinates'); + * drawBoxes(); * } * - * function draw() { - * texture(img); - * textureMode(IMAGE); - * 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(); + * 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); * } * *
      + * * @alt - * quad with a texture, mapped using image coordinates + * Canvas switches between two camera views, each showing a series of spinning + * 3D boxes. */ - _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; - } + _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]); }; - /** - * Sets the global texture wrapping mode. This controls how textures behave - * when their uv's go outside of the 0 to 1 range. There are three options: - * CLAMP, REPEAT, and MIRROR. - * - * CLAMP causes the pixels at the edge of the texture to extend to the bounds. - * REPEAT causes the texture to tile repeatedly until reaching the bounds. - * MIRROR works similarly to REPEAT but it flips the texture with every new tile. - * - * REPEAT & MIRROR are only available if the texture - * is a power of two size (128, 256, 512, 1024, etc.). + var _default = _main.default.Camera; + exports.default = _default; + }, + { + '../core/main': 298, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.math.hypot': 188, + 'core-js/modules/es.string.sub': 218 + } + ], + 348: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.math.log2'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.typed-array.float32-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.math.log2'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.typed-array.float32-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } /** + * An internal class to store data that will be sent to a p5.RenderBuffer. + * Those need to eventually go into a Float32Array, so this class provides a + * variable-length array container backed by a Float32Array so that it can be + * sent to the GPU without allocating a new array each frame. * - * This method will affect all textures in your sketch until a subsequent - * textureWrap() call is made. + * Like a C++ vector, its fixed-length Float32Array backing its contents will + * double in size when it goes over its capacity. * - * If only one argument is provided, it will be applied to both the - * horizontal and vertical axes. - * @method textureWrap - * @param {Constant} wrapX either CLAMP, REPEAT, or MIRROR - * @param {Constant} [wrapY] either CLAMP, REPEAT, or MIRROR * @example *
      * - * let img; - * function preload() { - * img = loadImage('assets/rockies128.jpg'); - * } - * - * function setup() { - * createCanvas(100, 100, WEBGL); - * textureWrap(MIRROR); - * describe('an image of the rocky mountains repeated in mirrored tiles'); - * } - * - * function draw() { - * background(0); - * - * let dX = mouseX; - * let dY = mouseY; + * // Initialize storage with a capacity of 4 + * const storage = new DataArray(4); + * console.log(storage.data.length); // 4 + * console.log(storage.length); // 0 + * console.log(storage.dataArray()); // Empty Float32Array * - * let u = lerp(1.0, 2.0, dX); - * let v = lerp(1.0, 2.0, dY); - * - * scale(width / 2); - * - * texture(img); - * - * beginShape(TRIANGLES); - * vertex(-1, -1, 0, 0, 0); - * vertex(1, -1, 0, u, 0); - * vertex(1, 1, 0, u, v); - * - * vertex(1, 1, 0, u, v); - * vertex(-1, 1, 0, 0, v); - * vertex(-1, -1, 0, 0, 0); - * endShape(); - * } - * - *
      - * - * @alt - * an image of the rocky mountains repeated in mirrored tiles - */ - _main.default.prototype.textureWrap = function (wrapX) { - var wrapY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : wrapX; - this._renderer.textureWrapX = wrapX; - this._renderer.textureWrapY = wrapY; - var textures = this._renderer.textures; - for (var i = 0; i < textures.length; i++) { - textures[i].setWrapMode(wrapX, wrapY); - } - }; - /** - * Sets the current material as a normal material. - * - * A normal material is not affected by light. It is often used as - * a placeholder material when debugging. - * - * Surfaces facing the X-axis become red, those facing the Y-axis - * become green, and those facing the Z-axis become blue. - * - * You can view more materials in this - * example. - * - * @method normalMaterial - * @chainable - * @example - *
      - * - * function setup() { - * createCanvas(100, 100, WEBGL); - * describe('Sphere with normal material'); - * } - * - * function draw() { - * background(200); - * normalMaterial(); - * sphere(40); - * } - * - *
      - * @alt - * Sphere with normal material - */ - _main.default.prototype.normalMaterial = function () { - this._assert3d('normalMaterial'); - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - _main.default._validateParameters('normalMaterial', args); - this._renderer.drawMode = constants.FILL; - this._renderer._useSpecularMaterial = false; - this._renderer._useEmissiveMaterial = false; - this._renderer._useNormalMaterial = true; - this._renderer.curFillColor = [ - 1, - 1, - 1, - 1 - ]; - this._renderer._setProperty('_doFill', true); - this.noStroke(); - return this; - }; - /** - * Sets the ambient color of the material. - * - * The ambientMaterial() color is the color the object will reflect - * under **any** lighting. - * - * Consider an ambientMaterial() with the color yellow (255, 255, 0). - * If the light emits the color white (255, 255, 255), then the object - * will appear yellow as it will reflect the red and green components - * of the light. If the light emits the color red (255, 0, 0), then - * the object will appear red as it will reflect the red component - * of the light. If the light emits the color blue (0, 0, 255), - * then the object will appear black, as there is no component of - * the light that it can reflect. - * - * You can view more materials in this - * example. - * - * @method ambientMaterial - * @param {Number} v1 red or hue value relative to the current - * color range - * @param {Number} v2 green or saturation value relative to the - * current color range - * @param {Number} v3 blue or brightness value relative to the - * current color range - * @chainable - * @example - *
      - * - * function setup() { - * createCanvas(100, 100, WEBGL); - * describe('sphere reflecting red, blue, and green light'); - * } - * function draw() { - * background(0); - * noStroke(); - * ambientLight(255); - * ambientMaterial(70, 130, 230); - * sphere(40); - * } - * - *
      - * @alt - * sphere reflecting red, blue, and green light - * - * @example - *
      - * - * // ambientLight is both red and blue (magenta), - * // so object only reflects it's red and blue components - * function setup() { - * createCanvas(100, 100, WEBGL); - * describe('box reflecting only red and blue light'); - * } - * function draw() { - * background(70); - * ambientLight(255, 0, 255); // magenta light - * ambientMaterial(255); // white material - * box(30); - * } - * - *
      - * @alt - * box reflecting only red and blue light - * - * @example - *
      - * - * // ambientLight is green. Since object does not contain - * // green, it does not reflect any light - * function setup() { - * createCanvas(100, 100, WEBGL); - * describe('box reflecting no light'); - * } - * function draw() { - * background(70); - * ambientLight(0, 255, 0); // green light - * ambientMaterial(255, 0, 255); // magenta material - * box(30); - * } - * - *
      - * @alt - * box reflecting no light - */ - /** - * @method ambientMaterial - * @param {Number} gray number specifying value between - * white and black - * @chainable - */ - /** - * @method ambientMaterial - * @param {p5.Color|Number[]|String} color - * color as a p5.Color, - * as an array, or as a CSS string - * @chainable - */ - _main.default.prototype.ambientMaterial = function (v1, v2, v3) { - this._assert3d('ambientMaterial'); - _main.default._validateParameters('ambientMaterial', arguments); - var color = _main.default.prototype.color.apply(this, arguments); - this._renderer.curAmbientColor = color._array; - this._renderer._useNormalMaterial = false; - this._renderer._enableLighting = true; - this._renderer._tex = null; - this._renderer._setProperty('_doFill', true); - return this; - }; - /** - * Sets the emissive color of the material. - * - * An emissive material will display the emissive color at - * full strength regardless of lighting. This can give the - * appearance that the object is glowing. - * - * Note, "emissive" is a misnomer in the sense that the material - * does not actually emit light that will affect surrounding objects. - * - * You can view more materials in this - * example. - * - * @method emissiveMaterial - * @param {Number} v1 red or hue value relative to the current - * color range - * @param {Number} v2 green or saturation value relative to the - * current color range - * @param {Number} v3 blue or brightness value relative to the - * current color range - * @param {Number} [alpha] alpha value relative to current color - * range (default is 0-255) - * @chainable - * @example - *
      - * - * function setup() { - * createCanvas(100, 100, WEBGL); - * describe('sphere with green emissive material'); - * } - * function draw() { - * background(0); - * noStroke(); - * ambientLight(0); - * emissiveMaterial(130, 230, 0); - * sphere(40); - * } - * - *
      - * - * @alt - * sphere with green emissive material - */ - /** - * @method emissiveMaterial - * @param {Number} gray number specifying value between - * white and black - * @chainable - */ - /** - * @method emissiveMaterial - * @param {p5.Color|Number[]|String} color - * color as a p5.Color, - * as an array, or as a CSS string - * @chainable - */ - _main.default.prototype.emissiveMaterial = function (v1, v2, v3, a) { - this._assert3d('emissiveMaterial'); - _main.default._validateParameters('emissiveMaterial', arguments); - var color = _main.default.prototype.color.apply(this, arguments); - this._renderer.curEmissiveColor = color._array; - this._renderer._useEmissiveMaterial = true; - this._renderer._useNormalMaterial = false; - this._renderer._enableLighting = true; - this._renderer._tex = null; - return this; - }; - /** - * Sets the specular color of the material. - * - * A specular material is reflective (shiny). The shininess can be - * controlled by the shininess() function. - * - * Like ambientMaterial(), - * the specularMaterial() color is the color the object will reflect - * under ambientLight(). - * However unlike ambientMaterial(), for all other types of lights - * (directionalLight(), - * pointLight(), - * spotLight()), - * a specular material will reflect the **color of the light source**. - * This is what gives it its "shiny" appearance. - * - * You can view more materials in this - * example. - * - * @method specularMaterial - * @param {Number} gray number specifying value between white and black. - * @param {Number} [alpha] alpha value relative to current color range - * (default is 0-255) - * @chainable - * - * @example - *
      - * - * function setup() { - * createCanvas(100, 100, WEBGL); - * noStroke(); - * describe('torus with specular material'); - * } - * - * function draw() { - * background(0); - * - * ambientLight(60); - * - * // add point light to showcase specular material - * let locX = mouseX - width / 2; - * let locY = mouseY - height / 2; - * pointLight(255, 255, 255, locX, locY, 50); - * - * specularMaterial(250); - * shininess(50); - * torus(30, 10, 64, 64); - * } - * - *
      - * @alt - * torus with specular material - */ - /** - * @method specularMaterial - * @param {Number} v1 red or hue value relative to - * the current color range - * @param {Number} v2 green or saturation value - * relative to the current color range - * @param {Number} v3 blue or brightness value - * relative to the current color range - * @param {Number} [alpha] - * @chainable - */ - /** - * @method specularMaterial - * @param {p5.Color|Number[]|String} color - * color as a p5.Color, - * as an array, or as a CSS string - * @chainable - */ - _main.default.prototype.specularMaterial = function (v1, v2, v3, alpha) { - this._assert3d('specularMaterial'); - _main.default._validateParameters('specularMaterial', arguments); - var color = _main.default.prototype.color.apply(this, arguments); - this._renderer.curSpecularColor = color._array; - this._renderer._useSpecularMaterial = true; - this._renderer._useNormalMaterial = false; - this._renderer._enableLighting = true; - this._renderer._tex = null; - return this; - }; - /** - * Sets the amount of gloss ("shininess") of a - * specularMaterial(). - * - * The default and minimum value is 1. - * - * @method shininess - * @param {Number} shine degree of shininess - * @chainable - * @example - *
      - * - * function setup() { - * createCanvas(100, 100, WEBGL); - * describe('two spheres, one more shiny than the other'); - * } - * 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); - * } + * storage.push(1, 2, 3, 4, 5, 6); + * console.log(storage.data.length); // 8 + * console.log(storage.length); // 6 + * console.log(storage.dataArray()); // Float32Array{1, 2, 3, 4, 5, 6} * *
      - * @alt - * two spheres, one more shiny than the other - */ - _main.default.prototype.shininess = function (shine) { - this._assert3d('shininess'); - _main.default._validateParameters('shininess', arguments); - if (shine < 1) { - shine = 1; - } - this._renderer._useShininess = shine; - return this; - }; - /** - * @private blends colors according to color components. - * If alpha value is less than 1, or non-standard blendMode - * we need to enable blending on our gl context. - * @param {Number[]} color [description] - * @return {Number[]]} Normalized numbers array - */ - _main.default.RendererGL.prototype._applyColorBlend = function (colors) { - var gl = this.GL; - var isTexture = this.drawMode === constants.TEXTURE; - var doBlend = this.userFillShader || this.userStrokeShader || this.userPointShader || isTexture || this.curBlendMode !== constants.BLEND || colors[colors.length - 1] < 1 || this._isErasing; - if (doBlend !== this._isBlending) { - if (doBlend || this.curBlendMode !== constants.BLEND && this.curBlendMode !== constants.ADD) { - gl.enable(gl.BLEND); - } else { - gl.disable(gl.BLEND); - } - gl.depthMask(true); - this._isBlending = doBlend; - } - this._applyBlendMode(); - return colors; - }; - /** - * @private sets blending in gl context to curBlendMode - * @param {Number[]} color [description] - * @return {Number[]]} Normalized numbers array */ - _main.default.RendererGL.prototype._applyBlendMode = function () { - if (this._cachedBlendMode === this.curBlendMode) { - return; - } - var gl = this.GL; - switch (this.curBlendMode) { - case constants.BLEND: - gl.blendEquation(gl.FUNC_ADD); - gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); - break; - case constants.ADD: - gl.blendEquation(gl.FUNC_ADD); - gl.blendFunc(gl.ONE, gl.ONE); - break; - case constants.REMOVE: - gl.blendEquation(gl.FUNC_ADD); - gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_ALPHA); - break; - case constants.MULTIPLY: - gl.blendEquation(gl.FUNC_ADD); - gl.blendFunc(gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA); - break; - case constants.SCREEN: - gl.blendEquation(gl.FUNC_ADD); - gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_COLOR); - break; - case constants.EXCLUSION: - gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); - gl.blendFuncSeparate(gl.ONE_MINUS_DST_COLOR, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE); - break; - case constants.REPLACE: - gl.blendEquation(gl.FUNC_ADD); - gl.blendFunc(gl.ONE, gl.ZERO); - break; - case constants.SUBTRACT: - gl.blendEquationSeparate(gl.FUNC_REVERSE_SUBTRACT, gl.FUNC_ADD); - gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); - break; - case constants.DARKEST: - if (this.blendExt) { - gl.blendEquationSeparate(this.blendExt.MIN_EXT, gl.FUNC_ADD); - gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE); - } else { - console.warn('blendMode(DARKEST) does not work in your browser in WEBGL mode.'); - } - break; - case constants.LIGHTEST: - if (this.blendExt) { - gl.blendEquationSeparate(this.blendExt.MAX_EXT, gl.FUNC_ADD); - gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE); - } else { - console.warn('blendMode(LIGHTEST) does not work in your browser in WEBGL mode.'); + + _main.default.DataArray = /*#__PURE__*/ function () { + function DataArray() { + var initialLength = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 128; + _classCallCheck(this, DataArray); + this.length = 0; + this.data = new Float32Array(initialLength); + this.initialLength = initialLength; + } /** + * Returns a Float32Array window sized to the exact length of the data + */ + + _createClass(DataArray, [ + { + key: 'dataArray', + value: function dataArray() { + return this.subArray(0, this.length); + } /** + * A "soft" clear, which keeps the underlying storage size the same, but + * empties the contents of its dataArray() + */ + + }, + { + key: 'clear', + value: function clear() { + this.length = 0; + } /** + * Can be used to scale a DataArray back down to fit its contents. + */ + + }, + { + key: 'rescale', + value: function rescale() { + if (this.length < this.data.length / 2) { + // Find the power of 2 size that fits the data + var targetLength = 1 << Math.ceil(Math.log2(this.length)); + var newData = new Float32Array(targetLength); + newData.set(this.data.subarray(0, this.length), 0); + this.data = newData; + } + } /** + * A full reset, which allocates a new underlying Float32Array at its initial + * length + */ + + }, + { + key: 'reset', + value: function reset() { + this.clear(); + this.data = new Float32Array(this.initialLength); + } /** + * Adds values to the DataArray, expanding its internal storage to + * accommodate the new items. + */ + + }, + { + key: 'push', + value: function push() { + for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) { + values[_key] = arguments[_key]; + } + this.ensureLength(this.length + values.length); + this.data.set(values, this.length); + this.length += values.length; + } /** + * Returns a copy of the data from the index `from`, inclusive, to the index + * `to`, exclusive + */ + + }, + { + key: 'slice', + value: function slice(from, to) { + return this.data.slice(from, Math.min(to, this.length)); + } /** + * Returns a mutable Float32Array window from the index `from`, inclusive, to + * the index `to`, exclusive + */ + + }, + { + key: 'subArray', + value: function subArray(from, to) { + return this.data.subarray(from, Math.min(to, this.length)); + } /** + * Expand capacity of the internal storage until it can fit a target size + */ + + }, + { + key: 'ensureLength', + value: function ensureLength(target) { + while (this.data.length < target) { + var newData = new Float32Array(this.data.length * 2); + newData.set(this.data, 0); + this.data = newData; + } } - 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; + } + ]); + return DataArray; + }(); + var _default = _main.default.DataArray; exports.default = _default; }, { - '../core/constants': 278, - '../core/main': 290, - './p5.Texture': 346, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.join': 177, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + '../core/main': 298, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.math.log2': 189, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.typed-array.copy-within': 223, + 'core-js/modules/es.typed-array.every': 224, + 'core-js/modules/es.typed-array.fill': 225, + 'core-js/modules/es.typed-array.filter': 226, + 'core-js/modules/es.typed-array.find': 228, + 'core-js/modules/es.typed-array.find-index': 227, + 'core-js/modules/es.typed-array.float32-array': 229, + 'core-js/modules/es.typed-array.for-each': 231, + 'core-js/modules/es.typed-array.includes': 232, + 'core-js/modules/es.typed-array.index-of': 233, + 'core-js/modules/es.typed-array.iterator': 236, + 'core-js/modules/es.typed-array.join': 237, + 'core-js/modules/es.typed-array.last-index-of': 238, + 'core-js/modules/es.typed-array.map': 239, + 'core-js/modules/es.typed-array.reduce': 241, + 'core-js/modules/es.typed-array.reduce-right': 240, + 'core-js/modules/es.typed-array.reverse': 242, + 'core-js/modules/es.typed-array.set': 243, + 'core-js/modules/es.typed-array.slice': 244, + 'core-js/modules/es.typed-array.some': 245, + 'core-js/modules/es.typed-array.sort': 246, + 'core-js/modules/es.typed-array.subarray': 247, + 'core-js/modules/es.typed-array.to-locale-string': 248, + 'core-js/modules/es.typed-array.to-string': 249 } ], - 338: [ + 349: [ function (_dereq_, module, exports) { 'use strict'; - Object.defineProperty(exports, '__esModule', { - value: true - }); - exports.default = void 0; - var _main = _interopRequireDefault(_dereq_('../core/main')); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: - obj - }; - } /** - * @module 3D - * @submodule Camera - * @requires core - */ - //////////////////////////////////////////////////////////////////////////////// - // p5.Prototype Methods - //////////////////////////////////////////////////////////////////////////////// - /** - * Sets the position of the current camera in a 3D sketch. - * Parameters for this function define the camera's position, - * the center of the sketch (where the camera is pointing), - * and an up direction (the orientation of the camera). - * - * This function simulates the movements of the camera, allowing objects to be - * viewed from various angles. Remember, it does not move the objects themselves - * but the camera instead. For example when the centerX value is positive, - * and the camera is rotating to the right side of the sketch, - * the object will seem like it's moving to the left. - * - * See this example - * to view the position of your camera. - * - * If no parameters are given, the following default is used: - * camera(0, 0, (height/2) / tan(PI/6), 0, 0, 0, 0, 1, 0) - * @method camera - * @constructor - * @for p5 - * @param {Number} [x] camera position value on x axis - * @param {Number} [y] camera position value on y axis - * @param {Number} [z] camera position value on z axis - * @param {Number} [centerX] x coordinate representing center of the sketch - * @param {Number} [centerY] y coordinate representing center of the sketch - * @param {Number} [centerZ] z coordinate representing center of the sketch - * @param {Number} [upX] x component of direction 'up' from camera - * @param {Number} [upY] y component of direction 'up' from camera - * @param {Number} [upZ] z component of direction 'up' from camera - * @chainable - * @example - *
      - * - * function setup() { - * createCanvas(100, 100, WEBGL); - * describe('a square moving closer and then away from the camera.'); - * } - * function draw() { - * background(204); - * //move the camera away from the plane by a sin wave - * camera(0, 0, 20 + sin(frameCount * 0.01) * 10, 0, 0, 0, 0, 1, 0); - * plane(10, 10); - * } - * - *
      - * - * @example - *
      - * - * //move slider to see changes! - * //sliders control the first 6 parameters of camera() - * let sliderGroup = []; - * let X; - * let Y; - * let Z; - * let centerX; - * let centerY; - * let centerZ; - * let h = 20; - * - * function setup() { - * createCanvas(100, 100, WEBGL); - * //create sliders - * for (var i = 0; i < 6; i++) { - * if (i === 2) { - * sliderGroup[i] = createSlider(10, 400, 200); - * } else { - * sliderGroup[i] = createSlider(-400, 400, 0); - * } - * h = map(i, 0, 6, 5, 85); - * sliderGroup[i].position(10, height + h); - * sliderGroup[i].style('width', '80px'); - * } - * describe( - * 'White square repeatedly grows to fill canvas and then shrinks. An interactive example of a red cube with 3 sliders for moving it across x, y, z axis and 3 sliders for shifting its center.' - * ); - * } - * - * function draw() { - * background(60); - * // assigning sliders' value to each parameters - * X = sliderGroup[0].value(); - * Y = sliderGroup[1].value(); - * Z = sliderGroup[2].value(); - * centerX = sliderGroup[3].value(); - * centerY = sliderGroup[4].value(); - * centerZ = sliderGroup[5].value(); - * camera(X, Y, Z, centerX, centerY, centerZ, 0, 1, 0); - * stroke(255); - * fill(255, 102, 94); - * box(85); - * } - * - *
      - * @alt - * White square repeatedly grows to fill canvas and then shrinks. - * An interactive example of a red cube with 3 sliders for moving it across x, y, - * z axis and 3 sliders for shifting its center. - */ - - _main.default.prototype.camera = function () { - var _this$_renderer$_curC; - this._assert3d('camera'); - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.fill'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.get-prototype-of'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.reflect.construct'); + _dereq_('core-js/modules/es.reflect.get'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.typed-array.float32-array'); + _dereq_('core-js/modules/es.typed-array.uint8-array'); + _dereq_('core-js/modules/es.typed-array.uint8-clamped-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; } - _main.default._validateParameters('camera', args); - (_this$_renderer$_curC = this._renderer._curCamera).camera.apply(_this$_renderer$_curC, args); - return this; - }; - /** - * Sets a perspective projection for the current camera in a 3D sketch. - * This projection represents depth through foreshortening: objects - * that are close to the camera appear their actual size while those - * that are further away from the camera appear smaller. - * - * The parameters to this function define the viewing frustum - * (the truncated pyramid within which objects are seen by the camera) through - * vertical field of view, aspect ratio (usually width/height), and near and far - * clipping planes. - * - * If no parameters are given, the following default is used: - * perspective(PI/3, width/height, eyeZ/10, eyeZ*10), - * where eyeZ is equal to ((height/2) / tan(PI/6)). - * @method perspective - * @for p5 - * @param {Number} [fovy] camera frustum vertical field of view, - * from bottom to top of view, in angleMode units - * @param {Number} [aspect] camera frustum aspect ratio - * @param {Number} [near] frustum near plane length - * @param {Number} [far] frustum far plane length - * @chainable - * @example - *
      - * - * //drag the mouse to look around! - * function setup() { - * createCanvas(100, 100, WEBGL); - * perspective(PI / 3.0, width / height, 0.1, 500); - * describe( - * 'two colored 3D boxes move back and forth, rotating as mouse is dragged.' - * ); - * } - * 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(); - * } - * - *
      - * - * @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]; + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; } - _main.default._validateParameters('perspective', args); - (_this$_renderer$_curC2 = this._renderer._curCamera).perspective.apply(_this$_renderer$_curC2, args); - return this; - }; - /** - * Sets an orthographic projection for the current camera in a 3D sketch - * and defines a box-shaped viewing frustum within which objects are seen. - * In this projection, all objects with the same dimension appear the same - * size, regardless of whether they are near or far from the camera. - * - * The parameters to this function specify the viewing frustum where - * left and right are the minimum and maximum x values, top and bottom are - * the minimum and maximum y values, and near and far are the minimum and - * maximum z values. - * - * If no parameters are given, the following default is used: - * ortho(-width/2, width/2, -height/2, height/2). - * @method ortho - * @for p5 - * @param {Number} [left] camera frustum left plane - * @param {Number} [right] camera frustum right plane - * @param {Number} [bottom] camera frustum bottom plane - * @param {Number} [top] camera frustum top plane - * @param {Number} [near] camera frustum near plane - * @param {Number} [far] camera frustum far plane - * @chainable - * @example - *
      - * - * //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); - * describe( - * 'two 3D boxes move back and forth along same plane, rotating as mouse is dragged.' - * ); - * } - * 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(); - * } - * - *
      - * - * @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]; + return _typeof(obj); + } + _dereq_('core-js/modules/es.array.fill'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.get-prototype-of'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.typed-array.float32-array'); + _dereq_('core-js/modules/es.typed-array.uint8-array'); + _dereq_('core-js/modules/es.typed-array.uint8-clamped-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + var _p = _dereq_('./p5.Texture'); + var _p2 = _dereq_('./p5.RendererGL'); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; } - _main.default._validateParameters('ortho', args); - (_this$_renderer$_curC3 = this._renderer._curCamera).ortho.apply(_this$_renderer$_curC3, args); - return this; - }; - /** - * Sets the frustum of the current camera as defined by - * the parameters. - * - * A frustum is a geometric form: a pyramid with its top - * cut off. With the viewer's eye at the imaginary top of - * the pyramid, the six planes of the frustum act as clipping - * planes when rendering a 3D view. Thus, any form inside the - * clipping planes is visible; anything outside - * those planes is not visible. - * - * Setting the frustum changes the perspective of the scene being rendered. - * This can be achieved more simply in many cases by using - * perspective(). - * - * If no parameters are given, the following default is used: - * frustum(-width/2, width/2, -height/2, height/2, 0, max(width, height)). - * @method frustum - * @for p5 - * @param {Number} [left] camera frustum left plane - * @param {Number} [right] camera frustum right plane - * @param {Number} [bottom] camera frustum bottom plane - * @param {Number} [top] camera frustum top plane - * @param {Number} [near] camera frustum near plane - * @param {Number} [far] camera frustum far plane - * @chainable - * @example - *
      - * - * function setup() { - * createCanvas(100, 100, WEBGL); - * setAttributes('antialias', true); - * frustum(-0.1, 0.1, -0.1, 0.1, 0.1, 200); - * describe( - * 'two 3D boxes move back and forth along same plane, rotating as mouse is dragged.' - * ); - * } - * function draw() { - * background(200); - * orbitControl(); - * normalMaterial(); - * - * 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(); - * } - * - *
      - * - * @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]; + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; } - _main.default._validateParameters('frustum', args); - (_this$_renderer$_curC4 = this._renderer._curCamera).frustum.apply(_this$_renderer$_curC4, args); - return this; - }; //////////////////////////////////////////////////////////////////////////////// - // p5.Camera - //////////////////////////////////////////////////////////////////////////////// - /** - * Creates a new p5.Camera object and sets it - * as the current (active) camera. - * - * The new camera is initialized with a default position - * (see camera()) - * and a default perspective projection - * (see perspective()). - * Its properties can be controlled with the p5.Camera - * methods. - * - * Note: Every 3D sketch starts with a default camera initialized. - * This camera can be controlled with the global methods - * camera(), - * perspective(), ortho(), - * and frustum() if it is the only camera - * in the scene. - * @method createCamera - * @return {p5.Camera} The newly created camera object. - * @for p5 - * @example - *
      - * // Creates a camera object and animates it around a box. - * let camera; - * function setup() { - * createCanvas(100, 100, WEBGL); - * background(0); - * camera = createCamera(); - * describe('An example that creates a camera and moves it around the box.'); - * } - * - * function draw() { - * background(0); - * // The camera will automatically - * // rotate to look at [0, 0, 0]. - * camera.lookAt(0, 0, 0); - * - * // The camera will move on the - * // x axis. - * camera.setPosition(sin(frameCount / 60) * 200, 0, 100); - * box(20); - * - * // A 'ground' box to give the viewer - * // a better idea of where the camera - * // is looking. - * translate(0, 50, 0); - * rotateX(HALF_PI); - * box(150, 150, 20); - * } - *
      - * - * @alt - * An example that creates a camera and moves it around the box. - */ - _main.default.prototype.createCamera = function () { - this._assert3d('createCamera'); - var _cam = new _main.default.Camera(this._renderer); // compute default camera settings, then set a default camera - _cam._computeCameraDefaultSettings(); - _cam._setDefaultCamera(); // set renderer current camera to the new camera - this._renderer._curCamera = _cam; - return _cam; - }; - /** - * This class describes a camera for use in p5's - * - * WebGL mode. It contains camera position, orientation, and projection - * information necessary for rendering a 3D scene. - * - * New p5.Camera objects can be made through the - * createCamera() function and controlled through - * the methods described below. A camera created in this way will use a default - * position in the scene and a default perspective projection until these - * properties are changed through the various methods available. It is possible - * to create multiple cameras, in which case the current camera - * can be set through the setCamera() method. - * - * Note: - * The methods below operate in two coordinate systems: the 'world' coordinate - * system describe positions in terms of their relationship to the origin along - * the X, Y and Z axes whereas the camera's 'local' coordinate system - * describes positions from the camera's point of view: left-right, up-down, - * and forward-backward. The move() method, - * for instance, moves the camera along its own axes, whereas the - * setPosition() - * method sets the camera's position in world-space. - * - * The camera object propreties - * eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ - * which describes camera position, orientation, and projection - * are also accessible via the camera object generated using - * createCamera() - * - * @class p5.Camera - * @param {rendererGL} rendererGL instance of WebGL renderer - * @example - *
      - * - * let cam; - * let delta = 0.01; - * - * function setup() { - * createCanvas(100, 100, WEBGL); - * normalMaterial(); - * cam = createCamera(); - * // set initial pan angle - * cam.pan(-0.8); - * describe( - * 'camera view pans left and right across a series of rotating 3D boxes.' - * ); - * } - * - * function draw() { - * background(200); - * - * // pan camera according to angle 'delta' - * cam.pan(delta); - * - * // every 160 frames, switch direction - * if (frameCount % 160 === 0) { - * delta *= -1; - * } - * - * rotateX(frameCount * 0.01); - * translate(-100, 0, 0); - * box(20); - * translate(35, 0, 0); - * box(20); - * translate(35, 0, 0); - * box(20); - * translate(35, 0, 0); - * box(20); - * translate(35, 0, 0); - * box(20); - * translate(35, 0, 0); - * box(20); - * translate(35, 0, 0); - * box(20); - * } - * - *
      - * - * @alt - * camera view pans left and right across a series of rotating 3D boxes. - */ - _main.default.Camera = function (renderer) { - this._renderer = renderer; - this.cameraType = 'default'; - this.cameraMatrix = new _main.default.Matrix(); - this.projMatrix = new _main.default.Matrix(); - }; - /** - * camera position value on x axis - * @property {Number} eyeX - * @readonly - * @example - * - *
      - * let cam, div; - * function setup() { - * createCanvas(100, 100, WEBGL); - * background(0); - * cam = createCamera(); - * div = createDiv(); - * div.position(0, 0); - * describe('An example showing the use of camera object properties'); - * } - * - * function draw() { - * orbitControl(); - * box(10); - * div.html('eyeX = ' + cam.eyeX); - * } - *
      - * - * @alt - * An example showing the use of camera object properties - * - */ - /** - * camera position value on y axis - * @property {Number} eyeY - * @readonly - * @example - *
      - * let cam, div; - * function setup() { - * createCanvas(100, 100, WEBGL); - * background(0); - * cam = createCamera(); - * div = createDiv(); - * div.position(0, 0); - * describe('An example showing the use of camera object properties'); - * } - * - * function draw() { - * orbitControl(); - * box(10); - * div.html('eyeY = ' + cam.eyeY); - * } - *
      - * - * @alt - * An example showing the use of camera object properties - * - */ - /** - * camera position value on z axis - * @property {Number} eyeZ - * @readonly - * @example - *
      - * let cam, div; - * function setup() { - * createCanvas(100, 100, WEBGL); - * background(0); - * cam = createCamera(); - * div = createDiv(); - * div.position(0, 0); - * describe('An example showing the use of camera object properties'); - * } - * - * function draw() { - * orbitControl(); - * box(10); - * div.html('eyeZ = ' + cam.eyeZ); - * } - *
      - * - * @alt - * An example showing the use of camera object properties - * - */ - /** - * x coordinate representing center of the sketch - * @property {Number} centerX - * @readonly - * @example - *
      - * let cam, div; - * function setup() { - * createCanvas(100, 100, WEBGL); - * background(255); - * cam = createCamera(); - * cam.lookAt(1, 0, 0); - * div = createDiv('centerX = ' + cam.centerX); - * div.position(0, 0); - * div.style('color', 'white'); - * describe('An example showing the use of camera object properties'); - * } - * - * function draw() { - * orbitControl(); - * box(10); - * } - *
      - * - * @alt - * An example showing the use of camera object properties - * - */ - /** - * y coordinate representing center of the sketch - * @property {Number} centerY - * @readonly - * @example - *
      - * let cam, div; - * function setup() { - * createCanvas(100, 100, WEBGL); - * background(255); - * cam = createCamera(); - * cam.lookAt(0, 1, 0); - * div = createDiv('centerY = ' + cam.centerY); - * div.position(0, 0); - * div.style('color', 'white'); - * describe('An example showing the use of camera object properties'); - * } - * - * function draw() { - * orbitControl(); - * box(10); - * } - *
      - * - * @alt - * An example showing the use of camera object properties - * - */ - /** - * z coordinate representing center of the sketch - * @property {Number} centerZ - * @readonly - * @example - *
      - * let cam, div; - * function setup() { - * createCanvas(100, 100, WEBGL); - * background(255); - * cam = createCamera(); - * cam.lookAt(0, 0, 1); - * div = createDiv('centerZ = ' + cam.centerZ); - * div.position(0, 0); - * div.style('color', 'white'); - * describe('An example showing the use of camera object properties'); - * } - * - * function draw() { - * orbitControl(); - * box(10); - * } - *
      - * - * @alt - * An example showing the use of camera object properties - * - */ - /** - * x component of direction 'up' from camera - * @property {Number} upX - * @readonly - * @example - *
      - * let cam, div; - * function setup() { - * createCanvas(100, 100, WEBGL); - * background(255); - * cam = createCamera(); - * div = createDiv('upX = ' + cam.upX); - * div.position(0, 0); - * div.style('color', 'blue'); - * div.style('font-size', '18px'); - * describe('An example showing the use of camera object properties'); - * } - *
      - * - * @alt - * An example showing the use of camera object properties - * - */ - /** - * y component of direction 'up' from camera - * @property {Number} upY - * @readonly - * @example - *
      - * let cam, div; - * function setup() { - * createCanvas(100, 100, WEBGL); - * background(255); - * cam = createCamera(); - * div = createDiv('upY = ' + cam.upY); - * div.position(0, 0); - * div.style('color', 'blue'); - * div.style('font-size', '18px'); - * describe('An example showing the use of camera object properties'); - * } - *
      - * - * @alt - * An example showing the use of camera object properties - * - */ - /** - * z component of direction 'up' from camera - * @property {Number} upZ - * @readonly - * @example - *
      - * let cam, div; - * function setup() { - * createCanvas(100, 100, WEBGL); - * background(255); - * cam = createCamera(); - * div = createDiv('upZ = ' + cam.upZ); - * div.position(0, 0); - * div.style('color', 'blue'); - * div.style('font-size', '18px'); - * describe('An example showing the use of camera object properties'); - * } - *
      - * - * @alt - * An example showing the use of camera object properties - * - */ - //////////////////////////////////////////////////////////////////////////////// - // Camera Projection Methods - //////////////////////////////////////////////////////////////////////////////// - /** - * Sets a perspective projection. - * Accepts the same parameters as the global - * perspective(). - * More information on this function can be found there. - * @method perspective - * @for p5.Camera - * @example - *
      - * - * // drag the mouse to look around! - * - * let cam; - * - * function setup() { - * createCanvas(100, 100, WEBGL); - * // create a camera - * cam = createCamera(); - * // give it a perspective projection - * cam.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(); - * } - * - *
      - * @alt - * two colored 3D boxes move back and forth, rotating as mouse is dragged. - */ - _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; + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); + } + function _nonIterableRest() { + throw new TypeError('Invalid attempt to destructure non-iterable instance'); + } + function _iterableToArrayLimit(arr, i) { + if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === '[object Arguments]')) { + return; + } + var _arr = [ + ]; + var _n = true; + var _d = false; + var _e = undefined; + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i['return'] != null) _i['return'](); + } finally { + if (_d) throw _e; + } + } + return _arr; + } + function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; + } + function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); } else { - this.cameraFOV = this._renderer._pInst._toRadians(fovy); + obj[key] = value; } - if (typeof aspect === 'undefined') { - aspect = this.defaultAspectRatio; + return obj; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); } - if (typeof near === 'undefined') { - near = this.defaultCameraNear; + } + 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); } - if (typeof far === 'undefined') { - far = this.defaultCameraFar; + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } + function _get(target, property, receiver) { + if (typeof Reflect !== 'undefined' && Reflect.get) { + _get = Reflect.get; + } else { + _get = function _get(target, property, receiver) { + var base = _superPropBase(target, property); + if (!base) return; + var desc = Object.getOwnPropertyDescriptor(base, property); + if (desc.get) { + return desc.get.call(receiver); + } + return desc.value; + }; } - if (near <= 0.0001) { - near = 0.01; - console.log('Avoid perspective near plane values close to or below 0. ' + 'Setting value to 0.01.'); + return _get(target, property, receiver || target); + } + function _superPropBase(object, property) { + while (!Object.prototype.hasOwnProperty.call(object, property)) { + object = _getPrototypeOf(object); + if (object === null) break; } - if (far < near) { - console.log('Perspective far plane value is less than near plane value. ' + 'Nothing will be shown.'); + return object; + } + function _inherits(subClass, superClass) { + if (typeof superClass !== 'function' && superClass !== null) { + throw new TypeError('Super expression must either be null or a function'); } - this.aspectRatio = aspect; - this.cameraNear = near; - this.cameraFar = far; - this.projMatrix = _main.default.Matrix.identity(); - var f = 1 / Math.tan(this.cameraFOV / 2); - var nf = 1 / (this.cameraNear - this.cameraFar); - /* eslint-disable indent */ - this.projMatrix.set(f / aspect, 0, 0, 0, 0, - f, 0, 0, 0, 0, (far + near) * nf, - 1, 0, 0, 2 * far * near * nf, 0); - /* eslint-enable indent */ - if (this._isActive()) { - this._renderer.uPMatrix.set(this.projMatrix.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]); + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + if (superClass) _setPrototypeOf(subClass, superClass); + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + return _setPrototypeOf(o, p); + } + function _createSuper(Derived) { + function isNativeReflectConstruct() { + if (typeof Reflect === 'undefined' || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === 'function') return true; + try { + Date.prototype.toString.call(Reflect.construct(Date, [ + ], function () { + })); + return true; + } catch (e) { + return false; + } } - }; - /** - * Sets an orthographic projection. - * Accepts the same parameters as the global - * ortho(). - * More information on this function can be found there. - * @method ortho - * @for p5.Camera - * @example - *
      - * - * // drag the mouse to look around! - * // there's no vanishing point - * - * let cam; - * - * function setup() { - * createCanvas(100, 100, WEBGL); - * // create a camera - * cam = createCamera(); - * // give it an orthographic projection - * cam.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(); - * } - * - *
      - * @alt - * two 3D boxes move back and forth along same plane, rotating as mouse is dragged. - */ - _main.default.Camera.prototype.ortho = function (left, right, bottom, top, near, far) { - if (left === undefined) left = - this._renderer.width / 2; - if (right === undefined) right = + this._renderer.width / 2; - if (bottom === undefined) bottom = - this._renderer.height / 2; - if (top === undefined) top = + this._renderer.height / 2; - if (near === undefined) near = 0; - if (far === undefined) far = Math.max(this._renderer.width, this._renderer.height); - var w = right - left; - var h = top - bottom; - var d = far - near; - var x = + 2 / w; - var y = + 2 / h; - var z = - 2 / d; - var tx = - (right + left) / w; - var ty = - (top + bottom) / h; - var tz = - (far + near) / d; - this.projMatrix = _main.default.Matrix.identity(); - /* eslint-disable indent */ - this.projMatrix.set(x, 0, 0, 0, 0, - y, 0, 0, 0, 0, z, 0, tx, ty, tz, 1); - /* eslint-enable indent */ - if (this._isActive()) { - this._renderer.uPMatrix.set(this.projMatrix.mat4[0], this.projMatrix.mat4[1], this.projMatrix.mat4[2], this.projMatrix.mat4[3], this.projMatrix.mat4[4], this.projMatrix.mat4[5], this.projMatrix.mat4[6], this.projMatrix.mat4[7], this.projMatrix.mat4[8], this.projMatrix.mat4[9], this.projMatrix.mat4[10], this.projMatrix.mat4[11], this.projMatrix.mat4[12], this.projMatrix.mat4[13], this.projMatrix.mat4[14], this.projMatrix.mat4[15]); - } - this.cameraType = 'custom'; - }; - /** - * Sets the camera's frustum. - * Accepts the same parameters as the global - * frustum(). - * More information on this function can be found there. - * @method frustum - * @for p5.Camera - * @example - *
      - * - * let cam; - * - * function setup() { - * x = createCanvas(100, 100, WEBGL); - * setAttributes('antialias', true); - * // create a camera - * cam = createCamera(); - * // set its frustum - * cam.frustum(-0.1, 0.1, -0.1, 0.1, 0.1, 200); - * } - * - * function draw() { - * background(200); - * orbitControl(); - * normalMaterial(); - * - * 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(); - * } - * - *
      - * @alt - * two 3D boxes move back and forth along same plane, rotating as mouse is dragged. - */ - _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 * near) / w; - var y = + (2 * near) / h; - var z = - (2 * far * near) / d; - var tx = (right + left) / w; - var ty = (top + bottom) / h; - var tz = - (far + near) / d; - this.projMatrix = _main.default.Matrix.identity(); - /* eslint-disable indent */ - this.projMatrix.set(x, 0, 0, 0, 0, y, 0, 0, tx, ty, tz, - 1, 0, 0, z, 0); - /* eslint-enable indent */ - if (this._isActive()) { - this._renderer.uPMatrix.set(this.projMatrix.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); - /* eslint-disable max-len */ - var rotatedCenter = [ - centerX * rotation.mat4[0] + centerY * rotation.mat4[4] + centerZ * rotation.mat4[8], - centerX * rotation.mat4[1] + centerY * rotation.mat4[5] + centerZ * rotation.mat4[9], - centerX * rotation.mat4[2] + centerY * rotation.mat4[6] + centerZ * rotation.mat4[10] - ]; - /* eslint-enable max-len */ - // add eye position back into center - rotatedCenter[0] += this.eyeX; - rotatedCenter[1] += this.eyeY; - rotatedCenter[2] += this.eyeZ; - this.camera(this.eyeX, this.eyeY, this.eyeZ, rotatedCenter[0], rotatedCenter[1], rotatedCenter[2], this.upX, this.upY, this.upZ); - }; - /** - * Panning rotates the camera view to the left and right. - * @method pan - * @param {Number} angle amount to rotate camera in current - * angleMode units. - * Greater than 0 values rotate counterclockwise (to the left). - * @example - *
      - * - * 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); - * } - * - *
      - * - * @alt - * camera view pans left and right across a series of rotating 3D boxes. - */ - _main.default.Camera.prototype.pan = function (amount) { - var local = this._getLocalAxes(); - this._rotateView(amount, local.y[0], local.y[1], local.y[2]); - }; - /** - * Tilting rotates the camera view up and down. - * @method tilt - * @param {Number} angle amount to rotate camera in current - * angleMode units. - * Greater than 0 values rotate counterclockwise (to the left). - * @example - *
      - * - * 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); - * } - * - *
      - * - * @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 - *
      - * - * 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); - * } - * - *
      - * - * @alt - * camera view of rotating 3D cubes changes to look at a new random - * point every second . - */ - _main.default.Camera.prototype.lookAt = function (x, y, z) { - this.camera(this.eyeX, this.eyeY, this.eyeZ, x, y, z, this.upX, this.upY, this.upZ); - }; //////////////////////////////////////////////////////////////////////////////// - // Camera Position Methods - //////////////////////////////////////////////////////////////////////////////// - /** - * Sets the camera's position and orientation. - * Accepts the same parameters as the global - * camera(). - * More information on this function can be found there. - * @method camera - * @for p5.Camera - * @example - *
      - * - * let cam; - * - * function setup() { - * createCanvas(100, 100, WEBGL); - * // Create a camera. - * // createCamera() sets the newly created camera as - * // the current (active) camera. - * cam = createCamera(); - * } - * - * function draw() { - * background(204); - * // Move the camera away from the plane by a sin wave - * cam.camera(0, 0, 20 + sin(frameCount * 0.01) * 10, 0, 0, 0, 0, 1, 0); - * plane(10, 10); - * } - * - *
      - * @alt - * White square repeatedly grows to fill canvas and then shrinks. - * - * @example - *
      - * - * // move slider to see changes! - * // sliders control the first 6 parameters of camera() + return function () { + var Super = _getPrototypeOf(Derived), + result; + if (isNativeReflectConstruct()) { + var NewTarget = _getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return _possibleConstructorReturn(this, result); + }; + } + function _possibleConstructorReturn(self, call) { + if (call && (_typeof(call) === 'object' || typeof call === 'function')) { + return call; + } + return _assertThisInitialized(self); + } + function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called'); + } + return self; + } + function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); + } /** + * @module Rendering + * @requires constants + */ + + var FramebufferCamera = /*#__PURE__*/ function (_p5$Camera) { + _inherits(FramebufferCamera, _p5$Camera); + var _super = _createSuper(FramebufferCamera); + /** + * A p5.Camera attached to a + * p5.Framebuffer. + * + * @class p5.FramebufferCamera + * @constructor + * @param {p5.Framebuffer} framebuffer The framebuffer this camera is + * attached to + * @private + */ + function FramebufferCamera(framebuffer) { + var _this; + _classCallCheck(this, FramebufferCamera); + _this = _super.call(this, framebuffer.target._renderer); + _this.fbo = framebuffer; + // WebGL textures are upside-down compared to textures that come from + // images and graphics. Framebuffer cameras need to invert their y + // axes when being rendered to so that the texture comes out rightway up + // when read in shaders or image(). + _this.yScale = - 1; + return _this; + } + _createClass(FramebufferCamera, [ + { + key: '_computeCameraDefaultSettings', + value: function _computeCameraDefaultSettings() { + _get(_getPrototypeOf(FramebufferCamera.prototype), '_computeCameraDefaultSettings', this).call(this); + this.defaultAspectRatio = this.fbo.width / this.fbo.height; + this.defaultCameraFOV = 2 * Math.atan(this.fbo.height / 2 / this.defaultEyeZ); + } + } + ]); + return FramebufferCamera; + }(_main.default.Camera); + _main.default.FramebufferCamera = FramebufferCamera; + var FramebufferTexture = /*#__PURE__*/ function () { + /** + * A p5.Texture corresponding to a property of a + * p5.Framebuffer. + * + * @class p5.FramebufferTexture + * @param {p5.Framebuffer} framebuffer The framebuffer represented by this + * texture + * @param {String} property The property of the framebuffer represented by + * this texture, either `color` or `depth` + * @private + */ + function FramebufferTexture(framebuffer, property) { + _classCallCheck(this, FramebufferTexture); + this.framebuffer = framebuffer; + this.property = property; + } + _createClass(FramebufferTexture, [ + { + key: 'rawTexture', + value: function rawTexture() { + return this.framebuffer[this.property]; + } + }, + { + key: 'width', + get: function get() { + return this.framebuffer.width * this.framebuffer.density; + } + }, + { + key: 'height', + get: function get() { + return this.framebuffer.height * this.framebuffer.density; + } + } + ]); + return FramebufferTexture; + }(); + _main.default.FramebufferTexture = FramebufferTexture; + var Framebuffer = /*#__PURE__*/ function () { + /** + * An object that one can draw to and then read as a texture. While similar + * to a p5.Graphics, using a p5.Framebuffer as a texture will generally run + * much faster, as it lives within the same WebGL context as the canvas it + * is created on. It only works in WebGL mode. + * + * @class p5.Framebuffer + * @constructor + * @param {p5.Graphics|p5} target A p5 global instance or p5.Graphics + * @param {Object} [settings] A settings object + */ + function Framebuffer(target) { + var _this2 = this; + var settings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { + }; + _classCallCheck(this, Framebuffer); + this.target = target; + this.target._renderer.framebuffers.add(this); + this._isClipApplied = false; + /** + * A Uint8ClampedArray + * containing the values for all the pixels in the Framebuffer. + * + * Like the main canvas pixels property, call + * loadPixels() before reading + * it, and call updatePixels() + * afterwards to update its data. + * + * Note that updating pixels via this property will be slower than + * drawing to the framebuffer directly. + * Consider using a shader instead of looping over pixels. + * + * @property {Number[]} pixels + */ + this.pixels = [ + ]; + this.format = settings.format || constants.UNSIGNED_BYTE; + this.channels = settings.channels || (target._renderer._pInst._glAttributes.alpha ? constants.RGBA : constants.RGB); + this.useDepth = settings.depth === undefined ? true : settings.depth; + this.depthFormat = settings.depthFormat || constants.FLOAT; + this.textureFiltering = settings.textureFiltering || constants.LINEAR; + if (settings.antialias === undefined) { + this.antialiasSamples = target._renderer._pInst._glAttributes.antialias ? 2 : 0; + } else if (typeof settings.antialias === 'number') { + this.antialiasSamples = settings.antialias; + } else { + this.antialiasSamples = settings.antialias ? 2 : 0; + } + this.antialias = this.antialiasSamples > 0; + if (this.antialias && target.webglVersion !== constants.WEBGL2) { + console.warn('Antialiasing is unsupported in a WebGL 1 context'); + this.antialias = false; + } + if (settings.width && settings.height) { + this.width = settings.width; + this.height = settings.height; + this.autoSized = false; + } else { + if (settings.width === undefined !== (settings.height === undefined)) { + console.warn('Please supply both width and height for a framebuffer to give it a ' + 'size. Only one was given, so the framebuffer will match the size ' + 'of its canvas.'); + } + this.width = target.width; + this.height = target.height; + this.autoSized = true; + } + this.density = settings.density || target.pixelDensity(); + var gl = target._renderer.GL; + this.gl = gl; + this._checkIfFormatsAvailable(); + if (settings.stencil && !this.useDepth) { + console.warn('A stencil buffer can only be used if also using depth. Since the framebuffer has no depth buffer, the stencil buffer will be ignored.'); + } + this.useStencil = this.useDepth && (settings.stencil === undefined ? true : settings.stencil); + this.framebuffer = gl.createFramebuffer(); + if (!this.framebuffer) { + throw new Error('Unable to create a framebuffer'); + } + if (this.antialias) { + this.aaFramebuffer = gl.createFramebuffer(); + if (!this.aaFramebuffer) { + throw new Error('Unable to create a framebuffer for antialiasing'); + } + } + this._recreateTextures(); + var prevCam = this.target._renderer._curCamera; + this.defaultCamera = this.createCamera(); + this.target._renderer._curCamera = prevCam; + this.draw(function () { + return _this2.target.clear(); + }); + } /** + * Resizes the framebuffer to the given width and height. + * + * @method resize + * @param {Number} width + * @param {Number} height + * + * @example + *
      + * + * let framebuffer; + * function setup() { + * createCanvas(100, 100, WEBGL); + * framebuffer = createFramebuffer(); + * noStroke(); + * } + * + * function mouseMoved() { + * framebuffer.resize( + * max(20, mouseX), + * max(20, mouseY) + * ); + * } + * + * function draw() { + * // Draw to the framebuffer + * framebuffer.begin(); + * background(255); + * normalMaterial(); + * sphere(20); + * framebuffer.end(); + * + * background(100); + * // Draw the framebuffer to the main canvas + * image(framebuffer, -width/2, -height/2); + * } + * + *
      + * + * @alt + * A red, green, and blue sphere is drawn in the middle of a white rectangle + * which starts in the top left of the canvas and whose bottom right is at + * the user's mouse + */ + + _createClass(Framebuffer, [ + { + key: 'resize', + value: function resize(width, height) { + this.autoSized = false; + this.width = width; + this.height = height; + this._handleResize(); + } /** + * Gets or sets the pixel scaling for high pixel density displays. By + * default, the density will match that of the canvas the framebuffer was + * created on, which will match the display density. + * + * Call this method with no arguments to get the current density, or pass + * in a number to set the density. + * + * @method pixelDensity + * @param {Number} [density] A scaling factor for the number of pixels per + * side of the framebuffer + */ + + }, + { + key: 'pixelDensity', + value: function pixelDensity(density) { + if (density) { + this.autoSized = false; + this.density = density; + this._handleResize(); + } else { + return this.density; + } + } /** + * Gets or sets whether or not this framebuffer will automatically resize + * along with the canvas it's attached to in order to match its size. + * + * Call this method with no arguments to see if it is currently auto-sized, + * or pass in a boolean to set this property. + * + * @method autoSized + * @param {Boolean} [autoSized] Whether or not the framebuffer should resize + * along with the canvas it's attached to + */ + + }, + { + key: 'autoSized', + value: function autoSized(_autoSized) { + if (_autoSized === undefined) { + return this.autoSized; + } else { + this.autoSized = _autoSized; + this._handleResize(); + } + } /** + * Checks the capabilities of the current WebGL environment to see if the + * settings supplied by the user are capable of being fulfilled. If they + * are not, warnings will be logged and the settings will be changed to + * something close that can be fulfilled. + * + * @private + */ + + }, + { + key: '_checkIfFormatsAvailable', + value: function _checkIfFormatsAvailable() { + var gl = this.gl; + if (this.useDepth && this.target.webglVersion === constants.WEBGL && !gl.getExtension('WEBGL_depth_texture')) { + console.warn('Unable to create depth textures in this environment. Falling back ' + 'to a framebuffer without depth.'); + this.useDepth = false; + } + if (this.useDepth && this.target.webglVersion === constants.WEBGL && this.depthFormat === constants.FLOAT) { + console.warn('FLOAT depth format is unavailable in WebGL 1. ' + 'Defaulting to UNSIGNED_INT.'); + this.depthFormat = constants.UNSIGNED_INT; + } + if (![constants.UNSIGNED_BYTE, + constants.FLOAT, + constants.HALF_FLOAT].includes(this.format)) { + console.warn('Unknown Framebuffer format. ' + 'Please use UNSIGNED_BYTE, FLOAT, or HALF_FLOAT. ' + 'Defaulting to UNSIGNED_BYTE.'); + this.format = constants.UNSIGNED_BYTE; + } + if (this.useDepth && ![constants.UNSIGNED_INT, + constants.FLOAT].includes(this.depthFormat)) { + console.warn('Unknown Framebuffer depth format. ' + 'Please use UNSIGNED_INT or FLOAT. Defaulting to FLOAT.'); + this.depthFormat = constants.FLOAT; + } + var support = (0, _p.checkWebGLCapabilities) (this.target._renderer); + if (!support.float && this.format === constants.FLOAT) { + console.warn('This environment does not support FLOAT textures. ' + 'Falling back to UNSIGNED_BYTE.'); + this.format = constants.UNSIGNED_BYTE; + } + if (this.useDepth && !support.float && this.depthFormat === constants.FLOAT) { + console.warn('This environment does not support FLOAT depth textures. ' + 'Falling back to UNSIGNED_INT.'); + this.depthFormat = constants.UNSIGNED_INT; + } + if (!support.halfFloat && this.format === constants.HALF_FLOAT) { + console.warn('This environment does not support HALF_FLOAT textures. ' + 'Falling back to UNSIGNED_BYTE.'); + this.format = constants.UNSIGNED_BYTE; + } + if (this.channels === constants.RGB && [ + constants.FLOAT, + constants.HALF_FLOAT + ].includes(this.format)) { + console.warn('FLOAT and HALF_FLOAT formats do not work cross-platform with only ' + 'RGB channels. Falling back to RGBA.'); + this.channels = constants.RGBA; + } + } /** + * Creates new textures and renderbuffers given the current size of the + * framebuffer. + * + * @private + */ + + }, + { + key: '_recreateTextures', + value: function _recreateTextures() { + var gl = this.gl; + this._updateSize(); + var prevBoundTexture = gl.getParameter(gl.TEXTURE_BINDING_2D); + var prevBoundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING); + var colorTexture = gl.createTexture(); + if (!colorTexture) { + throw new Error('Unable to create color texture'); + } + gl.bindTexture(gl.TEXTURE_2D, colorTexture); + var colorFormat = this._glColorFormat(); + gl.texImage2D(gl.TEXTURE_2D, 0, colorFormat.internalFormat, this.width * this.density, this.height * this.density, 0, colorFormat.format, colorFormat.type, null); + this.colorTexture = colorTexture; + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, colorTexture, 0); + if (this.useDepth) { + // Create the depth texture + var depthTexture = gl.createTexture(); + if (!depthTexture) { + throw new Error('Unable to create depth texture'); + } + var depthFormat = this._glDepthFormat(); + gl.bindTexture(gl.TEXTURE_2D, depthTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, depthFormat.internalFormat, this.width * this.density, this.height * this.density, 0, depthFormat.format, depthFormat.type, null); + gl.framebufferTexture2D(gl.FRAMEBUFFER, this.useStencil ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0); + this.depthTexture = depthTexture; + } // Create separate framebuffer for antialiasing + + if (this.antialias) { + this.colorRenderbuffer = gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, this.colorRenderbuffer); + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, Math.max(0, Math.min(this.antialiasSamples, gl.getParameter(gl.MAX_SAMPLES))), colorFormat.internalFormat, this.width * this.density, this.height * this.density); + if (this.useDepth) { + var _depthFormat = this._glDepthFormat(); + this.depthRenderbuffer = gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, this.depthRenderbuffer); + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, Math.max(0, Math.min(this.antialiasSamples, gl.getParameter(gl.MAX_SAMPLES))), _depthFormat.internalFormat, this.width * this.density, this.height * this.density); + } + gl.bindFramebuffer(gl.FRAMEBUFFER, this.aaFramebuffer); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, this.colorRenderbuffer); + if (this.useDepth) { + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, this.useStencil ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this.depthRenderbuffer); + } + } + if (this.useDepth) { + this.depth = new FramebufferTexture(this, 'depthTexture'); + var depthFilter = gl.NEAREST; + this.depthP5Texture = new _main.default.Texture(this.target._renderer, this.depth, { + minFilter: depthFilter, + magFilter: depthFilter + }); + this.target._renderer.textures.set(this.depth, this.depthP5Texture); + } + this.color = new FramebufferTexture(this, 'colorTexture'); + var filter = this.textureFiltering === constants.LINEAR ? gl.LINEAR : gl.NEAREST; + this.colorP5Texture = new _main.default.Texture(this.target._renderer, this.color, { + minFilter: filter, + magFilter: filter + }); + this.target._renderer.textures.set(this.color, this.colorP5Texture); + gl.bindTexture(gl.TEXTURE_2D, prevBoundTexture); + gl.bindFramebuffer(gl.FRAMEBUFFER, prevBoundFramebuffer); + } /** + * To create a WebGL texture, one needs to supply three pieces of information: + * the type (the data type each channel will be stored as, e.g. int or float), + * the format (the color channels that will each be stored in the previously + * specified type, e.g. rgb or rgba), and the internal format (the specifics + * of how data for each channel, in the aforementioned type, will be packed + * together, such as how many bits to use, e.g. RGBA32F or RGB565.) + * + * The format and channels asked for by the user hint at what these values + * need to be, and the WebGL version affects what options are avaiable. + * This method returns the values for these three properties, given the + * framebuffer's settings. + * + * @private + */ + + }, + { + key: '_glColorFormat', + value: function _glColorFormat() { + var type, + format, + internalFormat; + var gl = this.gl; + if (this.format === constants.FLOAT) { + type = gl.FLOAT; + } else if (this.format === constants.HALF_FLOAT) { + type = this.target.webglVersion === constants.WEBGL2 ? gl.HALF_FLOAT : gl.getExtension('OES_texture_half_float').HALF_FLOAT_OES; + } else { + type = gl.UNSIGNED_BYTE; + } + if (this.channels === constants.RGBA) { + format = gl.RGBA; + } else { + format = gl.RGB; + } + if (this.target.webglVersion === constants.WEBGL2) { + var _gl$UNSIGNED_BYTE, + _table; + // https://webgl2fundamentals.org/webgl/lessons/webgl-data-textures.html + var table = (_table = { + }, _defineProperty(_table, gl.FLOAT, _defineProperty({ + }, gl.RGBA, gl.RGBA32F)), _defineProperty(_table, gl.HALF_FLOAT, _defineProperty({ + }, gl.RGBA, gl.RGBA16F)), _defineProperty(_table, gl.UNSIGNED_BYTE, (_gl$UNSIGNED_BYTE = { + }, _defineProperty(_gl$UNSIGNED_BYTE, gl.RGBA, gl.RGBA8), _defineProperty(_gl$UNSIGNED_BYTE, gl.RGB, gl.RGB8), _gl$UNSIGNED_BYTE)), _table); + internalFormat = table[type][format]; + } else if (this.format === constants.HALF_FLOAT) { + internalFormat = gl.RGBA; + } else { + internalFormat = format; + } + return { + internalFormat: internalFormat, + format: format, + type: type + }; + } /** + * To create a WebGL texture, one needs to supply three pieces of information: + * the type (the data type each channel will be stored as, e.g. int or float), + * the format (the color channels that will each be stored in the previously + * specified type, e.g. rgb or rgba), and the internal format (the specifics + * of how data for each channel, in the aforementioned type, will be packed + * together, such as how many bits to use, e.g. RGBA32F or RGB565.) + * + * This method takes into account the settings asked for by the user and + * returns values for these three properties that can be used for the + * texture storing depth information. + * + * @private + */ + + }, + { + key: '_glDepthFormat', + value: function _glDepthFormat() { + var type, + format, + internalFormat; + var gl = this.gl; + if (this.useStencil) { + if (this.depthFormat === constants.FLOAT) { + type = gl.FLOAT_32_UNSIGNED_INT_24_8_REV; + } else if (this.target.webglVersion === constants.WEBGL2) { + type = gl.UNSIGNED_INT_24_8; + } else { + type = gl.getExtension('WEBGL_depth_texture').UNSIGNED_INT_24_8_WEBGL; + } + } else { + if (this.depthFormat === constants.FLOAT) { + type = gl.FLOAT; + } else { + type = gl.UNSIGNED_INT; + } + } + if (this.useStencil) { + format = gl.DEPTH_STENCIL; + } else { + format = gl.DEPTH_COMPONENT; + } + if (this.useStencil) { + if (this.depthFormat === constants.FLOAT) { + internalFormat = gl.DEPTH32F_STENCIL8; + } else if (this.target.webglVersion === constants.WEBGL2) { + internalFormat = gl.DEPTH24_STENCIL8; + } else { + internalFormat = gl.DEPTH_STENCIL; + } + } else if (this.target.webglVersion === constants.WEBGL2) { + if (this.depthFormat === constants.FLOAT) { + internalFormat = gl.DEPTH_COMPONENT32F; + } else { + internalFormat = gl.DEPTH_COMPONENT24; + } + } else { + internalFormat = gl.DEPTH_COMPONENT; + } + return { + internalFormat: internalFormat, + format: format, + type: type + }; + } /** + * A method that will be called when recreating textures. If the framebuffer + * is auto-sized, it will update its width, height, and density properties. + * + * @private + */ + + }, + { + key: '_updateSize', + value: function _updateSize() { + if (this.autoSized) { + this.width = this.target.width; + this.height = this.target.height; + this.density = this.target.pixelDensity(); + } + } /** + * Called when the canvas that the framebuffer is attached to resizes. If the + * framebuffer is auto-sized, it will update its textures to match the new + * size. + * + * @private + */ + + }, + { + key: '_canvasSizeChanged', + value: function _canvasSizeChanged() { + if (this.autoSized) { + this._handleResize(); + } + } /** + * Called when the size of the framebuffer has changed (either by being + * manually updated or from auto-size updates when its canvas changes size.) + * Old textures and renderbuffers will be deleted, and then recreated with the + * new size. + * + * @private + */ + + }, + { + key: '_handleResize', + value: function _handleResize() { + var oldColor = this.color; + var oldDepth = this.depth; + var oldColorRenderbuffer = this.colorRenderbuffer; + var oldDepthRenderbuffer = this.depthRenderbuffer; + this._deleteTexture(oldColor); + if (oldDepth) this._deleteTexture(oldDepth); + var gl = this.gl; + if (oldColorRenderbuffer) gl.deleteRenderbuffer(oldColorRenderbuffer); + if (oldDepthRenderbuffer) gl.deleteRenderbuffer(oldDepthRenderbuffer); + this._recreateTextures(); + this.defaultCamera._resize(); + } /** + * Creates and returns a new + * p5.FramebufferCamera to be used + * while drawing to this framebuffer. The camera will be set as the + * currently active camera. + * + * @method createCamera + * @returns {p5.Camera} A new camera + */ + + }, + { + key: 'createCamera', + value: function createCamera() { + var cam = new FramebufferCamera(this); + cam._computeCameraDefaultSettings(); + cam._setDefaultCamera(); + this.target._renderer._curCamera = cam; + return cam; + } /** + * Given a raw texture wrapper, delete its stored texture from WebGL memory, + * and remove it from p5's list of active textures. + * + * @param {p5.FramebufferTexture} texture + * @private + */ + + }, + { + key: '_deleteTexture', + value: function _deleteTexture(texture) { + var gl = this.gl; + gl.deleteTexture(texture.rawTexture()); + this.target._renderer.textures.delete(texture); + } /** + * Removes the framebuffer and frees its resources. + * + * @method remove + * + * @example + *
      + * + * let framebuffer; + * function setup() { + * createCanvas(100, 100, WEBGL); + * } + * + * function draw() { + * const useFramebuffer = (frameCount % 120) > 60; + * if (useFramebuffer && !framebuffer) { + * // Create a new framebuffer for us to use + * framebuffer = createFramebuffer(); + * } else if (!useFramebuffer && framebuffer) { + * // Free the old framebuffer's resources + * framebuffer.remove(); + * framebuffer = undefined; + * } + * + * background(255); + * if (useFramebuffer) { + * // Draw to the framebuffer + * framebuffer.begin(); + * background(255); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * fill(255, 0, 0); + * box(30); + * framebuffer.end(); + * + * image(framebuffer, -width/2, -height/2); + * } + * } + * + *
      + * + * @alt + * A rotating red cube blinks on and off every second. + */ + + }, + { + key: 'remove', + value: function remove() { + var gl = this.gl; + this._deleteTexture(this.color); + if (this.depth) this._deleteTexture(this.depth); + gl.deleteFramebuffer(this.framebuffer); + if (this.aaFramebuffer) { + gl.deleteFramebuffer(this.aaFramebuffer); + } + if (this.depthRenderbuffer) { + gl.deleteRenderbuffer(this.depthRenderbuffer); + } + if (this.colorRenderbuffer) { + gl.deleteRenderbuffer(this.colorRenderbuffer); + } + this.target._renderer.framebuffers.delete(this); + } /** + * Begin drawing to this framebuffer. Subsequent drawing functions to the + * canvas the framebuffer is attached to will not be immediately visible, and + * will instead be drawn to the framebuffer's texture. Call + * end() when finished to make draw + * functions go right to the canvas again and to be able to read the + * contents of the framebuffer's texture. + * + * @method begin + * + * @example + *
      + * + * let framebuffer; + * function setup() { + * createCanvas(100, 100, WEBGL); + * framebuffer = createFramebuffer(); + * noStroke(); + * } + * + * function draw() { + * // Draw to the framebuffer + * framebuffer.begin(); + * background(255); + * translate(0, 10*sin(frameCount * 0.01), 0); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * fill(255, 0, 0); + * box(50); + * framebuffer.end(); + * + * background(100); + * // Draw the framebuffer to the main canvas + * image(framebuffer, -50, -50, 25, 25); + * image(framebuffer, 0, 0, 35, 35); + * } + * + *
      + * + * @alt + * A video of a floating and rotating red cube is pasted twice on the + * canvas: once in the top left, and again, larger, in the bottom right. + */ + + }, + { + key: 'begin', + value: function begin() { + this.prevFramebuffer = this.target._renderer.activeFramebuffer(); + if (this.prevFramebuffer) { + this.prevFramebuffer._beforeEnd(); + } + this.target._renderer.activeFramebuffers.push(this); + this._beforeBegin(); + this.target.push(); + // Apply the framebuffer's camera. This does almost what + // RendererGL.reset() does, but this does not try to clear any buffers; + // it only sets the camera. + this.target.setCamera(this.defaultCamera); + this.target._renderer.uMVMatrix.set(this.target._renderer._curCamera.cameraMatrix.mat4[0], this.target._renderer._curCamera.cameraMatrix.mat4[1], this.target._renderer._curCamera.cameraMatrix.mat4[2], this.target._renderer._curCamera.cameraMatrix.mat4[3], this.target._renderer._curCamera.cameraMatrix.mat4[4], this.target._renderer._curCamera.cameraMatrix.mat4[5], this.target._renderer._curCamera.cameraMatrix.mat4[6], this.target._renderer._curCamera.cameraMatrix.mat4[7], this.target._renderer._curCamera.cameraMatrix.mat4[8], this.target._renderer._curCamera.cameraMatrix.mat4[9], this.target._renderer._curCamera.cameraMatrix.mat4[10], this.target._renderer._curCamera.cameraMatrix.mat4[11], this.target._renderer._curCamera.cameraMatrix.mat4[12], this.target._renderer._curCamera.cameraMatrix.mat4[13], this.target._renderer._curCamera.cameraMatrix.mat4[14], this.target._renderer._curCamera.cameraMatrix.mat4[15]); + } /** + * When making a p5.Framebuffer active so that it may be drawn to, this method + * returns the underlying WebGL framebuffer that needs to be active to + * support this. Antialiased framebuffers first write to a multisampled + * renderbuffer, while other framebuffers can write directly to their main + * framebuffers. + * + * @method _framebufferToBind + * @private + */ + + }, + { + key: '_framebufferToBind', + value: function _framebufferToBind() { + if (this.antialias) { + // If antialiasing, draw to an antialiased renderbuffer rather + // than directly to the texture. In end() we will copy from the + // renderbuffer to the texture. + return this.aaFramebuffer; + } else { + return this.framebuffer; + } + } /** + * Ensures that the framebuffer is ready to be drawn to + * + * @method _beforeBegin + * @private + */ + + }, + { + key: '_beforeBegin', + value: function _beforeBegin() { + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, this._framebufferToBind()); + this.target._renderer.viewport(this.width * this.density, this.height * this.density); + } /** + * Ensures that the framebuffer is ready to be read by other framebuffers. + * + * @method _beforeEnd + * @private + */ + + }, + { + key: '_beforeEnd', + value: function _beforeEnd() { + if (this.antialias) { + var gl = this.gl; + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, this.aaFramebuffer); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, this.framebuffer); + var partsToCopy = [ + [gl.COLOR_BUFFER_BIT, + this.colorP5Texture.glMagFilter] + ]; + if (this.useDepth) { + partsToCopy.push([gl.DEPTH_BUFFER_BIT, + this.depthP5Texture.glMagFilter]); + } + for (var _i = 0, _partsToCopy = partsToCopy; _i < _partsToCopy.length; _i++) { + var _partsToCopy$_i = _slicedToArray(_partsToCopy[_i], 2), + flag = _partsToCopy$_i[0], + filter = _partsToCopy$_i[1]; + gl.blitFramebuffer(0, 0, this.width * this.density, this.height * this.density, 0, 0, this.width * this.density, this.height * this.density, flag, filter); + } + } + } /** + * After having previously called + * begin(), this method stops drawing + * functions from going to the framebuffer's texture, allowing them to go + * right to the canvas again. After this, one can read from the framebuffer's + * texture. + * + * @method end + */ + + }, + { + key: 'end', + value: function end() { + var gl = this.gl; + this.target.pop(); + var fbo = this.target._renderer.activeFramebuffers.pop(); + if (fbo !== this) { + throw new Error('It looks like you\'ve called end() while another Framebuffer is active.'); + } + this._beforeEnd(); + if (this.prevFramebuffer) { + this.prevFramebuffer._beforeBegin(); + } else { + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + this.target._renderer.viewport(this.target._renderer._origViewport.width, this.target._renderer._origViewport.height); + } + this.target._renderer._applyStencilTestIfClipping(); + } /** + * Run a function while drawing to the framebuffer rather than to its canvas. + * This is equivalent to calling `framebuffer.begin()`, running the function, + * and then calling `framebuffer.end()`, but ensures that one never + * accidentally forgets `begin` or `end`. + * + * @method draw + * @param {Function} callback A function to run that draws to the canvas. The + * function will immediately be run, but it will draw to the framebuffer + * instead of the canvas. + * + * @example + *
      + * + * let framebuffer; + * function setup() { + * createCanvas(100, 100, WEBGL); + * framebuffer = createFramebuffer(); + * noStroke(); + * } + * + * function draw() { + * // Draw to the framebuffer + * framebuffer.draw(function() { + * background(255); + * translate(0, 10*sin(frameCount * 0.01), 0); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * fill(255, 0, 0); + * box(50); + * }); + * + * background(100); + * // Draw the framebuffer to the main canvas + * image(framebuffer, -50, -50, 25, 25); + * image(framebuffer, 0, 0, 35, 35); + * } + * + *
      + * + * @alt + * A video of a floating and rotating red cube is pasted twice on the + * canvas: once in the top left, and again, larger, in the bottom right. + */ + + }, + { + key: 'draw', + value: function draw(callback) { + this.begin(); + callback(); + this.end(); + } /** + * Call this befpre updating pixels + * and calling updatePixels + * to replace the content of the framebuffer with the data in the pixels + * array. + */ + + }, + { + key: 'loadPixels', + value: function loadPixels() { + var gl = this.gl; + var prevFramebuffer = this.target._renderer.activeFramebuffer(); + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); + var colorFormat = this._glColorFormat(); + this.pixels = (0, _p2.readPixelsWebGL) (this.pixels, gl, this.framebuffer, 0, 0, this.width * this.density, this.height * this.density, colorFormat.format, colorFormat.type); + if (prevFramebuffer) { + gl.bindFramebuffer(gl.FRAMEBUFFER, prevFramebuffer._framebufferToBind()); + } else { + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + } + } /** + * Get a region of pixels from the canvas in the form of a + * p5.Image, or a single pixel as an array of + * numbers. + * + * Returns an array of [R,G,B,A] values for any pixel or grabs a section of + * an image. If the Framebuffer has been set up to not store alpha values, then + * only [R,G,B] will be returned. If no parameters are specified, the entire + * image is returned. + * Use the x and y parameters to get the value of one pixel. Get a section of + * the display window by specifying additional w and h parameters. When + * getting an image, the x and y parameters define the coordinates for the + * upper-left corner of the image, regardless of the current imageMode(). + * + * @method get + * @param {Number} x x-coordinate of the pixel + * @param {Number} y y-coordinate of the pixel + * @param {Number} w width of the section to be returned + * @param {Number} h height of the section to be returned + * @return {p5.Image} the rectangle p5.Image + */ + /** + * @method get + * @return {p5.Image} the whole p5.Image + */ + /** + * @method get + * @param {Number} x + * @param {Number} y + * @return {Number[]} color of pixel at x,y in array format [R, G, B, A] + */ + + }, + { + key: 'get', + value: function get(x, y, w, h) { + _main.default._validateParameters('p5.Framebuffer.get', arguments); + var colorFormat = this._glColorFormat(); + if (x === undefined && y === undefined) { + x = 0; + y = 0; + w = this.width; + h = this.height; + } else if (w === undefined && h === undefined) { + if (x < 0 || y < 0 || x >= this.width || y >= this.height) { + console.warn('The x and y values passed to p5.Framebuffer.get are outside of its range and will be clamped.'); + x = this.target.constrain(x, 0, this.width - 1); + y = this.target.constrain(y, 0, this.height - 1); + } + return (0, _p2.readPixelWebGL) (this.gl, this.framebuffer, x * this.density, y * this.density, colorFormat.format, colorFormat.type); + } + x = this.target.constrain(x, 0, this.width - 1); + y = this.target.constrain(y, 0, this.height - 1); + w = this.target.constrain(w, 1, this.width - x); + h = this.target.constrain(h, 1, this.height - y); + var rawData = (0, _p2.readPixelsWebGL) (undefined, this.gl, this.framebuffer, x * this.density, y * this.density, w * this.density, h * this.density, colorFormat.format, colorFormat.type); + // Framebuffer data might be either a Uint8Array or Float32Array + // depending on its format, and it may or may not have an alpha channel. + // To turn it into an image, we have to normalize the data into a + // Uint8ClampedArray with alpha. + var fullData = new Uint8ClampedArray(w * h * this.density * this.density * 4); + // Default channels that aren't in the framebuffer (e.g. alpha, if the + // framebuffer is in RGB mode instead of RGBA) to 255 + fullData.fill(255); + var channels = colorFormat.type === this.gl.RGB ? 3 : 4; + for (var _y = 0; _y < h * this.density; _y++) { + for (var _x = 0; _x < w * this.density; _x++) { + for (var channel = 0; channel < 4; channel++) { + var idx = (_y * w * this.density + _x) * 4 + channel; + if (channel < channels) { + // Find the index of this pixel in `rawData`, which might have a + // different number of channels + var rawDataIdx = channels === 4 ? idx : (_y * w * this.density + _x) * channels + channel; + fullData[idx] = rawData[rawDataIdx]; + } + } + } + } // Create an image from the data + + var region = new _main.default.Image(w * this.density, h * this.density); + region.imageData = region.canvas.getContext('2d').createImageData(region.width, region.height); + region.imageData.data.set(fullData); + region.pixels = region.imageData.data; + region.updatePixels(); + if (this.density !== 1) { + // TODO: support get() at a pixel density > 1 + region.resize(w, h); + } + return region; + } /** + * Call this after initially calling + * loadPixels() and updating pixels + * to replace the content of the framebuffer with the data in the pixels + * array. + * + * This will also clear the depth buffer so that any future drawing done + * afterwards will go on top. + * + * @example + *
      + * + * let framebuffer; + * function setup() { + * createCanvas(100, 100, WEBGL); + * framebuffer = createFramebuffer(); + * } + * function draw() { + * noStroke(); + * lights(); + * + * // Draw a sphere to the framebuffer + * framebuffer.begin(); + * background(0); + * sphere(25); + * framebuffer.end(); + * + * // Load its pixels and draw a gradient over the lower half of the canvas + * framebuffer.loadPixels(); + * for (let y = height/2; y < height; y++) { + * for (let x = 0; x < width; x++) { + * const idx = (y * width + x) * 4; + * framebuffer.pixels[idx] = (x / width) * 255; + * framebuffer.pixels[idx + 1] = (y / height) * 255; + * framebuffer.pixels[idx + 2] = 255; + * framebuffer.pixels[idx + 3] = 255; + * } + * } + * framebuffer.updatePixels(); + * + * // Draw a cube on top of the pixels we just wrote + * framebuffer.begin(); + * push(); + * translate(20, 20); + * rotateX(0.5); + * rotateY(0.5); + * box(20); + * pop(); + * framebuffer.end(); + * + * image(framebuffer, -width/2, -height/2); + * noLoop(); + * } + * + *
      + * + * @alt + * A sphere partly occluded by a gradient from cyan to white to magenta on + * the lower half of the canvas, with a 3D cube drawn on top of that in the + * lower right corner. + */ + + }, + { + key: 'updatePixels', + value: function updatePixels() { + var gl = this.gl; + this.colorP5Texture.bindTexture(); + var colorFormat = this._glColorFormat(); + var channels = colorFormat.format === gl.RGBA ? 4 : 3; + var len = this.width * this.height * this.density * this.density * channels; + var TypedArrayClass = colorFormat.type === gl.UNSIGNED_BYTE ? Uint8Array : Float32Array; + if (!(this.pixels instanceof TypedArrayClass) || this.pixels.length !== len) { + throw new Error('The pixels array has not been set correctly. Please call loadPixels() before updatePixels().'); + } + gl.texImage2D(gl.TEXTURE_2D, 0, colorFormat.internalFormat, this.width * this.density, this.height * this.density, 0, colorFormat.format, colorFormat.type, this.pixels); + this.colorP5Texture.unbindTexture(); + var prevFramebuffer = this.target._renderer.activeFramebuffer(); + if (this.antialias) { + // We need to make sure the antialiased framebuffer also has the updated + // pixels so that if more is drawn to it, it goes on top of the updated + // pixels instead of replacing them. + // We can't blit the framebuffer to the multisampled antialias + // framebuffer to leave both in the same state, so instead we have + // to use image() to put the framebuffer texture onto the antialiased + // framebuffer. + this.begin(); + this.target.push(); + this.target.imageMode(this.target.CENTER); + this.target.resetMatrix(); + this.target.noStroke(); + this.target.clear(); + this.target.image(this, 0, 0); + this.target.pop(); + if (this.useDepth) { + gl.clearDepth(1); + gl.clear(gl.DEPTH_BUFFER_BIT); + } + this.end(); + } else { + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); + if (this.useDepth) { + gl.clearDepth(1); + gl.clear(gl.DEPTH_BUFFER_BIT); + } + if (prevFramebuffer) { + gl.bindFramebuffer(gl.FRAMEBUFFER, prevFramebuffer._framebufferToBind()); + } else { + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + } + } + } + } + ]); + return Framebuffer; + }(); + /** + * A texture with the color information of the framebuffer. Pass this (or the + * framebuffer itself) to texture() to draw it to + * the canvas, or pass it to a shader with + * setUniform() to read its data. * - * let sliderGroup = []; - * let X; - * let Y; - * let Z; - * let centerX; - * let centerY; - * let centerZ; - * let h = 20; - * let cam; + * Since Framebuffers are controlled by WebGL, their y coordinates are stored + * flipped compared to images and videos. When texturing with a framebuffer + * texture, you may want to flip vertically, e.g. with + * `plane(framebuffer.width, -framebuffer.height)`. * - * function setup() { - * createCanvas(100, 100, WEBGL); - * // create a camera - * cam = createCamera(); - * // create sliders - * for (var i = 0; i < 6; i++) { - * if (i === 2) { - * sliderGroup[i] = createSlider(10, 400, 200); - * } else { - * sliderGroup[i] = createSlider(-400, 400, 0); - * } - * h = map(i, 0, 6, 5, 85); - * sliderGroup[i].position(10, height + h); - * sliderGroup[i].style('width', '80px'); - * } - * } + * @property {p5.FramebufferTexture} color + * @for p5.Framebuffer * - * function draw() { - * background(60); - * // assigning sliders' value to each parameters - * X = sliderGroup[0].value(); - * Y = sliderGroup[1].value(); - * Z = sliderGroup[2].value(); - * centerX = sliderGroup[3].value(); - * centerY = sliderGroup[4].value(); - * centerZ = sliderGroup[5].value(); - * cam.camera(X, Y, Z, centerX, centerY, centerZ, 0, 1, 0); - * stroke(255); - * fill(255, 102, 94); - * box(85); - * } - *
      - *
      - * @alt - * An interactive example of a red cube with 3 sliders for moving it across x, y, - * z axis and 3 sliders for shifting its center. - */ - _main.default.Camera.prototype.camera = function (eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ) { - if (typeof eyeX === 'undefined') { - eyeX = this.defaultEyeX; - eyeY = this.defaultEyeY; - eyeZ = this.defaultEyeZ; - centerX = eyeX; - centerY = eyeY; - centerZ = 0; - upX = 0; - upY = 1; - upZ = 0; - } - this.eyeX = eyeX; - this.eyeY = eyeY; - this.eyeZ = eyeZ; - if (typeof centerX !== 'undefined') { - this.centerX = centerX; - this.centerY = centerY; - this.centerZ = centerZ; - } - if (typeof upX !== 'undefined') { - this.upX = upX; - this.upY = upY; - this.upZ = upZ; - } - var local = this._getLocalAxes(); // the camera affects the model view matrix, insofar as it - // inverse translates the world to the eye position of the camera - // and rotates it. - /* eslint-disable indent */ - this.cameraMatrix.set(local.x[0], local.y[0], local.z[0], 0, local.x[1], local.y[1], local.z[1], 0, local.x[2], local.y[2], local.z[2], 0, 0, 0, 0, 1); - /* eslint-enable indent */ - var tx = - eyeX; - var ty = - eyeY; - var tz = - eyeZ; - this.cameraMatrix.translate([tx, - ty, - tz]); - if (this._isActive()) { - this._renderer.uMVMatrix.set(this.cameraMatrix.mat4[0], this.cameraMatrix.mat4[1], this.cameraMatrix.mat4[2], this.cameraMatrix.mat4[3], this.cameraMatrix.mat4[4], this.cameraMatrix.mat4[5], this.cameraMatrix.mat4[6], this.cameraMatrix.mat4[7], this.cameraMatrix.mat4[8], this.cameraMatrix.mat4[9], this.cameraMatrix.mat4[10], this.cameraMatrix.mat4[11], this.cameraMatrix.mat4[12], this.cameraMatrix.mat4[13], this.cameraMatrix.mat4[14], this.cameraMatrix.mat4[15]); - } - return this; - }; - /** - * Move camera along its local axes while maintaining current camera orientation. - * @method move - * @param {Number} x amount to move along camera's left-right axis - * @param {Number} y amount to move along camera's up-down axis - * @param {Number} z amount to move along camera's forward-backward axis * @example *
      * - * // see the camera move along its own axes while maintaining its orientation - * let cam; - * let delta = 0.5; - * + * let framebuffer; * function setup() { * createCanvas(100, 100, WEBGL); - * normalMaterial(); - * cam = createCamera(); + * framebuffer = createFramebuffer(); + * noStroke(); * } * * 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; - * } + * // Draw to the framebuffer + * framebuffer.begin(); + * background(255); + * normalMaterial(); + * sphere(20); + * framebuffer.end(); * - * 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); + * // Draw the framebuffer to the main canvas + * image(framebuffer.color, -width/2, -height/2); * } * *
      * * @alt - * camera view moves along a series of 3D boxes, maintaining the same - * orientation throughout the move - */ - _main.default.Camera.prototype.move = function (x, y, z) { - var local = this._getLocalAxes(); // scale local axes by movement amounts - // based on http://learnwebgl.brown37.net/07_cameras/camera_linear_motion.html - var dx = [ - local.x[0] * x, - local.x[1] * x, - local.x[2] * x - ]; - var dy = [ - local.y[0] * y, - local.y[1] * y, - local.y[2] * y - ]; - var dz = [ - local.z[0] * z, - local.z[1] * z, - local.z[2] * z - ]; - this.camera(this.eyeX + dx[0] + dy[0] + dz[0], this.eyeY + dx[1] + dy[1] + dz[1], this.eyeZ + dx[2] + dy[2] + dz[2], this.centerX + dx[0] + dy[0] + dz[0], this.centerY + dx[1] + dy[1] + dz[1], this.centerZ + dx[2] + dy[2] + dz[2], this.upX, this.upY, this.upZ); - }; + * A red, green, and blue sphere in the middle of the canvas + */ /** - * 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 - *
      - * - * // press '1' '2' or '3' keys to set camera position - * - * let cam; - * - * function setup() { - * createCanvas(100, 100, WEBGL); - * normalMaterial(); - * cam = createCamera(); - * } + * A texture with the depth information of the framebuffer. If the framebuffer + * was created with `{ depth: false }` in its settings, then this property will + * be undefined. Pass this to texture() to draw it to + * the canvas, or pass it to a shader with + * setUniform() to read its data. * - * 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); - * } + * Since Framebuffers are controlled by WebGL, their y coordinates are stored + * flipped compared to images and videos. When texturing with a framebuffer + * texture, you may want to flip vertically, e.g. with + * `plane(framebuffer.width, -framebuffer.height)`. * - * box(20); - * } - * - *
      + * @property {p5.FramebufferTexture|undefined} depth + * @for p5.Framebuffer * - * @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, this.upX, this.upY, this.upZ); - }; //////////////////////////////////////////////////////////////////////////////// - // 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 / Math.tan(this.defaultCameraFOV / 2); - 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 - var newUpY = this.upY > 0 ? 1 : - 1; // add change according to the direction of newupY - camTheta += newUpY * dTheta; - camPhi += newUpY * dPhi; // if camPhi becomes >= PI or <= 0, - // upY of camera need to be flipped to the other side - if (camPhi <= 0 || camPhi >= Math.PI) { - newUpY *= - 1; - } - camRadius += dRadius; // prevent zooming through the center: - if (camRadius < 0) { - camRadius = 0.1; - } // 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, newUpY, 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 the current (active) camera of a 3D sketch. - * Allows for switching between multiple cameras. - * @method setCamera - * @param {p5.Camera} cam p5.Camera object - * @for p5 * @example *
      * - * 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; + * let framebuffer; + * let depthShader; + * + * const vert = ` + * precision highp float; + * attribute vec3 aPosition; + * attribute vec2 aTexCoord; + * uniform mat4 uModelViewMatrix; + * uniform mat4 uProjectionMatrix; + * varying vec2 vTexCoord; + * void main() { + * vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0); + * gl_Position = uProjectionMatrix * viewModelPosition; + * vTexCoord = aTexCoord; + * } + * `; * - * describe( - * 'Canvas switches between two camera views, each showing a series of spinning 3D boxes.' + * const frag = ` + * precision highp float; + * varying vec2 vTexCoord; + * uniform sampler2D depth; + * void main() { + * float depthVal = texture2D(depth, vTexCoord).r; + * gl_FragColor = mix( + * vec4(1., 1., 0., 1.), // yellow + * vec4(0., 0., 1., 1.), // blue + * pow(depthVal, 6.) * ); * } + * `; * - * 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 setup() { + * createCanvas(100, 100, WEBGL); + * framebuffer = createFramebuffer(); + * depthShader = createShader(vert, frag); + * noStroke(); * } * - * function drawBoxes() { + * function draw() { + * // Draw to the framebuffer + * framebuffer.begin(); + * background(255); * 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); + * box(20, 20, 100); + * framebuffer.end(); + * + * push(); + * shader(depthShader); + * depthShader.setUniform('depth', framebuffer.depth); + * plane(framebuffer.width, framebuffer.height); + * pop(); * } * *
      * * @alt - * Canvas switches between two camera views, each showing a series of spinning - * 3D boxes. + * A video of a rectangular prism rotating, with parts closest to the camera + * appearing yellow and colors getting progressively more blue the farther + * from the camera they go */ - _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; + _main.default.Framebuffer = Framebuffer; + var _default = Framebuffer; exports.default = _default; }, { - '../core/main': 290 + '../core/constants': 286, + '../core/main': 298, + './p5.RendererGL': 355, + './p5.Texture': 357, + 'core-js/modules/es.array.fill': 172, + 'core-js/modules/es.array.includes': 177, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.get-prototype-of': 198, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.reflect.construct': 202, + 'core-js/modules/es.reflect.get': 203, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.includes': 209, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.typed-array.copy-within': 223, + 'core-js/modules/es.typed-array.every': 224, + 'core-js/modules/es.typed-array.fill': 225, + 'core-js/modules/es.typed-array.filter': 226, + 'core-js/modules/es.typed-array.find': 228, + 'core-js/modules/es.typed-array.find-index': 227, + 'core-js/modules/es.typed-array.float32-array': 229, + 'core-js/modules/es.typed-array.for-each': 231, + 'core-js/modules/es.typed-array.includes': 232, + 'core-js/modules/es.typed-array.index-of': 233, + 'core-js/modules/es.typed-array.iterator': 236, + 'core-js/modules/es.typed-array.join': 237, + 'core-js/modules/es.typed-array.last-index-of': 238, + 'core-js/modules/es.typed-array.map': 239, + 'core-js/modules/es.typed-array.reduce': 241, + 'core-js/modules/es.typed-array.reduce-right': 240, + 'core-js/modules/es.typed-array.reverse': 242, + 'core-js/modules/es.typed-array.set': 243, + 'core-js/modules/es.typed-array.slice': 244, + 'core-js/modules/es.typed-array.some': 245, + 'core-js/modules/es.typed-array.sort': 246, + 'core-js/modules/es.typed-array.subarray': 247, + 'core-js/modules/es.typed-array.to-locale-string': 248, + 'core-js/modules/es.typed-array.to-string': 249, + 'core-js/modules/es.typed-array.uint8-array': 252, + 'core-js/modules/es.typed-array.uint8-clamped-array': 253, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 339: [ + 350: [ function (_dereq_, module, exports) { 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.from'); + _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.map'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.set'); + _dereq_('core-js/modules/es.string.iterator'); _dereq_('core-js/modules/es.string.sub'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.map'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.set'); + _dereq_('core-js/modules/es.string.iterator'); _dereq_('core-js/modules/es.string.sub'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + _dereq_('core-js/modules/web.dom-collections.iterator'); Object.defineProperty(exports, '__esModule', { value: true }); exports.default = void 0; var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; - } /** - * @module Shape - * @submodule 3D Primitives - * @for p5 - * @requires core - * @requires p5.Geometry - */ + } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + function _nonIterableSpread() { + throw new TypeError('Invalid attempt to spread non-iterable instance'); + } + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === '[object Arguments]') return Array.from(iter); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + return arr2; + } + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } /** + * @module Shape + * @submodule 3D Primitives + * @for p5 + * @requires core + * @requires p5.Geometry + */ //some of the functions are adjusted from Three.js(http://threejs.org) /** * p5 Geometry class @@ -101122,442 +113054,755 @@ * @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 = [ - ]; // The tangents going into or out of a vertex on a line. Along a straight - // line segment, both should be equal. At an endpoint, one or the other - // will not exist and will be all 0. In joins between line segments, they - // may be different, as they will be the tangents on either side of the join. - this.lineTangentsIn = [ - ]; - this.lineTangentsOut = [ - ]; // When drawing lines with thickness, entries in this buffer represent which - // side of the centerline the vertex will be placed. The sign of the number - // will represent the side of the centerline, and the absolute value will be - // used as an enum to determine which part of the cap or join each vertex - // represents. See the doc comments for _addCap and _addJoin for diagrams. - this.lineSides = [ - ]; //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 = [ - ]; // One color per vertex representing the stroke color at that vertex - this.vertexStrokeColors = [ - ]; // One color per line vertex, generated automatically based on - // vertexStrokeColors in _edgesToVertices() - this.lineVertexColors = [ - ]; - 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.lineTangentsIn.length = 0; - this.lineTangentsOut.length = 0; - this.lineSides.length = 0; - this.vertices.length = 0; - this.edges.length = 0; - this.vertexColors.length = 0; - this.vertexStrokeColors.length = 0; - this.lineVertexColors.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]); + _main.default.Geometry = /*#__PURE__*/ function () { + function Geometry(detailX, detailY, callback) { + _classCallCheck(this, Geometry); + //an array containing every vertex + //@type [p5.Vector] + this.vertices = [ + ]; + //an array containing every vertex for stroke drawing + this.lineVertices = new _main.default.DataArray(); + // The tangents going into or out of a vertex on a line. Along a straight + // line segment, both should be equal. At an endpoint, one or the other + // will not exist and will be all 0. In joins between line segments, they + // may be different, as they will be the tangents on either side of the join. + this.lineTangentsIn = new _main.default.DataArray(); + this.lineTangentsOut = new _main.default.DataArray(); + // When drawing lines with thickness, entries in this buffer represent which + // side of the centerline the vertex will be placed. The sign of the number + // will represent the side of the centerline, and the absolute value will be + // used as an enum to determine which part of the cap or join each vertex + // represents. See the doc comments for _addCap and _addJoin for diagrams. + this.lineSides = new _main.default.DataArray(); + //an array 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 = [ + ]; + // One color per vertex representing the stroke color at that vertex + this.vertexStrokeColors = [ + ]; + // One color per line vertex, generated automatically based on + // vertexStrokeColors in _edgesToVertices() + this.lineVertexColors = new _main.default.DataArray(); + this.detailX = detailX !== undefined ? detailX : 1; + this.detailY = detailY !== undefined ? detailY : 1; + this.dirtyFlags = { + }; + if (callback instanceof Function) { + callback.call(this); } + return this; // TODO: is this a constructor? } - 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 + _createClass(Geometry, [ + { + key: 'reset', + value: function reset() { + this.lineVertices.clear(); + this.lineTangentsIn.clear(); + this.lineTangentsOut.clear(); + this.lineSides.clear(); + this.vertices.length = 0; + this.edges.length = 0; + this.vertexColors.length = 0; + this.vertexStrokeColors.length = 0; + this.lineVertexColors.clear(); + this.vertexNormals.length = 0; + this.uvs.length = 0; + this.dirtyFlags = { + }; + } /** + * Removes the internal colors of p5.Geometry. + * Using `clearColors()`, you can use `fill()` to supply new colors before drawing each shape. + * If `clearColors()` is not used, the shapes will use their internal colors by ignoring `fill()`. + * + * @method clearColors + * + * @example + *
      + * + * let shape01; + * let shape02; + * let points = []; + * + * function setup() { + * createCanvas(600, 600, WEBGL); + * points.push(new p5.Vector(-1, -1, 0), new p5.Vector(-1, 1, 0), + * new p5.Vector(1, -1, 0), new p5.Vector(-1, -1, 0)); + * buildShape01(); + * buildShape02(); + * } + * function draw() { + * background(0); + * fill('pink'); // shape01 retains its internal blue color, so it won't turn pink. + * model(shape01); + * fill('yellow'); // Now, shape02 is yellow. + * model(shape02); + * } + * + * function buildShape01() { + * beginGeometry(); + * fill('blue'); // shape01's color is blue because its internal colors remain. + * beginShape(); + * for (let vec of points) vertex(vec.x * 100, vec.y * 100, vec.z * 100); + * endShape(CLOSE); + * shape01 = endGeometry(); + * } + * + * function buildShape02() { + * beginGeometry(); + * fill('red'); // shape02.clearColors() removes its internal colors. Now, shape02 is red. + * beginShape(); + * for (let vec of points) vertex(vec.x * 200, vec.y * 200, vec.z * 200); + * endShape(CLOSE); + * shape02 = endGeometry(); + * shape02.clearColors(); // Resets shape02's colors. + * } + * + *
      + */ + + }, + { + key: 'clearColors', + value: function clearColors() { + this.vertexColors = [ + ]; + return this; + } /** + * computes faces for geometry objects based on the vertices. + * @method computeFaces + * @chainable + */ + + }, + { + key: 'computeFaces', + value: function computeFaces() { + this.faces.length = 0; + var sliceCount = this.detailX + 1; + var a, + b, + c, + d; + for (var i = 0; i < this.detailY; i++) { + for (var j = 0; j < this.detailX; j++) { + a = i * sliceCount + j; // + offset; + b = i * sliceCount + j + 1; // + offset; + c = (i + 1) * sliceCount + j + 1; // + offset; + d = (i + 1) * sliceCount + j; // + offset; + this.faces.push([a, + b, + d]); + this.faces.push([d, + b, + c]); + } + } + return this; + } + }, + { + key: '_getFaceNormal', + value: function _getFaceNormal(faceId) { + //This assumes that vA->vB->vC is a counter-clockwise ordering + var face = this.faces[faceId]; + var vA = this.vertices[face[0]]; + var vB = this.vertices[face[1]]; + var vC = this.vertices[face[2]]; + var ab = _main.default.Vector.sub(vB, vA); + var ac = _main.default.Vector.sub(vC, vA); + var n = _main.default.Vector.cross(ab, ac); + var ln = _main.default.Vector.mag(n); + var sinAlpha = ln / (_main.default.Vector.mag(ab) * _main.default.Vector.mag(ac)); + if (sinAlpha === 0 || isNaN(sinAlpha)) { + console.warn('p5.Geometry.prototype._getFaceNormal:', 'face has colinear sides or a repeated vertex'); + return n; + } + if (sinAlpha > 1) sinAlpha = 1; // handle float rounding error + return n.mult(Math.asin(sinAlpha) / ln); + } /** + * This function calculates normals for each face, where each vertex's normal is the average of the normals of all faces it's connected to. + * i.e computes smooth normals per vertex as an average of each face. + * + * When using `FLAT` shading, vertices are disconnected/duplicated i.e each face has its own copy of vertices. + * When using `SMOOTH` shading, vertices are connected/deduplicated i.e each face has its vertices shared with other faces. + * + * Options can include: + * - `roundToPrecision`: Precision value for rounding computations. Defaults to 3. + * + * @method computeNormals + * @param {String} [shadingType] shading type (`FLAT` for flat shading or `SMOOTH` for smooth shading) for buildGeometry() outputs. Defaults to `FLAT`. + * @param {Object} [options] An optional object with configuration. + * @chainable + * + * @example + *
      + * + * let helix; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * helix = buildGeometry(() => { + * beginShape(); + * + * for (let i = 0; i < TWO_PI * 3; i += 0.6) { + * let radius = 20; + * let x = cos(i) * radius; + * let y = sin(i) * radius; + * let z = map(i, 0, TWO_PI * 3, -30, 30); + * vertex(x, y, z); + * } + * endShape(); + * }); + * helix.computeNormals(); + * } + * function draw() { + * background(255); + * stroke(0); + * fill(150, 200, 250); + * lights(); + * rotateX(PI*0.2); + * orbitControl(); + * model(helix); + * } + * + *
      + * + * @alt + * A 3D helix using the computeNormals() function by default uses `FLAT` to create a flat shading effect on the helix. + * + * @example + *
      + * + * let star; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * star = buildGeometry(() => { + * beginShape(); + * for (let i = 0; i < TWO_PI; i += PI / 5) { + * let outerRadius = 60; + * let innerRadius = 30; + * let xOuter = cos(i) * outerRadius; + * let yOuter = sin(i) * outerRadius; + * let zOuter = random(-20, 20); + * vertex(xOuter, yOuter, zOuter); + * + * let nextI = i + PI / 5 / 2; + * let xInner = cos(nextI) * innerRadius; + * let yInner = sin(nextI) * innerRadius; + * let zInner = random(-20, 20); + * vertex(xInner, yInner, zInner); + * } + * endShape(CLOSE); + * }); + * star.computeNormals(SMOOTH); + * } + * function draw() { + * background(255); + * stroke(0); + * fill(150, 200, 250); + * lights(); + * rotateX(PI*0.2); + * orbitControl(); + * model(star); + * } + * + *
      + * + * @alt + * A star-like geometry, here the computeNormals(SMOOTH) is applied for a smooth shading effect. + * This helps to avoid the faceted appearance that can occur with flat shading. + */ + + }, + { + key: 'computeNormals', + value: function computeNormals() { + var _this = this; + var shadingType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : constants.FLAT; + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { + }, + _ref$roundToPrecision = _ref.roundToPrecision, + roundToPrecision = _ref$roundToPrecision === void 0 ? 3 : _ref$roundToPrecision; + var vertexNormals = this.vertexNormals; + var vertices = this.vertices; + var faces = this.faces; + var iv; + if (shadingType === constants.SMOOTH) { + var vertexIndices = { + }; + var uniqueVertices = [ + ]; + var power = Math.pow(10, roundToPrecision); + var rounded = function rounded(val) { + return Math.round(val * power) / power; + }; + var getKey = function getKey(vert) { + return ''.concat(rounded(vert.x), ',').concat(rounded(vert.y), ',').concat(rounded(vert.z)); + }; + // loop through each vertex and add uniqueVertices + for (var i = 0; i < vertices.length; i++) { + var vertex = vertices[i]; + var key = getKey(vertex); + if (vertexIndices[key] === undefined) { + vertexIndices[key] = uniqueVertices.length; + uniqueVertices.push(vertex); + } + } // update face indices to use the deduplicated vertex indices + + faces.forEach(function (face) { + for (var fv = 0; fv < 3; ++fv) { + var originalVertexIndex = face[fv]; + var originalVertex = vertices[originalVertexIndex]; + var _key = getKey(originalVertex); + face[fv] = vertexIndices[_key]; + } + }); + // update edge indices to use the deduplicated vertex indices + this.edges.forEach(function (edge) { + for (var ev = 0; ev < 2; ++ev) { + var originalVertexIndex = edge[ev]; + var originalVertex = vertices[originalVertexIndex]; + var _key2 = getKey(originalVertex); + edge[ev] = vertexIndices[_key2]; + } + }); + // update the deduplicated vertices + this.vertices = vertices = uniqueVertices; + } // initialize the vertexNormals array with empty vectors + + vertexNormals.length = 0; + for (iv = 0; iv < vertices.length; ++iv) { + vertexNormals.push(new _main.default.Vector()); + } // loop through all the faces adding its normal to the normal + // of each of its vertices + + faces.forEach(function (face, f) { + var faceNormal = _this._getFaceNormal(f); + // all three vertices get the normal added + for (var fv = 0; fv < 3; ++fv) { + var vertexIndex = face[fv]; + vertexNormals[vertexIndex].add(faceNormal); + } + }); + // normalize the normals + for (iv = 0; iv < vertices.length; ++iv) { + vertexNormals[iv].normalize(); + } + return this; + } /** + * Averages the vertex normals. Used in curved + * surfaces + * @method averageNormals + * @chainable + */ + + }, + { + key: 'averageNormals', + value: function averageNormals() { + for (var i = 0; i <= this.detailY; i++) { + var offset = this.detailX + 1; + var temp = _main.default.Vector.add(this.vertexNormals[i * offset], this.vertexNormals[i * offset + this.detailX]); + temp = _main.default.Vector.div(temp, 2); + this.vertexNormals[i * offset] = temp; + this.vertexNormals[i * offset + this.detailX] = temp; + } + return this; + } /** + * Averages pole normals. Used in spherical primitives + * @method averagePoleNormals + * @chainable + */ + + }, + { + key: 'averagePoleNormals', + value: function averagePoleNormals() { + //average the north pole + var sum = new _main.default.Vector(0, 0, 0); + for (var i = 0; i < this.detailX; i++) { + sum.add(this.vertexNormals[i]); + } + sum = _main.default.Vector.div(sum, this.detailX); + for (var _i = 0; _i < this.detailX; _i++) { + this.vertexNormals[_i] = sum; + } //average the south pole + + sum = new _main.default.Vector(0, 0, 0); + for (var _i2 = this.vertices.length - 1; _i2 > this.vertices.length - 1 - this.detailX; _i2--) { + sum.add(this.vertexNormals[_i2]); + } + sum = _main.default.Vector.div(sum, this.detailX); + for (var _i3 = this.vertices.length - 1; _i3 > this.vertices.length - 1 - this.detailX; _i3--) { + this.vertexNormals[_i3] = sum; + } + return this; + } /** + * Create a 2D array for establishing stroke connections + * @private + * @chainable + */ + + }, + { + key: '_makeTriangleEdges', + value: function _makeTriangleEdges() { + this.edges.length = 0; + for (var j = 0; j < this.faces.length; j++) { + this.edges.push([this.faces[j][0], + this.faces[j][1]]); + this.edges.push([this.faces[j][1], + this.faces[j][2]]); + this.edges.push([this.faces[j][2], + this.faces[j][0]]); + } + return this; + } /** + * Converts each line segment into the vertices and vertex attributes needed + * to turn the line into a polygon on screen. This will include: + * - Two triangles line segment to create a rectangle + * - Two triangles per endpoint to create a stroke cap rectangle. A fragment + * shader is responsible for displaying the appropriate cap style within + * that rectangle. + * - Four triangles per join between adjacent line segments, creating a quad on + * either side of the join, perpendicular to the lines. A vertex shader will + * discard the quad in the "elbow" of the join, and a fragment shader will + * display the appropriate join style within the remaining quad. + * + * @private + * @chainable + */ + + }, + { + key: '_edgesToVertices', + value: function _edgesToVertices() { + this.lineVertices.clear(); + this.lineTangentsIn.clear(); + this.lineTangentsOut.clear(); + this.lineSides.clear(); + var potentialCaps = new Map(); + var connected = new Set(); + var lastValidDir; + for (var i = 0; i < this.edges.length; i++) { + var prevEdge = this.edges[i - 1]; + var currEdge = this.edges[i]; + var begin = this.vertices[currEdge[0]]; + var end = this.vertices[currEdge[1]]; + var fromColor = this.vertexStrokeColors.length > 0 ? this.vertexStrokeColors.slice(currEdge[0] * 4, (currEdge[0] + 1) * 4) : [ + 0, + 0, + 0, + 0 + ]; + var toColor = this.vertexStrokeColors.length > 0 ? this.vertexStrokeColors.slice(currEdge[1] * 4, (currEdge[1] + 1) * 4) : [ + 0, + 0, + 0, + 0 + ]; + var dir = end.copy().sub(begin).normalize(); + var dirOK = dir.magSq() > 0; + if (dirOK) { + this._addSegment(begin, end, fromColor, toColor, dir); + } + if (i > 0 && prevEdge[1] === currEdge[0]) { + if (!connected.has(currEdge[0])) { + connected.add(currEdge[0]); + potentialCaps.delete(currEdge[0]); + // Add a join if this segment shares a vertex with the previous. Skip + // actually adding join vertices if either the previous segment or this + // one has a length of 0. + // + // Don't add a join if the tangents point in the same direction, which + // would mean the edges line up exactly, and there is no need for a join. + if (lastValidDir && dirOK && dir.dot(lastValidDir) < 1 - 1e-8) { + this._addJoin(begin, lastValidDir, dir, fromColor); + } + } + } else { + // Start a new line + if (dirOK && !connected.has(currEdge[0])) { + var existingCap = potentialCaps.get(currEdge[0]); + if (existingCap) { + this._addJoin(begin, existingCap.dir, dir, fromColor); + potentialCaps.delete(currEdge[0]); + connected.add(currEdge[0]); + } else { + potentialCaps.set(currEdge[0], { + point: begin, + dir: dir.copy().mult( - 1), + color: fromColor + }); + } + } + if (lastValidDir && !connected.has(prevEdge[1])) { + var _existingCap = potentialCaps.get(prevEdge[1]); + if (_existingCap) { + this._addJoin(this.vertices[prevEdge[1]], lastValidDir, _existingCap.dir.copy().mult( - 1), fromColor); + potentialCaps.delete(prevEdge[1]); + connected.add(prevEdge[1]); + } else { + // Close off the last segment with a cap + potentialCaps.set(prevEdge[1], { + point: this.vertices[prevEdge[1]], + dir: lastValidDir, + color: fromColor + }); + } + lastValidDir = undefined; + } + } + if (i === this.edges.length - 1 && !connected.has(currEdge[1])) { + var _existingCap2 = potentialCaps.get(currEdge[1]); + if (_existingCap2) { + this._addJoin(end, dir, _existingCap2.dir.copy().mult( - 1), toColor); + potentialCaps.delete(currEdge[1]); + connected.add(currEdge[1]); + } else { + potentialCaps.set(currEdge[1], { + point: end, + dir: dir, + color: toColor + }); + } + } + if (dirOK) { + lastValidDir = dir; + } + } + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = potentialCaps.values() [Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _step$value = _step.value, + point = _step$value.point, + _dir = _step$value.dir, + color = _step$value.color; + this._addCap(point, _dir, color); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + return this; + } /** + * Adds the vertices and vertex attributes for two triangles making a rectangle + * for a straight line segment. A vertex shader is responsible for picking + * proper coordinates on the screen given the centerline positions, the tangent, + * and the side of the centerline each vertex belongs to. Sides follow the + * following scheme: + * + * -1 -1 + * o-------------o + * | | + * o-------------o + * 1 1 + * + * @private + * @chainable + */ - 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; - }; - /** - * Converts each line segment into the vertices and vertex attributes needed - * to turn the line into a polygon on screen. This will include: - * - Two triangles line segment to create a rectangle - * - Two triangles per endpoint to create a stroke cap rectangle. A fragment - * shader is responsible for displaying the appropriate cap style within - * that rectangle. - * - Four triangles per join between adjacent line segments, creating a quad on - * either side of the join, perpendicular to the lines. A vertex shader will - * discard the quad in the "elbow" of the join, and a fragment shader will - * display the appropriate join style within the remaining quad. - * - * @private - * @chainable - */ - _main.default.Geometry.prototype._edgesToVertices = function () { - this.lineVertices.length = 0; - this.lineTangentsIn.length = 0; - this.lineTangentsOut.length = 0; - this.lineSides.length = 0; - var closed = this.edges.length > 1 && this.edges[0][0] === this.edges[this.edges.length - 1][1]; - var addedStartingCap = false; - var lastValidDir; - for (var i = 0; i < this.edges.length; i++) { - var prevEdge = this.edges[i - 1]; - var currEdge = this.edges[i]; - var begin = this.vertices[currEdge[0]]; - var end = this.vertices[currEdge[1]]; - var fromColor = this.vertexStrokeColors.length > 0 ? this.vertexStrokeColors.slice(currEdge[0] * 4, (currEdge[0] + 1) * 4) : [ - 0, - 0, - 0, - 0 - ]; - var toColor = this.vertexStrokeColors.length > 0 ? this.vertexStrokeColors.slice(currEdge[1] * 4, (currEdge[1] + 1) * 4) : [ - 0, - 0, - 0, - 0 - ]; - var dir = end.copy().sub(begin).normalize(); - var dirOK = dir.magSq() > 0; - if (dirOK) { - this._addSegment(begin, end, fromColor, toColor, dir); - } - if (i > 0 && prevEdge[1] === currEdge[0]) { - // Add a join if this segment shares a vertex with the previous. Skip - // actually adding join vertices if either the previous segment or this - // one has a length of 0. - // - // Don't add a join if the tangents point in the same direction, which - // would mean the edges line up exactly, and there is no need for a join. - if (lastValidDir && dirOK && dir.dot(lastValidDir) < 1 - 1e-8) { - this._addJoin(begin, lastValidDir, dir, fromColor); - } - if (dirOK && !addedStartingCap && !closed) { - this._addCap(begin, dir.copy().mult( - 1), fromColor); - addedStartingCap = true; - } - } else { - addedStartingCap = false; // Start a new line - if (dirOK && (!closed || i > 0)) { - this._addCap(begin, dir.copy().mult( - 1), fromColor); - addedStartingCap = true; - } - if (lastValidDir && (!closed || i < this.edges.length - 1)) { - // Close off the last segment with a cap - this._addCap(this.vertices[prevEdge[1]], lastValidDir, fromColor); - lastValidDir = undefined; - } - } - if (i === this.edges.length - 1) { - if (closed) { - this._addJoin(end, dir, this.vertices[this.edges[0][1]].copy().sub(end).normalize(), toColor); - } else { - this._addCap(end, dir, toColor); + }, + { + key: '_addSegment', + value: function _addSegment(begin, end, fromColor, toColor, dir) { + var _this$lineVertices, + _this$lineVertexColor; + var a = begin.array(); + var b = end.array(); + var dirArr = dir.array(); + this.lineSides.push(1, 1, - 1, 1, - 1, - 1); + for (var _i4 = 0, _arr = [ + this.lineTangentsIn, + this.lineTangentsOut + ]; _i4 < _arr.length; _i4++) { + var tangents = _arr[_i4]; + for (var i = 0; i < 6; i++) { + tangents.push.apply(tangents, _toConsumableArray(dirArr)); + } + }(_this$lineVertices = this.lineVertices).push.apply(_this$lineVertices, _toConsumableArray(a).concat(_toConsumableArray(b), _toConsumableArray(a), _toConsumableArray(b), _toConsumableArray(b), _toConsumableArray(a))); + (_this$lineVertexColor = this.lineVertexColors).push.apply(_this$lineVertexColor, _toConsumableArray(fromColor).concat(_toConsumableArray(toColor), _toConsumableArray(fromColor), _toConsumableArray(toColor), _toConsumableArray(toColor), _toConsumableArray(fromColor))); + return this; + } /** + * Adds the vertices and vertex attributes for two triangles representing the + * stroke cap of a line. A fragment shader is responsible for displaying the + * appropriate cap style within the rectangle they make. + * + * The lineSides buffer will include the following values for the points on + * the cap rectangle: + * + * -1 -2 + * -----------o---o + * | | + * -----------o---o + * 1 2 + * @private + * @chainable + */ + + }, + { + key: '_addCap', + value: function _addCap(point, tangent, color) { + var ptArray = point.array(); + var tanInArray = tangent.array(); + var tanOutArray = [ + 0, + 0, + 0 + ]; + for (var i = 0; i < 6; i++) { + var _this$lineVertices2, + _this$lineTangentsIn, + _this$lineTangentsOut, + _this$lineVertexColor2; + (_this$lineVertices2 = this.lineVertices).push.apply(_this$lineVertices2, _toConsumableArray(ptArray)); + (_this$lineTangentsIn = this.lineTangentsIn).push.apply(_this$lineTangentsIn, _toConsumableArray(tanInArray)); + (_this$lineTangentsOut = this.lineTangentsOut).push.apply(_this$lineTangentsOut, tanOutArray); + (_this$lineVertexColor2 = this.lineVertexColors).push.apply(_this$lineVertexColor2, _toConsumableArray(color)); + } + this.lineSides.push( - 1, 2, - 2, 1, 2, - 1); + return this; + } /** + * Adds the vertices and vertex attributes for four triangles representing a + * join between two adjacent line segments. This creates a quad on either side + * of the shared vertex of the two line segments, with each quad perpendicular + * to the lines. A vertex shader will discard all but the quad in the "elbow" of + * the join, and a fragment shader will display the appropriate join style + * within the remaining quad. + * + * The lineSides buffer will include the following values for the points on + * the join rectangles: + * + * -1 -2 + * -------------o----o + * | | + * 1 o----o----o -3 + * | | 0 | + * --------o----o | + * 2| 3 | + * | | + * | | + * @private + * @chainable + */ + + }, + { + key: '_addJoin', + value: function _addJoin(point, fromTangent, toTangent, color) { + var ptArray = point.array(); + var tanInArray = fromTangent.array(); + var tanOutArray = toTangent.array(); + for (var i = 0; i < 12; i++) { + var _this$lineVertices3, + _this$lineTangentsIn2, + _this$lineTangentsOut2, + _this$lineVertexColor3; + (_this$lineVertices3 = this.lineVertices).push.apply(_this$lineVertices3, _toConsumableArray(ptArray)); + (_this$lineTangentsIn2 = this.lineTangentsIn).push.apply(_this$lineTangentsIn2, _toConsumableArray(tanInArray)); + (_this$lineTangentsOut2 = this.lineTangentsOut).push.apply(_this$lineTangentsOut2, _toConsumableArray(tanOutArray)); + (_this$lineVertexColor3 = this.lineVertexColors).push.apply(_this$lineVertexColor3, _toConsumableArray(color)); + } + this.lineSides.push( - 1, - 3, - 2, - 1, 0, - 3); + this.lineSides.push(3, 1, 2, 3, 0, 1); + return this; + } /** + * Modifies all vertices to be centered within the range -100 to 100. + * @method normalize + * @chainable + */ + + }, + { + key: 'normalize', + value: function normalize() { + if (this.vertices.length > 0) { + // Find the corners of our bounding box + var maxPosition = this.vertices[0].copy(); + var minPosition = this.vertices[0].copy(); + for (var i = 0; i < this.vertices.length; i++) { + maxPosition.x = Math.max(maxPosition.x, this.vertices[i].x); + minPosition.x = Math.min(minPosition.x, this.vertices[i].x); + maxPosition.y = Math.max(maxPosition.y, this.vertices[i].y); + minPosition.y = Math.min(minPosition.y, this.vertices[i].y); + maxPosition.z = Math.max(maxPosition.z, this.vertices[i].z); + minPosition.z = Math.min(minPosition.z, this.vertices[i].z); + } + var center = _main.default.Vector.lerp(maxPosition, minPosition, 0.5); + var dist = _main.default.Vector.sub(maxPosition, minPosition); + var longestDist = Math.max(Math.max(dist.x, dist.y), dist.z); + var scale = 200 / longestDist; + for (var _i5 = 0; _i5 < this.vertices.length; _i5++) { + this.vertices[_i5].sub(center); + this.vertices[_i5].mult(scale); + } + } + return this; } } - if (dirOK) { - lastValidDir = dir; - } - } - return this; - }; - /** - * Adds the vertices and vertex attributes for two triangles making a rectangle - * for a straight line segment. A vertex shader is responsible for picking - * proper coordinates on the screen given the centerline positions, the tangent, - * and the side of the centerline each vertex belongs to. Sides follow the - * following scheme: - * - * -1 -1 - * o-------------o - * | | - * o-------------o - * 1 1 - * - * @private - * @chainable - */ - _main.default.Geometry.prototype._addSegment = function (begin, end, fromColor, toColor, dir) { - var a = begin.array(); - var b = end.array(); - var dirArr = dir.array(); - this.lineSides.push(1, - 1, 1, 1, - 1, - 1); - for (var _i4 = 0, _arr = [ - this.lineTangentsIn, - this.lineTangentsOut - ]; _i4 < _arr.length; _i4++) { - var tangents = _arr[_i4]; - tangents.push(dirArr, dirArr, dirArr, dirArr, dirArr, dirArr); - } - this.lineVertices.push(a, a, b, b, a, b); - this.lineVertexColors.push(fromColor, fromColor, toColor, toColor, fromColor, toColor); - return this; - }; - /** - * Adds the vertices and vertex attributes for two triangles representing the - * stroke cap of a line. A fragment shader is responsible for displaying the - * appropriate cap style within the rectangle they make. - * - * The lineSides buffer will include the following values for the points on - * the cap rectangle: - * - * -1 -2 - * -----------o---o - * | | - * -----------o---o - * 1 2 - * @private - * @chainable - */ - _main.default.Geometry.prototype._addCap = function (point, tangent, color) { - var ptArray = point.array(); - var tanInArray = tangent.array(); - var tanOutArray = [ - 0, - 0, - 0 - ]; - for (var i = 0; i < 6; i++) { - this.lineVertices.push(ptArray); - this.lineTangentsIn.push(tanInArray); - this.lineTangentsOut.push(tanOutArray); - this.lineVertexColors.push(color); - } - this.lineSides.push( - 1, - 2, 2, 2, 1, - 1); - return this; - }; - /** - * Adds the vertices and vertex attributes for four triangles representing a - * join between two adjacent line segments. This creates a quad on either side - * of the shared vertex of the two line segments, with each quad perpendicular - * to the lines. A vertex shader will discard all but the quad in the "elbow" of - * the join, and a fragment shader will display the appropriate join style - * within the remaining quad. - * - * The lineSides buffer will include the following values for the points on - * the join rectangles: - * - * -1 -2 - * -------------o----o - * | | - * 1 o----o----o -3 - * | | 0 | - * --------o----o | - * 2| 3 | - * | | - * | | - * @private - * @chainable - */ - _main.default.Geometry.prototype._addJoin = function (point, fromTangent, toTangent, color) { - var ptArray = point.array(); - var tanInArray = fromTangent.array(); - var tanOutArray = toTangent.array(); - for (var i = 0; i < 12; i++) { - this.lineVertices.push(ptArray); - this.lineTangentsIn.push(tanInArray); - this.lineTangentsOut.push(tanOutArray); - this.lineVertexColors.push(color); - } - for (var _i5 = 0, _arr2 = [ - - 1, - 1 - ]; _i5 < _arr2.length; _i5++) { - var side = _arr2[_i5]; - this.lineSides.push(side, 2 * side, 3 * side, side, 3 * side, 0); - } - 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 _i6 = 0; _i6 < this.vertices.length; _i6++) { - this.vertices[_i6].sub(center); - this.vertices[_i6].mult(scale); - } - } - return this; - }; + ]); + return Geometry; + }(); var _default = _main.default.Geometry; exports.default = _default; }, { - '../core/main': 290, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.string.sub': 210 + '../core/constants': 286, + '../core/main': 298, + 'core-js/modules/es.array.concat': 169, + 'core-js/modules/es.array.for-each': 175, + 'core-js/modules/es.array.from': 176, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.map': 187, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.set': 207, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.string.sub': 218, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.for-each': 255, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 340: [ + 351: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.array.iterator'); @@ -101622,23 +113867,42 @@ 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 - */ + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } /** + * @requires constants + * @todo see methods below needing further implementation. + * future consideration: implement SIMD optimizations + * when browser compatibility becomes available + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/ + * Reference/Global_Objects/SIMD + */ var GLMAT_ARRAY_TYPE = Array; var isMatrixArray = function isMatrixArray(x) { - return x instanceof Array; + return Array.isArray(x); }; if (typeof Float32Array !== 'undefined') { GLMAT_ARRAY_TYPE = Float32Array; isMatrixArray = function isMatrixArray(x) { - return x instanceof Array || x instanceof Float32Array; + return Array.isArray(x) || x instanceof Float32Array; }; } /** * A class to describe a 4×4 matrix @@ -101646,759 +113910,1087 @@ * @class p5.Matrix * @private * @constructor - * @param {Array} [mat4] array literal of our 4×4 matrix - */ + * @param {Array} [mat4] column-major array literal of our 4×4 matrix + */ + + _main.default.Matrix = /*#__PURE__*/ function () { + function _class() { + var _ref; + _classCallCheck(this, _class); + // This is default behavior when object + // instantiated using createMatrix() + // @todo implement createMatrix() in core/math.js + if (arguments.length && (_ref = arguments.length - 1, _ref < 0 || arguments.length <= _ref ? undefined : arguments[_ref]) instanceof _main.default) { + var _ref2; + this.p5 = (_ref2 = arguments.length - 1, _ref2 < 0 || arguments.length <= _ref2 ? undefined : arguments[_ref2]); + } + if ((arguments.length <= 0 ? undefined : arguments[0]) === 'mat3') { + this.mat3 = Array.isArray(arguments.length <= 1 ? undefined : arguments[1]) ? arguments.length <= 1 ? undefined : arguments[1] : new GLMAT_ARRAY_TYPE([1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1]); + } else { + this.mat4 = Array.isArray(arguments.length <= 0 ? undefined : arguments[0]) ? arguments.length <= 0 ? undefined : arguments[0] : new GLMAT_ARRAY_TYPE([1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1]); + } + return this; + } /** + * 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 = 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 + _createClass(_class, [ + { + key: 'set', + value: function set(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 + */ - 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 / det; - this.mat4[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; - this.mat4[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; - this.mat4[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; - this.mat4[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; - this.mat4[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; - this.mat4[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; - this.mat4[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; - this.mat4[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; - this.mat4[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; - this.mat4[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; - this.mat4[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; - this.mat4[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; - this.mat4[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; - this.mat4[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; - this.mat4[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; - this.mat4[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; - return this; - }; - /** - * Inverts a 3×3 matrix - * @method invert3x3 - * @chainable - */ - _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 / 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 3×3 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 4×4 matrix to its 3×3 inverse transform - * commonly used in MVMatrix to NMatrix conversions. - * @method invertTranspose - * @param {p5.Matrix} mat4 the matrix to be based on to invert - * @chainable - * @todo finish implementation - */ - _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; + }, + { + key: 'get', + value: function get() { + return new _main.default.Matrix(this.mat4, this.p5); + } /** + * return a copy of this matrix. + * If this matrix is 4x4, a 4x4 matrix with exactly the same entries will be + * generated. The same is true if this matrix is 3x3. + * + * @method copy + * @return {p5.Matrix} the result matrix + */ + + }, + { + key: 'copy', + value: function copy() { + if (this.mat3 !== undefined) { + var copied3x3 = new _main.default.Matrix('mat3', this.p5); + copied3x3.mat3[0] = this.mat3[0]; + copied3x3.mat3[1] = this.mat3[1]; + copied3x3.mat3[2] = this.mat3[2]; + copied3x3.mat3[3] = this.mat3[3]; + copied3x3.mat3[4] = this.mat3[4]; + copied3x3.mat3[5] = this.mat3[5]; + copied3x3.mat3[6] = this.mat3[6]; + copied3x3.mat3[7] = this.mat3[7]; + copied3x3.mat3[8] = this.mat3[8]; + return copied3x3; + } + var copied = new _main.default.Matrix(this.p5); + copied.mat4[0] = this.mat4[0]; + copied.mat4[1] = this.mat4[1]; + copied.mat4[2] = this.mat4[2]; + copied.mat4[3] = this.mat4[3]; + copied.mat4[4] = this.mat4[4]; + copied.mat4[5] = this.mat4[5]; + copied.mat4[6] = this.mat4[6]; + copied.mat4[7] = this.mat4[7]; + copied.mat4[8] = this.mat4[8]; + copied.mat4[9] = this.mat4[9]; + copied.mat4[10] = this.mat4[10]; + copied.mat4[11] = this.mat4[11]; + copied.mat4[12] = this.mat4[12]; + copied.mat4[13] = this.mat4[13]; + copied.mat4[14] = this.mat4[14]; + copied.mat4[15] = this.mat4[15]; + return copied; + } /** + * return an identity matrix + * @method identity + * @return {p5.Matrix} the result matrix + */ + + }, + { + key: 'transpose', + /** + * transpose according to a given matrix + * @method transpose + * @param {p5.Matrix|Float32Array|Number[]} a the matrix to be + * based on to transpose + * @chainable + */ + value: function transpose(a) { + var a01, + a02, + a03, + a12, + a13, + a23; + if (a instanceof _main.default.Matrix) { + a01 = a.mat4[1]; + a02 = a.mat4[2]; + a03 = a.mat4[3]; + a12 = a.mat4[6]; + a13 = a.mat4[7]; + a23 = a.mat4[11]; + this.mat4[0] = a.mat4[0]; + this.mat4[1] = a.mat4[4]; + this.mat4[2] = a.mat4[8]; + this.mat4[3] = a.mat4[12]; + this.mat4[4] = a01; + this.mat4[5] = a.mat4[5]; + this.mat4[6] = a.mat4[9]; + this.mat4[7] = a.mat4[13]; + this.mat4[8] = a02; + this.mat4[9] = a12; + this.mat4[10] = a.mat4[10]; + this.mat4[11] = a.mat4[14]; + this.mat4[12] = a03; + this.mat4[13] = a13; + this.mat4[14] = a23; + this.mat4[15] = a.mat4[15]; + } else if (isMatrixArray(a)) { + a01 = a[1]; + a02 = a[2]; + a03 = a[3]; + a12 = a[6]; + a13 = a[7]; + a23 = a[11]; + this.mat4[0] = a[0]; + this.mat4[1] = a[4]; + this.mat4[2] = a[8]; + this.mat4[3] = a[12]; + this.mat4[4] = a01; + this.mat4[5] = a[5]; + this.mat4[6] = a[9]; + this.mat4[7] = a[13]; + this.mat4[8] = a02; + this.mat4[9] = a12; + this.mat4[10] = a[10]; + this.mat4[11] = a[14]; + this.mat4[12] = a03; + this.mat4[13] = a13; + this.mat4[14] = a23; + this.mat4[15] = a[15]; + } + return this; + } /** + * invert matrix according to a give matrix + * @method invert + * @param {p5.Matrix|Float32Array|Number[]} a the matrix to be + * based on to invert + * @chainable + */ + + }, + { + key: 'invert', + value: function invert(a) { + var a00, + a01, + a02, + a03, + a10, + a11, + a12, + a13; + var a20, + a21, + a22, + a23, + a30, + a31, + a32, + a33; + if (a instanceof _main.default.Matrix) { + a00 = a.mat4[0]; + a01 = a.mat4[1]; + a02 = a.mat4[2]; + a03 = a.mat4[3]; + a10 = a.mat4[4]; + a11 = a.mat4[5]; + a12 = a.mat4[6]; + a13 = a.mat4[7]; + a20 = a.mat4[8]; + a21 = a.mat4[9]; + a22 = a.mat4[10]; + a23 = a.mat4[11]; + a30 = a.mat4[12]; + a31 = a.mat4[13]; + a32 = a.mat4[14]; + a33 = a.mat4[15]; + } else if (isMatrixArray(a)) { + a00 = a[0]; + a01 = a[1]; + a02 = a[2]; + a03 = a[3]; + a10 = a[4]; + a11 = a[5]; + a12 = a[6]; + a13 = a[7]; + a20 = a[8]; + a21 = a[9]; + a22 = a[10]; + a23 = a[11]; + a30 = a[12]; + a31 = a[13]; + a32 = a[14]; + a33 = a[15]; + } + var b00 = a00 * a11 - a01 * a10; + var b01 = a00 * a12 - a02 * a10; + var b02 = a00 * a13 - a03 * a10; + var b03 = a01 * a12 - a02 * a11; + var b04 = a01 * a13 - a03 * a11; + var b05 = a02 * a13 - a03 * a12; + var b06 = a20 * a31 - a21 * a30; + var b07 = a20 * a32 - a22 * a30; + var b08 = a20 * a33 - a23 * a30; + var b09 = a21 * a32 - a22 * a31; + var b10 = a21 * a33 - a23 * a31; + var b11 = a22 * a33 - a23 * a32; + // Calculate the determinant + var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + if (!det) { + return null; + } + det = 1 / det; + this.mat4[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + this.mat4[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + this.mat4[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + this.mat4[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; + this.mat4[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + this.mat4[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + this.mat4[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + this.mat4[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; + this.mat4[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + this.mat4[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + this.mat4[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + this.mat4[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; + this.mat4[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; + this.mat4[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; + this.mat4[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; + this.mat4[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; + return this; + } /** + * Inverts a 3×3 matrix + * @method invert3x3 + * @chainable + */ + + }, + { + key: 'invert3x3', + value: function invert3x3() { + var a00 = this.mat3[0]; + var a01 = this.mat3[1]; + var a02 = this.mat3[2]; + var a10 = this.mat3[3]; + var a11 = this.mat3[4]; + var a12 = this.mat3[5]; + var a20 = this.mat3[6]; + var a21 = this.mat3[7]; + var a22 = this.mat3[8]; + var b01 = a22 * a11 - a12 * a21; + var b11 = - a22 * a10 + a12 * a20; + var b21 = a21 * a10 - a11 * a20; + // Calculate the determinant + var det = a00 * b01 + a01 * b11 + a02 * b21; + if (!det) { + return null; + } + det = 1 / det; + this.mat3[0] = b01 * det; + this.mat3[1] = ( - a22 * a01 + a02 * a21) * det; + this.mat3[2] = (a12 * a01 - a02 * a11) * det; + this.mat3[3] = b11 * det; + this.mat3[4] = (a22 * a00 - a02 * a20) * det; + this.mat3[5] = ( - a12 * a00 + a02 * a10) * det; + this.mat3[6] = b21 * det; + this.mat3[7] = ( - a21 * a00 + a01 * a20) * det; + this.mat3[8] = (a11 * a00 - a01 * a10) * det; + return this; + } /** + * This function is only for 3x3 matrices. + * transposes a 3×3 p5.Matrix by a mat3 + * If there is an array of arguments, the matrix obtained by transposing + * the 3x3 matrix generated based on that array is set. + * If no arguments, it transposes itself and returns it. + * + * @method transpose3x3 + * @param {Number[]} mat3 1-dimensional array + * @chainable + */ + + }, + { + key: 'transpose3x3', + value: function transpose3x3(mat3) { + if (mat3 === undefined) { + mat3 = this.mat3; + } + var a01 = mat3[1]; + var a02 = mat3[2]; + var a12 = mat3[5]; + this.mat3[0] = mat3[0]; + this.mat3[1] = mat3[3]; + this.mat3[2] = mat3[6]; + this.mat3[3] = a01; + this.mat3[4] = mat3[4]; + this.mat3[5] = mat3[7]; + this.mat3[6] = a02; + this.mat3[7] = a12; + this.mat3[8] = mat3[8]; + return this; + } /** + * converts a 4×4 matrix to its 3×3 inverse transform + * commonly used in MVMatrix to NMatrix conversions. + * @method invertTranspose + * @param {p5.Matrix} mat4 the matrix to be based on to invert + * @chainable + * @todo finish implementation + */ + + }, + { + key: 'inverseTranspose', + value: function inverseTranspose(_ref3) { + var mat4 = _ref3.mat4; + if (this.mat3 === undefined) { + _main.default._friendlyError('sorry, this function only works with mat3'); + } else { + //convert mat4 -> mat3 + this.mat3[0] = mat4[0]; + this.mat3[1] = mat4[1]; + this.mat3[2] = mat4[2]; + this.mat3[3] = mat4[4]; + this.mat3[4] = mat4[5]; + this.mat3[5] = mat4[6]; + this.mat3[6] = mat4[8]; + this.mat3[7] = mat4[9]; + this.mat3[8] = mat4[10]; + } + var inverse = this.invert3x3(); + // check inverse succeeded + if (inverse) { + inverse.transpose3x3(this.mat3); + } else { + // in case of singularity, just zero the matrix + for (var i = 0; i < 9; i++) { + this.mat3[i] = 0; + } + } + return this; + } /** + * inspired by Toji's mat4 determinant + * @method determinant + * @return {Number} Determinant of our 4×4 matrix + */ + + }, + { + key: 'determinant', + value: function determinant() { + var d00 = this.mat4[0] * this.mat4[5] - this.mat4[1] * this.mat4[4], + d01 = this.mat4[0] * this.mat4[6] - this.mat4[2] * this.mat4[4], + d02 = this.mat4[0] * this.mat4[7] - this.mat4[3] * this.mat4[4], + d03 = this.mat4[1] * this.mat4[6] - this.mat4[2] * this.mat4[5], + d04 = this.mat4[1] * this.mat4[7] - this.mat4[3] * this.mat4[5], + d05 = this.mat4[2] * this.mat4[7] - this.mat4[3] * this.mat4[6], + d06 = this.mat4[8] * this.mat4[13] - this.mat4[9] * this.mat4[12], + d07 = this.mat4[8] * this.mat4[14] - this.mat4[10] * this.mat4[12], + d08 = this.mat4[8] * this.mat4[15] - this.mat4[11] * this.mat4[12], + d09 = this.mat4[9] * this.mat4[14] - this.mat4[10] * this.mat4[13], + d10 = this.mat4[9] * this.mat4[15] - this.mat4[11] * this.mat4[13], + d11 = this.mat4[10] * this.mat4[15] - this.mat4[11] * this.mat4[14]; + // Calculate the determinant + return d00 * d11 - d01 * d10 + d02 * d09 + d03 * d08 - d04 * d07 + d05 * d06; + } /** + * multiply two mat4s + * @method mult + * @param {p5.Matrix|Float32Array|Number[]} multMatrix The matrix + * we want to multiply by + * @chainable + */ + + }, + { + key: 'mult', + value: function mult(multMatrix) { + var _src; + if (multMatrix === this || multMatrix === this.mat4) { + _src = this.copy().mat4; // only need to allocate in this rare case + } else if (multMatrix instanceof _main.default.Matrix) { + _src = multMatrix.mat4; + } else if (isMatrixArray(multMatrix)) { + _src = multMatrix; + } else if (arguments.length === 16) { + _src = arguments; + } else { + return; // nothing to do. + } // each row is used for the multiplier + + var b0 = this.mat4[0], + b1 = this.mat4[1], + b2 = this.mat4[2], + b3 = this.mat4[3]; + this.mat4[0] = b0 * _src[0] + b1 * _src[4] + b2 * _src[8] + b3 * _src[12]; + this.mat4[1] = b0 * _src[1] + b1 * _src[5] + b2 * _src[9] + b3 * _src[13]; + this.mat4[2] = b0 * _src[2] + b1 * _src[6] + b2 * _src[10] + b3 * _src[14]; + this.mat4[3] = b0 * _src[3] + b1 * _src[7] + b2 * _src[11] + b3 * _src[15]; + b0 = this.mat4[4]; + b1 = this.mat4[5]; + b2 = this.mat4[6]; + b3 = this.mat4[7]; + this.mat4[4] = b0 * _src[0] + b1 * _src[4] + b2 * _src[8] + b3 * _src[12]; + this.mat4[5] = b0 * _src[1] + b1 * _src[5] + b2 * _src[9] + b3 * _src[13]; + this.mat4[6] = b0 * _src[2] + b1 * _src[6] + b2 * _src[10] + b3 * _src[14]; + this.mat4[7] = b0 * _src[3] + b1 * _src[7] + b2 * _src[11] + b3 * _src[15]; + b0 = this.mat4[8]; + b1 = this.mat4[9]; + b2 = this.mat4[10]; + b3 = this.mat4[11]; + this.mat4[8] = b0 * _src[0] + b1 * _src[4] + b2 * _src[8] + b3 * _src[12]; + this.mat4[9] = b0 * _src[1] + b1 * _src[5] + b2 * _src[9] + b3 * _src[13]; + this.mat4[10] = b0 * _src[2] + b1 * _src[6] + b2 * _src[10] + b3 * _src[14]; + this.mat4[11] = b0 * _src[3] + b1 * _src[7] + b2 * _src[11] + b3 * _src[15]; + b0 = this.mat4[12]; + b1 = this.mat4[13]; + b2 = this.mat4[14]; + b3 = this.mat4[15]; + this.mat4[12] = b0 * _src[0] + b1 * _src[4] + b2 * _src[8] + b3 * _src[12]; + this.mat4[13] = b0 * _src[1] + b1 * _src[5] + b2 * _src[9] + b3 * _src[13]; + this.mat4[14] = b0 * _src[2] + b1 * _src[6] + b2 * _src[10] + b3 * _src[14]; + this.mat4[15] = b0 * _src[3] + b1 * _src[7] + b2 * _src[11] + b3 * _src[15]; + return this; + } + }, + { + key: 'apply', + value: function apply(multMatrix) { + var _src; + if (multMatrix === this || multMatrix === this.mat4) { + _src = this.copy().mat4; // only need to allocate in this rare case + } else if (multMatrix instanceof _main.default.Matrix) { + _src = multMatrix.mat4; + } else if (isMatrixArray(multMatrix)) { + _src = multMatrix; + } else if (arguments.length === 16) { + _src = arguments; + } else { + return; // nothing to do. + } + var mat4 = this.mat4; + // each row is used for the multiplier + var m0 = mat4[0]; + var m4 = mat4[4]; + var m8 = mat4[8]; + var m12 = mat4[12]; + mat4[0] = _src[0] * m0 + _src[1] * m4 + _src[2] * m8 + _src[3] * m12; + mat4[4] = _src[4] * m0 + _src[5] * m4 + _src[6] * m8 + _src[7] * m12; + mat4[8] = _src[8] * m0 + _src[9] * m4 + _src[10] * m8 + _src[11] * m12; + mat4[12] = _src[12] * m0 + _src[13] * m4 + _src[14] * m8 + _src[15] * m12; + var m1 = mat4[1]; + var m5 = mat4[5]; + var m9 = mat4[9]; + var m13 = mat4[13]; + mat4[1] = _src[0] * m1 + _src[1] * m5 + _src[2] * m9 + _src[3] * m13; + mat4[5] = _src[4] * m1 + _src[5] * m5 + _src[6] * m9 + _src[7] * m13; + mat4[9] = _src[8] * m1 + _src[9] * m5 + _src[10] * m9 + _src[11] * m13; + mat4[13] = _src[12] * m1 + _src[13] * m5 + _src[14] * m9 + _src[15] * m13; + var m2 = mat4[2]; + var m6 = mat4[6]; + var m10 = mat4[10]; + var m14 = mat4[14]; + mat4[2] = _src[0] * m2 + _src[1] * m6 + _src[2] * m10 + _src[3] * m14; + mat4[6] = _src[4] * m2 + _src[5] * m6 + _src[6] * m10 + _src[7] * m14; + mat4[10] = _src[8] * m2 + _src[9] * m6 + _src[10] * m10 + _src[11] * m14; + mat4[14] = _src[12] * m2 + _src[13] * m6 + _src[14] * m10 + _src[15] * m14; + var m3 = mat4[3]; + var m7 = mat4[7]; + var m11 = mat4[11]; + var m15 = mat4[15]; + mat4[3] = _src[0] * m3 + _src[1] * m7 + _src[2] * m11 + _src[3] * m15; + mat4[7] = _src[4] * m3 + _src[5] * m7 + _src[6] * m11 + _src[7] * m15; + mat4[11] = _src[8] * m3 + _src[9] * m7 + _src[10] * m11 + _src[11] * m15; + mat4[15] = _src[12] * m3 + _src[13] * m7 + _src[14] * m11 + _src[15] * m15; + return this; + } /** + * scales a p5.Matrix by scalars or a vector + * @method scale + * @param {p5.Vector|Float32Array|Number[]} s vector to scale by + * @chainable + */ + + }, + { + key: 'scale', + value: function scale(x, y, z) { + if (x instanceof _main.default.Vector) { + // x is a vector, extract the components from it. + y = x.y; + z = x.z; + x = x.x; // must be last + } else if (x instanceof Array) { + // x is an array, extract the components from it. + y = x[1]; + z = x[2]; + x = x[0]; // must be last + } + this.mat4[0] *= x; + this.mat4[1] *= x; + this.mat4[2] *= x; + this.mat4[3] *= x; + this.mat4[4] *= y; + this.mat4[5] *= y; + this.mat4[6] *= y; + this.mat4[7] *= y; + this.mat4[8] *= z; + this.mat4[9] *= z; + this.mat4[10] *= z; + this.mat4[11] *= z; + return this; + } /** + * rotate our Matrix around an axis by the given angle. + * @method rotate + * @param {Number} a The angle of rotation in radians + * @param {p5.Vector|Number[]} axis the axis(es) to rotate around + * @chainable + * inspired by Toji's gl-matrix lib, mat4 rotation + */ + + }, + { + key: 'rotate', + value: function rotate(a, x, y, z) { + if (x instanceof _main.default.Vector) { + // x is a vector, extract the components from it. + y = x.y; + z = x.z; + x = x.x; //must be last + } else if (x instanceof Array) { + // x is an array, extract the components from it. + y = x[1]; + z = x[2]; + x = x[0]; //must be last + } + var len = Math.sqrt(x * x + y * y + z * z); + x *= 1 / len; + y *= 1 / len; + z *= 1 / len; + var a00 = this.mat4[0]; + var a01 = this.mat4[1]; + var a02 = this.mat4[2]; + var a03 = this.mat4[3]; + var a10 = this.mat4[4]; + var a11 = this.mat4[5]; + var a12 = this.mat4[6]; + var a13 = this.mat4[7]; + var a20 = this.mat4[8]; + var a21 = this.mat4[9]; + var a22 = this.mat4[10]; + var a23 = this.mat4[11]; + //sin,cos, and tan of respective angle + var sA = Math.sin(a); + var cA = Math.cos(a); + var tA = 1 - cA; + // Construct the elements of the rotation matrix + var b00 = x * x * tA + cA; + var b01 = y * x * tA + z * sA; + var b02 = z * x * tA - y * sA; + var b10 = x * y * tA - z * sA; + var b11 = y * y * tA + cA; + var b12 = z * y * tA + x * sA; + var b20 = x * z * tA + y * sA; + var b21 = y * z * tA - x * sA; + var b22 = z * z * tA + cA; + // rotation-specific matrix multiplication + this.mat4[0] = a00 * b00 + a10 * b01 + a20 * b02; + this.mat4[1] = a01 * b00 + a11 * b01 + a21 * b02; + this.mat4[2] = a02 * b00 + a12 * b01 + a22 * b02; + this.mat4[3] = a03 * b00 + a13 * b01 + a23 * b02; + this.mat4[4] = a00 * b10 + a10 * b11 + a20 * b12; + this.mat4[5] = a01 * b10 + a11 * b11 + a21 * b12; + this.mat4[6] = a02 * b10 + a12 * b11 + a22 * b12; + this.mat4[7] = a03 * b10 + a13 * b11 + a23 * b12; + this.mat4[8] = a00 * b20 + a10 * b21 + a20 * b22; + this.mat4[9] = a01 * b20 + a11 * b21 + a21 * b22; + this.mat4[10] = a02 * b20 + a12 * b21 + a22 * b22; + this.mat4[11] = a03 * b20 + a13 * b21 + a23 * b22; + return this; + } /** + * @todo finish implementing this method! + * translates + * @method translate + * @param {Number[]} v vector to translate by + * @chainable + */ + + }, + { + key: 'translate', + value: function translate(v) { + var x = v[0], + y = v[1], + z = v[2] || 0; + this.mat4[12] += this.mat4[0] * x + this.mat4[4] * y + this.mat4[8] * z; + this.mat4[13] += this.mat4[1] * x + this.mat4[5] * y + this.mat4[9] * z; + this.mat4[14] += this.mat4[2] * x + this.mat4[6] * y + this.mat4[10] * z; + this.mat4[15] += this.mat4[3] * x + this.mat4[7] * y + this.mat4[11] * z; + } + }, + { + key: 'rotateX', + value: function rotateX(a) { + this.rotate(a, 1, 0, 0); + } + }, + { + key: 'rotateY', + value: function rotateY(a) { + this.rotate(a, 0, 1, 0); + } + }, + { + key: 'rotateZ', + value: function rotateZ(a) { + this.rotate(a, 0, 0, 1); + } /** + * sets the perspective matrix + * @method perspective + * @param {Number} fovy [description] + * @param {Number} aspect [description] + * @param {Number} near near clipping plane + * @param {Number} far far clipping plane + * @chainable + */ + + }, + { + key: 'perspective', + value: function perspective(fovy, aspect, near, far) { + var f = 1 / Math.tan(fovy / 2), + nf = 1 / (near - far); + this.mat4[0] = f / aspect; + this.mat4[1] = 0; + this.mat4[2] = 0; + this.mat4[3] = 0; + this.mat4[4] = 0; + this.mat4[5] = f; + this.mat4[6] = 0; + this.mat4[7] = 0; + this.mat4[8] = 0; + this.mat4[9] = 0; + this.mat4[10] = (far + near) * nf; + this.mat4[11] = - 1; + this.mat4[12] = 0; + this.mat4[13] = 0; + this.mat4[14] = 2 * far * near * nf; + this.mat4[15] = 0; + return this; + } /** + * sets the ortho matrix + * @method ortho + * @param {Number} left [description] + * @param {Number} right [description] + * @param {Number} bottom [description] + * @param {Number} top [description] + * @param {Number} near near clipping plane + * @param {Number} far far clipping plane + * @chainable + */ + + }, + { + key: 'ortho', + value: function ortho(left, right, bottom, top, near, far) { + var lr = 1 / (left - right), + bt = 1 / (bottom - top), + nf = 1 / (near - far); + this.mat4[0] = - 2 * lr; + this.mat4[1] = 0; + this.mat4[2] = 0; + this.mat4[3] = 0; + this.mat4[4] = 0; + this.mat4[5] = - 2 * bt; + this.mat4[6] = 0; + this.mat4[7] = 0; + this.mat4[8] = 0; + this.mat4[9] = 0; + this.mat4[10] = 2 * nf; + this.mat4[11] = 0; + this.mat4[12] = (left + right) * lr; + this.mat4[13] = (top + bottom) * bt; + this.mat4[14] = (far + near) * nf; + this.mat4[15] = 1; + return this; + } /** + * apply a matrix to a vector with x,y,z,w components + * get the results in the form of an array + * @method multiplyVec4 + * @param {Number} + * @return {Number[]} + */ + + }, + { + key: 'multiplyVec4', + value: function multiplyVec4(x, y, z, w) { + var result = new Array(4); + var m = this.mat4; + result[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w; + result[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w; + result[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w; + result[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w; + return result; + } /** + * Applies a matrix to a vector. + * The fourth component is set to 1. + * Returns a vector consisting of the first + * through third components of the result. + * + * @method multiplyPoint + * @param {p5.Vector} + * @return {p5.Vector} + */ + + }, + { + key: 'multiplyPoint', + value: function multiplyPoint(_ref4) { + var x = _ref4.x, + y = _ref4.y, + z = _ref4.z; + var array = this.multiplyVec4(x, y, z, 1); + return new _main.default.Vector(array[0], array[1], array[2]); + } /** + * Applies a matrix to a vector. + * The fourth component is set to 1. + * Returns the result of dividing the 1st to 3rd components + * of the result by the 4th component as a vector. + * + * @method multiplyAndNormalizePoint + * @param {p5.Vector} + * @return {p5.Vector} + */ + + }, + { + key: 'multiplyAndNormalizePoint', + value: function multiplyAndNormalizePoint(_ref5) { + var x = _ref5.x, + y = _ref5.y, + z = _ref5.z; + var array = this.multiplyVec4(x, y, z, 1); + array[0] /= array[3]; + array[1] /= array[3]; + array[2] /= array[3]; + return new _main.default.Vector(array[0], array[1], array[2]); + } /** + * Applies a matrix to a vector. + * The fourth component is set to 0. + * Returns a vector consisting of the first + * through third components of the result. + * + * @method multiplyDirection + * @param {p5.Vector} + * @return {p5.Vector} + */ + + }, + { + key: 'multiplyDirection', + value: function multiplyDirection(_ref6) { + var x = _ref6.x, + y = _ref6.y, + z = _ref6.z; + var array = this.multiplyVec4(x, y, z, 0); + return new _main.default.Vector(array[0], array[1], array[2]); + } /** + * This function is only for 3x3 matrices. + * multiply two mat3s. It is an operation to multiply the 3x3 matrix of + * the argument from the right. Arguments can be a 3x3 p5.Matrix, + * a Float32Array of length 9, or a javascript array of length 9. + * In addition, it can also be done by enumerating 9 numbers. + * + * @method mult3x3 + * @param {p5.Matrix|Float32Array|Number[]} multMatrix The matrix + * we want to multiply by + * @chainable + */ + + }, + { + key: 'mult3x3', + value: function mult3x3(multMatrix) { + var _src; + if (multMatrix === this || multMatrix === this.mat3) { + _src = this.copy().mat3; // only need to allocate in this rare case + } else if (multMatrix instanceof _main.default.Matrix) { + _src = multMatrix.mat3; + } else if (isMatrixArray(multMatrix)) { + _src = multMatrix; + } else if (arguments.length === 9) { + _src = arguments; + } else { + return; // nothing to do. + } // each row is used for the multiplier + + var b0 = this.mat3[0]; + var b1 = this.mat3[1]; + var b2 = this.mat3[2]; + this.mat3[0] = b0 * _src[0] + b1 * _src[3] + b2 * _src[6]; + this.mat3[1] = b0 * _src[1] + b1 * _src[4] + b2 * _src[7]; + this.mat3[2] = b0 * _src[2] + b1 * _src[5] + b2 * _src[8]; + b0 = this.mat3[3]; + b1 = this.mat3[4]; + b2 = this.mat3[5]; + this.mat3[3] = b0 * _src[0] + b1 * _src[3] + b2 * _src[6]; + this.mat3[4] = b0 * _src[1] + b1 * _src[4] + b2 * _src[7]; + this.mat3[5] = b0 * _src[2] + b1 * _src[5] + b2 * _src[8]; + b0 = this.mat3[6]; + b1 = this.mat3[7]; + b2 = this.mat3[8]; + this.mat3[6] = b0 * _src[0] + b1 * _src[3] + b2 * _src[6]; + this.mat3[7] = b0 * _src[1] + b1 * _src[4] + b2 * _src[7]; + this.mat3[8] = b0 * _src[2] + b1 * _src[5] + b2 * _src[8]; + return this; + } /** + * This function is only for 3x3 matrices. + * A function that returns a column vector of a 3x3 matrix. + * + * @method column + * @param {Number} columnIndex matrix column number + * @return {p5.Vector} + */ + + }, + { + key: 'column', + value: function column(columnIndex) { + return new _main.default.Vector(this.mat3[3 * columnIndex], this.mat3[3 * columnIndex + 1], this.mat3[3 * columnIndex + 2]); + } /** + * This function is only for 3x3 matrices. + * A function that returns a row vector of a 3x3 matrix. + * + * @method row + * @param {Number} rowIndex matrix row number + * @return {p5.Vector} + */ + + }, + { + key: 'row', + value: function row(rowIndex) { + return new _main.default.Vector(this.mat3[rowIndex], this.mat3[rowIndex + 3], this.mat3[rowIndex + 6]); + } /** + * Returns the diagonal elements of the matrix in the form of an array. + * A 3x3 matrix will return an array of length 3. + * A 4x4 matrix will return an array of length 4. + * + * @method diagonal + * @return {Number[]} An array obtained by arranging the diagonal elements + * of the matrix in ascending order of index + */ + + }, + { + key: 'diagonal', + value: function diagonal() { + if (this.mat3 !== undefined) { + return [this.mat3[0], + this.mat3[4], + this.mat3[8]]; + } + return [this.mat4[0], + this.mat4[5], + this.mat4[10], + this.mat4[15]]; + } /** + * This function is only for 3x3 matrices. + * Takes a vector and returns the vector resulting from multiplying to + * that vector by this matrix from left. + * + * @method multiplyVec3 + * @param {p5.Vector} multVector the vector to which this matrix applies + * @param {p5.Vector} [target] The vector to receive the result + * @return {p5.Vector} + */ + + }, + { + key: 'multiplyVec3', + value: function multiplyVec3(multVector, target) { + if (target === undefined) { + target = multVector.copy(); + } + target.x = this.row(0).dot(multVector); + target.y = this.row(1).dot(multVector); + target.z = this.row(2).dot(multVector); + return target; + } /** + * This function is only for 4x4 matrices. + * Creates a 3x3 matrix whose entries are the top left 3x3 part and returns it. + * + * @method createSubMatrix3x3 + * @return {p5.Matrix} + */ + + }, + { + key: 'createSubMatrix3x3', + value: function createSubMatrix3x3() { + var result = new _main.default.Matrix('mat3'); + result.mat3[0] = this.mat4[0]; + result.mat3[1] = this.mat4[1]; + result.mat3[2] = this.mat4[2]; + result.mat3[3] = this.mat4[4]; + result.mat3[4] = this.mat4[5]; + result.mat3[5] = this.mat4[6]; + result.mat3[6] = this.mat4[8]; + result.mat3[7] = this.mat4[9]; + result.mat3[8] = this.mat4[10]; + return result; + } /** + * PRIVATE + */ + // matrix methods adapted from: + // https://developer.mozilla.org/en-US/docs/Web/WebGL/ + // gluPerspective + // + // function _makePerspective(fovy, aspect, znear, zfar){ + // const ymax = znear * Math.tan(fovy * Math.PI / 360.0); + // const ymin = -ymax; + // const xmin = ymin * aspect; + // const xmax = ymax * aspect; + // return _makeFrustum(xmin, xmax, ymin, ymax, znear, zfar); + // } + //// + //// glFrustum + //// + //function _makeFrustum(left, right, bottom, top, znear, zfar){ + // const X = 2*znear/(right-left); + // const Y = 2*znear/(top-bottom); + // const A = (right+left)/(right-left); + // const B = (top+bottom)/(top-bottom); + // const C = -(zfar+znear)/(zfar-znear); + // const D = -2*zfar*znear/(zfar-znear); + // const frustrumMatrix =[ + // X, 0, A, 0, + // 0, Y, B, 0, + // 0, 0, C, D, + // 0, 0, -1, 0 + //]; + //return frustrumMatrix; + // } + // function _setMVPMatrices(){ + ////an identity matrix + ////@TODO use the p5.Matrix class to abstract away our MV matrices and + ///other math + //const _mvMatrix = + //[ + // 1.0,0.0,0.0,0.0, + // 0.0,1.0,0.0,0.0, + // 0.0,0.0,1.0,0.0, + // 0.0,0.0,0.0,1.0 + //]; + + } + ], [ + { + key: 'identity', + value: function identity(pInst) { + return new _main.default.Matrix(pInst); + } } - } - return this; - }; - /** - * inspired by Toji's mat4 determinant - * @method determinant - * @return {Number} Determinant of our 4×4 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 / 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 - //]; + ]); + return _class; + }(); var _default = _main.default.Matrix; exports.default = _default; }, { - '../core/main': 290, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.typed-array.copy-within': 215, - 'core-js/modules/es.typed-array.every': 216, - 'core-js/modules/es.typed-array.fill': 217, - 'core-js/modules/es.typed-array.filter': 218, - 'core-js/modules/es.typed-array.find': 220, - 'core-js/modules/es.typed-array.find-index': 219, - 'core-js/modules/es.typed-array.float32-array': 221, - 'core-js/modules/es.typed-array.for-each': 223, - 'core-js/modules/es.typed-array.includes': 224, - 'core-js/modules/es.typed-array.index-of': 225, - 'core-js/modules/es.typed-array.iterator': 228, - 'core-js/modules/es.typed-array.join': 229, - 'core-js/modules/es.typed-array.last-index-of': 230, - 'core-js/modules/es.typed-array.map': 231, - 'core-js/modules/es.typed-array.reduce': 233, - 'core-js/modules/es.typed-array.reduce-right': 232, - 'core-js/modules/es.typed-array.reverse': 234, - 'core-js/modules/es.typed-array.set': 235, - 'core-js/modules/es.typed-array.slice': 236, - 'core-js/modules/es.typed-array.some': 237, - 'core-js/modules/es.typed-array.sort': 238, - 'core-js/modules/es.typed-array.subarray': 239, - 'core-js/modules/es.typed-array.to-locale-string': 240, - 'core-js/modules/es.typed-array.to-string': 241 + '../core/main': 298, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.typed-array.copy-within': 223, + 'core-js/modules/es.typed-array.every': 224, + 'core-js/modules/es.typed-array.fill': 225, + 'core-js/modules/es.typed-array.filter': 226, + 'core-js/modules/es.typed-array.find': 228, + 'core-js/modules/es.typed-array.find-index': 227, + 'core-js/modules/es.typed-array.float32-array': 229, + 'core-js/modules/es.typed-array.for-each': 231, + 'core-js/modules/es.typed-array.includes': 232, + 'core-js/modules/es.typed-array.index-of': 233, + 'core-js/modules/es.typed-array.iterator': 236, + 'core-js/modules/es.typed-array.join': 237, + 'core-js/modules/es.typed-array.last-index-of': 238, + 'core-js/modules/es.typed-array.map': 239, + 'core-js/modules/es.typed-array.reduce': 241, + 'core-js/modules/es.typed-array.reduce-right': 240, + 'core-js/modules/es.typed-array.reverse': 242, + 'core-js/modules/es.typed-array.set': 243, + 'core-js/modules/es.typed-array.slice': 244, + 'core-js/modules/es.typed-array.some': 245, + 'core-js/modules/es.typed-array.sort': 246, + 'core-js/modules/es.typed-array.subarray': 247, + 'core-js/modules/es.typed-array.to-locale-string': 248, + 'core-js/modules/es.typed-array.to-string': 249 } ], - 341: [ + 352: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.array.map'); @@ -102414,74 +115006,107 @@ 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 + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } + _main.default.RenderBuffer = /*#__PURE__*/ function () { + function _class(size, src, dst, attr, renderer, map) { + _classCallCheck(this, _class); + this.size = size; // the number of FLOATs in each vertex + this.src = src; // the name of the model's source array + this.dst = dst; // the name of the geometry's buffer + this.attr = attr; // the name of the vertex attribute + this._renderer = renderer; + this.map = map; // optional, a transformation function to apply to src + } /** + * Enables and binds the buffers used by shader when the appropriate data exists in geometry. + * Must always be done prior to drawing geometry in WebGL. + * @param {p5.Geometry} geometry Geometry that is going to be drawn + * @param {p5.Shader} shader Active shader + * @private + */ - var attr = attributes[this.attr]; - if (!attr) { - return; - } // check if the model has the appropriate source array - - var buffer = geometry[this.dst]; - var src = model[this.src]; - if (src.length > 0) { - // check if we need to create the GL buffer - var createBuffer = !buffer; - if (createBuffer) { - // create and remember the buffer - geometry[this.dst] = buffer = gl.createBuffer(); - } // bind the buffer - - gl.bindBuffer(gl.ARRAY_BUFFER, buffer); // check if we need to fill the buffer with data - if (createBuffer || model.dirtyFlags[this.src] !== false) { - var map = this.map; // get the values from the model, possibly transformed - var values = map ? map(src) : src; // fill the buffer with the values - this._renderer._bindBuffer(buffer, gl.ARRAY_BUFFER, values); // mark the model's source array as clean - model.dirtyFlags[this.src] = false; - } // enable the attribute - - shader.enableAttrib(attr, this.size); - } else { - var loc = attr.location; - if (loc === - 1 || !this._renderer.registerEnabled[loc]) { - return; - } // Disable register corresponding to unused attribute + _createClass(_class, [ + { + key: '_prepareBuffer', + value: function _prepareBuffer(geometry, shader) { + var attributes = shader.attributes; + var gl = this._renderer.GL; + var model; + if (geometry.model) { + model = geometry.model; + } else { + model = geometry; + } // loop through each of the buffer definitions - gl.disableVertexAttribArray(loc); // Record register availability - this._renderer.registerEnabled[loc] = false; - } - }; + var attr = attributes[this.attr]; + if (!attr) { + return; + } // check if the model has the appropriate source array + + var buffer = geometry[this.dst]; + var src = model[this.src]; + if (src.length > 0) { + // check if we need to create the GL buffer + var createBuffer = !buffer; + if (createBuffer) { + // create and remember the buffer + geometry[this.dst] = buffer = gl.createBuffer(); + } // bind the buffer + + gl.bindBuffer(gl.ARRAY_BUFFER, buffer); + // check if we need to fill the buffer with data + if (createBuffer || model.dirtyFlags[this.src] !== false) { + var map = this.map; + // get the values from the model, possibly transformed + var values = map ? map(src) : src; + // fill the buffer with the values + this._renderer._bindBuffer(buffer, gl.ARRAY_BUFFER, values); + // mark the model's source array as clean + model.dirtyFlags[this.src] = false; + } // enable the attribute + + shader.enableAttrib(attr, this.size); + } else { + var loc = attr.location; + if (loc === - 1 || !this._renderer.registerEnabled.has(loc)) { + return; + } // Disable register corresponding to unused attribute + + gl.disableVertexAttribArray(loc); + // Record register availability + this._renderer.registerEnabled.delete(loc); + } + } + } + ]); + return _class; + }(); var _default = _main.default.RenderBuffer; exports.default = _default; }, { - '../core/main': 290, - 'core-js/modules/es.array.map': 179 + '../core/main': 298, + 'core-js/modules/es.array.map': 182 } ], - 342: [ + 353: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -102489,10 +115114,12 @@ _dereq_('core-js/modules/es.symbol.iterator'); _dereq_('core-js/modules/es.array.concat'); _dereq_('core-js/modules/es.array.fill'); + _dereq_('core-js/modules/es.array.find-index'); _dereq_('core-js/modules/es.array.from'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.map'); _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.map'); _dereq_('core-js/modules/es.object.get-own-property-descriptor'); _dereq_('core-js/modules/es.object.to-string'); _dereq_('core-js/modules/es.regexp.to-string'); @@ -102528,12 +115155,12 @@ _dereq_('core-js/modules/es.symbol.iterator'); _dereq_('core-js/modules/es.array.concat'); _dereq_('core-js/modules/es.array.fill'); - _dereq_('core-js/modules/es.array.from'); + _dereq_('core-js/modules/es.array.find-index'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.map'); _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.map'); _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.regexp.to-string'); _dereq_('core-js/modules/es.string.iterator'); _dereq_('core-js/modules/web.dom-collections.iterator'); Object.defineProperty(exports, '__esModule', { @@ -102606,7 +115233,20 @@ } return arr2; } - } /** + } /** + * Welcome to RendererGL Immediate Mode. + * Immediate mode is used for drawing custom shapes + * from a set of vertices. Immediate Mode is activated + * when you call beginShape() & de-activated when you call endShape(). + * Immediate mode is a style of programming borrowed + * from OpenGL's (now-deprecated) immediate mode. + * It differs from p5.js' default, Retained Mode, which caches + * geometries and buffers on the CPU to reduce the number of webgl + * draw calls. Retained mode is more efficient & performative, + * however, Immediate Mode is useful for sketching quick + * geometric ideas. + */ + /** * Begin shape drawing. This is a helpful way of generating * custom shapes quickly. However in WEBGL mode, application * performance will likely drop as a result of too many calls to @@ -102625,6 +115265,8 @@ _main.default.RendererGL.prototype.beginShape = function (mode) { this.immediateMode.shapeMode = mode !== undefined ? mode : constants.TESS; this.immediateMode.geometry.reset(); + this.immediateMode.contourIndices = [ + ]; return this; }; var immediateBufferStrides = { @@ -102634,6 +115276,12 @@ vertexStrokeColors: 4, uvs: 2 }; + _main.default.RendererGL.prototype.beginContour = function () { + if (this.immediateMode.shapeMode !== constants.TESS) { + throw new Error('WebGL mode can only use contours with beginShape(TESS).'); + } + this.immediateMode.contourIndices.push(this.immediateMode.geometry.vertices.length); + }; /** * adds a vertex to be drawn in a custom Shape. * @private @@ -102666,7 +115314,8 @@ } var z, u, - v; // default to (x, y) mode: all other arguments assumed to be 0. + v; + // default to (x, y) mode: all other arguments assumed to be 0. z = u = v = 0; if (arguments.length === 3) { // (x, y, z) mode: (u, v) assumed to be 0. @@ -102698,13 +115347,15 @@ 1 ]; this.immediateMode.geometry.vertexStrokeColors.push(lineVertexColor[0], lineVertexColor[1], lineVertexColor[2], lineVertexColor[3]); - if (this.textureMode === constants.IMAGE) { + if (this.textureMode === constants.IMAGE && !this.isProcessingVertices) { if (this._tex !== null) { if (this._tex.width > 0 && this._tex.height > 0) { u /= this._tex.width; v /= this._tex.height; } - } else if (!this.isProcessingVertices && this._tex === null && arguments.length >= 4) { + } else if (this.userFillShader !== undefined || this.userStrokeShader !== undefined || this.userPointShader !== undefined) { + // Do nothing if user-defined shaders are present + } else if (this._tex === null && arguments.length >= 4) { // Only throw this warning if custom uv's have been provided console.warn('You must first call texture() before using' + ' vertex() with image based u and v coordinates'); } @@ -102743,23 +115394,46 @@ * @chainable */ _main.default.RendererGL.prototype.endShape = function (mode, isCurve, isBezier, isQuadratic, isContour, shapeKind) { + var count = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 1; if (this.immediateMode.shapeMode === constants.POINTS) { this._drawPoints(this.immediateMode.geometry.vertices, this.immediateMode.buffers.point); return this; + } // When we are drawing a shape then the shape mode is TESS, + // but in case of triangle we can skip the breaking into small triangle + // this can optimize performance by skipping the step of breaking it into triangles + + if (this.immediateMode.geometry.vertices.length === 3 && this.immediateMode.shapeMode === constants.TESS) { + this.immediateMode.shapeMode === constants.TRIANGLES; } this.isProcessingVertices = true; this._processVertices.apply(this, arguments); this.isProcessingVertices = false; + // LINE_STRIP and LINES are not used for rendering, instead + // they only indicate a way to modify vertices during the _processVertices() step + if (this.immediateMode.shapeMode === constants.LINE_STRIP || this.immediateMode.shapeMode === constants.LINES) { + this.immediateMode.shapeMode = constants.TRIANGLE_FAN; + } // WebGL doesn't support the QUADS and QUAD_STRIP modes, so we + // need to convert them to a supported format. In `vertex()`, we reformat + // the input data into the formats specified below. + + if (this.immediateMode.shapeMode === constants.QUADS) { + this.immediateMode.shapeMode = constants.TRIANGLES; + } else if (this.immediateMode.shapeMode === constants.QUAD_STRIP) { + this.immediateMode.shapeMode = constants.TRIANGLE_STRIP; + } if (this._doFill) { - if (this.immediateMode.geometry.vertices.length > 1) { - this._drawImmediateFill(); + if (!this.geometryBuilder && this.immediateMode.geometry.vertices.length >= 3) { + this._drawImmediateFill(count); } } if (this._doStroke) { - if (this.immediateMode.geometry.lineVertices.length > 1) { + if (!this.geometryBuilder && this.immediateMode.geometry.lineVertices.length >= 1) { this._drawImmediateStroke(); } } + if (this.geometryBuilder) { + this.geometryBuilder.addImmediate(); + } this.isBezier = false; this.isQuadratic = false; this.isCurve = false; @@ -102783,11 +115457,17 @@ 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 + if (!this.geometryBuilder) { + 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._doFill && (this.isBezier || this.isQuadratic || this.isCurve || convexShape) && this.immediateMode.shapeMode !== constants.LINES; + var convexShape = this.immediateMode.shapeMode === constants.TESS; + // If the shape has a contour, we have to re-triangulate to cut out the + // contour region + var hasContour = this.immediateMode.contourIndices.length > 0; + // We tesselate when drawing curves or convex shapes + var shouldTess = this._doFill && (this.isBezier || this.isQuadratic || this.isCurve || convexShape || hasContour) && this.immediateMode.shapeMode !== constants.LINES; if (shouldTess) { this._tesselateShape(); } @@ -102802,6 +115482,8 @@ var res = [ ]; var i = 0; + var contourIndices = this.immediateMode.contourIndices.slice(); + var contourStart = 0; switch (shapeMode) { case constants.TRIANGLE_STRIP: for (i = 0; i < verts.length - 2; i++) { @@ -102871,13 +115553,25 @@ i + 1]); break; default: - for (i = 0; i < verts.length - 1; i++) { - res.push([i, - i + 1]); + // TODO: handle contours in other modes too + for (i = 0; i < verts.length; i++) { + // Handle breaks between contours + if (i + 1 < verts.length && i + 1 !== contourIndices[0]) { + res.push([i, + i + 1]); + } else { + if (shouldClose || contourStart) { + res.push([i, + contourStart]); + } + if (contourIndices.length > 0) { + contourStart = contourIndices.shift(); + } + } } break; } - if (shouldClose) { + if (shapeMode !== constants.TESS && shouldClose) { res.push([verts.length - 1, 0]); } @@ -102889,24 +115583,20 @@ */ _main.default.RendererGL.prototype._tesselateShape = function () { var _this = this; + // TODO: handle non-TESS shape modes that have contours this.immediateMode.shapeMode = constants.TRIANGLES; var contours = [ - this._flatten(this.immediateMode.geometry.vertices.map(function (vert, i) { - return [vert.x, - vert.y, - vert.z, - _this.immediateMode.geometry.uvs[i * 2], - _this.immediateMode.geometry.uvs[i * 2 + 1], - _this.immediateMode.geometry.vertexColors[i * 4], - _this.immediateMode.geometry.vertexColors[i * 4 + 1], - _this.immediateMode.geometry.vertexColors[i * 4 + 2], - _this.immediateMode.geometry.vertexColors[i * 4 + 3], - _this.immediateMode.geometry.vertexNormals[i].x, - _this.immediateMode.geometry.vertexNormals[i].y, - _this.immediateMode.geometry.vertexNormals[i].z]; - })) + [] ]; + for (var i = 0; i < this.immediateMode.geometry.vertices.length; i++) { + if (this.immediateMode.contourIndices.length > 0 && this.immediateMode.contourIndices[0] === i) { + this.immediateMode.contourIndices.shift(); + contours.push([]); + } + contours[contours.length - 1].push(this.immediateMode.geometry.vertices[i].x, this.immediateMode.geometry.vertices[i].y, this.immediateMode.geometry.vertices[i].z, this.immediateMode.geometry.uvs[i * 2], this.immediateMode.geometry.uvs[i * 2 + 1], this.immediateMode.geometry.vertexColors[i * 4], this.immediateMode.geometry.vertexColors[i * 4 + 1], this.immediateMode.geometry.vertexColors[i * 4 + 2], this.immediateMode.geometry.vertexColors[i * 4 + 3], this.immediateMode.geometry.vertexNormals[i].x, this.immediateMode.geometry.vertexNormals[i].y, this.immediateMode.geometry.vertexNormals[i].z); + } var polyTriangles = this._triangulate(contours); + var originalVertices = this.immediateMode.geometry.vertices; this.immediateMode.geometry.vertices = [ ]; this.immediateMode.geometry.vertexNormals = [ @@ -102920,6 +115610,48 @@ this.normal.apply(this, _toConsumableArray(polyTriangles.slice(j + 9, j + 12))); this.vertex.apply(this, _toConsumableArray(polyTriangles.slice(j, j + 5))); } + if (this.geometryBuilder) { + // Tesselating the face causes the indices of edge vertices to stop being + // correct. When rendering, this is not a problem, since _edgesToVertices + // will have been called before this, and edge vertex indices are no longer + // needed. However, the geometry builder still needs this information, so + // when one is active, we need to update the indices. + // + // We record index mappings in a Map so that once we have found a + // corresponding vertex, we don't need to loop to find it again. + var newIndex = new Map(); + this.immediateMode.geometry.edges = this.immediateMode.geometry.edges.map(function (edge) { + return edge.map(function (origIdx) { + if (!newIndex.has(origIdx)) { + var orig = originalVertices[origIdx]; + var newVertIndex = _this.immediateMode.geometry.vertices.findIndex(function (v) { + return orig.x === v.x && orig.y === v.y && orig.z === v.z; + }); + if (newVertIndex === - 1) { + // The tesselation process didn't output a vertex with the exact + // coordinate as before, potentially due to numerical issues. This + // doesn't happen often, but in this case, pick the closest point + var closestDist = Infinity; + var closestIndex = 0; + for (var _i = 0; _i < _this.immediateMode.geometry.vertices.length; _i++) { + var vert = _this.immediateMode.geometry.vertices[_i]; + var dX = orig.x - vert.x; + var dY = orig.y - vert.y; + var dZ = orig.z - vert.z; + var dist = dX * dX + dY * dY + dZ * dZ; + if (dist < closestDist) { + closestDist = dist; + closestIndex = _i; + } + } + newVertIndex = closestIndex; + } + newIndex.set(origIdx, newVertIndex); + } + return newIndex.get(origIdx); + }); + }); + } this.immediateMode.geometry.vertexColors = colors; }; /** @@ -102928,9 +115660,11 @@ * @private */ _main.default.RendererGL.prototype._drawImmediateFill = function () { + var count = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; var gl = this.GL; this._useVertexColor = this.immediateMode.geometry.vertexColors.length > 0; - var shader = this._getImmediateFillShader(); + var shader; + shader = this._getImmediateFillShader(); this._setFillUniforms(shader); var _iteratorNormalCompletion = true; var _didIteratorError = false; @@ -102939,9 +115673,7 @@ 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; @@ -102956,19 +115688,17 @@ } } } - if (this.immediateMode.shapeMode === constants.LINE_STRIP || this.immediateMode.shapeMode === constants.LINES) { - this.immediateMode.shapeMode = constants.TRIANGLE_FAN; - } // WebGL 1 doesn't support the QUADS and QUAD_STRIP modes, so we - // need to convert them to a supported format. In `vertex()`, we reformat - // the input data into the formats specified below. - - if (this.immediateMode.shapeMode === constants.QUADS) { - this.immediateMode.shapeMode = constants.TRIANGLES; - } else if (this.immediateMode.shapeMode === constants.QUAD_STRIP) { - this.immediateMode.shapeMode = constants.TRIANGLE_STRIP; - } + shader.disableRemainingAttributes(); this._applyColorBlend(this.curFillColor); - gl.drawArrays(this.immediateMode.shapeMode, 0, this.immediateMode.geometry.vertices.length); + if (count === 1) { + gl.drawArrays(this.immediateMode.shapeMode, 0, this.immediateMode.geometry.vertices.length); + } else { + try { + gl.drawArraysInstanced(this.immediateMode.shapeMode, 0, this.immediateMode.geometry.vertices.length, count); + } catch (e) { + console.log('🌸 p5.js says: Instancing is only supported in WebGL2 mode'); + } + } shader.unbindShader(); }; /** @@ -102978,10 +115708,8 @@ */ _main.default.RendererGL.prototype._drawImmediateStroke = function () { var gl = this.GL; - var faceCullingEnabled = gl.isEnabled(gl.CULL_FACE); // Prevent strokes from getting removed by culling - gl.disable(gl.CULL_FACE); - var shader = this._getImmediateStrokeShader(); this._useLineColor = this.immediateMode.geometry.vertexStrokeColors.length > 0; + var shader = this._getImmediateStrokeShader(); this._setStrokeUniforms(shader); var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; @@ -103005,38 +115733,38 @@ } } } + shader.disableRemainingAttributes(); this._applyColorBlend(this.curStrokeColor); - gl.drawArrays(gl.TRIANGLES, 0, this.immediateMode.geometry.lineVertices.length); - if (faceCullingEnabled) { - gl.enable(gl.CULL_FACE); - } + gl.drawArrays(gl.TRIANGLES, 0, this.immediateMode.geometry.lineVertices.length / 3); shader.unbindShader(); }; var _default = _main.default.RendererGL; exports.default = _default; }, { - '../core/constants': 278, - '../core/main': 290, - './p5.RenderBuffer': 341, - 'core-js/modules/es.array.concat': 167, - 'core-js/modules/es.array.fill': 170, - 'core-js/modules/es.array.from': 173, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.map': 179, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.to-string': 200, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + '../core/constants': 286, + '../core/main': 298, + './p5.RenderBuffer': 352, + 'core-js/modules/es.array.concat': 169, + 'core-js/modules/es.array.fill': 172, + 'core-js/modules/es.array.find-index': 174, + 'core-js/modules/es.array.from': 176, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.map': 182, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.map': 187, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 343: [ + 354: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -103045,6 +115773,7 @@ _dereq_('core-js/modules/es.array.fill'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.some'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); _dereq_('core-js/modules/es.object.keys'); _dereq_('core-js/modules/es.object.to-string'); _dereq_('core-js/modules/es.string.iterator'); @@ -103074,7 +115803,32 @@ _dereq_('core-js/modules/es.typed-array.subarray'); _dereq_('core-js/modules/es.typed-array.to-locale-string'); _dereq_('core-js/modules/es.typed-array.to-string'); + _dereq_('core-js/modules/es.weak-map'); _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } _dereq_('core-js/modules/es.symbol'); _dereq_('core-js/modules/es.symbol.description'); _dereq_('core-js/modules/es.symbol.iterator'); @@ -103118,15 +115872,66 @@ var _main = _interopRequireDefault(_dereq_('../core/main')); _dereq_('./p5.RendererGL'); _dereq_('./p5.RenderBuffer'); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; - } //Retained Mode. The default mode for rendering 3D primitives + } //Retained Mode. The default mode for rendering 3D primitives //in WEBGL. + /** + * @param {p5.Geometry} geometry The model whose resources will be freed + */ - var hashCount = 0; + _main.default.RendererGL.prototype.freeGeometry = function (geometry) { + if (!geometry.gid) { + console.warn('The model you passed to freeGeometry does not have an id!'); + return; + } + this._freeBuffers(geometry.gid); + }; /** * _initBufferDefaults * @private @@ -103136,13 +115941,12 @@ * @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) { + this._freeBuffers(gId); + //@TODO remove this limit on hashes in retainedMode.geometry + if (Object.keys(this.retainedMode.geometry).length > 1000) { var key = Object.keys(this.retainedMode.geometry) [0]; - delete this.retainedMode.geometry[key]; - hashCount--; - } //create a new entry in our retainedMode.geometry + this._freeBuffers(key); + } //create a new entry in our retainedMode.geometry return this.retainedMode.geometry[gId] = { }; @@ -103153,7 +115957,6 @@ return; } delete this.retainedMode.geometry[gId]; - hashCount--; var gl = this.GL; if (buffers.indexBuffer) { gl.deleteBuffer(buffers.indexBuffer); @@ -103184,7 +115987,7 @@ } } } - } // free all the buffers + } // free all the buffers freeBuffers(this.retainedMode.buffers.stroke); freeBuffers(this.retainedMode.buffers.fill); @@ -103197,35 +116000,39 @@ * @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 gl = this.GL; + //initialize the gl buffers for our geom groups var buffers = this._initBufferDefaults(gId); buffers.model = model; var indexBuffer = buffers.indexBuffer; if (model.faces.length) { // allocate space for faces if (!indexBuffer) indexBuffer = buffers.indexBuffer = gl.createBuffer(); - var vals = _main.default.RendererGL.prototype._flatten(model.faces); // If any face references a vertex with an index greater than the maximum + var vals = _main.default.RendererGL.prototype._flatten(model.faces); + // If any face references a vertex with an index greater than the maximum // un-singed 16 bit integer, then we need to use a Uint32Array instead of a // Uint16Array var hasVertexIndicesOverMaxUInt16 = vals.some(function (v) { return v > 65535; }); var type = hasVertexIndicesOverMaxUInt16 ? Uint32Array : Uint16Array; - this._bindBuffer(indexBuffer, gl.ELEMENT_ARRAY_BUFFER, vals, type); // If we're using a Uint32Array for our indexBuffer we will need to pass a + this._bindBuffer(indexBuffer, gl.ELEMENT_ARRAY_BUFFER, vals, type); + // If we're using a Uint32Array for our indexBuffer we will need to pass a // different enum value to WebGL draw triangles. This happens in // the _drawElements function. - buffers.indexBufferType = hasVertexIndicesOverMaxUInt16 ? gl.UNSIGNED_INT : gl.UNSIGNED_SHORT; // the vertex count is based on the number of faces + buffers.indexBufferType = hasVertexIndicesOverMaxUInt16 ? gl.UNSIGNED_INT : gl.UNSIGNED_SHORT; + // the vertex count is based on the number of faces buffers.vertexCount = model.faces.length * 3; } else { // the index buffer is unused, remove it if (indexBuffer) { gl.deleteBuffer(indexBuffer); buffers.indexBuffer = null; - } // the vertex count comes directly from the model + } // the vertex count comes directly from the model buffers.vertexCount = model.vertices ? model.vertices.length : 0; } - buffers.lineVertexCount = model.lineVertices ? model.lineVertices.length : 0; + buffers.lineVertexCount = model.lineVertices ? model.lineVertices.length / 3 : 0; return buffers; }; /** @@ -103237,19 +116044,17 @@ _main.default.RendererGL.prototype.drawBuffers = function (gId) { var gl = this.GL; var geometry = this.retainedMode.geometry[gId]; - if (this._doStroke && geometry.lineVertexCount > 0) { - var faceCullingEnabled = gl.isEnabled(gl.CULL_FACE); // Prevent strokes from getting removed by culling - gl.disable(gl.CULL_FACE); - var strokeShader = this._getRetainedStrokeShader(); - this._useLineColor = geometry.model.vertexStrokeColors.length > 0; - this._setStrokeUniforms(strokeShader); + if (!this.geometryBuilder && this._doFill && this.retainedMode.geometry[gId].vertexCount > 0) { + this._useVertexColor = geometry.model.vertexColors.length > 0; + var fillShader = this._getRetainedFillShader(); + this._setFillUniforms(fillShader); var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { - for (var _iterator2 = this.retainedMode.buffers.stroke[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + for (var _iterator2 = this.retainedMode.buffers.fill[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var buff = _step2.value; - buff._prepareBuffer(geometry, strokeShader); + buff._prepareBuffer(geometry, fillShader); } } catch (err) { _didIteratorError2 = true; @@ -103265,24 +116070,26 @@ } } } - this._applyColorBlend(this.curStrokeColor); - this._drawArrays(gl.TRIANGLES, gId); - if (faceCullingEnabled) { - gl.enable(gl.CULL_FACE); + fillShader.disableRemainingAttributes(); + if (geometry.indexBuffer) { + //vertex index buffer + this._bindBuffer(geometry.indexBuffer, gl.ELEMENT_ARRAY_BUFFER); } - strokeShader.unbindShader(); + this._applyColorBlend(this.curFillColor); + this._drawElements(gl.TRIANGLES, gId); + fillShader.unbindShader(); } - if (this._doFill) { - this._useVertexColor = geometry.model.vertexColors.length > 0; - var fillShader = this._getRetainedFillShader(); - this._setFillUniforms(fillShader); + if (!this.geometryBuilder && this._doStroke && geometry.lineVertexCount > 0) { + this._useLineColor = geometry.model.vertexStrokeColors.length > 0; + var strokeShader = this._getRetainedStrokeShader(); + this._setStrokeUniforms(strokeShader); var _iteratorNormalCompletion3 = true; var _didIteratorError3 = false; var _iteratorError3 = undefined; try { - for (var _iterator3 = this.retainedMode.buffers.fill[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + for (var _iterator3 = this.retainedMode.buffers.stroke[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { var _buff = _step3.value; - _buff._prepareBuffer(geometry, fillShader); + _buff._prepareBuffer(geometry, strokeShader); } } catch (err) { _didIteratorError3 = true; @@ -103298,13 +116105,13 @@ } } } - 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(); + strokeShader.disableRemainingAttributes(); + this._applyColorBlend(this.curStrokeColor); + this._drawArrays(gl.TRIANGLES, gId); + strokeShader.unbindShader(); + } + if (this.geometryBuilder) { + this.geometryBuilder.addRetained(geometry); } return this; }; @@ -103338,15 +116145,16 @@ }; _main.default.RendererGL.prototype._drawElements = function (drawMode, gId) { var buffers = this.retainedMode.geometry[gId]; - var gl = this.GL; // render the fill + var gl = this.GL; + // render the fill if (buffers.indexBuffer) { // If this model is using a Uint32Array we need to ensure the // OES_element_index_uint WebGL extension is enabled. - if (buffers.indexBufferType === gl.UNSIGNED_INT) { + if (this._pInst.webglVersion !== constants.WEBGL2 && buffers.indexBufferType === gl.UNSIGNED_INT) { if (!gl.getExtension('OES_element_index_uint')) { throw new Error('Unable to render a 3d model with > 65535 triangles. Your web browser does not support the WebGL Extension OES_element_index_uint.'); } - } // we're drawing faces + } // we're drawing faces gl.drawElements(gl.TRIANGLES, buffers.vertexCount, buffers.indexBufferType, 0); } else { @@ -103360,6 +116168,7 @@ this._setPointUniforms(pointShader); this._bindBuffer(vertexBuffer, gl.ARRAY_BUFFER, this._vToNArray(vertices), Float32Array, gl.STATIC_DRAW); pointShader.enableAttrib(pointShader.attributes.aPosition, 3); + this._applyColorBlend(this.curStrokeColor); gl.drawArrays(gl.Points, 0, vertices.length); pointShader.unbindShader(); }; @@ -103367,64 +116176,74 @@ exports.default = _default; }, { - '../core/main': 290, - './p5.RenderBuffer': 341, - './p5.RendererGL': 344, - 'core-js/modules/es.array.fill': 170, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.some': 181, - 'core-js/modules/es.object.keys': 194, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.typed-array.copy-within': 215, - 'core-js/modules/es.typed-array.every': 216, - 'core-js/modules/es.typed-array.fill': 217, - 'core-js/modules/es.typed-array.filter': 218, - 'core-js/modules/es.typed-array.find': 220, - 'core-js/modules/es.typed-array.find-index': 219, - 'core-js/modules/es.typed-array.float32-array': 221, - 'core-js/modules/es.typed-array.for-each': 223, - 'core-js/modules/es.typed-array.includes': 224, - 'core-js/modules/es.typed-array.index-of': 225, - 'core-js/modules/es.typed-array.iterator': 228, - 'core-js/modules/es.typed-array.join': 229, - 'core-js/modules/es.typed-array.last-index-of': 230, - 'core-js/modules/es.typed-array.map': 231, - 'core-js/modules/es.typed-array.reduce': 233, - 'core-js/modules/es.typed-array.reduce-right': 232, - 'core-js/modules/es.typed-array.reverse': 234, - 'core-js/modules/es.typed-array.set': 235, - 'core-js/modules/es.typed-array.slice': 236, - 'core-js/modules/es.typed-array.some': 237, - 'core-js/modules/es.typed-array.sort': 238, - 'core-js/modules/es.typed-array.subarray': 239, - 'core-js/modules/es.typed-array.to-locale-string': 240, - 'core-js/modules/es.typed-array.to-string': 241, - 'core-js/modules/es.typed-array.uint16-array': 242, - 'core-js/modules/es.typed-array.uint32-array': 243, - 'core-js/modules/web.dom-collections.iterator': 248 + '../core/constants': 286, + '../core/main': 298, + './p5.RenderBuffer': 352, + './p5.RendererGL': 355, + 'core-js/modules/es.array.fill': 172, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.some': 184, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.keys': 199, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.typed-array.copy-within': 223, + 'core-js/modules/es.typed-array.every': 224, + 'core-js/modules/es.typed-array.fill': 225, + 'core-js/modules/es.typed-array.filter': 226, + 'core-js/modules/es.typed-array.find': 228, + 'core-js/modules/es.typed-array.find-index': 227, + 'core-js/modules/es.typed-array.float32-array': 229, + 'core-js/modules/es.typed-array.for-each': 231, + 'core-js/modules/es.typed-array.includes': 232, + 'core-js/modules/es.typed-array.index-of': 233, + 'core-js/modules/es.typed-array.iterator': 236, + 'core-js/modules/es.typed-array.join': 237, + 'core-js/modules/es.typed-array.last-index-of': 238, + 'core-js/modules/es.typed-array.map': 239, + 'core-js/modules/es.typed-array.reduce': 241, + 'core-js/modules/es.typed-array.reduce-right': 240, + 'core-js/modules/es.typed-array.reverse': 242, + 'core-js/modules/es.typed-array.set': 243, + 'core-js/modules/es.typed-array.slice': 244, + 'core-js/modules/es.typed-array.some': 245, + 'core-js/modules/es.typed-array.sort': 246, + 'core-js/modules/es.typed-array.subarray': 247, + 'core-js/modules/es.typed-array.to-locale-string': 248, + 'core-js/modules/es.typed-array.to-string': 249, + 'core-js/modules/es.typed-array.uint16-array': 250, + 'core-js/modules/es.typed-array.uint32-array': 251, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 344: [ + 355: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); _dereq_('core-js/modules/es.symbol.description'); _dereq_('core-js/modules/es.symbol.iterator'); _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.copy-within'); + _dereq_('core-js/modules/es.array.every'); _dereq_('core-js/modules/es.array.fill'); - _dereq_('core-js/modules/es.array.filter'); _dereq_('core-js/modules/es.array.from'); _dereq_('core-js/modules/es.array.includes'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.some'); + _dereq_('core-js/modules/es.map'); _dereq_('core-js/modules/es.object.assign'); _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.get-prototype-of'); _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.reflect.construct'); + _dereq_('core-js/modules/es.reflect.get'); _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.set'); _dereq_('core-js/modules/es.string.includes'); _dereq_('core-js/modules/es.string.iterator'); _dereq_('core-js/modules/es.typed-array.float32-array'); @@ -103486,15 +116305,18 @@ _dereq_('core-js/modules/es.symbol.description'); _dereq_('core-js/modules/es.symbol.iterator'); _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.copy-within'); + _dereq_('core-js/modules/es.array.every'); _dereq_('core-js/modules/es.array.fill'); - _dereq_('core-js/modules/es.array.filter'); _dereq_('core-js/modules/es.array.from'); _dereq_('core-js/modules/es.array.includes'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.some'); + _dereq_('core-js/modules/es.map'); _dereq_('core-js/modules/es.object.assign'); _dereq_('core-js/modules/es.object.to-string'); - _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.set'); _dereq_('core-js/modules/es.string.includes'); _dereq_('core-js/modules/es.string.iterator'); _dereq_('core-js/modules/es.typed-array.float32-array'); @@ -103530,15 +116352,21 @@ Object.defineProperty(exports, '__esModule', { value: true }); + exports.readPixelsWebGL = readPixelsWebGL; + exports.readPixelWebGL = readPixelWebGL; exports.default = void 0; var _main = _interopRequireDefault(_dereq_('../core/main')); var constants = _interopRequireWildcard(_dereq_('../core/constants')); + var _GeometryBuilder = _interopRequireDefault(_dereq_('./GeometryBuilder')); var _libtess = _interopRequireDefault(_dereq_('libtess')); _dereq_('./p5.Shader'); _dereq_('./p5.Camera'); _dereq_('../core/p5.Renderer'); _dereq_('./p5.Matrix'); + _dereq_('./p5.Framebuffer'); var _path = _dereq_('path'); + var _p6 = _dereq_('./p5.Texture'); + var _filterShaderFrags; function _getRequireWildcardCache() { if (typeof WeakMap !== 'function') return null; var cache = new WeakMap(); @@ -103563,45 +116391,164 @@ } 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]; - } + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + function _nonIterableSpread() { + throw new TypeError('Invalid attempt to spread non-iterable instance'); + } + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === '[object Arguments]') return Array.from(iter); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + return arr2; + } + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } + function _get(target, property, receiver) { + if (typeof Reflect !== 'undefined' && Reflect.get) { + _get = Reflect.get; + } else { + _get = function _get(target, property, receiver) { + var base = _superPropBase(target, property); + if (!base) return; + var desc = Object.getOwnPropertyDescriptor(base, property); + if (desc.get) { + return desc.get.call(receiver); + } + return desc.value; + }; + } + return _get(target, property, receiver || target); + } + function _superPropBase(object, property) { + while (!Object.prototype.hasOwnProperty.call(object, property)) { + object = _getPrototypeOf(object); + if (object === null) break; + } + return object; + } + function _inherits(subClass, superClass) { + if (typeof superClass !== 'function' && superClass !== null) { + throw new TypeError('Super expression must either be null or a function'); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + if (superClass) _setPrototypeOf(subClass, superClass); + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + return _setPrototypeOf(o, p); + } + function _createSuper(Derived) { + function isNativeReflectConstruct() { + if (typeof Reflect === 'undefined' || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === 'function') return true; + try { + Date.prototype.toString.call(Reflect.construct(Date, [ + ], function () { + })); + return true; + } catch (e) { + return false; } } - newObj.default = obj; - if (cache) { - cache.set(obj, newObj); - } - return newObj; - } - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - default: - obj + return function () { + var Super = _getPrototypeOf(Derived), + result; + if (isNativeReflectConstruct()) { + var NewTarget = _getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return _possibleConstructorReturn(this, result); }; } - function _toConsumableArray(arr) { - return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + function _possibleConstructorReturn(self, call) { + if (call && (_typeof(call) === 'object' || typeof call === 'function')) { + return call; + } + return _assertThisInitialized(self); } - function _nonIterableSpread() { - throw new TypeError('Invalid attempt to spread non-iterable instance'); + function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called'); + } + return self; } - function _iterableToArray(iter) { - if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === '[object Arguments]') return Array.from(iter); + function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); } - 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 _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; } + return obj; } var STROKE_CAP_ENUM = { }; @@ -103615,7 +116562,8 @@ var defineStrokeJoinEnum = function defineStrokeJoinEnum(key, val) { lineDefs += '#define STROKE_JOIN_'.concat(key, ' ').concat(val, '\n'); STROKE_JOIN_ENUM[constants[key]] = val; - }; // Define constants in line shaders for each type of cap/join, and also record + }; + // Define constants in line shaders for each type of cap/join, and also record // the values in JS objects defineStrokeCapEnum('ROUND', 0); defineStrokeCapEnum('PROJECT', 1); @@ -103623,303 +116571,35 @@ defineStrokeJoinEnum('ROUND', 0); defineStrokeJoinEnum('MITER', 1); defineStrokeJoinEnum('BEVEL', 2); - 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 lightingShader = '#define PI 3.141592\n\nprecision highp float;\nprecision highp int;\n\nuniform mat4 uViewMatrix;\n\nuniform bool uUseLighting;\n\nuniform int uAmbientLightCount;\nuniform vec3 uAmbientColor[5];\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\n// setting from _setImageLightUniforms()\n// boolean to initiate the calculateImageDiffuse and calculateImageSpecular\nuniform bool uUseImageLight;\n// texture for use in calculateImageDiffuse\nuniform sampler2D environmentMapDiffused;\n// texture for use in calculateImageSpecular\nuniform sampler2D environmentMapSpecular;\n// roughness for use in calculateImageSpecular\nuniform float levelOfDetail;\n\nconst float specularFactor = 2.0;\nconst float diffuseFactor = 0.73;\n\nstruct LightResult {\n float specular;\n float diffuse;\n};\n\nfloat _phongSpecular(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float shininess) {\n\n vec3 R = reflect(lightDirection, surfaceNormal);\n return pow(max(0.0, dot(R, viewDirection)), shininess);\n}\n\nfloat _lambertDiffuse(vec3 lightDirection, vec3 surfaceNormal) {\n return max(0.0, dot(-lightDirection, surfaceNormal));\n}\n\nLightResult _light(vec3 viewDirection, vec3 normal, vec3 lightVector) {\n\n vec3 lightDir = normalize(lightVector);\n\n //compute our diffuse & specular terms\n LightResult lr;\n if (uSpecular)\n lr.specular = _phongSpecular(lightDir, viewDirection, normal, uShininess);\n lr.diffuse = _lambertDiffuse(lightDir, normal);\n return lr;\n}\n\n// converts the range of "value" from [min1 to max1] to [min2 to max2]\nfloat map(float value, float min1, float max1, float min2, float max2) {\n return min2 + (value - min1) * (max2 - min2) / (max1 - min1);\n}\n\nvec2 mapTextureToNormal( vec3 v ){\n // x = r sin(phi) cos(theta) \n // y = r cos(phi) \n // z = r sin(phi) sin(theta)\n float phi = acos( v.y );\n // if phi is 0, then there are no x, z components\n float theta = 0.0;\n // else \n theta = acos(v.x / sin(phi));\n float sinTheta = v.z / sin(phi);\n if (sinTheta < 0.0) {\n // Turn it into -theta, but in the 0-2PI range\n theta = 2.0 * PI - theta;\n }\n theta = theta / (2.0 * 3.14159);\n phi = phi / 3.14159 ;\n \n vec2 angles = vec2( fract(theta + 0.25), 1.0 - phi );\n return angles;\n}\n\n\nvec3 calculateImageDiffuse( vec3 vNormal, vec3 vViewPosition ){\n // make 2 seperate builds \n vec3 worldCameraPosition = vec3(0.0, 0.0, 0.0); // hardcoded world camera position\n vec3 worldNormal = normalize(vNormal);\n vec2 newTexCoor = mapTextureToNormal( worldNormal );\n vec4 texture = TEXTURE( environmentMapDiffused, newTexCoor );\n // this is to make the darker sections more dark\n // png and jpg usually flatten the brightness so it is to reverse that\n return smoothstep(vec3(0.0), vec3(0.8), texture.xyz);\n}\n\nvec3 calculateImageSpecular( vec3 vNormal, vec3 vViewPosition ){\n vec3 worldCameraPosition = vec3(0.0, 0.0, 0.0);\n vec3 worldNormal = normalize(vNormal);\n vec3 lightDirection = normalize( vViewPosition - worldCameraPosition );\n vec3 R = reflect(lightDirection, worldNormal);\n vec2 newTexCoor = mapTextureToNormal( R );\n#ifdef WEBGL2\n vec4 outColor = textureLod(environmentMapSpecular, newTexCoor, levelOfDetail);\n#else\n vec4 outColor = TEXTURE(environmentMapSpecular, newTexCoor);\n#endif\n // this is to make the darker sections more dark\n // png and jpg usually flatten the brightness so it is to reverse that\n return pow(outColor.xyz, vec3(10.0));\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 if( uUseImageLight ){\n totalDiffuse += calculateImageDiffuse(normal, modelPosition);\n totalSpecular += calculateImageSpecular(normal, modelPosition);\n }\n\n totalDiffuse *= diffuseFactor;\n totalSpecular *= specularFactor;\n}\n'; + var webgl2CompatibilityShader = '#ifdef WEBGL2\n\n#define IN in\n#define OUT out\n\n#ifdef FRAGMENT_SHADER\nout vec4 outColor;\n#define OUT_COLOR outColor\n#endif\n#define TEXTURE texture\n\n#else\n\n#ifdef FRAGMENT_SHADER\n#define IN varying\n#else\n#define IN attribute\n#endif\n#define OUT varying\n#define TEXTURE texture2D\n\n#ifdef FRAGMENT_SHADER\n#define OUT_COLOR gl_FragColor\n#endif\n\n#endif\n'; var defaultShaders = { - 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 = vec4(vColor.rgb, 1.) * vColor.a;\n}\n', - normalVert: 'attribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\nattribute vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\n\nuniform vec4 uMaterialColor;\nuniform bool uUseVertexColor;\n\nvarying vec3 vVertexNormal;\nvarying highp vec2 vVertTexCoord;\nvarying vec4 vColor;\n\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vVertexNormal = normalize(vec3( uNormalMatrix * aNormal ));\n vVertTexCoord = aTexCoord;\n vColor = (uUseVertexColor ? aVertexColor : uMaterialColor);\n}\n', - normalFrag: 'precision mediump float;\nvarying vec3 vVertexNormal;\nvoid main(void) {\n gl_FragColor = vec4(vVertexNormal, 1.0);\n}', - basicFrag: 'precision mediump float;\nvarying vec4 vColor;\nvoid main(void) {\n gl_FragColor = vec4(vColor.rgb, 1.) * vColor.a;\n}\n', - lightVert: lightingShader + '// include lighting.glgl\n\nattribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\nattribute vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\n\nuniform bool uUseVertexColor;\nuniform vec4 uMaterialColor;\n\nvarying highp vec2 vVertTexCoord;\nvarying vec3 vDiffuseColor;\nvarying vec3 vSpecularColor;\nvarying vec4 vColor;\n\nvoid main(void) {\n\n vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * viewModelPosition;\n\n vec3 vertexNormal = normalize(uNormalMatrix * aNormal);\n vVertTexCoord = aTexCoord;\n\n totalLight(viewModelPosition.xyz, vertexNormal, vDiffuseColor, vSpecularColor);\n\n for (int i = 0; i < 8; i++) {\n if (i < uAmbientLightCount) {\n vDiffuseColor += uAmbientColor[i];\n }\n }\n \n vColor = (uUseVertexColor ? aVertexColor : uMaterialColor);\n}\n', - lightTextureFrag: 'precision highp float;\n\nuniform vec4 uTint;\nuniform sampler2D uSampler;\nuniform bool isTexture;\nuniform bool uEmissive;\n\nvarying highp vec2 vVertTexCoord;\nvarying vec3 vDiffuseColor;\nvarying vec3 vSpecularColor;\nvarying vec4 vColor;\n\nvoid main(void) {\n if(uEmissive && !isTexture) {\n gl_FragColor = vColor;\n }\n else {\n vec4 baseColor = isTexture ? texture2D(uSampler, vVertTexCoord) * (uTint / vec4(255, 255, 255, 255)) : vColor;\n gl_FragColor = vec4(gl_FragColor.rgb * vDiffuseColor + vSpecularColor, 1.) * baseColor.a;\n }\n}\n', - phongVert: 'precision highp float;\nprecision highp int;\n\nattribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\nattribute vec4 aVertexColor;\n\nuniform vec3 uAmbientColor[5];\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\nuniform int uAmbientLightCount;\n\nuniform bool uUseVertexColor;\nuniform vec4 uMaterialColor;\n\nvarying vec3 vNormal;\nvarying vec2 vTexCoord;\nvarying vec3 vViewPosition;\nvarying vec3 vAmbientColor;\nvarying vec4 vColor;\n\nvoid main(void) {\n\n vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n\n // Pass varyings to fragment shader\n vViewPosition = viewModelPosition.xyz;\n gl_Position = uProjectionMatrix * viewModelPosition; \n\n vNormal = uNormalMatrix * aNormal;\n vTexCoord = aTexCoord;\n\n // TODO: this should be a uniform\n vAmbientColor = vec3(0.0);\n for (int i = 0; i < 5; i++) {\n if (i < uAmbientLightCount) {\n vAmbientColor += uAmbientColor[i];\n }\n }\n \n vColor = (uUseVertexColor ? aVertexColor : uMaterialColor);\n}\n', - phongFrag: lightingShader + '// include lighting.glsl\nprecision highp float;\nprecision highp int;\n\nuniform vec4 uSpecularMatColor;\nuniform vec4 uAmbientMatColor;\nuniform vec4 uEmissiveMatColor;\n\nuniform vec4 uTint;\nuniform sampler2D uSampler;\nuniform bool isTexture;\n\nvarying vec3 vNormal;\nvarying vec2 vTexCoord;\nvarying vec3 vViewPosition;\nvarying vec3 vAmbientColor;\nvarying vec4 vColor;\n\nvoid main(void) {\n\n vec3 diffuse;\n vec3 specular;\n totalLight(vViewPosition, normalize(vNormal), diffuse, specular);\n\n // Calculating final color as result of all lights (plus emissive term).\n\n vec4 baseColor = isTexture ? texture2D(uSampler, vTexCoord) * (uTint / vec4(255, 255, 255, 255)) : vColor;\n gl_FragColor = vec4(diffuse * baseColor.rgb + \n vAmbientColor * uAmbientMatColor.rgb + \n specular * uSpecularMatColor.rgb + \n uEmissiveMatColor.rgb, 1.) * baseColor.a;\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 // Expand glyph bounding boxes by 1px on each side to give a bit of room\n // for antialiasing\n vec2 pixelScale = vec2(\n 1. / uModelViewMatrix[0][0],\n 1. / uModelViewMatrix[1][1]\n );\n vec2 offset = pixelScale * normalize(aTexCoord - vec2(0.5, 0.5)) * vec2(1., -1.);\n vec2 textureOffset = offset * (1. / vec2(\n uGlyphRect.z - uGlyphRect.x,\n uGlyphRect.w - uGlyphRect.y\n ));\n\n // move to the corner of the glyph\n positionVec4.xy += uGlyphRect.xy;\n\n // move to the letter\'s line offset\n positionVec4.x += uGlyphOffset;\n\n positionVec4.xy += offset;\n \n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vTexCoord = aTexCoord + textureOffset;\n w = gl_Position.w;\n}\n', - fontFrag: '#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 = vec4(uMaterialColor.rgb, 1.) * uMaterialColor.a;\n gl_FragColor *= saturate(max(antialias, cover));\n}\n', - lineVert: lineDefs + '/*\n Part of the Processing project - http://processing.org\n Copyright (c) 2012-15 The Processing Foundation\n Copyright (c) 2004-12 Ben Fry and Casey Reas\n Copyright (c) 2001-04 Massachusetts Institute of Technology\n This library is free software; you can redistribute it and/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation, version 2.1.\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n You should have received a copy of the GNU Lesser General\n Public License along with this library; if not, write to the\n Free Software Foundation, Inc., 59 Temple Place, Suite 330,\n Boston, MA 02111-1307 USA\n*/\n\n#define PROCESSING_LINE_SHADER\n\nprecision mediump float;\nprecision mediump int;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform float uStrokeWeight;\n\nuniform bool uUseLineColor;\nuniform vec4 uMaterialColor;\n\nuniform vec4 uViewport;\nuniform int uPerspective;\nuniform int uStrokeJoin;\n\nattribute vec4 aPosition;\nattribute vec3 aTangentIn;\nattribute vec3 aTangentOut;\nattribute float aSide;\nattribute vec4 aVertexColor;\n\nvarying vec4 vColor;\nvarying vec2 vTangent;\nvarying vec2 vCenter;\nvarying vec2 vPosition;\nvarying float vMaxDist;\nvarying float vCap;\nvarying float vJoin;\n\nvec2 lineIntersection(vec2 aPoint, vec2 aDir, vec2 bPoint, vec2 bDir) {\n // Rotate and translate so a starts at the origin and goes out to the right\n bPoint -= aPoint;\n vec2 rotatedBFrom = vec2(\n bPoint.x*aDir.x + bPoint.y*aDir.y,\n bPoint.y*aDir.x - bPoint.x*aDir.y\n );\n vec2 bTo = bPoint + bDir;\n vec2 rotatedBTo = vec2(\n bTo.x*aDir.x + bTo.y*aDir.y,\n bTo.y*aDir.x - bTo.x*aDir.y\n );\n float intersectionDistance =\n rotatedBTo.x + (rotatedBFrom.x - rotatedBTo.x) * rotatedBTo.y /\n (rotatedBTo.y - rotatedBFrom.y);\n return aPoint + aDir * intersectionDistance;\n}\n\nvoid main() {\n // 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 // Caps have one of either the in or out tangent set to 0\n vCap = (aTangentIn == vec3(0.)) != (aTangentOut == (vec3(0.)))\n ? 1. : 0.;\n\n // Joins have two unique, defined tangents\n vJoin = (\n aTangentIn != vec3(0.) &&\n aTangentOut != vec3(0.) &&\n aTangentIn != aTangentOut\n ) ? 1. : 0.;\n\n vec4 posp = uModelViewMatrix * aPosition;\n vec4 posqIn = uModelViewMatrix * (aPosition + vec4(aTangentIn, 0));\n vec4 posqOut = uModelViewMatrix * (aPosition + vec4(aTangentOut, 0));\n\n // Moving vertices slightly toward the camera\n // to avoid depth-fighting with the fill triangles.\n // Discussed here:\n // http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=252848 \n posp.xyz = posp.xyz * scale;\n posqIn.xyz = posqIn.xyz * scale;\n posqOut.xyz = posqOut.xyz * scale;\n\n vec4 p = uProjectionMatrix * posp;\n vec4 qIn = uProjectionMatrix * posqIn;\n vec4 qOut = uProjectionMatrix * posqOut;\n vCenter = p.xy;\n\n // formula to convert from clip space (range -1..1) to screen space (range 0..[width or height])\n // screen_p = (p.xy/p.w + <1,1>) * 0.5 * uViewport.zw\n\n // prevent division by W by transforming the tangent formula (div by 0 causes\n // the line to disappear, see https://github.com/processing/processing/issues/5183)\n // t = screen_q - screen_p\n //\n // tangent is normalized and we don\'t care which aDirection it points to (+-)\n // t = +- normalize( screen_q - screen_p )\n // t = +- normalize( (q.xy/q.w+<1,1>)*0.5*uViewport.zw - (p.xy/p.w+<1,1>)*0.5*uViewport.zw )\n //\n // extract common factor, <1,1> - <1,1> cancels out\n // t = +- normalize( (q.xy/q.w - p.xy/p.w) * 0.5 * uViewport.zw )\n //\n // convert to common divisor\n // t = +- normalize( ((q.xy*p.w - p.xy*q.w) / (p.w*q.w)) * 0.5 * uViewport.zw )\n //\n // remove the common scalar divisor/factor, not needed due to normalize and +-\n // (keep uViewport - can\'t remove because it has different components for x and y\n // and corrects for aspect ratio, see https://github.com/processing/processing/issues/5181)\n // t = +- normalize( (q.xy*p.w - p.xy*q.w) * uViewport.zw )\n\n vec2 tangentIn = normalize((qIn.xy*p.w - p.xy*qIn.w) * uViewport.zw);\n vec2 tangentOut = normalize((qOut.xy*p.w - p.xy*qOut.w) * uViewport.zw);\n\n vec2 curPerspScale;\n if(uPerspective == 1) {\n // Perspective ---\n // convert from world to clip by multiplying with projection scaling factor\n // to get the right thickness (see https://github.com/processing/processing/issues/5182)\n // 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 vec2 offset;\n if (vJoin == 1.) {\n vTangent = normalize(tangentIn + tangentOut);\n vec2 normalIn = vec2(-tangentIn.y, tangentIn.x);\n vec2 normalOut = vec2(-tangentOut.y, tangentOut.x);\n float side = sign(aSide);\n float sideEnum = abs(aSide);\n\n // We generate vertices for joins on either side of the centerline, but\n // the "elbow" side is the only one needing a join. By not setting the\n // offset for the other side, all its vertices will end up in the same\n // spot and not render, effectively discarding it.\n if (sign(dot(tangentOut, vec2(-tangentIn.y, tangentIn.x))) != side) {\n // Side enums:\n // 1: the side going into the join\n // 2: the middle of the join\n // 3: the side going out of the join\n if (sideEnum == 2.) {\n // Calculate the position + tangent on either side of the join, and\n // find where the lines intersect to find the elbow of the join\n vec2 c = (posp.xy/posp.w + vec2(1.,1.)) * 0.5 * uViewport.zw;\n vec2 intersection = lineIntersection(\n c + (side * normalIn * uStrokeWeight / 2.) * curPerspScale,\n tangentIn,\n c + (side * normalOut * uStrokeWeight / 2.) * curPerspScale,\n tangentOut\n );\n offset = (intersection - c);\n\n // When lines are thick and the angle of the join approaches 180, the\n // elbow might be really far from the center. We\'ll apply a limit to\n // the magnitude to avoid lines going across the whole screen when this\n // happens.\n float mag = length(offset);\n float maxMag = 3. * uStrokeWeight;\n if (mag > maxMag) {\n offset *= maxMag / mag;\n }\n } else if (sideEnum == 1.) {\n offset = side * normalIn * curPerspScale * uStrokeWeight / 2.;\n } else if (sideEnum == 3.) {\n offset = side * normalOut * curPerspScale * uStrokeWeight / 2.;\n }\n }\n if (uStrokeJoin == STROKE_JOIN_BEVEL) {\n vec2 avgNormal = vec2(-vTangent.y, vTangent.x);\n vMaxDist = abs(dot(avgNormal, normalIn * uStrokeWeight / 2.));\n } else {\n vMaxDist = uStrokeWeight / 2.;\n }\n } else {\n vec2 tangent = aTangentIn == vec3(0.) ? tangentOut : tangentIn;\n vTangent = tangent;\n vec2 normal = vec2(-tangent.y, tangent.x);\n\n float normalOffset = sign(aSide);\n // Caps will have side values of -2 or 2 on the edge of the cap that\n // extends out from the line\n float tangentOffset = abs(aSide) - 1.;\n offset = (normal * normalOffset + tangent * tangentOffset) *\n uStrokeWeight * 0.5 * curPerspScale;\n vMaxDist = uStrokeWeight / 2.;\n }\n vPosition = vCenter + offset / curPerspScale;\n\n gl_Position.xy = p.xy + offset.xy;\n gl_Position.zw = p.zw;\n \n vColor = (uUseLineColor ? aVertexColor : uMaterialColor);\n}\n', - lineFrag: lineDefs + 'precision mediump float;\nprecision mediump int;\n\nuniform vec4 uMaterialColor;\nuniform int uStrokeCap;\nuniform int uStrokeJoin;\nuniform float uStrokeWeight;\n\nvarying vec4 vColor;\nvarying vec2 vTangent;\nvarying vec2 vCenter;\nvarying vec2 vPosition;\nvarying float vMaxDist;\nvarying float vCap;\nvarying float vJoin;\n\nfloat distSquared(vec2 a, vec2 b) {\n vec2 aToB = b - a;\n return dot(aToB, aToB);\n}\n\nvoid main() {\n if (vCap > 0.) {\n if (\n uStrokeCap == STROKE_CAP_ROUND &&\n distSquared(vPosition, vCenter) > uStrokeWeight * uStrokeWeight * 0.25\n ) {\n discard;\n } else if (\n uStrokeCap == STROKE_CAP_SQUARE &&\n dot(vPosition - vCenter, vTangent) > 0.\n ) {\n discard;\n }\n // Use full area for PROJECT\n } else if (vJoin > 0.) {\n if (\n uStrokeJoin == STROKE_JOIN_ROUND &&\n distSquared(vPosition, vCenter) > uStrokeWeight * uStrokeWeight * 0.25\n ) {\n discard;\n } else if (uStrokeJoin == STROKE_JOIN_BEVEL) {\n vec2 normal = vec2(-vTangent.y, vTangent.x);\n if (abs(dot(vPosition - vCenter, normal)) > vMaxDist) {\n discard;\n }\n }\n // Use full area for MITER\n }\n gl_FragColor = vec4(vColor.rgb, 1.) * vColor.a;\n}\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 float mask = 0.0;\n\n // make a circular mask using the gl_PointCoord (goes from 0 - 1 on a point)\n // might be able to get a nicer edge on big strokeweights with smoothstep but slightly less performant\n\n mask = step(0.98, length(gl_PointCoord * 2.0 - 1.0));\n\n // if strokeWeight is 1 or less lets just draw a square\n // this prevents weird artifacting from carving circles when our points are really small\n // if strokeWeight is larger than 1, we just use it as is\n\n mask = mix(0.0, mask, clamp(floor(vStrokeWeight - 0.5),0.0,1.0));\n\n // throw away the borders of the mask\n // otherwise we get weird alpha blending issues\n\n if(mask > 0.98){\n discard;\n }\n\n gl_FragColor = vec4(uMaterialColor.rgb, 1.) * uMaterialColor.a;\n}\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.curAmbientColor = this._cachedFillStyle = [ - 1, - 1, - 1, - 1 - ]; - this.curSpecularColor = this._cachedFillStyle = [ - 0, - 0, - 0, - 0 - ]; - this.curEmissiveColor = this._cachedFillStyle = [ - 0, - 0, - 0, - 0 - ]; - this.curStrokeColor = this._cachedStrokeStyle = [ - 0, - 0, - 0, - 1 - ]; - this.curBlendMode = constants.BLEND; - this._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._useLineColor = false; - this._useVertexColor = false; - this.registerEnabled = [ - ]; - 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'); // Current vertex normal - this._currentNormal = new _main.default.Vector(0, 0, 1); // 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: { - stroke: [ - new _main.default.RenderBuffer(4, 'lineVertexColors', 'lineColorBuffer', 'aVertexColor', this, this._flatten), - new _main.default.RenderBuffer(3, 'lineVertices', 'lineVerticesBuffer', 'aPosition', this, this._flatten), - new _main.default.RenderBuffer(3, 'lineTangentsIn', 'lineTangentsInBuffer', 'aTangentIn', this, this._flatten), - new _main.default.RenderBuffer(3, 'lineTangentsOut', 'lineTangentsOutBuffer', 'aTangentOut', this, this._flatten), - new _main.default.RenderBuffer(1, 'lineSides', 'lineSidesBuffer', 'aSide', this) - ], - 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 BufferDef(3, 'vertexSpeculars', 'specularBuffer', 'aSpecularColor'), - new _main.default.RenderBuffer(2, 'uvs', 'uvBuffer', 'aTexCoord', this, this._flatten) - ], - 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: { - 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) - ], - stroke: [ - new _main.default.RenderBuffer(4, 'lineVertexColors', 'lineColorBuffer', 'aVertexColor', this, this._flatten), - new _main.default.RenderBuffer(3, 'lineVertices', 'lineVerticesBuffer', 'aPosition', this, this._flatten), - new _main.default.RenderBuffer(3, 'lineTangentsIn', 'lineTangentsInBuffer', 'aTangentIn', this, this._flatten), - new _main.default.RenderBuffer(3, 'lineTangentsOut', 'lineTangentsOutBuffer', 'aTangentOut', this, this._flatten), - new _main.default.RenderBuffer(1, 'lineSides', 'lineSidesBuffer', 'aSide', this) - ], - point: this.GL.createBuffer() - } - }; - this.pointSize = 5; //default point size - this.curStrokeWeight = 1; - this.curStrokeCap = constants.ROUND; - this.curStrokeJoin = constants.ROUND; // 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; // Used to distinguish between user calls to vertex() and internal calls - this.isProcessingVertices = false; - this._tessy = this._initTessy(); - this.fontInfos = { - }; - this._curShader = undefined; - return this; - }; - _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: true, - 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 () { - 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); - } - }; //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; - this.canvas = c; - } - var renderer = new _main.default.RendererGL(this._pInst.canvas, this._pInst, !isPGraphics); - this._pInst._setProperty('_renderer', renderer); - renderer.resize(w, h); - renderer._applyDefaults(); - if (!isPGraphics) { - this._pInst._elements.push(renderer); - } - if (typeof callback === 'function') { - //setTimeout with 0 forces the task to the back of the queue, this ensures that - //we finish switching out the renderer - setTimeout(function () { - callback.apply(window._renderer, options); - }, 0); - } - }; + immediateVert: 'IN vec3 aPosition;\nIN vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform float uResolution;\nuniform float uPointSize;\n\nOUT vec4 vColor;\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vColor = aVertexColor;\n gl_PointSize = uPointSize;\n}\n', + vertexColorVert: 'IN vec3 aPosition;\nIN vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nOUT vec4 vColor;\n\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vColor = aVertexColor;\n}\n', + vertexColorFrag: 'IN vec4 vColor;\nvoid main(void) {\n OUT_COLOR = vec4(vColor.rgb, 1.) * vColor.a;\n}\n', + normalVert: 'IN vec3 aPosition;\nIN vec3 aNormal;\nIN vec2 aTexCoord;\nIN vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\n\nuniform vec4 uMaterialColor;\nuniform bool uUseVertexColor;\n\nOUT vec3 vVertexNormal;\nOUT highp vec2 vVertTexCoord;\nOUT vec4 vColor;\n\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vVertexNormal = normalize(vec3( uNormalMatrix * aNormal ));\n vVertTexCoord = aTexCoord;\n vColor = (uUseVertexColor ? aVertexColor : uMaterialColor);\n}\n', + normalFrag: 'IN vec3 vVertexNormal;\nvoid main(void) {\n OUT_COLOR = vec4(vVertexNormal, 1.0);\n}\n', + basicFrag: 'IN vec4 vColor;\nvoid main(void) {\n OUT_COLOR = vec4(vColor.rgb, 1.) * vColor.a;\n}\n', + lightVert: lightingShader + '// include lighting.glgl\n\nIN vec3 aPosition;\nIN vec3 aNormal;\nIN vec2 aTexCoord;\nIN vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\n\nuniform bool uUseVertexColor;\nuniform vec4 uMaterialColor;\n\nOUT highp vec2 vVertTexCoord;\nOUT vec3 vDiffuseColor;\nOUT vec3 vSpecularColor;\nOUT vec4 vColor;\n\nvoid main(void) {\n\n vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * viewModelPosition;\n\n vec3 vertexNormal = normalize(uNormalMatrix * aNormal);\n vVertTexCoord = aTexCoord;\n\n totalLight(viewModelPosition.xyz, vertexNormal, vDiffuseColor, vSpecularColor);\n\n for (int i = 0; i < 8; i++) {\n if (i < uAmbientLightCount) {\n vDiffuseColor += uAmbientColor[i];\n }\n }\n \n vColor = (uUseVertexColor ? aVertexColor : uMaterialColor);\n}\n', + lightTextureFrag: 'uniform vec4 uTint;\nuniform sampler2D uSampler;\nuniform bool isTexture;\nuniform bool uEmissive;\n\nIN highp vec2 vVertTexCoord;\nIN vec3 vDiffuseColor;\nIN vec3 vSpecularColor;\nIN vec4 vColor;\n\nvoid main(void) {\n if(uEmissive && !isTexture) {\n OUT_COLOR = vColor;\n }\n else {\n vec4 baseColor = isTexture\n // Textures come in with premultiplied alpha. To apply tint and still have\n // premultiplied alpha output, we need to multiply the RGB channels by the\n // tint RGB, and all channels by the tint alpha.\n ? TEXTURE(uSampler, vVertTexCoord) * vec4(uTint.rgb/255., 1.) * (uTint.a/255.)\n // Colors come in with unmultiplied alpha, so we need to multiply the RGB\n // channels by alpha to convert it to premultiplied alpha.\n : vec4(vColor.rgb * vColor.a, vColor.a);\n OUT_COLOR = vec4(baseColor.rgb * vDiffuseColor + vSpecularColor, baseColor.a);\n }\n}\n', + phongVert: 'precision highp int;\n\nIN vec3 aPosition;\nIN vec3 aNormal;\nIN vec2 aTexCoord;\nIN vec4 aVertexColor;\n\nuniform vec3 uAmbientColor[5];\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\nuniform int uAmbientLightCount;\n\nuniform bool uUseVertexColor;\nuniform vec4 uMaterialColor;\n\nOUT vec3 vNormal;\nOUT vec2 vTexCoord;\nOUT vec3 vViewPosition;\nOUT vec3 vAmbientColor;\nOUT vec4 vColor;\n\nvoid main(void) {\n\n vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n\n // Pass varyings to fragment shader\n vViewPosition = viewModelPosition.xyz;\n gl_Position = uProjectionMatrix * viewModelPosition; \n\n vNormal = uNormalMatrix * aNormal;\n vTexCoord = aTexCoord;\n\n // TODO: this should be a uniform\n vAmbientColor = vec3(0.0);\n for (int i = 0; i < 5; i++) {\n if (i < uAmbientLightCount) {\n vAmbientColor += uAmbientColor[i];\n }\n }\n \n vColor = (uUseVertexColor ? aVertexColor : uMaterialColor);\n}\n', + phongFrag: lightingShader + '// include lighting.glsl\nprecision highp int;\n\nuniform bool uHasSetAmbient;\nuniform vec4 uSpecularMatColor;\nuniform vec4 uAmbientMatColor;\nuniform vec4 uEmissiveMatColor;\n\nuniform vec4 uTint;\nuniform sampler2D uSampler;\nuniform bool isTexture;\n\nIN vec3 vNormal;\nIN vec2 vTexCoord;\nIN vec3 vViewPosition;\nIN vec3 vAmbientColor;\nIN vec4 vColor;\n\nvoid main(void) {\n\n vec3 diffuse;\n vec3 specular;\n totalLight(vViewPosition, normalize(vNormal), diffuse, specular);\n\n // Calculating final color as result of all lights (plus emissive term).\n\n vec4 baseColor = isTexture\n // Textures come in with premultiplied alpha. To apply tint and still have\n // premultiplied alpha output, we need to multiply the RGB channels by the\n // tint RGB, and all channels by the tint alpha.\n ? TEXTURE(uSampler, vTexCoord) * vec4(uTint.rgb/255., 1.) * (uTint.a/255.)\n // Colors come in with unmultiplied alpha, so we need to multiply the RGB\n // channels by alpha to convert it to premultiplied alpha.\n : vec4(vColor.rgb * vColor.a, vColor.a);\n OUT_COLOR = vec4(diffuse * baseColor.rgb + \n vAmbientColor * (\n uHasSetAmbient ? uAmbientMatColor.rgb : baseColor.rgb\n ) + \n specular * uSpecularMatColor.rgb + \n uEmissiveMatColor.rgb, baseColor.a);\n}\n', + fontVert: 'IN vec3 aPosition;\nIN vec2 aTexCoord;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nuniform vec4 uGlyphRect;\nuniform float uGlyphOffset;\n\nOUT vec2 vTexCoord;\nOUT float w;\n\nvoid main() {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n\n // scale by the size of the glyph\'s rectangle\n positionVec4.xy *= uGlyphRect.zw - uGlyphRect.xy;\n\n // Expand glyph bounding boxes by 1px on each side to give a bit of room\n // for antialiasing\n vec3 newOrigin = (uModelViewMatrix * vec4(0., 0., 0., 1.)).xyz;\n vec3 newDX = (uModelViewMatrix * vec4(1., 0., 0., 1.)).xyz;\n vec3 newDY = (uModelViewMatrix * vec4(0., 1., 0., 1.)).xyz;\n vec2 pixelScale = vec2(\n 1. / length(newOrigin - newDX),\n 1. / length(newOrigin - newDY)\n );\n vec2 offset = pixelScale * normalize(aTexCoord - vec2(0.5, 0.5)) * vec2(1., -1.);\n vec2 textureOffset = offset * (1. / vec2(\n uGlyphRect.z - uGlyphRect.x,\n uGlyphRect.w - uGlyphRect.y\n ));\n\n // move to the corner of the glyph\n positionVec4.xy += uGlyphRect.xy;\n\n // move to the letter\'s line offset\n positionVec4.x += uGlyphOffset;\n\n positionVec4.xy += offset;\n \n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vTexCoord = aTexCoord + textureOffset;\n w = gl_Position.w;\n}\n', + fontFrag: '#ifndef WEBGL2\n#extension GL_OES_standard_derivatives : enable\n#endif\n\n#if 0\n // simulate integer math using floats\n\t#define int float\n\t#define ivec2 vec2\n\t#define INT(x) float(x)\n\n\tint ifloor(float v) { return floor(v); }\n\tivec2 ifloor(vec2 v) { return floor(v); }\n\n#else\n // use native integer math\n\tprecision highp int;\n\t#define INT(x) x\n\n\tint ifloor(float v) { return int(v); }\n\tint ifloor(int v) { return v; }\n\tivec2 ifloor(vec2 v) { return ivec2(v); }\n\n#endif\n\nuniform sampler2D uSamplerStrokes;\nuniform sampler2D uSamplerRowStrokes;\nuniform sampler2D uSamplerRows;\nuniform sampler2D uSamplerColStrokes;\nuniform sampler2D uSamplerCols;\n\nuniform ivec2 uStrokeImageSize;\nuniform ivec2 uCellsImageSize;\nuniform ivec2 uGridImageSize;\n\nuniform ivec2 uGridOffset;\nuniform ivec2 uGridSize;\nuniform vec4 uMaterialColor;\n\nIN vec2 vTexCoord;\n\n// some helper functions\nint ROUND(float v) { return ifloor(v + 0.5); }\nivec2 ROUND(vec2 v) { return ifloor(v + 0.5); }\nfloat saturate(float v) { return clamp(v, 0.0, 1.0); }\nvec2 saturate(vec2 v) { return clamp(v, 0.0, 1.0); }\n\nint mul(float v1, int v2) {\n return ifloor(v1 * float(v2));\n}\n\nivec2 mul(vec2 v1, ivec2 v2) {\n return ifloor(v1 * vec2(v2) + 0.5);\n}\n\n// unpack a 16-bit integer from a float vec2\nint getInt16(vec2 v) {\n ivec2 iv = ROUND(v * 255.0);\n return iv.x * INT(128) + iv.y;\n}\n\nvec2 pixelScale;\nvec2 coverage = vec2(0.0);\nvec2 weight = vec2(0.5);\nconst float minDistance = 1.0/8192.0;\nconst float hardness = 1.05; // amount of antialias\n\n// the maximum number of curves in a glyph\nconst int N = INT(250);\n\n// retrieves an indexed pixel from a sampler\nvec4 getTexel(sampler2D sampler, int pos, ivec2 size) {\n int width = size.x;\n int y = ifloor(pos / width);\n int x = pos - y * width; // pos % width\n\n return TEXTURE(sampler, (vec2(x, y) + 0.5) / vec2(size));\n}\n\nvoid calulateCrossings(vec2 p0, vec2 p1, vec2 p2, out vec2 C1, out vec2 C2) {\n\n // get the coefficients of the quadratic in t\n vec2 a = p0 - p1 * 2.0 + p2;\n vec2 b = p0 - p1;\n vec2 c = p0 - vTexCoord;\n\n // found out which values of \'t\' it crosses the axes\n vec2 surd = sqrt(max(vec2(0.0), b * b - a * c));\n vec2 t1 = ((b - surd) / a).yx;\n vec2 t2 = ((b + surd) / a).yx;\n\n // approximate straight lines to avoid rounding errors\n if (abs(a.y) < 0.001)\n t1.x = t2.x = c.y / (2.0 * b.y);\n\n if (abs(a.x) < 0.001)\n t1.y = t2.y = c.x / (2.0 * b.x);\n\n // plug into quadratic formula to find the corrdinates of the crossings\n C1 = ((a * t1 - b * 2.0) * t1 + c) * pixelScale;\n C2 = ((a * t2 - b * 2.0) * t2 + c) * pixelScale;\n}\n\nvoid coverageX(vec2 p0, vec2 p1, vec2 p2) {\n\n vec2 C1, C2;\n calulateCrossings(p0, p1, p2, C1, C2);\n\n // determine on which side of the x-axis the points lie\n bool y0 = p0.y > vTexCoord.y;\n bool y1 = p1.y > vTexCoord.y;\n bool y2 = p2.y > vTexCoord.y;\n\n // could web be under the curve (after t1)?\n if (y1 ? !y2 : y0) {\n // add the coverage for t1\n coverage.x += saturate(C1.x + 0.5);\n // calculate the anti-aliasing for t1\n weight.x = min(weight.x, abs(C1.x));\n }\n\n // are we outside the curve (after t2)?\n if (y1 ? !y0 : y2) {\n // subtract the coverage for t2\n coverage.x -= saturate(C2.x + 0.5);\n // calculate the anti-aliasing for t2\n weight.x = min(weight.x, abs(C2.x));\n }\n}\n\n// this is essentially the same as coverageX, but with the axes swapped\nvoid coverageY(vec2 p0, vec2 p1, vec2 p2) {\n\n vec2 C1, C2;\n calulateCrossings(p0, p1, p2, C1, C2);\n\n bool x0 = p0.x > vTexCoord.x;\n bool x1 = p1.x > vTexCoord.x;\n bool x2 = p2.x > vTexCoord.x;\n\n if (x1 ? !x2 : x0) {\n coverage.y -= saturate(C1.y + 0.5);\n weight.y = min(weight.y, abs(C1.y));\n }\n\n if (x1 ? !x0 : x2) {\n coverage.y += saturate(C2.y + 0.5);\n weight.y = min(weight.y, abs(C2.y));\n }\n}\n\nvoid main() {\n\n // calculate the pixel scale based on screen-coordinates\n pixelScale = hardness / fwidth(vTexCoord);\n\n // which grid cell is this pixel in?\n ivec2 gridCoord = ifloor(vTexCoord * vec2(uGridSize));\n\n // intersect curves in this row\n {\n // the index into the row info bitmap\n int rowIndex = gridCoord.y + uGridOffset.y;\n // fetch the info texel\n vec4 rowInfo = getTexel(uSamplerRows, rowIndex, uGridImageSize);\n // unpack the rowInfo\n int rowStrokeIndex = getInt16(rowInfo.xy);\n int rowStrokeCount = getInt16(rowInfo.zw);\n\n for (int iRowStroke = INT(0); iRowStroke < N; iRowStroke++) {\n if (iRowStroke >= rowStrokeCount)\n break;\n\n // each stroke is made up of 3 points: the start and control point\n // and the start of the next curve.\n // fetch the indices of this pair of strokes:\n vec4 strokeIndices = getTexel(uSamplerRowStrokes, rowStrokeIndex++, uCellsImageSize);\n\n // unpack the stroke index\n int strokePos = getInt16(strokeIndices.xy);\n\n // fetch the two strokes\n vec4 stroke0 = getTexel(uSamplerStrokes, strokePos + INT(0), uStrokeImageSize);\n vec4 stroke1 = getTexel(uSamplerStrokes, strokePos + INT(1), uStrokeImageSize);\n\n // calculate the coverage\n coverageX(stroke0.xy, stroke0.zw, stroke1.xy);\n }\n }\n\n // intersect curves in this column\n {\n int colIndex = gridCoord.x + uGridOffset.x;\n vec4 colInfo = getTexel(uSamplerCols, colIndex, uGridImageSize);\n int colStrokeIndex = getInt16(colInfo.xy);\n int colStrokeCount = getInt16(colInfo.zw);\n \n for (int iColStroke = INT(0); iColStroke < N; iColStroke++) {\n if (iColStroke >= colStrokeCount)\n break;\n\n vec4 strokeIndices = getTexel(uSamplerColStrokes, colStrokeIndex++, uCellsImageSize);\n\n int strokePos = getInt16(strokeIndices.xy);\n vec4 stroke0 = getTexel(uSamplerStrokes, strokePos + INT(0), uStrokeImageSize);\n vec4 stroke1 = getTexel(uSamplerStrokes, strokePos + INT(1), uStrokeImageSize);\n coverageY(stroke0.xy, stroke0.zw, stroke1.xy);\n }\n }\n\n weight = saturate(1.0 - weight * 2.0);\n float distance = max(weight.x + weight.y, minDistance); // manhattan approx.\n float antialias = abs(dot(coverage, weight) / distance);\n float cover = min(abs(coverage.x), abs(coverage.y));\n OUT_COLOR = vec4(uMaterialColor.rgb, 1.) * uMaterialColor.a;\n OUT_COLOR *= saturate(max(antialias, cover));\n}\n', + lineVert: lineDefs + '/*\n Part of the Processing project - http://processing.org\n Copyright (c) 2012-15 The Processing Foundation\n Copyright (c) 2004-12 Ben Fry and Casey Reas\n Copyright (c) 2001-04 Massachusetts Institute of Technology\n This library is free software; you can redistribute it and/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation, version 2.1.\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n You should have received a copy of the GNU Lesser General\n Public License along with this library; if not, write to the\n Free Software Foundation, Inc., 59 Temple Place, Suite 330,\n Boston, MA 02111-1307 USA\n*/\n\n#define PROCESSING_LINE_SHADER\n\nprecision mediump int;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform float uStrokeWeight;\n\nuniform bool uUseLineColor;\nuniform vec4 uMaterialColor;\n\nuniform vec4 uViewport;\nuniform int uPerspective;\nuniform int uStrokeJoin;\n\nIN vec4 aPosition;\nIN vec3 aTangentIn;\nIN vec3 aTangentOut;\nIN float aSide;\nIN vec4 aVertexColor;\n\nOUT vec4 vColor;\nOUT vec2 vTangent;\nOUT vec2 vCenter;\nOUT vec2 vPosition;\nOUT float vMaxDist;\nOUT float vCap;\nOUT float vJoin;\n\nvec2 lineIntersection(vec2 aPoint, vec2 aDir, vec2 bPoint, vec2 bDir) {\n // Rotate and translate so a starts at the origin and goes out to the right\n bPoint -= aPoint;\n vec2 rotatedBFrom = vec2(\n bPoint.x*aDir.x + bPoint.y*aDir.y,\n bPoint.y*aDir.x - bPoint.x*aDir.y\n );\n vec2 bTo = bPoint + bDir;\n vec2 rotatedBTo = vec2(\n bTo.x*aDir.x + bTo.y*aDir.y,\n bTo.y*aDir.x - bTo.x*aDir.y\n );\n float intersectionDistance =\n rotatedBTo.x + (rotatedBFrom.x - rotatedBTo.x) * rotatedBTo.y /\n (rotatedBTo.y - rotatedBFrom.y);\n return aPoint + aDir * intersectionDistance;\n}\n\nvoid main() {\n // Caps have one of either the in or out tangent set to 0\n vCap = (aTangentIn == vec3(0.)) != (aTangentOut == (vec3(0.)))\n ? 1. : 0.;\n\n // Joins have two unique, defined tangents\n vJoin = (\n aTangentIn != vec3(0.) &&\n aTangentOut != vec3(0.) &&\n aTangentIn != aTangentOut\n ) ? 1. : 0.;\n\n vec4 posp = uModelViewMatrix * aPosition;\n vec4 posqIn = uModelViewMatrix * (aPosition + vec4(aTangentIn, 0));\n vec4 posqOut = uModelViewMatrix * (aPosition + vec4(aTangentOut, 0));\n\n float facingCamera = pow(\n // The word space tangent\'s z value is 0 if it\'s facing the camera\n abs(normalize(posqIn-posp).z),\n\n // Using pow() here to ramp `facingCamera` up from 0 to 1 really quickly\n // so most lines get scaled and don\'t get clipped\n 0.25\n );\n\n // using a scale <1 moves the lines towards the camera\n // in order to prevent popping effects due to half of\n // the line disappearing behind the geometry faces.\n float scale = mix(1., 0.995, facingCamera);\n\n // Moving vertices slightly toward the camera\n // to avoid depth-fighting with the fill triangles.\n // Discussed here:\n // http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=252848 \n posp.xyz = posp.xyz * scale;\n posqIn.xyz = posqIn.xyz * scale;\n posqOut.xyz = posqOut.xyz * scale;\n\n vec4 p = uProjectionMatrix * posp;\n vec4 qIn = uProjectionMatrix * posqIn;\n vec4 qOut = uProjectionMatrix * posqOut;\n vCenter = p.xy;\n\n // formula to convert from clip space (range -1..1) to screen space (range 0..[width or height])\n // screen_p = (p.xy/p.w + <1,1>) * 0.5 * uViewport.zw\n\n // prevent division by W by transforming the tangent formula (div by 0 causes\n // the line to disappear, see https://github.com/processing/processing/issues/5183)\n // t = screen_q - screen_p\n //\n // tangent is normalized and we don\'t care which aDirection it points to (+-)\n // t = +- normalize( screen_q - screen_p )\n // t = +- normalize( (q.xy/q.w+<1,1>)*0.5*uViewport.zw - (p.xy/p.w+<1,1>)*0.5*uViewport.zw )\n //\n // extract common factor, <1,1> - <1,1> cancels out\n // t = +- normalize( (q.xy/q.w - p.xy/p.w) * 0.5 * uViewport.zw )\n //\n // convert to common divisor\n // t = +- normalize( ((q.xy*p.w - p.xy*q.w) / (p.w*q.w)) * 0.5 * uViewport.zw )\n //\n // remove the common scalar divisor/factor, not needed due to normalize and +-\n // (keep uViewport - can\'t remove because it has different components for x and y\n // and corrects for aspect ratio, see https://github.com/processing/processing/issues/5181)\n // t = +- normalize( (q.xy*p.w - p.xy*q.w) * uViewport.zw )\n\n vec2 tangentIn = normalize((qIn.xy*p.w - p.xy*qIn.w) * uViewport.zw);\n vec2 tangentOut = normalize((qOut.xy*p.w - p.xy*qOut.w) * uViewport.zw);\n\n vec2 curPerspScale;\n if(uPerspective == 1) {\n // Perspective ---\n // convert from world to clip by multiplying with projection scaling factor\n // to get the right thickness (see https://github.com/processing/processing/issues/5182)\n\n // The y value of the projection matrix may be flipped if rendering to a Framebuffer.\n // Multiplying again by its sign here negates the flip to get just the scale.\n curPerspScale = (uProjectionMatrix * vec4(1, sign(uProjectionMatrix[1][1]), 0, 0)).xy;\n } else {\n // No Perspective ---\n // multiply by W (to cancel out division by W later in the pipeline) and\n // convert from screen to clip (derived from clip to screen above)\n curPerspScale = p.w / (0.5 * uViewport.zw);\n }\n\n vec2 offset;\n if (vJoin == 1.) {\n vTangent = normalize(tangentIn + tangentOut);\n vec2 normalIn = vec2(-tangentIn.y, tangentIn.x);\n vec2 normalOut = vec2(-tangentOut.y, tangentOut.x);\n float side = sign(aSide);\n float sideEnum = abs(aSide);\n\n // We generate vertices for joins on either side of the centerline, but\n // the "elbow" side is the only one needing a join. By not setting the\n // offset for the other side, all its vertices will end up in the same\n // spot and not render, effectively discarding it.\n if (sign(dot(tangentOut, vec2(-tangentIn.y, tangentIn.x))) != side) {\n // Side enums:\n // 1: the side going into the join\n // 2: the middle of the join\n // 3: the side going out of the join\n if (sideEnum == 2.) {\n // Calculate the position + tangent on either side of the join, and\n // find where the lines intersect to find the elbow of the join\n vec2 c = (posp.xy/posp.w + vec2(1.,1.)) * 0.5 * uViewport.zw;\n vec2 intersection = lineIntersection(\n c + (side * normalIn * uStrokeWeight / 2.),\n tangentIn,\n c + (side * normalOut * uStrokeWeight / 2.),\n tangentOut\n );\n offset = (intersection - c);\n\n // When lines are thick and the angle of the join approaches 180, the\n // elbow might be really far from the center. We\'ll apply a limit to\n // the magnitude to avoid lines going across the whole screen when this\n // happens.\n float mag = length(offset);\n float maxMag = 3. * uStrokeWeight;\n if (mag > maxMag) {\n offset *= maxMag / mag;\n }\n } else if (sideEnum == 1.) {\n offset = side * normalIn * uStrokeWeight / 2.;\n } else if (sideEnum == 3.) {\n offset = side * normalOut * uStrokeWeight / 2.;\n }\n }\n if (uStrokeJoin == STROKE_JOIN_BEVEL) {\n vec2 avgNormal = vec2(-vTangent.y, vTangent.x);\n vMaxDist = abs(dot(avgNormal, normalIn * uStrokeWeight / 2.));\n } else {\n vMaxDist = uStrokeWeight / 2.;\n }\n } else {\n vec2 tangent = aTangentIn == vec3(0.) ? tangentOut : tangentIn;\n vTangent = tangent;\n vec2 normal = vec2(-tangent.y, tangent.x);\n\n float normalOffset = sign(aSide);\n // Caps will have side values of -2 or 2 on the edge of the cap that\n // extends out from the line\n float tangentOffset = abs(aSide) - 1.;\n offset = (normal * normalOffset + tangent * tangentOffset) *\n uStrokeWeight * 0.5;\n vMaxDist = uStrokeWeight / 2.;\n }\n vPosition = vCenter + offset;\n\n gl_Position.xy = p.xy + offset.xy * curPerspScale;\n gl_Position.zw = p.zw;\n \n vColor = (uUseLineColor ? aVertexColor : uMaterialColor);\n}\n', + lineFrag: lineDefs + 'precision mediump int;\n\nuniform vec4 uMaterialColor;\nuniform int uStrokeCap;\nuniform int uStrokeJoin;\nuniform float uStrokeWeight;\n\nIN vec4 vColor;\nIN vec2 vTangent;\nIN vec2 vCenter;\nIN vec2 vPosition;\nIN float vMaxDist;\nIN float vCap;\nIN float vJoin;\n\nfloat distSquared(vec2 a, vec2 b) {\n vec2 aToB = b - a;\n return dot(aToB, aToB);\n}\n\nvoid main() {\n if (vCap > 0.) {\n if (\n uStrokeCap == STROKE_CAP_ROUND &&\n distSquared(vPosition, vCenter) > uStrokeWeight * uStrokeWeight * 0.25\n ) {\n discard;\n } else if (\n uStrokeCap == STROKE_CAP_SQUARE &&\n dot(vPosition - vCenter, vTangent) > 0.\n ) {\n discard;\n }\n // Use full area for PROJECT\n } else if (vJoin > 0.) {\n if (\n uStrokeJoin == STROKE_JOIN_ROUND &&\n distSquared(vPosition, vCenter) > uStrokeWeight * uStrokeWeight * 0.25\n ) {\n discard;\n } else if (uStrokeJoin == STROKE_JOIN_BEVEL) {\n vec2 normal = vec2(-vTangent.y, vTangent.x);\n if (abs(dot(vPosition - vCenter, normal)) > vMaxDist) {\n discard;\n }\n }\n // Use full area for MITER\n }\n OUT_COLOR = vec4(vColor.rgb, 1.) * vColor.a;\n}\n', + pointVert: 'IN vec3 aPosition;\nuniform float uPointSize;\nOUT float vStrokeWeight;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nvoid main() {\n\tvec4 positionVec4 = vec4(aPosition, 1.0);\n\tgl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n\tgl_PointSize = uPointSize;\n\tvStrokeWeight = uPointSize;\n}\n', + pointFrag: 'precision mediump int;\nuniform vec4 uMaterialColor;\nIN float vStrokeWeight;\n\nvoid main(){\n float mask = 0.0;\n\n // make a circular mask using the gl_PointCoord (goes from 0 - 1 on a point)\n // might be able to get a nicer edge on big strokeweights with smoothstep but slightly less performant\n\n mask = step(0.98, length(gl_PointCoord * 2.0 - 1.0));\n\n // if strokeWeight is 1 or less lets just draw a square\n // this prevents weird artifacting from carving circles when our points are really small\n // if strokeWeight is larger than 1, we just use it as is\n\n mask = mix(0.0, mask, clamp(floor(vStrokeWeight - 0.5),0.0,1.0));\n\n // throw away the borders of the mask\n // otherwise we get weird alpha blending issues\n\n if(mask > 0.98){\n discard;\n }\n\n OUT_COLOR = vec4(uMaterialColor.rgb, 1.) * uMaterialColor.a;\n}\n', + imageLightVert: 'precision highp float;\nattribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nvarying vec3 localPos;\nvarying vec3 vWorldNormal;\nvarying vec3 vWorldPosition;\nvarying vec2 vTexCoord;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\n\nvoid main() {\n // Multiply the position by the matrix.\n vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * viewModelPosition; \n \n // orient the normals and pass to the fragment shader\n vWorldNormal = uNormalMatrix * aNormal;\n \n // send the view position to the fragment shader\n vWorldPosition = (uModelViewMatrix * vec4(aPosition, 1.0)).xyz;\n \n localPos = vWorldPosition;\n vTexCoord = aTexCoord;\n}\n\n\n/*\nin the vertex shader we\'ll compute the world position and world oriented normal of the vertices and pass those to the fragment shader as varyings.\n*/\n', + imageLightDiffusedFrag: 'precision highp float;\nvarying vec3 localPos;\n\n// the HDR cubemap converted (can be from an equirectangular environment map.)\nuniform sampler2D environmentMap;\nvarying vec2 vTexCoord;\n\nconst float PI = 3.14159265359;\n\nvec2 nTOE( vec3 v ){\n // x = r sin(phi) cos(theta) \n // y = r cos(phi) \n // z = r sin(phi) sin(theta)\n float phi = acos( v.y );\n // if phi is 0, then there are no x, z components\n float theta = 0.0;\n // else \n theta = acos(v.x / sin(phi));\n float sinTheta = v.z / sin(phi);\n if (sinTheta < 0.0) {\n // Turn it into -theta, but in the 0-2PI range\n theta = 2.0 * PI - theta;\n }\n theta = theta / (2.0 * 3.14159);\n phi = phi / 3.14159 ;\n \n vec2 angles = vec2( phi, theta );\n return angles;\n}\n\nvoid main()\n{ \t \n\t// the sample direction equals the hemisphere\'s orientation\n float phi = vTexCoord.x * 2.0 * PI;\n float theta = vTexCoord.y * PI;\n float x = sin(theta) * cos(phi);\n float y = sin(theta) * sin(phi);\n float z = cos(theta);\n vec3 normal = vec3( x, y, z);\n\n\t// Discretely sampling the hemisphere given the integral\'s\n // spherical coordinates translates to the following fragment code:\n\tvec3 irradiance = vec3(0.0); \n\tvec3 up\t= vec3(0.0, 1.0, 0.0);\n\tvec3 right = normalize(cross(up, normal));\n\tup = normalize(cross(normal, right));\n\n\t// We specify a fixed sampleDelta delta value to traverse\n // the hemisphere; decreasing or increasing the sample delta\n // will increase or decrease the accuracy respectively.\n\tconst float sampleDelta = 0.025;\n\tfloat nrSamples = 0.0;\n \n\tfor(float phi = 0.0; phi < 2.0 * PI; phi += sampleDelta)\n\t{\n for(float theta = 0.0; theta < ( 0.5 ) * PI; theta += sampleDelta)\n {\n // spherical to cartesian (in tangent space) // tangent space to world // add each sample result to irradiance\n float x = sin(theta) * cos(phi);\n float y = sin(theta) * sin(phi);\n float z = cos(theta);\n vec3 tangentSample = vec3( x, y, z);\n \n vec3 sampleVec = tangentSample.x * right + tangentSample.y * up + tangentSample.z * normal;\n irradiance += (texture2D(environmentMap, nTOE(sampleVec)).xyz) * cos(theta) * sin(theta);\n nrSamples++;\n }\n\t}\n\t// divide by the total number of samples taken, giving us the average sampled irradiance.\n\tirradiance = PI * irradiance * (1.0 / float(nrSamples )) ;\n \n \n\tgl_FragColor = vec4(irradiance, 1.0);\n}', + imageLightSpecularFrag: 'precision highp float;\r\nvarying vec3 localPos;\r\nvarying vec2 vTexCoord;\r\n\r\n// our texture\r\nuniform sampler2D environmentMap;\r\nuniform float roughness;\r\n\r\nconst float PI = 3.14159265359;\r\n\r\nfloat VanDerCorput(int bits);\r\nvec2 HammersleyNoBitOps(int i, int N);\r\nvec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness);\r\n\r\n\r\nvec2 nTOE( vec3 v ){\r\n // x = r sin(phi) cos(theta) \r\n // y = r cos(phi) \r\n // z = r sin(phi) sin(theta)\r\n float phi = acos( v.y );\r\n // if phi is 0, then there are no x, z components\r\n float theta = 0.0;\r\n // else \r\n theta = acos(v.x / sin(phi));\r\n float sinTheta = v.z / sin(phi);\r\n if (sinTheta < 0.0) {\r\n // Turn it into -theta, but in the 0-2PI range\r\n theta = 2.0 * PI - theta;\r\n }\r\n theta = theta / (2.0 * 3.14159);\r\n phi = phi / 3.14159 ;\r\n \r\n vec2 angles = vec2( phi, theta );\r\n return angles;\r\n}\r\n\r\n\r\nvoid main(){\r\n const int SAMPLE_COUNT = 1024; // 4096\r\n float totalWeight = 0.0;\r\n vec3 prefilteredColor = vec3(0.0);\r\n float phi = vTexCoord.x * 2.0 * PI;\r\n float theta = vTexCoord.y * PI;\r\n float x = sin(theta) * cos(phi);\r\n float y = sin(theta) * sin(phi);\r\n float z = cos(theta);\r\n vec3 N = vec3(x,y,z);\r\n vec3 V = N;\r\n for (int i = 0; i < SAMPLE_COUNT; ++i)\r\n {\r\n vec2 Xi = HammersleyNoBitOps(i, SAMPLE_COUNT);\r\n vec3 H = ImportanceSampleGGX(Xi, N, roughness);\r\n vec3 L = normalize(2.0 * dot(V, H) * H - V);\r\n\r\n float NdotL = max(dot(N, L), 0.0);\r\n if (NdotL > 0.0)\r\n {\r\n prefilteredColor += texture2D(environmentMap, nTOE(L)).xyz * NdotL;\r\n totalWeight += NdotL;\r\n }\r\n }\r\n prefilteredColor = prefilteredColor / totalWeight;\r\n\r\n gl_FragColor = vec4(prefilteredColor, 1.0);\r\n}\r\n\r\nvec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness){\r\n float a = roughness * roughness;\r\n\r\n float phi = 2.0 * PI * Xi.x;\r\n float cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (a * a - 1.0) * Xi.y));\r\n float sinTheta = sqrt(1.0 - cosTheta * cosTheta);\r\n // from spherical coordinates to cartesian coordinates\r\n vec3 H;\r\n H.x = cos(phi) * sinTheta;\r\n H.y = sin(phi) * sinTheta;\r\n H.z = cosTheta;\r\n\r\n // from tangent-space vector to world-space sample vector\r\n vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);\r\n vec3 tangent = normalize(cross(up, N));\r\n vec3 bitangent = cross(N, tangent);\r\n\r\n vec3 sampleVec = tangent * H.x + bitangent * H.y + N * H.z;\r\n return normalize(sampleVec);\r\n}\r\n\r\n\r\nfloat VanDerCorput(int n, int base)\r\n{\r\n float invBase = 1.0 / float(base);\r\n float denom = 1.0;\r\n float result = 0.0;\r\n\r\n for (int i = 0; i < 32; ++i)\r\n {\r\n\tif (n > 0)\r\n\t{\r\n \tdenom = mod(float(n), 2.0);\r\n \tresult += denom * invBase;\r\n \tinvBase = invBase / 2.0;\r\n \tn = int(float(n) / 2.0);\r\n\t}\r\n }\r\n\r\n return result;\r\n}\r\n\r\nvec2 HammersleyNoBitOps(int i, int N)\r\n{\r\n return vec2(float(i) / float(N), VanDerCorput(i, 2));\r\n}\r\n' + }; + for (var key in defaultShaders) { + defaultShaders[key] = webgl2CompatibilityShader + defaultShaders[key]; + } + var filterShaderFrags = (_filterShaderFrags = { + }, _defineProperty(_filterShaderFrags, constants.GRAY, 'precision highp float;\n\nvarying vec2 vTexCoord;\n\nuniform sampler2D tex0;\n\nfloat luma(vec3 color) {\n // weighted grayscale with luminance values\n return dot(color, vec3(0.2126, 0.7152, 0.0722));\n}\n\nvoid main() {\n vec4 tex = texture2D(tex0, vTexCoord);\n float gray = luma(tex.rgb);\n gl_FragColor = vec4(gray, gray, gray, tex.a);\n}\n'), _defineProperty(_filterShaderFrags, constants.ERODE, '// Reduces the bright areas in an image\n\nprecision highp float;\n\nvarying vec2 vTexCoord;\n\nuniform sampler2D tex0;\nuniform vec2 texelSize;\n\nfloat luma(vec3 color) {\n // weighted grayscale with luminance values\n // weights 77, 151, 28 taken from src/image/filters.js\n return dot(color, vec3(0.300781, 0.589844, 0.109375));\n}\n\nvoid main() {\n vec4 color = texture2D(tex0, vTexCoord);\n float lum = luma(color.rgb);\n\n // set current color as the darkest neighbor color\n\n vec4 neighbors[4];\n neighbors[0] = texture2D(tex0, vTexCoord + vec2( texelSize.x, 0.0));\n neighbors[1] = texture2D(tex0, vTexCoord + vec2(-texelSize.x, 0.0));\n neighbors[2] = texture2D(tex0, vTexCoord + vec2(0.0, texelSize.y));\n neighbors[3] = texture2D(tex0, vTexCoord + vec2(0.0, -texelSize.y));\n\n for (int i = 0; i < 4; i++) {\n vec4 neighborColor = neighbors[i];\n float neighborLum = luma(neighborColor.rgb);\n\n if (neighborLum < lum) {\n color = neighborColor;\n lum = neighborLum;\n }\n }\n\n gl_FragColor = color;\n}\n'), _defineProperty(_filterShaderFrags, constants.DILATE, '// Increase the bright areas in an image\n\nprecision highp float;\n\nvarying vec2 vTexCoord;\n\nuniform sampler2D tex0;\nuniform vec2 texelSize;\n\nfloat luma(vec3 color) {\n // weighted grayscale with luminance values\n // weights 77, 151, 28 taken from src/image/filters.js\n return dot(color, vec3(0.300781, 0.589844, 0.109375));\n}\n\nvoid main() {\n vec4 color = texture2D(tex0, vTexCoord);\n float lum = luma(color.rgb);\n\n // set current color as the brightest neighbor color\n\n vec4 neighbors[4];\n neighbors[0] = texture2D(tex0, vTexCoord + vec2( texelSize.x, 0.0));\n neighbors[1] = texture2D(tex0, vTexCoord + vec2(-texelSize.x, 0.0));\n neighbors[2] = texture2D(tex0, vTexCoord + vec2(0.0, texelSize.y));\n neighbors[3] = texture2D(tex0, vTexCoord + vec2(0.0, -texelSize.y));\n\n for (int i = 0; i < 4; i++) {\n vec4 neighborColor = neighbors[i];\n float neighborLum = luma(neighborColor.rgb);\n\n if (neighborLum > lum) {\n color = neighborColor;\n lum = neighborLum;\n }\n }\n\n gl_FragColor = color;\n}\n'), _defineProperty(_filterShaderFrags, constants.BLUR, 'precision highp float;\n\n// Two-pass blur filter, unweighted kernel.\n// See also a similar blur at Adam Ferriss\' repo of shader examples:\n// https://github.com/aferriss/p5jsShaderExamples/blob/gh-pages/4_image-effects/4-9_single-pass-blur/effect.frag\n\n\nuniform sampler2D tex0;\nvarying vec2 vTexCoord;\nuniform vec2 direction;\nuniform vec2 canvasSize;\nuniform float radius;\n\nfloat random(vec2 p) {\n vec3 p3 = fract(vec3(p.xyx) * .1031);\n p3 += dot(p3, p3.yzx + 33.33);\n return fract((p3.x + p3.y) * p3.z);\n}\n\n// This isn\'t a real Gaussian weight, it\'s a quadratic weight. It\'s what the\n// CPU mode\'s blur uses though, so we also use it here to match.\nfloat quadWeight(float x, float e) {\n return pow(e-abs(x), 2.);\n}\n\nvoid main(){\n vec2 uv = vTexCoord;\n\n // A reasonable maximum number of samples\n const float maxSamples = 64.0;\n\n float numSamples = floor(7. * radius);\n if (fract(numSamples / 2.) == 0.) {\n numSamples++;\n }\n vec4 avg = vec4(0.0);\n float total = 0.0;\n\n // Calculate the spacing to avoid skewing if numSamples > maxSamples\n float spacing = 1.0;\n if (numSamples > maxSamples) {\n spacing = numSamples / maxSamples;\n numSamples = maxSamples;\n }\n\n float randomOffset = (spacing - 1.0) * mix(-0.5, 0.5, random(gl_FragCoord.xy));\n for (float i = 0.0; i < maxSamples; i++) {\n if (i >= numSamples) break;\n\n float sample = i * spacing - (numSamples - 1.0) * 0.5 * spacing + randomOffset;\n vec2 sampleCoord = uv + vec2(sample, sample) / canvasSize * direction;\n float weight = quadWeight(sample, (numSamples - 1.0) * 0.5 * spacing);\n\n avg += weight * texture2D(tex0, sampleCoord);\n total += weight;\n }\n\n avg /= total;\n gl_FragColor = avg;\n}\n'), _defineProperty(_filterShaderFrags, constants.POSTERIZE, '// Limit color space for a stylized cartoon / poster effect\n\nprecision highp float;\n\nvarying vec2 vTexCoord;\n\nuniform sampler2D tex0;\nuniform float filterParameter;\n\nvec3 quantize(vec3 color, float n) {\n // restrict values to N options/bins\n // and floor each channel to nearest value\n //\n // eg. when N = 5, values = 0.0, 0.25, 0.50, 0.75, 1.0\n // then quantize (0.1, 0.7, 0.9) -> (0.0, 0.5, 1.0)\n\n color = color * n;\n color = floor(color);\n color = color / (n - 1.0);\n return color;\n}\n\nvoid main() {\n vec4 color = texture2D(tex0, vTexCoord);\n\n vec3 restrictedColor = quantize(color.rgb / color.a, filterParameter);\n\n gl_FragColor = vec4(restrictedColor.rgb * color.a, color.a);\n}\n'), _defineProperty(_filterShaderFrags, constants.OPAQUE, '// Set alpha channel to entirely opaque\n\nprecision highp float;\n\nvarying vec2 vTexCoord;\n\nuniform sampler2D tex0;\n\nvoid main() {\n vec4 color = texture2D(tex0, vTexCoord);\n gl_FragColor = vec4(color.rgb / color.a, 1.0);\n}\n'), _defineProperty(_filterShaderFrags, constants.INVERT, '// Set each pixel to inverse value\n// Note that original INVERT does not change the opacity, so this follows suit\n\nprecision highp float;\n\nvarying vec2 vTexCoord;\n\nuniform sampler2D tex0;\n\nvoid main() {\nvec4 color = texture2D(tex0, vTexCoord);\nvec3 origColor = color.rgb / color.a;\nvec3 invertedColor = vec3(1.0) - origColor;\ngl_FragColor = vec4(invertedColor * color.a, color.a);\n}\n'), _defineProperty(_filterShaderFrags, constants.THRESHOLD, '// Convert pixels to either white or black, \n// depending on if their luma is above or below filterParameter\n\nprecision highp float;\n\nvarying vec2 vTexCoord;\n\nuniform sampler2D tex0;\nuniform float filterParameter;\n\nfloat luma(vec3 color) {\n // weighted grayscale with luminance values\n return dot(color, vec3(0.2126, 0.7152, 0.0722));\n}\n\nvoid main() {\n vec4 color = texture2D(tex0, vTexCoord);\n float gray = luma(color.rgb / color.a);\n // floor() used to match src/image/filters.js\n float threshold = floor(filterParameter * 255.0) / 255.0;\n float blackOrWhite = step(threshold, gray);\n gl_FragColor = vec4(vec3(blackOrWhite) * color.a, color.a);\n}\n'), _filterShaderFrags); + var filterShaderVert = 'uniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nattribute vec3 aPosition;\n// texcoords only come from p5 to vertex shader\n// so pass texcoords on to the fragment shader in a varying variable\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n // transferring texcoords for the frag shader\n vTexCoord = aTexCoord;\n\n // copy position with a fourth coordinate for projection (1.0 is normal)\n vec4 positionVec4 = vec4(aPosition, 1.0);\n\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n'; /** * @module Rendering * @submodule Rendering @@ -103963,6 +116643,11 @@ * lighting shader otherwise per-vertex lighting is used. * default is true. * + * version - either 1 or 2, to specify which WebGL version to ask for. By + * default, WebGL 2 will be requested. If WebGL2 is not available, it will + * fall back to WebGL 1. You can check what version is used with by looking at + * the global `webglVersion` property. + * * @method setAttributes * @for p5 * @param {String} key Name of attribute @@ -104085,957 +116770,2139 @@ //changing value of previously altered attribute this._glAttributes[key] = value; unchanged = false; - } //setting all attributes with some change + } //setting all attributes with some change + + } else if (key instanceof Object) { + if (this._glAttributes !== key) { + this._glAttributes = key; + unchanged = false; + } + } //@todo_FES + + if (!this._renderer.isP3D || unchanged) { + return; + } + if (!this._setupDone) { + for (var x in this._renderer.retainedMode.geometry) { + if (this._renderer.retainedMode.geometry.hasOwnProperty(x)) { + _main.default._friendlyError('Sorry, Could not set the attributes, you need to call setAttributes() ' + 'before calling the other drawing methods in setup()'); + return; + } + } + } + this.push(); + this._renderer._resetContext(); + this.pop(); + if (this._renderer._curCamera) { + this._renderer._curCamera._renderer = this._renderer; + } + }; + /** + * @private + * @param {Uint8Array|Float32Array|undefined} pixels An existing pixels array to reuse if the size is the same + * @param {WebGLRenderingContext} gl The WebGL context + * @param {WebGLFramebuffer|null} framebuffer The Framebuffer to read + * @param {Number} x The x coordiante to read, premultiplied by pixel density + * @param {Number} y The y coordiante to read, premultiplied by pixel density + * @param {Number} width The width in pixels to be read (factoring in pixel density) + * @param {Number} height The height in pixels to be read (factoring in pixel density) + * @param {GLEnum} format Either RGB or RGBA depending on how many channels to read + * @param {GLEnum} type The datatype of each channel, e.g. UNSIGNED_BYTE or FLOAT + * @param {Number|undefined} flipY If provided, the total height with which to flip the y axis about + * @returns {Uint8Array|Float32Array} pixels A pixels array with the current state of the + * WebGL context read into it + */ + function readPixelsWebGL(pixels, gl, framebuffer, x, y, width, height, format, type, flipY) { + // Record the currently bound framebuffer so we can go back to it after, and + // bind the framebuffer we want to read from + var prevFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING); + gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); + var channels = format === gl.RGBA ? 4 : 3; + // Make a pixels buffer if it doesn't already exist + var len = width * height * channels; + var TypedArrayClass = type === gl.UNSIGNED_BYTE ? Uint8Array : Float32Array; + if (!(pixels instanceof TypedArrayClass) || pixels.length !== len) { + pixels = new TypedArrayClass(len); + } + gl.readPixels(x, flipY ? flipY - y - height : y, width, height, format, type, pixels); + // Re-bind whatever was previously bound + gl.bindFramebuffer(gl.FRAMEBUFFER, prevFramebuffer); + if (flipY) { + // WebGL pixels are inverted compared to 2D pixels, so we have to flip + // the resulting rows. Adapted from https://stackoverflow.com/a/41973289 + var halfHeight = Math.floor(height / 2); + var tmpRow = new TypedArrayClass(width * channels); + for (var _y = 0; _y < halfHeight; _y++) { + var topOffset = _y * width * 4; + var bottomOffset = (height - _y - 1) * width * 4; + tmpRow.set(pixels.subarray(topOffset, topOffset + width * 4)); + pixels.copyWithin(topOffset, bottomOffset, bottomOffset + width * 4); + pixels.set(tmpRow, bottomOffset); + } + } + return pixels; + } /** + * @private + * @param {WebGLRenderingContext} gl The WebGL context + * @param {WebGLFramebuffer|null} framebuffer The Framebuffer to read + * @param {Number} x The x coordinate to read, premultiplied by pixel density + * @param {Number} y The y coordinate to read, premultiplied by pixel density + * @param {GLEnum} format Either RGB or RGBA depending on how many channels to read + * @param {GLEnum} type The datatype of each channel, e.g. UNSIGNED_BYTE or FLOAT + * @param {Number|undefined} flipY If provided, the total height with which to flip the y axis about + * @returns {Number[]} pixels The channel data for the pixel at that location + */ + + function readPixelWebGL(gl, framebuffer, x, y, format, type, flipY) { + // Record the currently bound framebuffer so we can go back to it after, and + // bind the framebuffer we want to read from + var prevFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING); + gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); + var channels = format === gl.RGBA ? 4 : 3; + var TypedArrayClass = type === gl.UNSIGNED_BYTE ? Uint8Array : Float32Array; + var pixels = new TypedArrayClass(channels); + gl.readPixels(x, flipY ? flipY - y - 1 : y, 1, 1, format, type, pixels); + // Re-bind whatever was previously bound + gl.bindFramebuffer(gl.FRAMEBUFFER, prevFramebuffer); + return Array.from(pixels); + } /** + * 3D graphics class + * @private + * @class p5.RendererGL + * @constructor + * @extends p5.Renderer + * @todo extend class to include public method for offscreen + * rendering (FBO). + */ + + _main.default.RendererGL = /*#__PURE__*/ function (_p5$Renderer) { + _inherits(RendererGL, _p5$Renderer); + var _super = _createSuper(RendererGL); + function RendererGL(elt, pInst, isMainCanvas, attr) { + var _this; + _classCallCheck(this, RendererGL); + _this = _super.call(this, elt, pInst, isMainCanvas); + _this._setAttributeDefaults(pInst); + _this._initContext(); + _this.isP3D = true; //lets us know we're in 3d mode + // When constructing a new p5.Geometry, this will represent the builder + _this.geometryBuilder = undefined; + // This redundant property is useful in reminding you that you are + // interacting with WebGLRenderingContext, still worth considering future removal + _this.GL = _this.drawingContext; + _this._pInst._setProperty('drawingContext', _this.drawingContext); + // erasing + _this._isErasing = false; + // clipping + _this._clipDepths = [ + ]; + _this._isClipApplied = false; + _this._stencilTestOn = false; + // lights + _this._enableLighting = false; + _this.ambientLightColors = [ + ]; + _this.specularColors = [ + 1, + 1, + 1 + ]; + _this.directionalLightDirections = [ + ]; + _this.directionalLightDiffuseColors = [ + ]; + _this.directionalLightSpecularColors = [ + ]; + _this.pointLightPositions = [ + ]; + _this.pointLightDiffuseColors = [ + ]; + _this.pointLightSpecularColors = [ + ]; + _this.spotLightPositions = [ + ]; + _this.spotLightDirections = [ + ]; + _this.spotLightDiffuseColors = [ + ]; + _this.spotLightSpecularColors = [ + ]; + _this.spotLightAngle = [ + ]; + _this.spotLightConc = [ + ]; + // This property contains the input image if imageLight function + // is called. + // activeImageLight is checked by _setFillUniforms + // for sending uniforms to the fillshader + _this.activeImageLight = null; + // If activeImageLight property is Null, diffusedTextures, + // specularTextures are Empty. + // Else, it maps a p5.Image used by imageLight() to a p5.Graphics. + // p5.Graphics for this are calculated in getDiffusedTexture function + _this.diffusedTextures = new Map(); + // p5.Graphics for this are calculated in getSpecularTexture function + _this.specularTextures = new Map(); + _this.drawMode = constants.FILL; + _this.curFillColor = _this._cachedFillStyle = [ + 1, + 1, + 1, + 1 + ]; + _this.curAmbientColor = _this._cachedFillStyle = [ + 1, + 1, + 1, + 1 + ]; + _this.curSpecularColor = _this._cachedFillStyle = [ + 0, + 0, + 0, + 0 + ]; + _this.curEmissiveColor = _this._cachedFillStyle = [ + 0, + 0, + 0, + 0 + ]; + _this.curStrokeColor = _this._cachedStrokeStyle = [ + 0, + 0, + 0, + 1 + ]; + _this.curBlendMode = constants.BLEND; + _this._cachedBlendMode = undefined; + if (_this.webglVersion === constants.WEBGL2) { + _this.blendExt = _this.GL; + } else { + _this.blendExt = _this.GL.getExtension('EXT_blend_minmax'); + } + _this._isBlending = false; + _this._hasSetAmbient = false; + _this._useSpecularMaterial = false; + _this._useEmissiveMaterial = false; + _this._useNormalMaterial = false; + _this._useShininess = 1; + _this._useLineColor = false; + _this._useVertexColor = false; + _this.registerEnabled = new Set(); + _this._tint = [ + 255, + 255, + 255, + 255 + ]; + // lightFalloff variables + _this.constantAttenuation = 1; + _this.linearAttenuation = 0; + _this.quadraticAttenuation = 0; + /** + * model view, projection, & normal + * matrices + */ + _this.uMVMatrix = new _main.default.Matrix(); + _this.uPMatrix = new _main.default.Matrix(); + _this.uNMatrix = new _main.default.Matrix('mat3'); + // Current vertex normal + _this._currentNormal = new _main.default.Vector(0, 0, 1); + // Camera + _this._curCamera = new _main.default.Camera(_assertThisInitialized(_this)); + _this._curCamera._computeCameraDefaultSettings(); + _this._curCamera._setDefaultCamera(); + // FilterCamera + _this.filterCamera = new _main.default.Camera(_assertThisInitialized(_this)); + _this.filterCamera._computeCameraDefaultSettings(); + _this.filterCamera._setDefaultCamera(); + // Information about the previous frame's touch object + // for executing orbitControl() + _this.prevTouches = [ + ]; + // Velocity variable for use with orbitControl() + _this.zoomVelocity = 0; + _this.rotateVelocity = new _main.default.Vector(0, 0); + _this.moveVelocity = new _main.default.Vector(0, 0); + // Flags for recording the state of zooming, rotation and moving + _this.executeZoom = false; + _this.executeRotateAndMove = false; + _this._defaultLightShader = undefined; + _this._defaultImmediateModeShader = undefined; + _this._defaultNormalShader = undefined; + _this._defaultColorShader = undefined; + _this._defaultPointShader = undefined; + _this.userFillShader = undefined; + _this.userStrokeShader = undefined; + _this.userPointShader = undefined; + // Default drawing is done in Retained Mode + // Geometry and Material hashes stored here + _this.retainedMode = { + geometry: { + }, + buffers: { + stroke: [ + new _main.default.RenderBuffer(4, 'lineVertexColors', 'lineColorBuffer', 'aVertexColor', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(3, 'lineVertices', 'lineVerticesBuffer', 'aPosition', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(3, 'lineTangentsIn', 'lineTangentsInBuffer', 'aTangentIn', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(3, 'lineTangentsOut', 'lineTangentsOutBuffer', 'aTangentOut', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(1, 'lineSides', 'lineSidesBuffer', 'aSide', _assertThisInitialized(_this)) + ], + fill: [ + new _main.default.RenderBuffer(3, 'vertices', 'vertexBuffer', 'aPosition', _assertThisInitialized(_this), _this._vToNArray), + new _main.default.RenderBuffer(3, 'vertexNormals', 'normalBuffer', 'aNormal', _assertThisInitialized(_this), _this._vToNArray), + new _main.default.RenderBuffer(4, 'vertexColors', 'colorBuffer', 'aVertexColor', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(3, 'vertexAmbients', 'ambientBuffer', 'aAmbientColor', _assertThisInitialized(_this)), + //new BufferDef(3, 'vertexSpeculars', 'specularBuffer', 'aSpecularColor'), + new _main.default.RenderBuffer(2, 'uvs', 'uvBuffer', 'aTexCoord', _assertThisInitialized(_this), _this._flatten) + ], + text: [ + new _main.default.RenderBuffer(3, 'vertices', 'vertexBuffer', 'aPosition', _assertThisInitialized(_this), _this._vToNArray), + new _main.default.RenderBuffer(2, 'uvs', 'uvBuffer', 'aTexCoord', _assertThisInitialized(_this), _this._flatten) + ] + } + }; + // Immediate Mode + // Geometry and Material hashes stored here + _this.immediateMode = { + geometry: new _main.default.Geometry(), + shapeMode: constants.TRIANGLE_FAN, + contourIndices: [ + ], + _bezierVertex: [ + ], + _quadraticVertex: [ + ], + _curveVertex: [ + ], + buffers: { + fill: [ + new _main.default.RenderBuffer(3, 'vertices', 'vertexBuffer', 'aPosition', _assertThisInitialized(_this), _this._vToNArray), + new _main.default.RenderBuffer(3, 'vertexNormals', 'normalBuffer', 'aNormal', _assertThisInitialized(_this), _this._vToNArray), + new _main.default.RenderBuffer(4, 'vertexColors', 'colorBuffer', 'aVertexColor', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(3, 'vertexAmbients', 'ambientBuffer', 'aAmbientColor', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(2, 'uvs', 'uvBuffer', 'aTexCoord', _assertThisInitialized(_this), _this._flatten) + ], + stroke: [ + new _main.default.RenderBuffer(4, 'lineVertexColors', 'lineColorBuffer', 'aVertexColor', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(3, 'lineVertices', 'lineVerticesBuffer', 'aPosition', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(3, 'lineTangentsIn', 'lineTangentsInBuffer', 'aTangentIn', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(3, 'lineTangentsOut', 'lineTangentsOutBuffer', 'aTangentOut', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(1, 'lineSides', 'lineSidesBuffer', 'aSide', _assertThisInitialized(_this)) + ], + point: _this.GL.createBuffer() + } + }; + _this.pointSize = 5; //default point size + _this.curStrokeWeight = 1; + _this.curStrokeCap = constants.ROUND; + _this.curStrokeJoin = constants.ROUND; + // map of texture sources to textures created in this gl context via this.getTexture(src) + _this.textures = new Map(); + // set of framebuffers in use + _this.framebuffers = new Set(); + // stack of active framebuffers + _this.activeFramebuffers = [ + ]; + // for post processing step + _this.filterShader = undefined; + _this.filterLayer = undefined; + _this.filterLayerTemp = undefined; + _this.defaultFilterShaders = { + }; + _this.textureMode = constants.IMAGE; + // default wrap settings + _this.textureWrapX = constants.CLAMP; + _this.textureWrapY = constants.CLAMP; + _this._tex = null; + _this._curveTightness = 6; + // lookUpTable for coefficients needed to be calculated for bezierVertex, same are used for curveVertex + _this._lookUpTableBezier = [ + ]; + // lookUpTable for coefficients needed to be calculated for quadraticVertex + _this._lookUpTableQuadratic = [ + ]; + // current curveDetail in the Bezier lookUpTable + _this._lutBezierDetail = 0; + // current curveDetail in the Quadratic lookUpTable + _this._lutQuadraticDetail = 0; + // Used to distinguish between user calls to vertex() and internal calls + _this.isProcessingVertices = false; + _this._tessy = _this._initTessy(); + _this.fontInfos = { + }; + _this._curShader = undefined; + return _this; + } /** + * Starts creating a new p5.Geometry. Subsequent shapes drawn will be added + * to the geometry and then returned when + * endGeometry() is called. One can also use + * buildGeometry() to pass a function that + * draws shapes. + * + * If you need to draw complex shapes every frame which don't change over time, + * combining them upfront with `beginGeometry()` and `endGeometry()` and then + * drawing that will run faster than repeatedly drawing the individual pieces. + * + * @method beginGeometry + */ + + _createClass(RendererGL, [ + { + key: 'beginGeometry', + value: function beginGeometry() { + if (this.geometryBuilder) { + throw new Error('It looks like `beginGeometry()` is being called while another p5.Geometry is already being build.'); + } + this.geometryBuilder = new _GeometryBuilder.default(this); + } /** + * Finishes creating a new p5.Geometry that was + * started using beginGeometry(). One can also + * use buildGeometry() to pass a function that + * draws shapes. + * + * @method endGeometry + * @returns {p5.Geometry} The model that was built. + */ + + }, + { + key: 'endGeometry', + value: function endGeometry() { + if (!this.geometryBuilder) { + throw new Error('Make sure you call beginGeometry() before endGeometry()!'); + } + var geometry = this.geometryBuilder.finish(); + this.geometryBuilder = undefined; + return geometry; + } /** + * Creates a new p5.Geometry that contains all + * the shapes drawn in a provided callback function. The returned combined shape + * can then be drawn all at once using model(). + * + * If you need to draw complex shapes every frame which don't change over time, + * combining them with `buildGeometry()` once and then drawing that will run + * faster than repeatedly drawing the individual pieces. + * + * One can also draw shapes directly between + * beginGeometry() and + * endGeometry() instead of using a callback + * function. + * + * @method buildGeometry + * @param {Function} callback A function that draws shapes. + * @returns {p5.Geometry} The model that was built from the callback function. + */ + + }, + { + key: 'buildGeometry', + value: function buildGeometry(callback) { + this.beginGeometry(); + callback(); + return this.endGeometry(); + } ////////////////////////////////////////////// + // Setting + ////////////////////////////////////////////// + + }, + { + key: '_setAttributeDefaults', + value: function _setAttributeDefaults(pInst) { + // See issue #3850, safer to enable AA in Safari + var applyAA = navigator.userAgent.toLowerCase().includes('safari'); + var defaults = { + alpha: true, + depth: true, + stencil: true, + antialias: applyAA, + premultipliedAlpha: true, + preserveDrawingBuffer: true, + perPixelLighting: true, + version: 2 + }; + if (pInst._glAttributes === null) { + pInst._glAttributes = defaults; + } else { + pInst._glAttributes = Object.assign(defaults, pInst._glAttributes); + } + return; + } + }, + { + key: '_initContext', + value: function _initContext() { + if (this._pInst._glAttributes.version !== 1) { + // Unless WebGL1 is explicitly asked for, try to create a WebGL2 context + this.drawingContext = this.canvas.getContext('webgl2', this._pInst._glAttributes); + } + this.webglVersion = this.drawingContext ? constants.WEBGL2 : constants.WEBGL; + // If this is the main canvas, make sure the global `webglVersion` is set + this._pInst._setProperty('webglVersion', this.webglVersion); + if (!this.drawingContext) { + // If we were unable to create a WebGL2 context (either because it was + // disabled via `setAttributes({ version: 1 })` or because the device + // doesn't support it), fall back to a WebGL1 context + this.drawingContext = this.canvas.getContext('webgl', this._pInst._glAttributes) || this.canvas.getContext('experimental-webgl', this._pInst._glAttributes); + } + if (this.drawingContext === null) { + throw new Error('Error creating webgl context'); + } else { + var gl = this.drawingContext; + gl.enable(gl.DEPTH_TEST); + gl.depthFunc(gl.LEQUAL); + gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); + // Make sure all images are loaded into the canvas premultiplied so that + // they match the way we render colors. This will make framebuffer textures + // be encoded the same way as textures from everything else. + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true); + this._viewport = this.drawingContext.getParameter(this.drawingContext.VIEWPORT); + } + } //This is helper function to reset the context anytime the attributes + //are changed with setAttributes() + + }, + { + key: '_resetContext', + value: function _resetContext(options, callback) { + var w = this.width; + var h = this.height; + var defaultId = this.canvas.id; + var isPGraphics = this._pInst instanceof _main.default.Graphics; + if (isPGraphics) { + var pg = this._pInst; + pg.canvas.parentNode.removeChild(pg.canvas); + pg.canvas = document.createElement('canvas'); + var node = pg._pInst._userNode || document.body; + node.appendChild(pg.canvas); + _main.default.Element.call(pg, pg.canvas, pg._pInst); + pg.width = w; + pg.height = h; + } else { + var c = this.canvas; + if (c) { + c.parentNode.removeChild(c); + } + c = document.createElement('canvas'); + c.id = defaultId; + if (this._pInst._userNode) { + this._pInst._userNode.appendChild(c); + } else { + document.body.appendChild(c); + } + this._pInst.canvas = c; + this.canvas = c; + } + var renderer = new _main.default.RendererGL(this._pInst.canvas, this._pInst, !isPGraphics); + this._pInst._setProperty('_renderer', renderer); + renderer.resize(w, h); + renderer._applyDefaults(); + if (!isPGraphics) { + this._pInst._elements.push(renderer); + } + if (typeof callback === 'function') { + //setTimeout with 0 forces the task to the back of the queue, this ensures that + //we finish switching out the renderer + setTimeout(function () { + callback.apply(window._renderer, options); + }, 0); + } + } /** + * @class p5.RendererGL + */ + + }, + { + key: '_update', + value: function _update() { + // reset model view and apply initial camera transform + // (containing only look at info; no projection). + this.uMVMatrix.set(this._curCamera.cameraMatrix.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.clearStencil(0); + this.GL.clear(this.GL.DEPTH_BUFFER_BIT | this.GL.STENCIL_BUFFER_BIT); + this.GL.disable(this.GL.STENCIL_TEST); + } /** + * [background description] + */ + + }, + { + key: 'background', + value: function background() { + var _this$_pInst; + var _col = (_this$_pInst = this._pInst).color.apply(_this$_pInst, arguments); + var _r = _col.levels[0] / 255; + var _g = _col.levels[1] / 255; + var _b = _col.levels[2] / 255; + var _a = _col.levels[3] / 255; + this.clear(_r, _g, _b, _a); + } ////////////////////////////////////////////// + // COLOR + ////////////////////////////////////////////// + /** + * Basic fill material for geometry with a given color + * @method fill + * @class p5.RendererGL + * @param {Number|Number[]|String|p5.Color} v1 gray value, + * red or hue value (depending on the current color mode), + * or color Array, or CSS color string + * @param {Number} [v2] green or saturation value + * @param {Number} [v3] blue or brightness value + * @param {Number} [a] opacity + * @chainable + * @example + *
      + * + * function setup() { + * createCanvas(200, 200, WEBGL); + * } + * + * function draw() { + * background(0); + * noStroke(); + * fill(100, 100, 240); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * box(75, 75, 75); + * } + * + *
      + * + * @alt + * black canvas with purple cube spinning + */ + + }, + { + key: 'fill', + value: function fill(v1, v2, v3, a) { + //see material.js for more info on color blending in webgl + var color = _main.default.prototype.color.apply(this._pInst, arguments); + this.curFillColor = color._array; + this.drawMode = constants.FILL; + this._useNormalMaterial = false; + this._tex = null; + } /** + * Basic stroke material for geometry with a given color + * @method stroke + * @param {Number|Number[]|String|p5.Color} v1 gray value, + * red or hue value (depending on the current color mode), + * or color Array, or CSS color string + * @param {Number} [v2] green or saturation value + * @param {Number} [v3] blue or brightness value + * @param {Number} [a] opacity + * @example + *
      + * + * function setup() { + * createCanvas(200, 200, WEBGL); + * } + * + * function draw() { + * background(0); + * stroke(240, 150, 150); + * fill(100, 100, 240); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * box(75, 75, 75); + * } + * + *
      + * + * @alt + * black canvas with purple cube with pink outline spinning + */ + + }, + { + key: 'stroke', + value: function stroke(r, g, b, a) { + var color = _main.default.prototype.color.apply(this._pInst, arguments); + this.curStrokeColor = color._array; + } + }, + { + key: 'strokeCap', + value: function strokeCap(cap) { + this.curStrokeCap = cap; + } + }, + { + key: 'strokeJoin', + value: function strokeJoin(join) { + this.curStrokeJoin = join; + } + }, + { + key: 'getFilterLayer', + value: function getFilterLayer() { + if (!this.filterLayer) { + this.filterLayer = this._pInst.createFramebuffer(); + } + return this.filterLayer; + } + }, + { + key: 'getFilterLayerTemp', + value: function getFilterLayerTemp() { + if (!this.filterLayerTemp) { + this.filterLayerTemp = this._pInst.createFramebuffer(); + } + return this.filterLayerTemp; + } + }, + { + key: 'matchSize', + value: function matchSize(fboToMatch, target) { + if (fboToMatch.width !== target.width || fboToMatch.height !== target.height) { + fboToMatch.resize(target.width, target.height); + } + if (fboToMatch.pixelDensity() !== target.pixelDensity()) { + fboToMatch.pixelDensity(target.pixelDensity()); + } + } + }, + { + key: 'filter', + value: function filter() { + var _this2 = this; + var fbo = this.getFilterLayer(); + // use internal shader for filter constants BLUR, INVERT, etc + var filterParameter = undefined; + var operation = undefined; + if (typeof (arguments.length <= 0 ? undefined : arguments[0]) === 'string') { + var _defaults; + operation = arguments.length <= 0 ? undefined : arguments[0]; + var defaults = (_defaults = { + }, _defineProperty(_defaults, constants.BLUR, 3), _defineProperty(_defaults, constants.POSTERIZE, 4), _defineProperty(_defaults, constants.THRESHOLD, 0.5), _defaults); + var useDefaultParam = operation in defaults && (arguments.length <= 1 ? undefined : arguments[1]) === undefined; + filterParameter = useDefaultParam ? defaults[operation] : arguments.length <= 1 ? undefined : arguments[1]; + // Create and store shader for constants once on initial filter call. + // Need to store multiple in case user calls different filters, + // eg. filter(BLUR) then filter(GRAY) + if (!(operation in this.defaultFilterShaders)) { + this.defaultFilterShaders[operation] = new _main.default.Shader(fbo._renderer, filterShaderVert, filterShaderFrags[operation]); + } + this.filterShader = this.defaultFilterShaders[operation]; + } // use custom user-supplied shader + else { + this.filterShader = arguments.length <= 0 ? undefined : arguments[0]; + } // Setting the target to the framebuffer when applying a filter to a framebuffer. + + var target = this.activeFramebuffer() || this; + // Resize the framebuffer 'fbo' and adjust its pixel density if it doesn't match the target. + this.matchSize(fbo, target); + // Set filterCamera for framebuffers. + if (target !== this) { + this.filterCamera = this.getFilterLayer().createCamera(); + } + fbo.draw(function () { + return _this2._pInst.clear(); + }); // prevent undesirable feedback effects accumulating secretly. + var texelSize = [ + 1 / (target.width * target.pixelDensity()), + 1 / (target.height * target.pixelDensity()) + ]; + // apply blur shader with multiple passes. + if (operation === constants.BLUR) { + // Treating 'tmp' as a framebuffer. + var tmp = this.getFilterLayerTemp(); + // Resize the framebuffer 'tmp' and adjust its pixel density if it doesn't match the target. + this.matchSize(tmp, target); + // setup + this._pInst.push(); + this._pInst.noStroke(); + // draw main to temp buffer + this._pInst.shader(this.filterShader); + this.filterShader.setUniform('texelSize', texelSize); + this.filterShader.setUniform('canvasSize', [ + target.width, + target.height + ]); + this.filterShader.setUniform('radius', Math.max(1, filterParameter)); + // Horiz pass: draw `target` to `tmp` + tmp.draw(function () { + _this2.filterShader.setUniform('direction', [ + 1, + 0 + ]); + _this2.filterShader.setUniform('tex0', target); + _this2._pInst.clear(); + _this2._pInst.shader(_this2.filterShader); + _this2._pInst.rect( - target.width / 2, - target.height / 2, target.width, target.height); + }); + // Vert pass: draw `tmp` to `fbo` + fbo.draw(function () { + _this2.filterShader.setUniform('direction', [ + 0, + 1 + ]); + _this2.filterShader.setUniform('tex0', tmp); + _this2._pInst.clear(); + _this2._pInst.shader(_this2.filterShader); + _this2._pInst.rect( - target.width / 2, - target.height / 2, target.width, target.height); + }); + this._pInst.pop(); + } // every other non-blur shader uses single pass + else { + fbo.draw(function () { + _this2._pInst.noStroke(); + _this2._pInst.shader(_this2.filterShader); + _this2.filterShader.setUniform('tex0', target); + _this2.filterShader.setUniform('texelSize', texelSize); + _this2.filterShader.setUniform('canvasSize', [ + target.width, + target.height + ]); + // filterParameter uniform only used for POSTERIZE, and THRESHOLD + // but shouldn't hurt to always set + _this2.filterShader.setUniform('filterParameter', filterParameter); + _this2._pInst.rect( - target.width / 2, - target.height / 2, target.width, target.height); + }); + } // draw fbo contents onto main renderer. + + this._pInst.push(); + this._pInst.noStroke(); + this.clear(); + this._pInst.push(); + this._pInst.imageMode(constants.CORNER); + this._pInst.blendMode(constants.BLEND); + this.filterCamera._resize(); + this._pInst.setCamera(this.filterCamera); + this._pInst.resetMatrix(); + this._pInst.image(fbo, - this.width / 2, - this.height / 2, this.width, this.height); + this._pInst.pop(); + this._pInst.pop(); + } // Pass this off to the host instance so that we can treat a renderer and a + // framebuffer the same in filter() + + }, + { + key: 'pixelDensity', + value: function pixelDensity(newDensity) { + if (newDensity) { + return this._pInst.pixelDensity(newDensity); + } + return this._pInst.pixelDensity(); + } + }, + { + key: 'blendMode', + value: function blendMode(mode) { + if (mode === constants.DARKEST || mode === constants.LIGHTEST || mode === constants.ADD || mode === constants.BLEND || mode === constants.SUBTRACT || mode === constants.SCREEN || mode === constants.EXCLUSION || mode === constants.REPLACE || mode === constants.MULTIPLY || mode === constants.REMOVE) this.curBlendMode = mode; + else if (mode === constants.BURN || mode === constants.OVERLAY || mode === constants.HARD_LIGHT || mode === constants.SOFT_LIGHT || mode === constants.DODGE) { + console.warn('BURN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, and DODGE only work for blendMode in 2D mode.'); + } + } + }, + { + key: 'erase', + value: function erase(opacityFill, opacityStroke) { + if (!this._isErasing) { + this._cachedBlendMode = this.curBlendMode; + this._isErasing = true; + this.blendMode(constants.REMOVE); + this._cachedFillStyle = this.curFillColor.slice(); + this.curFillColor = [ + 1, + 1, + 1, + opacityFill / 255 + ]; + this._cachedStrokeStyle = this.curStrokeColor.slice(); + this.curStrokeColor = [ + 1, + 1, + 1, + opacityStroke / 255 + ]; + } + } + }, + { + key: 'noErase', + value: function noErase() { + if (this._isErasing) { + this.curFillColor = this._cachedFillStyle.slice(); + this.curStrokeColor = this._cachedStrokeStyle.slice(); + // It's necessary to restore post-erase state. Needs rework + var temp = this.curBlendMode; + this.blendMode(this._cachedBlendMode); + this._cachedBlendMode = temp; // If we don't do this, applyBlendMode() returns null + this._isErasing = false; + this._applyBlendMode(); // This sets _cachedBlendMode back to the original blendmode + } + } + }, + { + key: 'drawTarget', + value: function drawTarget() { + return this.activeFramebuffers[this.activeFramebuffers.length - 1] || this; + } + }, + { + key: 'beginClip', + value: function beginClip() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { + }; + _get(_getPrototypeOf(RendererGL.prototype), 'beginClip', this).call(this, options); + this.drawTarget()._isClipApplied = true; + var gl = this.GL; + gl.clearStencil(0); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.enable(gl.STENCIL_TEST); + this._stencilTestOn = true; + gl.stencilFunc(gl.ALWAYS, // the test + 1, // reference value + 255 // mask + ); + gl.stencilOp(gl.KEEP, // what to do if the stencil test fails + gl.KEEP, // what to do if the depth test fails + gl.REPLACE // what to do if both tests pass + ); + gl.disable(gl.DEPTH_TEST); + this._pInst.push(); + this._pInst.resetShader(); + if (this._doFill) this._pInst.fill(0, 0); + if (this._doStroke) this._pInst.stroke(0, 0); + } + }, + { + key: 'endClip', + value: function endClip() { + this._pInst.pop(); + var gl = this.GL; + gl.stencilOp(gl.KEEP, // what to do if the stencil test fails + gl.KEEP, // what to do if the depth test fails + gl.KEEP // what to do if both tests pass + ); + gl.stencilFunc(this._clipInvert ? gl.EQUAL : gl.NOTEQUAL, // the test + 0, // reference value + 255 // mask + ); + gl.enable(gl.DEPTH_TEST); + // Mark the depth at which the clip has been applied so that we can clear it + // when we pop past this depth + this._clipDepths.push(this._pushPopDepth); + _get(_getPrototypeOf(RendererGL.prototype), 'endClip', this).call(this); + } + }, + { + key: '_clearClip', + value: function _clearClip() { + this.GL.clearStencil(1); + this.GL.clear(this.GL.STENCIL_BUFFER_BIT); + if (this._clipDepths.length > 0) { + this._clipDepths.pop(); + } + this.drawTarget()._isClipApplied = false; + } /** + * Change weight of stroke + * @method strokeWeight + * @param {Number} stroke weight to be used for drawing + * @example + *
      + * + * function setup() { + * createCanvas(200, 400, WEBGL); + * setAttributes('antialias', true); + * } + * + * function draw() { + * background(0); + * noStroke(); + * translate(0, -100, 0); + * stroke(240, 150, 150); + * fill(100, 100, 240); + * push(); + * strokeWeight(8); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * sphere(75); + * pop(); + * push(); + * translate(0, 200, 0); + * strokeWeight(1); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * sphere(75); + * pop(); + * } + * + *
      + * + * @alt + * black canvas with two purple rotating spheres with pink + * outlines the sphere on top has much heavier outlines, + */ + + }, + { + key: 'strokeWeight', + value: function strokeWeight(w) { + if (this.curStrokeWeight !== w) { + this.pointSize = w; + this.curStrokeWeight = w; + } + } // x,y are canvas-relative (pre-scaled by _pixelDensity) + + }, + { + key: '_getPixel', + value: function _getPixel(x, y) { + var gl = this.GL; + return readPixelWebGL(gl, null, x, y, gl.RGBA, gl.UNSIGNED_BYTE, this._pInst.height * this._pInst.pixelDensity()); + } /** + * Loads the pixels data for this canvas into the pixels[] attribute. + * Note that updatePixels() and set() do not work. + * Any pixel manipulation must be done directly to the pixels[] array. + * + * @private + * @method loadPixels + */ + + }, + { + key: 'loadPixels', + value: function loadPixels() { + var pixelsState = this._pixelsState; + //@todo_FES + if (this._pInst._glAttributes.preserveDrawingBuffer !== true) { + console.log('loadPixels only works in WebGL when preserveDrawingBuffer ' + 'is true.'); + return; + } + var pd = this._pInst._pixelDensity; + var gl = this.GL; + pixelsState._setProperty('pixels', readPixelsWebGL(pixelsState.pixels, gl, null, 0, 0, this.width * pd, this.height * pd, gl.RGBA, gl.UNSIGNED_BYTE, this.height * pd)); + } + }, + { + key: 'updatePixels', + value: function updatePixels() { + var fbo = this._getTempFramebuffer(); + fbo.pixels = this._pixelsState.pixels; + fbo.updatePixels(); + this._pInst.push(); + this._pInst.resetMatrix(); + this._pInst.clear(); + this._pInst.imageMode(constants.CENTER); + this._pInst.image(fbo, 0, 0); + this._pInst.pop(); + this.GL.clearDepth(1); + this.GL.clear(this.GL.DEPTH_BUFFER_BIT); + } /** + * @private + * @returns {p5.Framebuffer} A p5.Framebuffer set to match the size and settings + * of the renderer's canvas. It will be created if it does not yet exist, and + * reused if it does. + */ + + }, + { + key: '_getTempFramebuffer', + value: function _getTempFramebuffer() { + if (!this._tempFramebuffer) { + this._tempFramebuffer = this._pInst.createFramebuffer({ + format: constants.UNSIGNED_BYTE, + useDepth: this._pInst._glAttributes.depth, + depthFormat: constants.UNSIGNED_INT, + antialias: this._pInst._glAttributes.antialias + }); + } + return this._tempFramebuffer; + } ////////////////////////////////////////////// + // HASH | for geometry + ////////////////////////////////////////////// + + }, + { + key: 'geometryInHash', + value: function geometryInHash(gId) { + return this.retainedMode.geometry[gId] !== undefined; + } + }, + { + key: 'viewport', + value: function viewport(w, h) { + this._viewport = [ + 0, + 0, + w, + h + ]; + this.GL.viewport(0, 0, w, h); + } /** + * [resize description] + * @private + * @param {Number} w [description] + * @param {Number} h [description] + */ + + }, + { + key: 'resize', + value: function resize(w, h) { + _main.default.Renderer.prototype.resize.call(this, w, h); + this._origViewport = { + width: this.GL.drawingBufferWidth, + height: this.GL.drawingBufferHeight + }; + this.viewport(this._origViewport.width, this._origViewport.height); + this._curCamera._resize(); + //resize pixels buffer + var pixelsState = this._pixelsState; + if (typeof pixelsState.pixels !== 'undefined') { + pixelsState._setProperty('pixels', new Uint8Array(this.GL.drawingBufferWidth * this.GL.drawingBufferHeight * 4)); + } + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = this.framebuffers[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var framebuffer = _step.value; + // Notify framebuffers of the resize so that any auto-sized framebuffers + // can also update their size + framebuffer._canvasSizeChanged(); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } /** + * clears color and depth buffers + * with r,g,b,a + * @private + * @param {Number} r normalized red val. + * @param {Number} g normalized green val. + * @param {Number} b normalized blue val. + * @param {Number} a normalized alpha val. + */ + + }, + { + key: 'clear', + value: function clear() { + var _r = (arguments.length <= 0 ? undefined : arguments[0]) || 0; + var _g = (arguments.length <= 1 ? undefined : arguments[1]) || 0; + var _b = (arguments.length <= 2 ? undefined : arguments[2]) || 0; + var _a = (arguments.length <= 3 ? undefined : arguments[3]) || 0; + var activeFramebuffer = this.activeFramebuffer(); + if (activeFramebuffer && activeFramebuffer.format === constants.UNSIGNED_BYTE && !activeFramebuffer.antialias && _a === 0) { + // Drivers on Intel Macs check for 0,0,0,0 exactly when drawing to a + // framebuffer and ignore the command if it's the only drawing command to + // the framebuffer. To work around it, we can set the alpha to a value so + // low that it still rounds down to 0, but that circumvents the buggy + // check in the driver. + _a = 1e-10; + } + this.GL.clearColor(_r * _a, _g * _a, _b * _a, _a); + this.GL.clearDepth(1); + this.GL.clear(this.GL.COLOR_BUFFER_BIT | this.GL.DEPTH_BUFFER_BIT); + } + }, + { + key: 'applyMatrix', + value: function applyMatrix(a, b, c, d, e, f) { + if (arguments.length === 16) { + _main.default.Matrix.prototype.apply.apply(this.uMVMatrix, arguments); + } else { + this.uMVMatrix.apply([a, + b, + 0, + 0, + c, + d, + 0, + 0, + 0, + 0, + 1, + 0, + e, + f, + 0, + 1]); + } + } /** + * [translate description] + * @private + * @param {Number} x [description] + * @param {Number} y [description] + * @param {Number} z [description] + * @chainable + * @todo implement handle for components or vector as args + */ + + }, + { + key: 'translate', + value: function translate(x, y, z) { + if (x instanceof _main.default.Vector) { + z = x.z; + y = x.y; + x = x.x; + } + this.uMVMatrix.translate([x, + y, + z]); + return this; + } /** + * Scales the Model View Matrix by a vector + * @private + * @param {Number | p5.Vector | Array} x [description] + * @param {Number} [y] y-axis scalar + * @param {Number} [z] z-axis scalar + * @chainable + */ + + }, + { + key: 'scale', + value: function scale(x, y, z) { + this.uMVMatrix.scale(x, y, z); + return this; + } + }, + { + key: 'rotate', + value: function rotate(rad, axis) { + if (typeof axis === 'undefined') { + return this.rotateZ(rad); + } + _main.default.Matrix.prototype.rotate.apply(this.uMVMatrix, arguments); + return this; + } + }, + { + key: 'rotateX', + value: function rotateX(rad) { + this.rotate(rad, 1, 0, 0); + return this; + } + }, + { + key: 'rotateY', + value: function rotateY(rad) { + this.rotate(rad, 0, 1, 0); + return this; + } + }, + { + key: 'rotateZ', + value: function rotateZ(rad) { + this.rotate(rad, 0, 0, 1); + return this; + } + }, + { + key: 'push', + value: function push() { + // get the base renderer style + var style = _main.default.Renderer.prototype.push.apply(this); + // add webgl-specific style properties + var properties = style.properties; + properties.uMVMatrix = this.uMVMatrix.copy(); + properties.uPMatrix = this.uPMatrix.copy(); + properties._curCamera = this._curCamera; + // make a copy of the current camera for the push state + // this preserves any references stored using 'createCamera' + this._curCamera = this._curCamera.copy(); + properties.ambientLightColors = this.ambientLightColors.slice(); + properties.specularColors = this.specularColors.slice(); + properties.directionalLightDirections = this.directionalLightDirections.slice(); + properties.directionalLightDiffuseColors = this.directionalLightDiffuseColors.slice(); + properties.directionalLightSpecularColors = this.directionalLightSpecularColors.slice(); + properties.pointLightPositions = this.pointLightPositions.slice(); + properties.pointLightDiffuseColors = this.pointLightDiffuseColors.slice(); + properties.pointLightSpecularColors = this.pointLightSpecularColors.slice(); + properties.spotLightPositions = this.spotLightPositions.slice(); + properties.spotLightDirections = this.spotLightDirections.slice(); + properties.spotLightDiffuseColors = this.spotLightDiffuseColors.slice(); + properties.spotLightSpecularColors = this.spotLightSpecularColors.slice(); + properties.spotLightAngle = this.spotLightAngle.slice(); + properties.spotLightConc = this.spotLightConc.slice(); + properties.userFillShader = this.userFillShader; + properties.userStrokeShader = this.userStrokeShader; + properties.userPointShader = this.userPointShader; + properties.pointSize = this.pointSize; + properties.curStrokeWeight = this.curStrokeWeight; + properties.curStrokeColor = this.curStrokeColor; + properties.curFillColor = this.curFillColor; + properties.curAmbientColor = this.curAmbientColor; + properties.curSpecularColor = this.curSpecularColor; + properties.curEmissiveColor = this.curEmissiveColor; + properties._hasSetAmbient = this._hasSetAmbient; + properties._useSpecularMaterial = this._useSpecularMaterial; + properties._useEmissiveMaterial = this._useEmissiveMaterial; + properties._useShininess = this._useShininess; + properties.constantAttenuation = this.constantAttenuation; + properties.linearAttenuation = this.linearAttenuation; + properties.quadraticAttenuation = this.quadraticAttenuation; + properties._enableLighting = this._enableLighting; + properties._useNormalMaterial = this._useNormalMaterial; + properties._tex = this._tex; + properties.drawMode = this.drawMode; + properties._currentNormal = this._currentNormal; + properties.curBlendMode = this.curBlendMode; + // So that the activeImageLight gets reset in push/pop + properties.activeImageLight = this.activeImageLight; + return style; + } + }, + { + key: 'pop', + value: function pop() { + var _get2; + if (this._clipDepths.length > 0 && this._pushPopDepth === this._clipDepths[this._clipDepths.length - 1]) { + this._clearClip(); + } + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + }(_get2 = _get(_getPrototypeOf(RendererGL.prototype), 'pop', this)).call.apply(_get2, [ + this + ].concat(args)); + this._applyStencilTestIfClipping(); + } + }, + { + key: '_applyStencilTestIfClipping', + value: function _applyStencilTestIfClipping() { + var drawTarget = this.drawTarget(); + if (drawTarget._isClipApplied !== this._stencilTestOn) { + if (drawTarget._isClipApplied) { + this.GL.enable(this.GL.STENCIL_TEST); + this._stencilTestOn = true; + } else { + this.GL.disable(this.GL.STENCIL_TEST); + this._stencilTestOn = false; + } + } + } + }, + { + key: 'resetMatrix', + value: function resetMatrix() { + this.uMVMatrix.set(this._curCamera.cameraMatrix.mat4[0], this._curCamera.cameraMatrix.mat4[1], this._curCamera.cameraMatrix.mat4[2], this._curCamera.cameraMatrix.mat4[3], this._curCamera.cameraMatrix.mat4[4], this._curCamera.cameraMatrix.mat4[5], this._curCamera.cameraMatrix.mat4[6], this._curCamera.cameraMatrix.mat4[7], this._curCamera.cameraMatrix.mat4[8], this._curCamera.cameraMatrix.mat4[9], this._curCamera.cameraMatrix.mat4[10], this._curCamera.cameraMatrix.mat4[11], this._curCamera.cameraMatrix.mat4[12], this._curCamera.cameraMatrix.mat4[13], this._curCamera.cameraMatrix.mat4[14], this._curCamera.cameraMatrix.mat4[15]); + return this; + } ////////////////////////////////////////////// + // SHADER + ////////////////////////////////////////////// + /* + * shaders are created and cached on a per-renderer basis, + * on the grounds that each renderer will have its own gl context + * and the shader must be valid in that context. + */ - } else if (key instanceof Object) { - if (this._glAttributes !== key) { - this._glAttributes = key; - unchanged = false; - } - } //@todo_FES + }, + { + key: '_getImmediateStrokeShader', + value: function _getImmediateStrokeShader() { + // select the stroke shader to use + var stroke = this.userStrokeShader; + if (!stroke || !stroke.isStrokeShader()) { + return this._getLineShader(); + } + return stroke; + } + }, + { + key: '_getRetainedStrokeShader', + value: function _getRetainedStrokeShader() { + return this._getImmediateStrokeShader(); + } /* + * selects which fill shader should be used based on renderer state, + * for use with begin/endShape and immediate vertex mode. + */ - 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; + }, + { + key: '_getImmediateFillShader', + value: function _getImmediateFillShader() { + var fill = this.userFillShader; + if (this._useNormalMaterial) { + if (!fill || !fill.isNormalShader()) { + return this._getNormalShader(); + } + } + if (this._enableLighting) { + if (!fill || !fill.isLightShader()) { + return this._getLightShader(); + } + } else if (this._tex) { + if (!fill || !fill.isTextureShader()) { + return this._getLightShader(); + } + } else if (!fill /*|| !fill.isColorShader()*/ ) { + return this._getImmediateModeShader(); + } + return fill; + } /* + * selects which fill shader should be used based on renderer state + * for retained mode. + */ + + }, + { + key: '_getRetainedFillShader', + value: function _getRetainedFillShader() { + if (this._useNormalMaterial) { + return this._getNormalShader(); + } + var fill = this.userFillShader; + if (this._enableLighting) { + if (!fill || !fill.isLightShader()) { + return this._getLightShader(); + } + } else if (this._tex) { + if (!fill || !fill.isTextureShader()) { + return this._getLightShader(); + } + } else if (!fill /* || !fill.isColorShader()*/ ) { + return this._getColorShader(); + } + return fill; } - } - } - 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.clear(_r, _g, _b, _a); - }; ////////////////////////////////////////////// - // COLOR - ////////////////////////////////////////////// - /** - * Basic fill material for geometry with a given color - * @method fill - * @class p5.RendererGL - * @param {Number|Number[]|String|p5.Color} v1 gray value, - * red or hue value (depending on the current color mode), - * or color Array, or CSS color string - * @param {Number} [v2] green or saturation value - * @param {Number} [v3] blue or brightness value - * @param {Number} [a] opacity - * @chainable - * @example - *
      - * - * function setup() { - * createCanvas(200, 200, WEBGL); - * } - * - * function draw() { - * background(0); - * noStroke(); - * fill(100, 100, 240); - * rotateX(frameCount * 0.01); - * rotateY(frameCount * 0.01); - * box(75, 75, 75); - * } - * - *
      - * - * @alt - * black canvas with purple cube spinning - */ - _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 - *
      - * - * function setup() { - * createCanvas(200, 200, WEBGL); - * } - * - * function draw() { - * background(0); - * stroke(240, 150, 150); - * fill(100, 100, 240); - * rotateX(frameCount * 0.01); - * rotateY(frameCount * 0.01); - * box(75, 75, 75); - * } - * - *
      - * - * @alt - * black canvas with purple cube with pink outline spinning - */ - _main.default.RendererGL.prototype.stroke = function (r, g, b, a) { - var color = _main.default.prototype.color.apply(this._pInst, arguments); - this.curStrokeColor = color._array; - }; - _main.default.RendererGL.prototype.strokeCap = function (cap) { - this.curStrokeCap = cap; - }; - _main.default.RendererGL.prototype.strokeJoin = function (join) { - this.curStrokeJoin = join; - }; - _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 - *
      - * - * function setup() { - * createCanvas(200, 400, WEBGL); - * setAttributes('antialias', true); - * } - * - * function draw() { - * background(0); - * noStroke(); - * translate(0, -100, 0); - * stroke(240, 150, 150); - * fill(100, 100, 240); - * push(); - * strokeWeight(8); - * rotateX(frameCount * 0.01); - * rotateY(frameCount * 0.01); - * sphere(75); - * pop(); - * push(); - * translate(0, 200, 0); - * strokeWeight(1); - * rotateX(frameCount * 0.01); - * rotateY(frameCount * 0.01); - * sphere(75); - * pop(); - * } - * - *
      - * - * @alt - * black canvas with two purple rotating spheres with pink - * outlines the sphere on top has much heavier outlines, - */ - _main.default.RendererGL.prototype.strokeWeight = function (w) { - if (this.curStrokeWeight !== w) { - this.pointSize = w; - this.curStrokeWeight = w; - } - }; // x,y are canvas-relative (pre-scaled by _pixelDensity) - _main.default.RendererGL.prototype._getPixel = function (x, y) { - var imageData, - index; - imageData = new Uint8Array(4); - this.drawingContext.readPixels(x, y, 1, 1, this.drawingContext.RGBA, this.drawingContext.UNSIGNED_BYTE, imageData); - index = 0; - return [imageData[index + 0], - imageData[index + 1], - imageData[index + 2], - imageData[index + 3]]; - }; - /** - * Loads the pixels data for this canvas into the pixels[] attribute. - * Note that updatePixels() and set() do not work. - * Any pixel manipulation must be done directly to the pixels[] array. - * - * @private - * @method loadPixels - */ - _main.default.RendererGL.prototype.loadPixels = function () { - var pixelsState = this._pixelsState; //@todo_FES - if (this._pInst._glAttributes.preserveDrawingBuffer !== true) { - console.log('loadPixels only works in WebGL when preserveDrawingBuffer ' + 'is true.'); - return; - } //if there isn't a renderer-level temporary pixels buffer - //make a new one + }, + { + key: '_getImmediatePointShader', + value: function _getImmediatePointShader() { + // select the point shader to use + var point = this.userPointShader; + if (!point || !point.isPointShader()) { + return this._getPointShader(); + } + return point; + } + }, + { + key: '_getRetainedLineShader', + value: function _getRetainedLineShader() { + return this._getImmediateLineShader(); + } + }, + { + key: '_getLightShader', + value: function _getLightShader() { + if (!this._defaultLightShader) { + if (this._pInst._glAttributes.perPixelLighting) { + this._defaultLightShader = new _main.default.Shader(this, this._webGL2CompatibilityPrefix('vert', 'highp') + defaultShaders.phongVert, this._webGL2CompatibilityPrefix('frag', 'highp') + defaultShaders.phongFrag); + } else { + this._defaultLightShader = new _main.default.Shader(this, this._webGL2CompatibilityPrefix('vert', 'highp') + defaultShaders.lightVert, this._webGL2CompatibilityPrefix('frag', 'highp') + defaultShaders.lightTextureFrag); + } + } + return this._defaultLightShader; + } + }, + { + key: '_getImmediateModeShader', + value: function _getImmediateModeShader() { + if (!this._defaultImmediateModeShader) { + this._defaultImmediateModeShader = new _main.default.Shader(this, this._webGL2CompatibilityPrefix('vert', 'mediump') + defaultShaders.immediateVert, this._webGL2CompatibilityPrefix('frag', 'mediump') + defaultShaders.vertexColorFrag); + } + return this._defaultImmediateModeShader; + } + }, + { + key: '_getNormalShader', + value: function _getNormalShader() { + if (!this._defaultNormalShader) { + this._defaultNormalShader = new _main.default.Shader(this, this._webGL2CompatibilityPrefix('vert', 'mediump') + defaultShaders.normalVert, this._webGL2CompatibilityPrefix('frag', 'mediump') + defaultShaders.normalFrag); + } + return this._defaultNormalShader; + } + }, + { + key: '_getColorShader', + value: function _getColorShader() { + if (!this._defaultColorShader) { + this._defaultColorShader = new _main.default.Shader(this, this._webGL2CompatibilityPrefix('vert', 'mediump') + defaultShaders.normalVert, this._webGL2CompatibilityPrefix('frag', 'mediump') + defaultShaders.basicFrag); + } + return this._defaultColorShader; + } + }, + { + key: '_getPointShader', + value: function _getPointShader() { + if (!this._defaultPointShader) { + this._defaultPointShader = new _main.default.Shader(this, this._webGL2CompatibilityPrefix('vert', 'mediump') + defaultShaders.pointVert, this._webGL2CompatibilityPrefix('frag', 'mediump') + defaultShaders.pointFrag); + } + return this._defaultPointShader; + } + }, + { + key: '_getLineShader', + value: function _getLineShader() { + if (!this._defaultLineShader) { + this._defaultLineShader = new _main.default.Shader(this, this._webGL2CompatibilityPrefix('vert', 'mediump') + defaultShaders.lineVert, this._webGL2CompatibilityPrefix('frag', 'mediump') + defaultShaders.lineFrag); + } + return this._defaultLineShader; + } + }, + { + key: '_getFontShader', + value: function _getFontShader() { + if (!this._defaultFontShader) { + if (this.webglVersion === constants.WEBGL) { + this.GL.getExtension('OES_standard_derivatives'); + } + this._defaultFontShader = new _main.default.Shader(this, this._webGL2CompatibilityPrefix('vert', 'mediump') + defaultShaders.fontVert, this._webGL2CompatibilityPrefix('frag', 'mediump') + defaultShaders.fontFrag); + } + return this._defaultFontShader; + } + }, + { + key: '_webGL2CompatibilityPrefix', + value: function _webGL2CompatibilityPrefix(shaderType, floatPrecision) { + var code = ''; + if (this.webglVersion === constants.WEBGL2) { + code += '#version 300 es\n#define WEBGL2\n'; + } + if (shaderType === 'vert') { + code += '#define VERTEX_SHADER\n'; + } else if (shaderType === 'frag') { + code += '#define FRAGMENT_SHADER\n'; + } + if (floatPrecision) { + code += 'precision '.concat(floatPrecision, ' float;\n'); + } + return code; + } + }, + { + key: '_getEmptyTexture', + value: function _getEmptyTexture() { + if (!this._emptyTexture) { + // a plain white texture RGBA, full alpha, single pixel. + var im = new _main.default.Image(1, 1); + im.set(0, 0, 255); + this._emptyTexture = new _main.default.Texture(this, im); + } + return this._emptyTexture; + } + }, + { + key: 'getTexture', + value: function getTexture(input) { + var src = input; + if (src instanceof _main.default.Framebuffer) { + src = src.color; + } + var texture = this.textures.get(src); + if (texture) { + return texture; + } + var tex = new _main.default.Texture(this, src); + this.textures.set(src, tex); + return tex; + } /* + * used in imageLight, + * To create a blurry image from the input non blurry img, if it doesn't already exist + * Add it to the diffusedTexture map, + * Returns the blurry image + * maps a p5.Image used by imageLight() to a p5.Graphics + */ - var pixels = pixelsState.pixels; - var len = this.GL.drawingBufferWidth * this.GL.drawingBufferHeight * 4; - if (!(pixels instanceof Uint8Array) || pixels.length !== len) { - pixels = new Uint8Array(len); - this._pixelsState._setProperty('pixels', pixels); - } - var pd = this._pInst._pixelDensity; - this.GL.readPixels(0, 0, this.width * pd, this.height * pd, this.GL.RGBA, this.GL.UNSIGNED_BYTE, pixels); - }; ////////////////////////////////////////////// - // HASH | for geometry - ////////////////////////////////////////////// - _main.default.RendererGL.prototype.geometryInHash = function (gId) { - return this.retainedMode.geometry[gId] !== undefined; - }; - /** - * [resize description] - * @private - * @param {Number} w [description] - * @param {Number} h [description] - */ - _main.default.RendererGL.prototype.resize = function (w, h) { - _main.default.Renderer.prototype.resize.call(this, w, h); - this.GL.viewport(0, 0, this.GL.drawingBufferWidth, this.GL.drawingBufferHeight); - this._viewport = this.GL.getParameter(this.GL.VIEWPORT); - this._curCamera._resize(); //resize pixels buffer - var pixelsState = this._pixelsState; - if (typeof pixelsState.pixels !== 'undefined') { - pixelsState._setProperty('pixels', new Uint8Array(this.GL.drawingBufferWidth * this.GL.drawingBufferHeight * 4)); - } - }; - /** - * clears color and depth buffers - * with r,g,b,a - * @private - * @param {Number} r normalized red val. - * @param {Number} g normalized green val. - * @param {Number} b normalized blue val. - * @param {Number} a normalized alpha val. - */ - _main.default.RendererGL.prototype.clear = function () { - var _r = (arguments.length <= 0 ? undefined : arguments[0]) || 0; - var _g = (arguments.length <= 1 ? undefined : arguments[1]) || 0; - var _b = (arguments.length <= 2 ? undefined : arguments[2]) || 0; - var _a = (arguments.length <= 3 ? undefined : arguments[3]) || 0; - this.GL.clearColor(_r * _a, _g * _a, _b * _a, _a); - this.GL.clearDepth(1); - this.GL.clear(this.GL.COLOR_BUFFER_BIT | this.GL.DEPTH_BUFFER_BIT); - }; - _main.default.RendererGL.prototype.applyMatrix = function (a, b, c, d, e, f) { - if (arguments.length === 16) { - _main.default.Matrix.prototype.apply.apply(this.uMVMatrix, arguments); - } else { - this.uMVMatrix.apply([a, - b, - 0, - 0, - c, - d, - 0, - 0, - 0, - 0, - 1, - 0, - e, - f, - 0, - 1]); - } - }; - /** - * [translate description] - * @private - * @param {Number} x [description] - * @param {Number} y [description] - * @param {Number} z [description] - * @chainable - * @todo implement handle for components or vector as args - */ - _main.default.RendererGL.prototype.translate = function (x, y, z) { - if (x instanceof _main.default.Vector) { - z = x.z; - y = x.y; - x = x.x; - } - this.uMVMatrix.translate([x, - y, - z]); - return this; - }; - /** - * Scales the Model View Matrix by a vector - * @private - * @param {Number | p5.Vector | Array} x [description] - * @param {Number} [y] y-axis scalar - * @param {Number} [z] z-axis scalar - * @chainable - */ - _main.default.RendererGL.prototype.scale = function (x, y, z) { - this.uMVMatrix.scale(x, y, z); - return this; - }; - _main.default.RendererGL.prototype.rotate = function (rad, axis) { - if (typeof axis === 'undefined') { - return this.rotateZ(rad); - } - _main.default.Matrix.prototype.rotate.apply(this.uMVMatrix, arguments); - return this; - }; - _main.default.RendererGL.prototype.rotateX = function (rad) { - this.rotate(rad, 1, 0, 0); - return this; - }; - _main.default.RendererGL.prototype.rotateY = function (rad) { - this.rotate(rad, 0, 1, 0); - return this; - }; - _main.default.RendererGL.prototype.rotateZ = function (rad) { - this.rotate(rad, 0, 0, 1); - return this; - }; - _main.default.RendererGL.prototype.push = function () { - // get the base renderer style - var style = _main.default.Renderer.prototype.push.apply(this); // add webgl-specific style properties - var properties = style.properties; - properties.uMVMatrix = this.uMVMatrix.copy(); - properties.uPMatrix = this.uPMatrix.copy(); - properties._curCamera = this._curCamera; // make a copy of the current camera for the push state - // this preserves any references stored using 'createCamera' - this._curCamera = this._curCamera.copy(); - properties.ambientLightColors = this.ambientLightColors.slice(); - properties.specularColors = this.specularColors.slice(); - properties.directionalLightDirections = this.directionalLightDirections.slice(); - properties.directionalLightDiffuseColors = this.directionalLightDiffuseColors.slice(); - properties.directionalLightSpecularColors = this.directionalLightSpecularColors.slice(); - properties.pointLightPositions = this.pointLightPositions.slice(); - properties.pointLightDiffuseColors = this.pointLightDiffuseColors.slice(); - properties.pointLightSpecularColors = this.pointLightSpecularColors.slice(); - properties.spotLightPositions = this.spotLightPositions.slice(); - properties.spotLightDirections = this.spotLightDirections.slice(); - properties.spotLightDiffuseColors = this.spotLightDiffuseColors.slice(); - properties.spotLightSpecularColors = this.spotLightSpecularColors.slice(); - properties.spotLightAngle = this.spotLightAngle.slice(); - properties.spotLightConc = this.spotLightConc.slice(); - properties.userFillShader = this.userFillShader; - properties.userStrokeShader = this.userStrokeShader; - properties.userPointShader = this.userPointShader; - properties.pointSize = this.pointSize; - properties.curStrokeWeight = this.curStrokeWeight; - properties.curStrokeColor = this.curStrokeColor; - properties.curFillColor = this.curFillColor; - properties.curAmbientColor = this.curAmbientColor; - properties.curSpecularColor = this.curSpecularColor; - properties.curEmissiveColor = this.curEmissiveColor; - properties._useSpecularMaterial = this._useSpecularMaterial; - properties._useEmissiveMaterial = this._useEmissiveMaterial; - properties._useShininess = this._useShininess; - properties.constantAttenuation = this.constantAttenuation; - properties.linearAttenuation = this.linearAttenuation; - properties.quadraticAttenuation = this.quadraticAttenuation; - properties._enableLighting = this._enableLighting; - properties._useNormalMaterial = this._useNormalMaterial; - properties._tex = this._tex; - properties.drawMode = this.drawMode; - properties._currentNormal = this._currentNormal; - properties.curBlendMode = this.curBlendMode; - return style; - }; - _main.default.RendererGL.prototype.resetMatrix = function () { - this.uMVMatrix.set(this._curCamera.cameraMatrix.mat4[0], this._curCamera.cameraMatrix.mat4[1], this._curCamera.cameraMatrix.mat4[2], this._curCamera.cameraMatrix.mat4[3], this._curCamera.cameraMatrix.mat4[4], this._curCamera.cameraMatrix.mat4[5], this._curCamera.cameraMatrix.mat4[6], this._curCamera.cameraMatrix.mat4[7], this._curCamera.cameraMatrix.mat4[8], this._curCamera.cameraMatrix.mat4[9], this._curCamera.cameraMatrix.mat4[10], this._curCamera.cameraMatrix.mat4[11], this._curCamera.cameraMatrix.mat4[12], this._curCamera.cameraMatrix.mat4[13], this._curCamera.cameraMatrix.mat4[14], this._curCamera.cameraMatrix.mat4[15]); - return this; - }; ////////////////////////////////////////////// - // SHADER - ////////////////////////////////////////////// - /* - * shaders are created and cached on a per-renderer basis, - * on the grounds that each renderer will have its own gl context - * and the shader must be valid in that context. - */ - _main.default.RendererGL.prototype._getImmediateStrokeShader = function () { - // select the stroke shader to use - var stroke = this.userStrokeShader; - if (!stroke || !stroke.isStrokeShader()) { - return this._getLineShader(); - } - return stroke; - }; - _main.default.RendererGL.prototype._getRetainedStrokeShader = _main.default.RendererGL.prototype._getImmediateStrokeShader; - /* - * selects which fill shader should be used based on renderer state, - * for use with begin/endShape and immediate vertex mode. - */ - _main.default.RendererGL.prototype._getImmediateFillShader = function () { - var fill = this.userFillShader; - if (this._useNormalMaterial) { - if (!fill || !fill.isNormalShader()) { - return this._getNormalShader(); - } - } - if (this._enableLighting) { - if (!fill || !fill.isLightShader()) { - return this._getLightShader(); - } - } else if (this._tex) { - if (!fill || !fill.isTextureShader()) { - return this._getLightShader(); - } - } else if (!fill /*|| !fill.isColorShader()*/ - ) { - return this._getImmediateModeShader(); - } - return fill; - }; - /* - * selects which fill shader should be used based on renderer state - * for retained mode. - */ - _main.default.RendererGL.prototype._getRetainedFillShader = function () { - if (this._useNormalMaterial) { - return this._getNormalShader(); - } - var fill = this.userFillShader; - if (this._enableLighting) { - if (!fill || !fill.isLightShader()) { - return this._getLightShader(); - } - } else if (this._tex) { - if (!fill || !fill.isTextureShader()) { - return this._getLightShader(); - } - } else if (!fill /* || !fill.isColorShader()*/ - ) { - return this._getColorShader(); - } - return fill; - }; - _main.default.RendererGL.prototype._getImmediatePointShader = function () { - // select the point shader to use - var point = this.userPointShader; - if (!point || !point.isPointShader()) { - return this._getPointShader(); - } - return point; - }; - _main.default.RendererGL.prototype._getRetainedLineShader = _main.default.RendererGL.prototype._getImmediateLineShader; - _main.default.RendererGL.prototype._getLightShader = function () { - if (!this._defaultLightShader) { - if (this._pInst._glAttributes.perPixelLighting) { - this._defaultLightShader = new _main.default.Shader(this, defaultShaders.phongVert, defaultShaders.phongFrag); - } else { - this._defaultLightShader = new _main.default.Shader(this, defaultShaders.lightVert, defaultShaders.lightTextureFrag); - } - } - return this._defaultLightShader; - }; - _main.default.RendererGL.prototype._getImmediateModeShader = function () { - if (!this._defaultImmediateModeShader) { - this._defaultImmediateModeShader = new _main.default.Shader(this, defaultShaders.immediateVert, defaultShaders.vertexColorFrag); - } - return this._defaultImmediateModeShader; - }; - _main.default.RendererGL.prototype._getNormalShader = function () { - if (!this._defaultNormalShader) { - this._defaultNormalShader = new _main.default.Shader(this, defaultShaders.normalVert, defaultShaders.normalFrag); - } - return this._defaultNormalShader; - }; - _main.default.RendererGL.prototype._getColorShader = function () { - if (!this._defaultColorShader) { - this._defaultColorShader = new _main.default.Shader(this, defaultShaders.normalVert, defaultShaders.basicFrag); - } - return this._defaultColorShader; - }; - _main.default.RendererGL.prototype._getPointShader = function () { - if (!this._defaultPointShader) { - this._defaultPointShader = new _main.default.Shader(this, defaultShaders.pointVert, defaultShaders.pointFrag); - } - return this._defaultPointShader; - }; - _main.default.RendererGL.prototype._getLineShader = function () { - if (!this._defaultLineShader) { - this._defaultLineShader = new _main.default.Shader(this, defaultShaders.lineVert, defaultShaders.lineFrag); - } - return this._defaultLineShader; - }; - _main.default.RendererGL.prototype._getFontShader = function () { - if (!this._defaultFontShader) { - this.GL.getExtension('OES_standard_derivatives'); - this._defaultFontShader = new _main.default.Shader(this, defaultShaders.fontVert, defaultShaders.fontFrag); - } - return this._defaultFontShader; - }; - _main.default.RendererGL.prototype._getEmptyTexture = function () { - if (!this._emptyTexture) { - // a plain white texture RGBA, full alpha, single pixel. - var im = new _main.default.Image(1, 1); - im.set(0, 0, 255); - this._emptyTexture = new _main.default.Texture(this, im); - } - return this._emptyTexture; - }; - _main.default.RendererGL.prototype.getTexture = function (img) { - var textures = this.textures; - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - try { - for (var _iterator = textures[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var texture = _step.value; - if (texture.src === img) return texture; - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return != null) { - _iterator.return(); + }, + { + key: 'getDiffusedTexture', + value: function getDiffusedTexture(input) { + // if one already exists for a given input image + if (this.diffusedTextures.get(input) != null) { + return this.diffusedTextures.get(input); + } // if not, only then create one + + var newGraphic; // maybe switch to framebuffer + // hardcoded to 200px, because it's going to be blurry and smooth + var smallWidth = 200; + var width = smallWidth; + var height = Math.floor(smallWidth * (input.height / input.width)); + newGraphic = this._pInst.createGraphics(width, height, constants.WEBGL); + // create graphics is like making a new sketch, all functions on main + // sketch it would be available on graphics + var irradiance = newGraphic.createShader(defaultShaders.imageLightVert, defaultShaders.imageLightDiffusedFrag); + newGraphic.shader(irradiance); + irradiance.setUniform('environmentMap', input); + newGraphic.noStroke(); + newGraphic.rectMode(newGraphic.CENTER); + newGraphic.rect(0, 0, newGraphic.width, newGraphic.height); + this.diffusedTextures.set(input, newGraphic); + return newGraphic; + } /* + * used in imageLight, + * To create a texture from the input non blurry image, if it doesn't already exist + * Creating 8 different levels of textures according to different + * sizes and atoring them in `levels` array + * Creating a new Mipmap texture with that `levels` array + * Storing the texture for input image in map called `specularTextures` + * maps the input p5.Image to a p5.MipmapTexture + */ + + }, + { + key: 'getSpecularTexture', + value: function getSpecularTexture(input) { + // check if already exits (there are tex of diff resolution so which one to check) + // currently doing the whole array + if (this.specularTextures.get(input) != null) { + return this.specularTextures.get(input); + } // Hardcoded size + + var size = 512; + var tex; + var levels = [ + ]; + var graphic = this._pInst.createGraphics(size, size, constants.WEBGL); + var count = Math.log(size) / Math.log(2); + graphic.pixelDensity(1); + // currently only 8 levels + // This loop calculates 8 graphics of varying size of canvas + // and corresponding different roughness levels. + // Roughness increases with the decrease in canvas size, + // because rougher surfaces have less detailed/more blurry reflections. + for (var w = size; w >= 1; w /= 2) { + graphic.resizeCanvas(w, w); + var currCount = Math.log(w) / Math.log(2); + var roughness = 1 - currCount / count; + var myShader = graphic.createShader(defaultShaders.imageLightVert, defaultShaders.imageLightSpecularFrag); + graphic.shader(myShader); + graphic.clear(); + myShader.setUniform('environmentMap', input); + myShader.setUniform('roughness', roughness); + graphic.noStroke(); + graphic.plane(w, w); + levels.push(graphic.get().drawingContext.getImageData(0, 0, w, w)); + } + graphic.remove(); + tex = new _p6.MipmapTexture(this, levels, { + }); + this.specularTextures.set(input, tex); + return tex; + } /** + * @method activeFramebuffer + * @private + * @returns {p5.Framebuffer|null} The currently active framebuffer, or null if + * the main canvas is the current draw target. + */ + + }, + { + key: 'activeFramebuffer', + value: function activeFramebuffer() { + return this.activeFramebuffers[this.activeFramebuffers.length - 1] || null; } - } finally { - if (_didIteratorError) { - throw _iteratorError; + }, + { + key: 'createFramebuffer', + value: function createFramebuffer(options) { + return new _main.default.Framebuffer(this, options); } - } - } - var tex = new _main.default.Texture(this, img); - textures.push(tex); - return tex; - }; - _main.default.RendererGL.prototype._setStrokeUniforms = function (strokeShader) { - strokeShader.bindShader(); // set the uniform values - strokeShader.setUniform('uUseLineColor', this._useLineColor); - strokeShader.setUniform('uMaterialColor', this.curStrokeColor); - strokeShader.setUniform('uStrokeWeight', this.curStrokeWeight); - strokeShader.setUniform('uStrokeCap', STROKE_CAP_ENUM[this.curStrokeCap]); - strokeShader.setUniform('uStrokeJoin', STROKE_JOIN_ENUM[this.curStrokeJoin]); - }; - _main.default.RendererGL.prototype._setFillUniforms = function (fillShader) { - fillShader.bindShader(); // TODO: optimize - fillShader.setUniform('uUseVertexColor', this._useVertexColor); - fillShader.setUniform('uMaterialColor', this.curFillColor); - fillShader.setUniform('isTexture', !!this._tex); - if (this._tex) { - fillShader.setUniform('uSampler', this._tex); - } - fillShader.setUniform('uTint', this._tint); - fillShader.setUniform('uAmbientMatColor', this.curAmbientColor); - fillShader.setUniform('uSpecularMatColor', this.curSpecularColor); - fillShader.setUniform('uEmissiveMatColor', this.curEmissiveColor); - fillShader.setUniform('uSpecular', this._useSpecularMaterial); - fillShader.setUniform('uEmissive', this._useEmissiveMaterial); - fillShader.setUniform('uShininess', this._useShininess); - fillShader.setUniform('uUseLighting', this._enableLighting); - var pointLightCount = this.pointLightDiffuseColors.length / 3; - fillShader.setUniform('uPointLightCount', pointLightCount); - fillShader.setUniform('uPointLightLocation', this.pointLightPositions); - fillShader.setUniform('uPointLightDiffuseColors', this.pointLightDiffuseColors); - fillShader.setUniform('uPointLightSpecularColors', this.pointLightSpecularColors); - var directionalLightCount = this.directionalLightDiffuseColors.length / 3; - fillShader.setUniform('uDirectionalLightCount', directionalLightCount); - fillShader.setUniform('uLightingDirection', this.directionalLightDirections); - fillShader.setUniform('uDirectionalDiffuseColors', this.directionalLightDiffuseColors); - fillShader.setUniform('uDirectionalSpecularColors', this.directionalLightSpecularColors); // TODO: sum these here... - var ambientLightCount = this.ambientLightColors.length / 3; - fillShader.setUniform('uAmbientLightCount', ambientLightCount); - fillShader.setUniform('uAmbientColor', this.ambientLightColors); - var spotLightCount = this.spotLightDiffuseColors.length / 3; - fillShader.setUniform('uSpotLightCount', spotLightCount); - fillShader.setUniform('uSpotLightAngle', this.spotLightAngle); - fillShader.setUniform('uSpotLightConc', this.spotLightConc); - fillShader.setUniform('uSpotLightDiffuseColors', this.spotLightDiffuseColors); - fillShader.setUniform('uSpotLightSpecularColors', this.spotLightSpecularColors); - fillShader.setUniform('uSpotLightLocation', this.spotLightPositions); - fillShader.setUniform('uSpotLightDirection', this.spotLightDirections); - fillShader.setUniform('uConstantAttenuation', this.constantAttenuation); - fillShader.setUniform('uLinearAttenuation', this.linearAttenuation); - fillShader.setUniform('uQuadraticAttenuation', this.quadraticAttenuation); - fillShader.bindTextures(); - }; - _main.default.RendererGL.prototype._setPointUniforms = function (pointShader) { - pointShader.bindShader(); // set the uniform values - pointShader.setUniform('uMaterialColor', this.curStrokeColor); // @todo is there an instance where this isn't stroke weight? - // should be they be same var? - pointShader.setUniform('uPointSize', this.pointSize * this._pInst._pixelDensity); - }; - /* Binds a buffer to the drawing context - * when passed more than two arguments it also updates or initializes - * the data associated with the buffer - */ - _main.default.RendererGL.prototype._bindBuffer = function (buffer, target, values, type, usage) { - if (!target) target = this.GL.ARRAY_BUFFER; - this.GL.bindBuffer(target, buffer); - if (values !== undefined) { - var data = new (type || Float32Array) (values); - this.GL.bufferData(target, data, usage || this.GL.STATIC_DRAW); - } - }; /////////////////////////////// - //// UTILITY FUNCTIONS - ////////////////////////////// - _main.default.RendererGL.prototype._arraysEqual = function (a, b) { - var aLength = a.length; - if (aLength !== b.length) return false; - for (var i = 0; i < aLength; i++) { - if (a[i] !== b[i]) return false; - } - return true; - }; - _main.default.RendererGL.prototype._isTypedArray = function (arr) { - var res = false; - res = arr instanceof Float32Array; - res = arr instanceof Float64Array; - res = arr instanceof Int16Array; - res = arr instanceof Uint16Array; - res = arr instanceof Uint32Array; - return res; - }; - /** - * turn a two dimensional array into one dimensional array - * @private - * @param {Array} arr 2-dimensional array - * @return {Array} 1-dimensional array - * [[1, 2, 3],[4, 5, 6]] -> [1, 2, 3, 4, 5, 6] - */ - _main.default.RendererGL.prototype._flatten = function (arr) { - //when empty, return empty - if (arr.length === 0) { - return []; - } else if (arr.length > 20000) { - //big models , load slower to avoid stack overflow - //faster non-recursive flatten via axelduch - //stackoverflow.com/questions/27266550/how-to-flatten-nested-array-in-javascript - var _toString = Object.prototype.toString; - var arrayTypeStr = '[object Array]'; - var result = [ - ]; - var nodes = arr.slice(); - var node; - node = nodes.pop(); - do { - if (_toString.call(node) === arrayTypeStr) { - nodes.push.apply(nodes, _toConsumableArray(node)); - } else { - result.push(node); + }, + { + key: '_setStrokeUniforms', + value: function _setStrokeUniforms(strokeShader) { + strokeShader.bindShader(); + // set the uniform values + strokeShader.setUniform('uUseLineColor', this._useLineColor); + strokeShader.setUniform('uMaterialColor', this.curStrokeColor); + strokeShader.setUniform('uStrokeWeight', this.curStrokeWeight); + strokeShader.setUniform('uStrokeCap', STROKE_CAP_ENUM[this.curStrokeCap]); + strokeShader.setUniform('uStrokeJoin', STROKE_JOIN_ENUM[this.curStrokeJoin]); } - } 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(); + }, + { + key: '_setFillUniforms', + value: function _setFillUniforms(fillShader) { + fillShader.bindShader(); + // TODO: optimize + fillShader.setUniform('uUseVertexColor', this._useVertexColor); + fillShader.setUniform('uMaterialColor', this.curFillColor); + fillShader.setUniform('isTexture', !!this._tex); + if (this._tex) { + fillShader.setUniform('uSampler', this._tex); + } + fillShader.setUniform('uTint', this._tint); + fillShader.setUniform('uHasSetAmbient', this._hasSetAmbient); + fillShader.setUniform('uAmbientMatColor', this.curAmbientColor); + fillShader.setUniform('uSpecularMatColor', this.curSpecularColor); + fillShader.setUniform('uEmissiveMatColor', this.curEmissiveColor); + fillShader.setUniform('uSpecular', this._useSpecularMaterial); + fillShader.setUniform('uEmissive', this._useEmissiveMaterial); + fillShader.setUniform('uShininess', this._useShininess); + this._setImageLightUniforms(fillShader); + fillShader.setUniform('uUseLighting', this._enableLighting); + var pointLightCount = this.pointLightDiffuseColors.length / 3; + fillShader.setUniform('uPointLightCount', pointLightCount); + fillShader.setUniform('uPointLightLocation', this.pointLightPositions); + fillShader.setUniform('uPointLightDiffuseColors', this.pointLightDiffuseColors); + fillShader.setUniform('uPointLightSpecularColors', this.pointLightSpecularColors); + var directionalLightCount = this.directionalLightDiffuseColors.length / 3; + fillShader.setUniform('uDirectionalLightCount', directionalLightCount); + fillShader.setUniform('uLightingDirection', this.directionalLightDirections); + fillShader.setUniform('uDirectionalDiffuseColors', this.directionalLightDiffuseColors); + fillShader.setUniform('uDirectionalSpecularColors', this.directionalLightSpecularColors); + // TODO: sum these here... + var ambientLightCount = this.ambientLightColors.length / 3; + 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(); + } // getting called from _setFillUniforms + + }, + { + key: '_setImageLightUniforms', + value: function _setImageLightUniforms(shader) { + //set uniform values + shader.setUniform('uUseImageLight', this.activeImageLight != null); + // true + if (this.activeImageLight) { + // this.activeImageLight has image as a key + // look up the texture from the diffusedTexture map + var diffusedLight = this.getDiffusedTexture(this.activeImageLight); + shader.setUniform('environmentMapDiffused', diffusedLight); + var specularLight = this.getSpecularTexture(this.activeImageLight); + // In p5js the range of shininess is >= 1, + // Therefore roughness range will be ([0,1]*8)*20 or [0, 160] + // The factor of 8 is because currently the getSpecularTexture + // only calculated 8 different levels of roughness + // The factor of 20 is just to spread up this range so that, + // [1, max] of shininess is converted to [0,160] of roughness + var roughness = 20 / this._useShininess; + shader.setUniform('levelOfDetail', roughness * 8); + shader.setUniform('environmentMapSpecular', specularLight); + } } - } finally { - if (_didIteratorError2) { - throw _iteratorError2; + }, + { + key: '_setPointUniforms', + value: function _setPointUniforms(pointShader) { + pointShader.bindShader(); + // set the uniform values + pointShader.setUniform('uMaterialColor', this.curStrokeColor); + // @todo is there an instance where this isn't stroke weight? + // should be they be same var? + pointShader.setUniform('uPointSize', this.pointSize * this._pInst._pixelDensity); + } /* Binds a buffer to the drawing context + * when passed more than two arguments it also updates or initializes + * the data associated with the buffer + */ + + }, + { + key: '_bindBuffer', + value: function _bindBuffer(buffer, target, values, type, usage) { + if (!target) target = this.GL.ARRAY_BUFFER; + this.GL.bindBuffer(target, buffer); + if (values !== undefined) { + var data = values; + if (values instanceof _main.default.DataArray) { + data = values.dataArray(); + } else if (!(data instanceof (type || Float32Array))) { + data = new (type || Float32Array) (data); + } + this.GL.bufferData(target, data, usage || this.GL.STATIC_DRAW); + } + } /////////////////////////////// + //// UTILITY FUNCTIONS + ////////////////////////////// + + }, + { + key: '_arraysEqual', + value: function _arraysEqual(a, b) { + var aLength = a.length; + if (aLength !== b.length) return false; + return a.every(function (ai, i) { + return ai === b[i]; + }); + } + }, + { + key: '_isTypedArray', + value: function _isTypedArray(arr) { + return [Float32Array, + Float64Array, + Int16Array, + Uint16Array, + Uint32Array].some(function (x) { + return arr instanceof x; + }); + } /** + * turn a two dimensional array into one dimensional array + * @private + * @param {Array} arr 2-dimensional array + * @return {Array} 1-dimensional array + * [[1, 2, 3],[4, 5, 6]] -> [1, 2, 3, 4, 5, 6] + */ + + }, + { + key: '_flatten', + value: function _flatten(arr) { + //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 result = [ + ]; + var nodes = arr.slice(); + var node; + node = nodes.pop(); + do { + if (Array.isArray(node)) { + 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] + */ + + }, + { + key: '_vToNArray', + value: function _vToNArray(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; + } // function to calculate BezierVertex Coefficients + + }, + { + key: '_bezierCoefficients', + value: function _bezierCoefficients(t) { + var t2 = t * t; + var t3 = t2 * t; + var mt = 1 - t; + var mt2 = mt * mt; + var mt3 = mt2 * mt; + return [mt3, + 3 * mt2 * t, + 3 * mt * t2, + t3]; + } // function to calculate QuadraticVertex Coefficients + + }, + { + key: '_quadraticCoefficients', + value: function _quadraticCoefficients(t) { + var t2 = t * t; + var mt = 1 - t; + var mt2 = mt * mt; + return [mt2, + 2 * mt * t, + t2]; + } // function to convert Bezier coordinates to Catmull Rom Splines + + }, + { + key: '_bezierToCatmull', + value: function _bezierToCatmull(w) { + var p1 = w[1]; + var p2 = w[1] + (w[2] - w[0]) / this._curveTightness; + var p3 = w[2] - (w[3] - w[1]) / this._curveTightness; + var p4 = w[2]; + var p = [ + p1, + p2, + p3, + p4 + ]; + return p; + } + }, + { + key: '_initTessy', + value: function _initTessy() { + // function called for each vertex of tesselator output + function vertexCallback(data, polyVertArray) { + for (var i = 0; i < data.length; i++) { + polyVertArray.push(data[i]); + } + } + function begincallback(type) { + if (type !== _libtess.default.primitiveType.GL_TRIANGLES) { + console.log('expected TRIANGLES but got type: '.concat(type)); + } + } + function errorcallback(errno) { + console.log('error callback'); + console.log('error number: '.concat(errno)); + } // callback for when segments intersect and must be split + + function combinecallback(coords, data, weight) { + var result = new Array(_main.default.RendererGL.prototype.tessyVertexSize).fill(0); + for (var i = 0; i < weight.length; i++) { + for (var j = 0; j < result.length; j++) { + if (weight[i] === 0 || !data[i]) continue; + result[j] += data[i][j] * weight[i]; + } + } + return result; + } + function edgeCallback(flag) { + // don't really care about the flag, but need no-strip/no-fan behavior + } + var tessy = new _libtess.default.GluTesselator(); + tessy.gluTessCallback(_libtess.default.gluEnum.GLU_TESS_VERTEX_DATA, vertexCallback); + tessy.gluTessCallback(_libtess.default.gluEnum.GLU_TESS_BEGIN, begincallback); + tessy.gluTessCallback(_libtess.default.gluEnum.GLU_TESS_ERROR, errorcallback); + tessy.gluTessCallback(_libtess.default.gluEnum.GLU_TESS_COMBINE, combinecallback); + tessy.gluTessCallback(_libtess.default.gluEnum.GLU_TESS_EDGE_FLAG, edgeCallback); + tessy.gluTessProperty(_libtess.default.gluEnum.GLU_TESS_WINDING_RULE, _libtess.default.windingRule.GLU_TESS_WINDING_NONZERO); + return tessy; + } + }, + { + key: '_triangulate', + value: function _triangulate(contours) { + // libtess will take 3d verts and flatten to a plane for tesselation. + // libtess is capable of calculating a plane to tesselate on, but + // if all of the vertices have the same z values, we'll just + // assume the face is facing the camera, letting us skip any performance + // issues or bugs in libtess's automatic calculation. + var z = contours[0] ? contours[0][2] : undefined; + var allSameZ = true; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + try { + for (var _iterator3 = contours[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var contour = _step3.value; + for (var j = 0; j < contour.length; j += _main.default.RendererGL.prototype.tessyVertexSize) { + if (contour[j + 2] !== z) { + allSameZ = false; + break; + } + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + if (allSameZ) { + this._tessy.gluTessNormal(0, 0, 1); + } else { + // Let libtess pick a plane for us + this._tessy.gluTessNormal(0, 0, 0); + } + var triangleVerts = [ + ]; + this._tessy.gluTessBeginPolygon(triangleVerts); + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + try { + for (var _iterator4 = contours[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var _contour = _step4.value; + this._tessy.gluTessBeginContour(); + for (var _j = 0; _j < _contour.length; _j += _main.default.RendererGL.prototype.tessyVertexSize) { + var coords = _contour.slice(_j, _j + _main.default.RendererGL.prototype.tessyVertexSize); + this._tessy.gluTessVertex(coords, coords); + } + this._tessy.gluTessEndContour(); + } // finish polygon + + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + this._tessy.gluTessEndPolygon(); + return triangleVerts; } } - } - return ret; - }; + ]); + return RendererGL; + }(_main.default.Renderer); /** * ensures that p5 is using a 3d renderer. throws an error if not. */ _main.default.prototype._assert3d = function (name) { if (!this._renderer.isP3D) throw new Error(''.concat(name, '() is only supported in WEBGL mode. If you\'d like to use 3D graphics and WebGL, see https://p5js.org/examples/form-3d-primitives.html for more information.')); - }; // function to initialize GLU Tesselator - _main.default.RendererGL.prototype.tessyVertexSize = 12; - _main.default.RendererGL.prototype._initTessy = function initTesselator() { - // function called for each vertex of tesselator output - function vertexCallback(data, polyVertArray) { - for (var i = 0; i < data.length; i++) { - polyVertArray[polyVertArray.length] = data[i]; - } - } - function begincallback(type) { - if (type !== _libtess.default.primitiveType.GL_TRIANGLES) { - console.log('expected TRIANGLES but got type: '.concat(type)); - } - } - function errorcallback(errno) { - console.log('error callback'); - console.log('error number: '.concat(errno)); - } // callback for when segments intersect and must be split - - function combinecallback(coords, data, weight) { - var result = new Array(_main.default.RendererGL.prototype.tessyVertexSize).fill(0); - for (var i = 0; i < weight.length; i++) { - for (var j = 0; j < result.length; j++) { - if (weight[i] === 0 || !data[i]) continue; - result[j] += data[i][j] * weight[i]; - } - } - return result; - } - function edgeCallback(flag) { // don't really care about the flag, but need no-strip/no-fan behavior - } - var tessy = new _libtess.default.GluTesselator(); - tessy.gluTessCallback(_libtess.default.gluEnum.GLU_TESS_VERTEX_DATA, vertexCallback); - tessy.gluTessCallback(_libtess.default.gluEnum.GLU_TESS_BEGIN, begincallback); - tessy.gluTessCallback(_libtess.default.gluEnum.GLU_TESS_ERROR, errorcallback); - tessy.gluTessCallback(_libtess.default.gluEnum.GLU_TESS_COMBINE, combinecallback); - tessy.gluTessCallback(_libtess.default.gluEnum.GLU_TESS_EDGE_FLAG, edgeCallback); - return tessy; - }; - _main.default.RendererGL.prototype._triangulate = function (contours) { - // libtess will take 3d verts and flatten to a plane for tesselation. - // libtess is capable of calculating a plane to tesselate on, but - // if all of the vertices have the same z values, we'll just - // assume the face is facing the camera, letting us skip any performance - // issues or bugs in libtess's automatic calculation. - var z = contours[0] ? contours[0][2] : undefined; - var allSameZ = true; - var _iteratorNormalCompletion3 = true; - var _didIteratorError3 = false; - var _iteratorError3 = undefined; - try { - for (var _iterator3 = contours[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { - var _contour = _step3.value; - for (var _j = 0; _j < _contour.length; _j += _main.default.RendererGL.prototype.tessyVertexSize) { - if (_contour[_j + 2] !== z) { - allSameZ = false; - break; - } - } - } - } catch (err) { - _didIteratorError3 = true; - _iteratorError3 = err; - } finally { - try { - if (!_iteratorNormalCompletion3 && _iterator3.return != null) { - _iterator3.return(); - } - } finally { - if (_didIteratorError3) { - throw _iteratorError3; - } - } - } - if (allSameZ) { - this._tessy.gluTessNormal(0, 0, 1); - } else { - // Let libtess pick a plane for us - this._tessy.gluTessNormal(0, 0, 0); - } - var triangleVerts = [ - ]; - this._tessy.gluTessBeginPolygon(triangleVerts); - for (var i = 0; i < contours.length; i++) { - this._tessy.gluTessBeginContour(); - var contour = contours[i]; - for (var j = 0; j < contour.length; j += _main.default.RendererGL.prototype.tessyVertexSize) { - var coords = contour.slice(j, j + _main.default.RendererGL.prototype.tessyVertexSize); - this._tessy.gluTessVertex(coords, coords); - } - this._tessy.gluTessEndContour(); - } // finish polygon - - this._tessy.gluTessEndPolygon(); - return triangleVerts; - }; // function to calculate BezierVertex Coefficients - _main.default.RendererGL.prototype._bezierCoefficients = function (t) { - var t2 = t * t; - var t3 = t2 * t; - var mt = 1 - t; - var mt2 = mt * mt; - var mt3 = mt2 * mt; - return [mt3, - 3 * mt2 * t, - 3 * mt * t2, - t3]; - }; // function to calculate QuadraticVertex Coefficients - _main.default.RendererGL.prototype._quadraticCoefficients = function (t) { - var t2 = t * t; - var mt = 1 - t; - var mt2 = mt * mt; - return [mt2, - 2 * mt * t, - t2]; - }; // function to convert Bezier coordinates to Catmull Rom Splines - _main.default.RendererGL.prototype._bezierToCatmull = function (w) { - var p1 = w[1]; - var p2 = w[1] + (w[2] - w[0]) / this._curveTightness; - var p3 = w[2] - (w[3] - w[1]) / this._curveTightness; - var p4 = w[2]; - var p = [ - p1, - p2, - p3, - p4 - ]; - return p; }; + // function to initialize GLU Tesselator + _main.default.RendererGL.prototype.tessyVertexSize = 12; var _default = _main.default.RendererGL; exports.default = _default; }, { - '../core/constants': 278, - '../core/main': 290, - '../core/p5.Renderer': 293, - './p5.Camera': 338, - './p5.Matrix': 340, - './p5.Shader': 345, - 'core-js/modules/es.array.concat': 167, - 'core-js/modules/es.array.fill': 170, - 'core-js/modules/es.array.filter': 171, - 'core-js/modules/es.array.from': 173, - 'core-js/modules/es.array.includes': 174, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.object.assign': 190, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.to-string': 200, - 'core-js/modules/es.string.includes': 203, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.typed-array.copy-within': 215, - 'core-js/modules/es.typed-array.every': 216, - 'core-js/modules/es.typed-array.fill': 217, - 'core-js/modules/es.typed-array.filter': 218, - 'core-js/modules/es.typed-array.find': 220, - 'core-js/modules/es.typed-array.find-index': 219, - 'core-js/modules/es.typed-array.float32-array': 221, - 'core-js/modules/es.typed-array.float64-array': 222, - 'core-js/modules/es.typed-array.for-each': 223, - 'core-js/modules/es.typed-array.includes': 224, - 'core-js/modules/es.typed-array.index-of': 225, - 'core-js/modules/es.typed-array.int16-array': 226, - 'core-js/modules/es.typed-array.iterator': 228, - 'core-js/modules/es.typed-array.join': 229, - 'core-js/modules/es.typed-array.last-index-of': 230, - 'core-js/modules/es.typed-array.map': 231, - 'core-js/modules/es.typed-array.reduce': 233, - 'core-js/modules/es.typed-array.reduce-right': 232, - 'core-js/modules/es.typed-array.reverse': 234, - 'core-js/modules/es.typed-array.set': 235, - 'core-js/modules/es.typed-array.slice': 236, - 'core-js/modules/es.typed-array.some': 237, - 'core-js/modules/es.typed-array.sort': 238, - 'core-js/modules/es.typed-array.subarray': 239, - 'core-js/modules/es.typed-array.to-locale-string': 240, - 'core-js/modules/es.typed-array.to-string': 241, - 'core-js/modules/es.typed-array.uint16-array': 242, - 'core-js/modules/es.typed-array.uint32-array': 243, - 'core-js/modules/es.typed-array.uint8-array': 244, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248, - 'libtess': 261, - 'path': 264 + '../core/constants': 286, + '../core/main': 298, + '../core/p5.Renderer': 301, + './GeometryBuilder': 342, + './p5.Camera': 347, + './p5.Framebuffer': 349, + './p5.Matrix': 351, + './p5.Shader': 356, + './p5.Texture': 357, + 'core-js/modules/es.array.concat': 169, + 'core-js/modules/es.array.copy-within': 170, + 'core-js/modules/es.array.every': 171, + 'core-js/modules/es.array.fill': 172, + 'core-js/modules/es.array.from': 176, + 'core-js/modules/es.array.includes': 177, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.array.some': 184, + 'core-js/modules/es.map': 187, + 'core-js/modules/es.object.assign': 194, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.get-prototype-of': 198, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.reflect.construct': 202, + 'core-js/modules/es.reflect.get': 203, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.set': 207, + 'core-js/modules/es.string.includes': 209, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.typed-array.copy-within': 223, + 'core-js/modules/es.typed-array.every': 224, + 'core-js/modules/es.typed-array.fill': 225, + 'core-js/modules/es.typed-array.filter': 226, + 'core-js/modules/es.typed-array.find': 228, + 'core-js/modules/es.typed-array.find-index': 227, + 'core-js/modules/es.typed-array.float32-array': 229, + 'core-js/modules/es.typed-array.float64-array': 230, + 'core-js/modules/es.typed-array.for-each': 231, + 'core-js/modules/es.typed-array.includes': 232, + 'core-js/modules/es.typed-array.index-of': 233, + 'core-js/modules/es.typed-array.int16-array': 234, + 'core-js/modules/es.typed-array.iterator': 236, + 'core-js/modules/es.typed-array.join': 237, + 'core-js/modules/es.typed-array.last-index-of': 238, + 'core-js/modules/es.typed-array.map': 239, + 'core-js/modules/es.typed-array.reduce': 241, + 'core-js/modules/es.typed-array.reduce-right': 240, + 'core-js/modules/es.typed-array.reverse': 242, + 'core-js/modules/es.typed-array.set': 243, + 'core-js/modules/es.typed-array.slice': 244, + 'core-js/modules/es.typed-array.some': 245, + 'core-js/modules/es.typed-array.sort': 246, + 'core-js/modules/es.typed-array.subarray': 247, + 'core-js/modules/es.typed-array.to-locale-string': 248, + 'core-js/modules/es.typed-array.to-string': 249, + 'core-js/modules/es.typed-array.uint16-array': 250, + 'core-js/modules/es.typed-array.uint32-array': 251, + 'core-js/modules/es.typed-array.uint8-array': 252, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256, + 'libtess': 269, + 'path': 272 } ], - 345: [ + 356: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -105044,7 +118911,9 @@ _dereq_('core-js/modules/es.array.index-of'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.some'); _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.object.keys'); _dereq_('core-js/modules/es.object.to-string'); _dereq_('core-js/modules/es.string.iterator'); _dereq_('core-js/modules/web.dom-collections.iterator'); @@ -105054,7 +118923,9 @@ _dereq_('core-js/modules/es.array.index-of'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.some'); _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.object.keys'); _dereq_('core-js/modules/es.object.to-string'); _dereq_('core-js/modules/es.string.iterator'); _dereq_('core-js/modules/web.dom-collections.iterator'); @@ -105068,13 +118939,32 @@ default: obj }; - } /** - * This module defines the p5.Shader class - * @module 3D - * @submodule Material - * @for p5 - * @requires core - */ + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } /** + * This module defines the p5.Shader class + * @module 3D + * @submodule Material + * @for p5 + * @requires core + */ /** * Shader class for WEBGL Mode * @class p5.Shader @@ -105085,532 +118975,706 @@ * @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 = { + _main.default.Shader = /*#__PURE__*/ function () { + function _class(renderer, vertSrc, fragSrc) { + _classCallCheck(this, _class); + // TODO: adapt this to not take ids, but rather, + // to take the source for a vertex and fragment shader + // to enable custom shaders at some later date + this._renderer = renderer; + this._vertSrc = vertSrc; + this._fragSrc = fragSrc; + this._vertShader = - 1; + this._fragShader = - 1; + this._glProgram = 0; + this._loadedAttributes = false; + this.attributes = { + }; + this._loadedUniforms = false; + this.uniforms = { }; - uniform.location = gl.getUniformLocation(this._glProgram, uniformInfo.name); - uniform.size = uniformInfo.size; - var uniformName = uniformInfo.name; //uniforms thats are arrays have their name returned as - //someUniform[0] which is a bit silly so we trim it - //off here. The size property tells us that its an array - //so we dont lose any information by doing this - if (uniformInfo.size > 1) { - uniformName = uniformName.substring(0, uniformName.indexOf('[0]')); - } - uniform.name = uniformName; - uniform.type = uniformInfo.type; - uniform._cachedData = undefined; - if (uniform.type === gl.SAMPLER_2D) { - uniform.samplerIndex = samplerIndex; - samplerIndex++; - this.samplers.push(uniform); - } - uniform.isArray = uniformInfo.size > 1 || uniform.type === gl.FLOAT_MAT3 || uniform.type === gl.FLOAT_MAT4 || uniform.type === gl.FLOAT_VEC2 || uniform.type === gl.FLOAT_VEC3 || uniform.type === gl.FLOAT_VEC4 || uniform.type === gl.INT_VEC2 || uniform.type === gl.INT_VEC4 || uniform.type === gl.INT_VEC3; - this.uniforms[uniformName] = uniform; - } - this._loadedUniforms = true; - }; - _main.default.Shader.prototype.compile = function () { // TODO - }; - /** - * initializes (if needed) and binds the shader program. - * @method bindShader - * @private - */ - _main.default.Shader.prototype.bindShader = function () { - this.init(); - if (!this._bound) { - this.useProgram(); - this._bound = true; - this._setMatrixUniforms(); - this.setUniform('uViewport', this._renderer._viewport); - } - }; - /** - * @method unbindShader - * @chainable - * @private - */ - _main.default.Shader.prototype.unbindShader = function () { - if (this._bound) { - this.unbindTextures(); //this._renderer.GL.useProgram(0); ?? this._bound = false; - } - return this; - }; - _main.default.Shader.prototype.bindTextures = function () { - var gl = this._renderer.GL; - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - try { - for (var _iterator = this.samplers[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var uniform = _step.value; - var tex = uniform.texture; - if (tex === undefined) { - // user hasn't yet supplied a texture for this slot. - // (or there may not be one--maybe just lighting), - // so we supply a default texture instead. - tex = this._renderer._getEmptyTexture(); - } - gl.activeTexture(gl.TEXTURE0 + uniform.samplerIndex); - tex.bindTexture(); - tex.update(); - gl.uniform1i(uniform.location, uniform.samplerIndex); - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return != null) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - }; - _main.default.Shader.prototype.updateTextures = function () { - var _iteratorNormalCompletion2 = true; - var _didIteratorError2 = false; - var _iteratorError2 = undefined; - try { - for (var _iterator2 = this.samplers[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { - var uniform = _step2.value; - var tex = uniform.texture; - if (tex) { - tex.update(); - } - } - } catch (err) { - _didIteratorError2 = true; - _iteratorError2 = err; - } finally { - try { - if (!_iteratorNormalCompletion2 && _iterator2.return != null) { - _iterator2.return(); - } - } finally { - if (_didIteratorError2) { - throw _iteratorError2; - } - } - } - }; - _main.default.Shader.prototype.unbindTextures = function () { - var _iteratorNormalCompletion3 = true; - var _didIteratorError3 = false; - var _iteratorError3 = undefined; - try { - for (var _iterator3 = this.samplers[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { - var uniform = _step3.value; - this.setUniform(uniform.name, this._renderer._getEmptyTexture()); - } - } catch (err) { - _didIteratorError3 = true; - _iteratorError3 = err; - } finally { - try { - if (!_iteratorNormalCompletion3 && _iterator3.return != null) { - _iterator3.return(); - } - } finally { - if (_didIteratorError3) { - throw _iteratorError3; - } - } - } - }; - _main.default.Shader.prototype._setMatrixUniforms = function () { - var viewMatrix = this._renderer._curCamera.cameraMatrix; - var projectionMatrix = this._renderer.uPMatrix; - var modelViewMatrix = this._renderer.uMVMatrix; - var modelViewProjectionMatrix = modelViewMatrix.copy(); - modelViewProjectionMatrix.mult(projectionMatrix); - if (this.isStrokeShader()) { - if (this._renderer._curCamera.cameraType === 'default') { - // strokes scale up as they approach camera, default - this.setUniform('uPerspective', 1); - } else { - // strokes have uniform scale regardless of distance from camera - this.setUniform('uPerspective', 0); - } - } - this.setUniform('uViewMatrix', viewMatrix.mat4); - this.setUniform('uProjectionMatrix', projectionMatrix.mat4); - this.setUniform('uModelViewMatrix', modelViewMatrix.mat4); - this.setUniform('uModelViewProjectionMatrix', modelViewProjectionMatrix.mat4); - if (this.uniforms.uNormalMatrix) { - this._renderer.uNMatrix.inverseTranspose(this._renderer.uMVMatrix); - this.setUniform('uNormalMatrix', this._renderer.uNMatrix.mat3); - } - }; - /** - * @method useProgram - * @chainable - * @private - */ - _main.default.Shader.prototype.useProgram = function () { - var gl = this._renderer.GL; - if (this._renderer._curShader !== this) { - gl.useProgram(this._glProgram); - this._renderer._curShader = this; - } - return this; - }; - /** - * Used to set the uniforms of a - * p5.Shader object. - * - * Uniforms are used as a way to provide shader programs - * (which run on the GPU) with values from a sketch - * (which runs on the CPU). - * - * @method setUniform - * @chainable - * @param {String} uniformName the name of the uniform. - * Must correspond to the name used in the vertex and fragment shaders - * @param {Boolean|Number|Number[]|p5.Image|p5.Graphics|p5.MediaElement|p5.Texture} - * data the data to associate with the uniform. The type can be - * a boolean (true/false), a number, an array of numbers, or - * an image (p5.Image, p5.Graphics, p5.MediaElement, p5.Texture) - * - * @example - *
      - * - * // Click within the image to toggle the value of uniforms - * // Note: for an alternative approach to the same example, - * // involving toggling between shaders please refer to: - * // https://p5js.org/reference/#/p5/shader - * - * let grad; - * let showRedGreen = false; - * - * function preload() { - * // note that we are using two instances - * // of the same vertex and fragment shaders - * grad = loadShader('assets/shader.vert', 'assets/shader-gradient.frag'); - * } - * - * function setup() { - * createCanvas(100, 100, WEBGL); - * shader(grad); - * noStroke(); - * - * describe( - * 'canvas toggles between a circular gradient of orange and blue vertically. and a circular gradient of red and green moving horizontally when mouse is clicked/pressed.' - * ); - * } - * - * function draw() { - * // update the offset values for each scenario, - * // moving the "grad" shader in either vertical or - * // horizontal direction each with differing colors - * - * if (showRedGreen === true) { - * grad.setUniform('colorCenter', [1, 0, 0]); - * grad.setUniform('colorBackground', [0, 1, 0]); - * grad.setUniform('offset', [sin(millis() / 2000), 1]); - * } else { - * grad.setUniform('colorCenter', [1, 0.5, 0]); - * grad.setUniform('colorBackground', [0.226, 0, 0.615]); - * grad.setUniform('offset', [0, sin(millis() / 2000) + 1]); - * } - * quad(-1, -1, 1, -1, 1, 1, -1, 1); - * } - * - * function mouseClicked() { - * showRedGreen = !showRedGreen; - * } - * - *
      - * - * @alt - * canvas toggles between a circular gradient of orange and blue vertically. and a circular gradient of red and green moving horizontally when mouse is clicked/pressed. - */ - _main.default.Shader.prototype.setUniform = function (uniformName, data) { - var uniform = this.uniforms[uniformName]; - if (!uniform) { - return; - } - var gl = this._renderer.GL; - if (uniform.isArray) { - if (uniform._cachedData && this._renderer._arraysEqual(uniform._cachedData, data)) { - return; - } else { - uniform._cachedData = data.slice(0); - } - } else if (uniform._cachedData && uniform._cachedData === data) { - return; - } else { - if (Array.isArray(data)) { - uniform._cachedData = data.slice(0); - } else { - uniform._cachedData = data; - } - } - var location = uniform.location; - this.useProgram(); - switch (uniform.type) { - case gl.BOOL: - if (data === true) { - gl.uniform1i(location, 1); - } else { - gl.uniform1i(location, 0); + this.samplers = [ + ]; + } /** + * Creates, compiles, and links the shader based on its + * sources for the vertex and fragment shaders (provided + * to the constructor). Populates known attributes and + * uniforms from the shader. + * @method init + * @chainable + * @private + */ + + _createClass(_class, [ + { + key: 'init', + value: function init() { + if (this._glProgram === 0 /* or context is stale? */ ) { + var gl = this._renderer.GL; + // @todo: once custom shading is allowed, + // friendly error messages should be used here to share + // compiler and linker errors. + //set up the shader by + // 1. creating and getting a gl id for the shader program, + // 2. compliling its vertex & fragment sources, + // 3. linking the vertex and fragment shaders + this._vertShader = gl.createShader(gl.VERTEX_SHADER); + //load in our default vertex shader + gl.shaderSource(this._vertShader, this._vertSrc); + gl.compileShader(this._vertShader); + // if our vertex shader failed compilation? + if (!gl.getShaderParameter(this._vertShader, gl.COMPILE_STATUS)) { + _main.default._friendlyError('Yikes! An error occurred compiling the vertex shader:'.concat(gl.getShaderInfoLog(this._vertShader))); + return null; + } + this._fragShader = gl.createShader(gl.FRAGMENT_SHADER); + //load in our material frag shader + gl.shaderSource(this._fragShader, this._fragSrc); + gl.compileShader(this._fragShader); + // if our frag shader failed compilation? + if (!gl.getShaderParameter(this._fragShader, gl.COMPILE_STATUS)) { + _main.default._friendlyError('Darn! An error occurred compiling the fragment shader:'.concat(gl.getShaderInfoLog(this._fragShader))); + return null; + } + this._glProgram = gl.createProgram(); + gl.attachShader(this._glProgram, this._vertShader); + gl.attachShader(this._glProgram, this._fragShader); + gl.linkProgram(this._glProgram); + if (!gl.getProgramParameter(this._glProgram, gl.LINK_STATUS)) { + _main.default._friendlyError('Snap! Error linking shader program: '.concat(gl.getProgramInfoLog(this._glProgram))); + } + this._loadAttributes(); + this._loadUniforms(); + } + return this; + } /** + * Shaders belong to the main canvas or a p5.Graphics. Once they are compiled, + * they can only be used in the context they were compiled on. + * + * Use this method to make a new copy of a shader that gets compiled on a + * different context. + * + * @method copyToContext + * @param {p5|p5.Graphics} context The graphic or instance to copy this shader to. + * Pass `window` if you need to copy to the main canvas. + * @returns {p5.Shader} A new shader on the target context. + * + * @example + *
      + * + * let graphic = createGraphics(200, 200, WEBGL); + * let graphicShader = graphic.createShader(vert, frag); + * graphic.shader(graphicShader); // Use graphicShader on the graphic + * + * let mainShader = graphicShader.copyToContext(window); + * shader(mainShader); // Use `mainShader` on the main canvas + * + *
      + */ + + }, + { + key: 'copyToContext', + value: function copyToContext(context) { + var shader = new _main.default.Shader(context._renderer, this._vertSrc, this._fragSrc); + shader.ensureCompiledOnContext(context); + return shader; + } /** + * @private + */ + + }, + { + key: 'ensureCompiledOnContext', + value: function ensureCompiledOnContext(context) { + if (this._glProgram !== 0 && this._renderer !== context._renderer) { + throw new Error('The shader being run is attached to a different context. Do you need to copy it to this context first with .copyToContext()?'); + } else if (this._glProgram === 0) { + this._renderer = context._renderer; + this.init(); + } + } /** + * Queries the active attributes for this shader and loads + * their names and locations into the attributes array. + * @method _loadAttributes + * @private + */ + + }, + { + key: '_loadAttributes', + value: function _loadAttributes() { + if (this._loadedAttributes) { + return; + } + this.attributes = { + }; + var gl = this._renderer.GL; + var numAttributes = gl.getProgramParameter(this._glProgram, gl.ACTIVE_ATTRIBUTES); + for (var i = 0; i < numAttributes; ++i) { + var attributeInfo = gl.getActiveAttrib(this._glProgram, i); + var name = attributeInfo.name; + var location = gl.getAttribLocation(this._glProgram, name); + var attribute = { + }; + attribute.name = name; + attribute.location = location; + attribute.index = i; + attribute.type = attributeInfo.type; + attribute.size = attributeInfo.size; + this.attributes[name] = attribute; + } + this._loadedAttributes = true; + } /** + * Queries the active uniforms for this shader and loads + * their names and locations into the uniforms array. + * @method _loadUniforms + * @private + */ + + }, + { + key: '_loadUniforms', + value: function _loadUniforms() { + if (this._loadedUniforms) { + return; + } + var gl = this._renderer.GL; + // Inspect shader and cache uniform info + var numUniforms = gl.getProgramParameter(this._glProgram, gl.ACTIVE_UNIFORMS); + var samplerIndex = 0; + for (var i = 0; i < numUniforms; ++i) { + var uniformInfo = gl.getActiveUniform(this._glProgram, i); + var uniform = { + }; + uniform.location = gl.getUniformLocation(this._glProgram, uniformInfo.name); + uniform.size = uniformInfo.size; + var uniformName = uniformInfo.name; + //uniforms thats are arrays have their name returned as + //someUniform[0] which is a bit silly so we trim it + //off here. The size property tells us that its an array + //so we dont lose any information by doing this + if (uniformInfo.size > 1) { + uniformName = uniformName.substring(0, uniformName.indexOf('[0]')); + } + uniform.name = uniformName; + uniform.type = uniformInfo.type; + uniform._cachedData = undefined; + if (uniform.type === gl.SAMPLER_2D) { + uniform.samplerIndex = samplerIndex; + samplerIndex++; + this.samplers.push(uniform); + } + uniform.isArray = uniformInfo.size > 1 || uniform.type === gl.FLOAT_MAT3 || uniform.type === gl.FLOAT_MAT4 || uniform.type === gl.FLOAT_VEC2 || uniform.type === gl.FLOAT_VEC3 || uniform.type === gl.FLOAT_VEC4 || uniform.type === gl.INT_VEC2 || uniform.type === gl.INT_VEC4 || uniform.type === gl.INT_VEC3; + this.uniforms[uniformName] = uniform; + } + this._loadedUniforms = true; } - break; - case gl.INT: - if (uniform.size > 1) { - data.length && gl.uniform1iv(location, data); - } else { - gl.uniform1i(location, data); + }, + { + key: 'compile', + value: function compile() { + // TODO + } /** + * initializes (if needed) and binds the shader program. + * @method bindShader + * @private + */ + + }, + { + key: 'bindShader', + value: function bindShader() { + this.init(); + if (!this._bound) { + this.useProgram(); + this._bound = true; + this._setMatrixUniforms(); + this.setUniform('uViewport', this._renderer._viewport); + } + } /** + * @method unbindShader + * @chainable + * @private + */ + + }, + { + key: 'unbindShader', + value: function unbindShader() { + if (this._bound) { + this.unbindTextures(); + //this._renderer.GL.useProgram(0); ?? + this._bound = false; + } + return this; } - break; - case gl.FLOAT: - if (uniform.size > 1) { - data.length && gl.uniform1fv(location, data); - } else { - gl.uniform1f(location, data); + }, + { + key: 'bindTextures', + value: function bindTextures() { + var gl = this._renderer.GL; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = this.samplers[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var uniform = _step.value; + var tex = uniform.texture; + if (tex === undefined) { + // user hasn't yet supplied a texture for this slot. + // (or there may not be one--maybe just lighting), + // so we supply a default texture instead. + tex = this._renderer._getEmptyTexture(); + } + gl.activeTexture(gl.TEXTURE0 + uniform.samplerIndex); + tex.bindTexture(); + tex.update(); + gl.uniform1i(uniform.location, uniform.samplerIndex); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } } - 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]); + }, + { + key: 'updateTextures', + value: function updateTextures() { + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + try { + for (var _iterator2 = this.samplers[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var uniform = _step2.value; + var tex = uniform.texture; + if (tex) { + tex.update(); + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } } - 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]); + }, + { + key: 'unbindTextures', + value: function unbindTextures() { + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + try { + for (var _iterator3 = this.samplers[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var uniform = _step3.value; + this.setUniform(uniform.name, this._renderer._getEmptyTexture()); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } } - 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]); + }, + { + key: '_setMatrixUniforms', + value: function _setMatrixUniforms() { + var viewMatrix = this._renderer._curCamera.cameraMatrix; + var projectionMatrix = this._renderer.uPMatrix; + var modelViewMatrix = this._renderer.uMVMatrix; + var modelViewProjectionMatrix = modelViewMatrix.copy(); + modelViewProjectionMatrix.mult(projectionMatrix); + if (this.isStrokeShader()) { + if (this._renderer._curCamera.cameraType === 'default') { + // strokes scale up as they approach camera, default + this.setUniform('uPerspective', 1); + } else { + // strokes have uniform scale regardless of distance from camera + this.setUniform('uPerspective', 0); + } + } + this.setUniform('uViewMatrix', viewMatrix.mat4); + this.setUniform('uProjectionMatrix', projectionMatrix.mat4); + this.setUniform('uModelViewMatrix', modelViewMatrix.mat4); + this.setUniform('uModelViewProjectionMatrix', modelViewProjectionMatrix.mat4); + if (this.uniforms.uNormalMatrix) { + this._renderer.uNMatrix.inverseTranspose(this._renderer.uMVMatrix); + this.setUniform('uNormalMatrix', this._renderer.uNMatrix.mat3); + } + } /** + * @method useProgram + * @chainable + * @private + */ + + }, + { + key: 'useProgram', + value: function useProgram() { + var gl = this._renderer.GL; + if (this._renderer._curShader !== this) { + gl.useProgram(this._glProgram); + this._renderer._curShader = this; + } + return this; + } /** + * Used to set the uniforms of a + * p5.Shader object. + * + * Uniforms are used as a way to provide shader programs + * (which run on the GPU) with values from a sketch + * (which runs on the CPU). + * + * Here are some examples of uniforms you can make: + * - booleans + * - Example: `setUniform('x', true)` becomes `uniform float x` with the value `1.0` + * - numbers + * - Example: `setUniform('x', -2)` becomes `uniform float x` with the value `-2.0` + * - arrays of numbers + * - Example: `setUniform('x', [0, 0.5, 1])` becomes `uniform vec3 x` with the value `vec3(0.0, 0.5, 1.0)` + * - a p5.Image, p5.Graphics, p5.MediaElement, or p5.Texture + * - Example: `setUniform('x', img)` becomes `uniform sampler2D x` + * + * @method setUniform + * @chainable + * @param {String} uniformName the name of the uniform. + * Must correspond to the name used in the vertex and fragment shaders + * @param {Boolean|Number|Number[]|p5.Image|p5.Graphics|p5.MediaElement|p5.Texture} + * data the data to associate with the uniform. The type can be + * a boolean (true/false), a number, an array of numbers, or + * an image (p5.Image, p5.Graphics, p5.MediaElement, p5.Texture) + * + * @example + *
      + * + * // Click within the image to toggle the value of uniforms + * // Note: for an alternative approach to the same example, + * // involving toggling between shaders please refer to: + * // https://p5js.org/reference/#/p5/shader + * + * let grad; + * let showRedGreen = false; + * + * function preload() { + * // note that we are using two instances + * // of the same vertex and fragment shaders + * grad = loadShader('assets/shader.vert', 'assets/shader-gradient.frag'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * shader(grad); + * noStroke(); + * + * describe( + * 'canvas toggles between a circular gradient of orange and blue vertically. and a circular gradient of red and green moving horizontally when mouse is clicked/pressed.' + * ); + * } + * + * function draw() { + * // update the offset values for each scenario, + * // moving the "grad" shader in either vertical or + * // horizontal direction each with differing colors + * + * if (showRedGreen === true) { + * grad.setUniform('colorCenter', [1, 0, 0]); + * grad.setUniform('colorBackground', [0, 1, 0]); + * grad.setUniform('offset', [sin(millis() / 2000), 1]); + * } else { + * grad.setUniform('colorCenter', [1, 0.5, 0]); + * grad.setUniform('colorBackground', [0.226, 0, 0.615]); + * grad.setUniform('offset', [0, sin(millis() / 2000) + 1]); + * } + * quad(-1, -1, 1, -1, 1, 1, -1, 1); + * } + * + * function mouseClicked() { + * showRedGreen = !showRedGreen; + * } + * + *
      + * + * @alt + * canvas toggles between a circular gradient of orange and blue vertically. and a circular gradient of red and green moving horizontally when mouse is clicked/pressed. + */ + + }, + { + key: 'setUniform', + value: function setUniform(uniformName, data) { + var uniform = this.uniforms[uniformName]; + if (!uniform) { + return; + } + var gl = this._renderer.GL; + if (uniform.isArray) { + if (uniform._cachedData && this._renderer._arraysEqual(uniform._cachedData, data)) { + return; + } else { + uniform._cachedData = data.slice(0); + } + } else if (uniform._cachedData && uniform._cachedData === data) { + return; + } else { + if (Array.isArray(data)) { + uniform._cachedData = data.slice(0); + } else { + uniform._cachedData = data; + } + } + var location = uniform.location; + this.useProgram(); + switch (uniform.type) { + case gl.BOOL: + if (data === true) { + gl.uniform1i(location, 1); + } else { + gl.uniform1i(location, 0); + } + break; + case gl.INT: + if (uniform.size > 1) { + data.length && gl.uniform1iv(location, data); + } else { + gl.uniform1i(location, data); + } + break; + case gl.FLOAT: + if (uniform.size > 1) { + data.length && gl.uniform1fv(location, data); + } else { + gl.uniform1f(location, data); + } + break; + case gl.FLOAT_MAT3: + gl.uniformMatrix3fv(location, false, data); + break; + case gl.FLOAT_MAT4: + gl.uniformMatrix4fv(location, false, data); + break; + case gl.FLOAT_VEC2: + if (uniform.size > 1) { + data.length && gl.uniform2fv(location, data); + } else { + gl.uniform2f(location, data[0], data[1]); + } + break; + case gl.FLOAT_VEC3: + if (uniform.size > 1) { + data.length && gl.uniform3fv(location, data); + } else { + gl.uniform3f(location, data[0], data[1], data[2]); + } + break; + case gl.FLOAT_VEC4: + if (uniform.size > 1) { + data.length && gl.uniform4fv(location, data); + } else { + gl.uniform4f(location, data[0], data[1], data[2], data[3]); + } + break; + case gl.INT_VEC2: + if (uniform.size > 1) { + data.length && gl.uniform2iv(location, data); + } else { + gl.uniform2i(location, data[0], data[1]); + } + break; + case gl.INT_VEC3: + if (uniform.size > 1) { + data.length && gl.uniform3iv(location, data); + } else { + gl.uniform3i(location, data[0], data[1], data[2]); + } + break; + case gl.INT_VEC4: + if (uniform.size > 1) { + data.length && gl.uniform4iv(location, data); + } else { + gl.uniform4i(location, data[0], data[1], data[2], data[3]); + } + break; + case gl.SAMPLER_2D: + gl.activeTexture(gl.TEXTURE0 + uniform.samplerIndex); + uniform.texture = data instanceof _main.default.Texture ? data : this._renderer.getTexture(data); + gl.uniform1i(location, uniform.samplerIndex); + if (uniform.texture.src.gifProperties) { + uniform.texture.src._animateGif(this._renderer._pInst); + } + break; + //@todo complete all types + } + return this; + } /* NONE OF THIS IS FAST OR EFFICIENT BUT BEAR WITH ME + * + * these shader "type" query methods are used by various + * facilities of the renderer to determine if changing + * the shader type for the required action (for example, + * do we need to load the default lighting shader if the + * current shader cannot handle lighting?) + * + **/ + + }, + { + key: 'isLightShader', + value: function isLightShader() { + return this.attributes.aNormal !== 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; } - break; - case gl.INT_VEC2: - if (uniform.size > 1) { - data.length && gl.uniform2iv(location, data); - } else { - gl.uniform2i(location, data[0], data[1]); + }, + { + key: 'isNormalShader', + value: function isNormalShader() { + return this.attributes.aNormal !== undefined; } - 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]); + }, + { + key: 'isTextureShader', + value: function isTextureShader() { + return this.samplers.length > 0; } - 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]); + }, + { + key: 'isColorShader', + value: function isColorShader() { + return this.attributes.aVertexColor !== undefined || this.uniforms.uMaterialColor !== undefined; } - break; - case gl.SAMPLER_2D: - gl.activeTexture(gl.TEXTURE0 + uniform.samplerIndex); - uniform.texture = data instanceof _main.default.Texture ? data : this._renderer.getTexture(data); - gl.uniform1i(location, uniform.samplerIndex); - if (uniform.texture.src.gifProperties) { - uniform.texture.src._animateGif(this._renderer._pInst); + }, + { + key: 'isTexLightShader', + value: function isTexLightShader() { + return this.isLightShader() && this.isTextureShader(); } - break; - //@todo complete all types - } - return this; - }; - /* NONE OF THIS IS FAST OR EFFICIENT BUT BEAR WITH ME - * - * these shader "type" query methods are used by various - * facilities of the renderer to determine if changing - * the shader type for the required action (for example, - * do we need to load the default lighting shader if the - * current shader cannot handle lighting?) - * - **/ - _main.default.Shader.prototype.isLightShader = function () { - return this.attributes.aNormal !== undefined || this.uniforms.uUseLighting !== undefined || this.uniforms.uAmbientLightCount !== undefined || this.uniforms.uDirectionalLightCount !== undefined || this.uniforms.uPointLightCount !== undefined || this.uniforms.uAmbientColor !== undefined || this.uniforms.uDirectionalDiffuseColors !== undefined || this.uniforms.uDirectionalSpecularColors !== undefined || this.uniforms.uPointLightLocation !== undefined || this.uniforms.uPointLightDiffuseColors !== undefined || this.uniforms.uPointLightSpecularColors !== undefined || this.uniforms.uLightingDirection !== undefined || this.uniforms.uSpecular !== undefined; - }; - _main.default.Shader.prototype.isNormalShader = function () { - return this.attributes.aNormal !== undefined; - }; - _main.default.Shader.prototype.isTextureShader = function () { - return this.samplers.length > 0; - }; - _main.default.Shader.prototype.isColorShader = function () { - return this.attributes.aVertexColor !== undefined || this.uniforms.uMaterialColor !== undefined; - }; - _main.default.Shader.prototype.isTexLightShader = function () { - return this.isLightShader() && this.isTextureShader(); - }; - _main.default.Shader.prototype.isStrokeShader = function () { - return this.uniforms.uStrokeWeight !== undefined; - }; - /** - * @method enableAttrib - * @chainable - * @private - */ - _main.default.Shader.prototype.enableAttrib = function (attr, size, type, normalized, stride, offset) { - if (attr) { - if (typeof IS_MINIFIED === 'undefined' && this.attributes[attr.name] !== attr) { - console.warn('The attribute "'.concat(attr.name, '"passed to enableAttrib does not belong to this shader.')); - } - var loc = attr.location; - if (loc !== - 1) { - var gl = this._renderer.GL; // Enable register even if it is disabled - if (!this._renderer.registerEnabled[loc]) { - gl.enableVertexAttribArray(loc); // Record register availability - this._renderer.registerEnabled[loc] = true; + }, + { + key: 'isStrokeShader', + value: function isStrokeShader() { + return this.uniforms.uStrokeWeight !== undefined; + } /** + * @method enableAttrib + * @chainable + * @private + */ + + }, + { + key: 'enableAttrib', + value: function enableAttrib(attr, size, type, normalized, stride, offset) { + if (attr) { + if (typeof IS_MINIFIED === 'undefined' && this.attributes[attr.name] !== attr) { + console.warn('The attribute "'.concat(attr.name, '"passed to enableAttrib does not belong to this shader.')); + } + var loc = attr.location; + if (loc !== - 1) { + var gl = this._renderer.GL; + // Enable register even if it is disabled + if (!this._renderer.registerEnabled.has(loc)) { + gl.enableVertexAttribArray(loc); + // Record register availability + this._renderer.registerEnabled.add(loc); + } + this._renderer.GL.vertexAttribPointer(loc, size, type || gl.FLOAT, normalized || false, stride || 0, offset || 0); + } + } + return this; + } /** + * Once all buffers have been bound, this checks to see if there are any + * remaining active attributes, likely left over from previous renders, + * and disables them so that they don't affect rendering. + * @method disableRemainingAttributes + * @private + */ + + }, + { + key: 'disableRemainingAttributes', + value: function disableRemainingAttributes() { + var _this = this; + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + try { + var _loop = function _loop() { + var location = _step4.value; + if (!Object.keys(_this.attributes).some(function (key) { + return _this.attributes[key].location === location; + })) { + _this._renderer.GL.disableVertexAttribArray(location); + _this._renderer.registerEnabled.delete(location); + } + }; + for (var _iterator4 = this._renderer.registerEnabled.values() [Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + _loop(); + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } } - this._renderer.GL.vertexAttribPointer(loc, size, type || gl.FLOAT, normalized || false, stride || 0, offset || 0); } - } - return this; - }; + ]); + return _class; + }(); var _default = _main.default.Shader; exports.default = _default; }, { - '../core/main': 290, - 'core-js/modules/es.array.index-of': 175, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.array.slice': 180, - 'core-js/modules/es.function.name': 183, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/web.dom-collections.iterator': 248 + '../core/main': 298, + 'core-js/modules/es.array.index-of': 178, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.array.slice': 183, + 'core-js/modules/es.array.some': 184, + 'core-js/modules/es.function.name': 186, + 'core-js/modules/es.object.keys': 199, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 346: [ + 357: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -105618,7 +119682,10 @@ _dereq_('core-js/modules/es.symbol.iterator'); _dereq_('core-js/modules/es.array.iterator'); _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.get-prototype-of'); _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.reflect.construct'); + _dereq_('core-js/modules/es.regexp.to-string'); _dereq_('core-js/modules/es.string.iterator'); _dereq_('core-js/modules/es.typed-array.uint8-array'); _dereq_('core-js/modules/es.typed-array.copy-within'); @@ -105699,7 +119766,8 @@ Object.defineProperty(exports, '__esModule', { value: true }); - exports.default = void 0; + exports.checkWebGLCapabilities = checkWebGLCapabilities; + exports.default = exports.MipmapTexture = void 0; var _main = _interopRequireDefault(_dereq_('../core/main')); var constants = _interopRequireWildcard(_dereq_('../core/constants')); function _getRequireWildcardCache() { @@ -105748,20 +119816,103 @@ default: obj }; - } /** - * This module defines the p5.Texture class - * @module 3D - * @submodule Material - * @for p5 - * @requires core - */ + } + function _inherits(subClass, superClass) { + if (typeof superClass !== 'function' && superClass !== null) { + throw new TypeError('Super expression must either be null or a function'); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + if (superClass) _setPrototypeOf(subClass, superClass); + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + return _setPrototypeOf(o, p); + } + function _createSuper(Derived) { + function isNativeReflectConstruct() { + if (typeof Reflect === 'undefined' || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === 'function') return true; + try { + Date.prototype.toString.call(Reflect.construct(Date, [ + ], function () { + })); + return true; + } catch (e) { + return false; + } + } + return function () { + var Super = _getPrototypeOf(Derived), + result; + if (isNativeReflectConstruct()) { + var NewTarget = _getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return _possibleConstructorReturn(this, result); + }; + } + function _possibleConstructorReturn(self, call) { + if (call && (_typeof(call) === 'object' || typeof call === 'function')) { + return call; + } + return _assertThisInitialized(self); + } + function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called'); + } + return self; + } + function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } /** + * This module defines the p5.Texture class + * @module 3D + * @submodule Material + * @for p5 + * @requires core + */ /** * Texture class for WEBGL Mode * @private * @class p5.Texture * @param {p5.RendererGL} renderer an instance of p5.RendererGL that * will provide the GL context for this new p5.Texture - * @param {p5.Image|p5.Graphics|p5.Element|p5.MediaElement|ImageData} [obj] the + * @param {p5.Image|p5.Graphics|p5.Element|p5.MediaElement|ImageData|p5.Framebuffer|p5.FramebufferTexture|ImageData} [obj] the * object containing the image data to store in the texture. * @param {Object} [settings] optional A javascript object containing texture * settings. @@ -105787,323 +119938,459 @@ * formats that are not implemented in p5. Defaults to gl.UNSIGNED_BYTE. */ - _main.default.Texture = function (renderer, obj, settings) { - this._renderer = renderer; - var gl = this._renderer.GL; - settings = settings || { - }; - if (settings.dataType === gl.FLOAT) { - var ext = gl.getExtension('OES_texture_float'); - if (!ext) { - console.log('Oh no, your device doesn\'t support floating point textures!'); - } - var linear = gl.getExtension('OES_texture_float_linear'); - if (!linear) { - console.log('Ack! Your device doesn\'t support linear filtering for floating point textures'); - } - } - this.src = obj; - this.glTex = undefined; - this.glTarget = gl.TEXTURE_2D; - this.glFormat = settings.format || gl.RGBA; - this.mipmaps = false; - this.glMinFilter = settings.minFilter || gl.LINEAR; - this.glMagFilter = settings.magFilter || gl.LINEAR; - this.glWrapS = settings.wrapS || gl.CLAMP_TO_EDGE; - this.glWrapT = settings.wrapT || gl.CLAMP_TO_EDGE; - this.glDataType = settings.dataType || gl.UNSIGNED_BYTE; // used to determine if this texture might need constant updating - // because it is a video or gif. - this.isSrcMediaElement = typeof _main.default.MediaElement !== 'undefined' && obj instanceof _main.default.MediaElement; - this._videoPrevUpdateTime = 0; - this.isSrcHTMLElement = typeof _main.default.Element !== 'undefined' && obj instanceof _main.default.Element && !(obj instanceof _main.default.Graphics) && !(obj instanceof _main.default.Renderer); - this.isSrcP5Image = obj instanceof _main.default.Image; - this.isSrcP5Graphics = obj instanceof _main.default.Graphics; - this.isSrcP5Renderer = obj instanceof _main.default.Renderer; - this.isImageData = typeof ImageData !== 'undefined' && obj instanceof ImageData; - var textureData = this._getTextureDataFromSource(); - this.width = textureData.width; - this.height = textureData.height; - this.init(textureData); - return this; - }; - _main.default.Texture.prototype._getTextureDataFromSource = function () { - var textureData; - if (this.isSrcP5Image) { - // param is a p5.Image - textureData = this.src.canvas; - } else if (this.isSrcMediaElement || this.isSrcP5Graphics || this.isSrcP5Renderer || this.isSrcHTMLElement) { - // if param is a video HTML element - textureData = this.src.elt; - } else if (this.isImageData) { - textureData = this.src; - } - return textureData; - }; - /** - * Initializes common texture parameters, creates a gl texture, - * tries to upload the texture for the first time if data is - * already available. - * @private - * @method init - */ - _main.default.Texture.prototype.init = function (data) { - var gl = this._renderer.GL; - this.glTex = gl.createTexture(); - this.glWrapS = this._renderer.textureWrapX; - this.glWrapT = this._renderer.textureWrapY; - this.setWrapMode(this.glWrapS, this.glWrapT); - this.bindTexture(); //gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, this.glMagFilter); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this.glMinFilter); - if (this.width === 0 || this.height === 0 || this.isSrcMediaElement && !this.src.loadedmetadata) { - // assign a 1×1 empty texture initially, because data is not yet ready, - // so that no errors occur in gl console! - var tmpdata = new Uint8Array([1, - 1, - 1, - 1]); - gl.texImage2D(this.glTarget, 0, gl.RGBA, 1, 1, 0, this.glFormat, this.glDataType, tmpdata); - } else { - // data is ready: just push the texture! - gl.texImage2D(this.glTarget, 0, this.glFormat, this.glFormat, this.glDataType, data); - } - }; - /** - * Checks if the source data for this texture has changed (if it's - * easy to do so) and reuploads the texture if necessary. If it's not - * possible or to expensive to do a calculation to determine wheter or - * not the data has occurred, this method simply re-uploads the texture. - * @method update - */ - _main.default.Texture.prototype.update = function () { - var data = this.src; - if (data.width === 0 || data.height === 0) { - return false; // nothing to do! - } - var textureData = this._getTextureDataFromSource(); - var updated = false; - var gl = this._renderer.GL; // pull texture from data, make sure width & height are appropriate - if (textureData.width !== this.width || textureData.height !== this.height) { - updated = true; // make sure that if the width and height of this.src have changed - // for some reason, we update our metadata and upload the texture again + _main.default.Texture = /*#__PURE__*/ function () { + function Texture(renderer, obj, settings) { + _classCallCheck(this, Texture); + this._renderer = renderer; + var gl = this._renderer.GL; + settings = settings || { + }; + this.src = obj; + this.glTex = undefined; + this.glTarget = gl.TEXTURE_2D; + this.glFormat = settings.format || gl.RGBA; + this.mipmaps = false; + this.glMinFilter = settings.minFilter || gl.LINEAR; + this.glMagFilter = settings.magFilter || gl.LINEAR; + this.glWrapS = settings.wrapS || gl.CLAMP_TO_EDGE; + this.glWrapT = settings.wrapT || gl.CLAMP_TO_EDGE; + this.glDataType = settings.dataType || gl.UNSIGNED_BYTE; + var support = checkWebGLCapabilities(renderer); + if (this.glFormat === gl.HALF_FLOAT && !support.halfFloat) { + console.log('This device does not support dataType HALF_FLOAT. Falling back to FLOAT.'); + this.glDataType = gl.FLOAT; + } + if (this.glFormat === gl.HALF_FLOAT && (this.glMinFilter === gl.LINEAR || this.glMagFilter === gl.LINEAR) && !support.halfFloatLinear) { + console.log('This device does not support linear filtering for dataType FLOAT. Falling back to NEAREST.'); + if (this.glMinFilter === gl.LINEAR) this.glMinFilter = gl.NEAREST; + if (this.glMagFilter === gl.LINEAR) this.glMagFilter = gl.NEAREST; + } + if (this.glFormat === gl.FLOAT && !support.float) { + console.log('This device does not support dataType FLOAT. Falling back to UNSIGNED_BYTE.'); + this.glDataType = gl.UNSIGNED_BYTE; + } + if (this.glFormat === gl.FLOAT && (this.glMinFilter === gl.LINEAR || this.glMagFilter === gl.LINEAR) && !support.floatLinear) { + console.log('This device does not support linear filtering for dataType FLOAT. Falling back to NEAREST.'); + if (this.glMinFilter === gl.LINEAR) this.glMinFilter = gl.NEAREST; + if (this.glMagFilter === gl.LINEAR) this.glMagFilter = gl.NEAREST; + } // used to determine if this texture might need constant updating + // because it is a video or gif. + + this.isSrcMediaElement = typeof _main.default.MediaElement !== 'undefined' && obj instanceof _main.default.MediaElement; + this._videoPrevUpdateTime = 0; + this.isSrcHTMLElement = typeof _main.default.Element !== 'undefined' && obj instanceof _main.default.Element && !(obj instanceof _main.default.Graphics) && !(obj instanceof _main.default.Renderer); + this.isSrcP5Image = obj instanceof _main.default.Image; + this.isSrcP5Graphics = obj instanceof _main.default.Graphics; + this.isSrcP5Renderer = obj instanceof _main.default.Renderer; + this.isImageData = typeof ImageData !== 'undefined' && obj instanceof ImageData; + this.isFramebufferTexture = obj instanceof _main.default.FramebufferTexture; + var textureData = this._getTextureDataFromSource(); this.width = textureData.width; this.height = textureData.height; - if (this.isSrcP5Image) { - data.setModified(false); - } else if (this.isSrcMediaElement || this.isSrcHTMLElement) { - // on the first frame the metadata comes in, the size will be changed - // from 0 to actual size, but pixels may not be available. - // flag for update in a future frame. - // if we don't do this, a paused video, for example, may not - // send the first frame to texture memory. - data.setModified(true); - } - } else if (this.isSrcP5Image) { - // for an image, we only update if the modified field has been set, - // for example, by a call to p5.Image.set - if (data.isModified()) { - updated = true; - data.setModified(false); - } - } else if (this.isSrcMediaElement) { - // for a media element (video), we'll check if the current time in - // the video frame matches the last time. if it doesn't match, the - // video has advanced or otherwise been taken to a new frame, - // and we need to upload it. - if (data.isModified()) { - // p5.MediaElement may have also had set/updatePixels, etc. called - // on it and should be updated, or may have been set for the first - // time! - updated = true; - data.setModified(false); - } else if (data.loadedmetadata) { - // if the meta data has been loaded, we can ask the video - // what it's current position (in time) is. - if (this._videoPrevUpdateTime !== data.time()) { - // update the texture in gpu mem only if the current - // video timestamp does not match the timestamp of the last - // time we uploaded this texture (and update the time we - // last uploaded, too) - this._videoPrevUpdateTime = data.time(); - updated = true; - } - } - } else if (this.isImageData) { - if (data._dirty) { - data._dirty = false; - updated = true; - } - } else { - /* data instanceof p5.Graphics, probably */ - // there is not enough information to tell if the texture can be - // conditionally updated; so to be safe, we just go ahead and upload it. - updated = true; - } - if (updated) { - this.bindTexture(); - gl.texImage2D(this.glTarget, 0, this.glFormat, this.glFormat, this.glDataType, textureData); - } - return updated; - }; - /** - * Binds the texture to the appropriate GL target. - * @method bindTexture - */ - _main.default.Texture.prototype.bindTexture = function () { - // bind texture using gl context + glTarget and - // generated gl texture object - var gl = this._renderer.GL; - gl.bindTexture(this.glTarget, this.glTex); - return this; - }; - /** - * Unbinds the texture from the appropriate GL target. - * @method unbindTexture - */ - _main.default.Texture.prototype.unbindTexture = function () { - // unbind per above, disable texturing on glTarget - var gl = this._renderer.GL; - gl.bindTexture(this.glTarget, null); - }; - /** - * Sets how a texture is be interpolated when upscaled or downscaled. - * Nearest filtering uses nearest neighbor scaling when interpolating - * Linear filtering uses WebGL's linear scaling when interpolating - * @method setInterpolation - * @param {String} downScale Specifies the texture filtering when - * textures are shrunk. Options are LINEAR or NEAREST - * @param {String} upScale Specifies the texture filtering when - * textures are magnified. Options are LINEAR or NEAREST - * @todo implement mipmapping filters - */ - _main.default.Texture.prototype.setInterpolation = function (downScale, upScale) { - var gl = this._renderer.GL; - if (downScale === constants.NEAREST) { - this.glMinFilter = gl.NEAREST; - } else { - this.glMinFilter = gl.LINEAR; - } - if (upScale === constants.NEAREST) { - this.glMagFilter = gl.NEAREST; - } else { - this.glMagFilter = gl.LINEAR; + this.init(textureData); + return this; } - this.bindTexture(); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this.glMinFilter); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, this.glMagFilter); - this.unbindTexture(); - }; - /** - * Sets the texture wrapping mode. This controls how textures behave - * when their uv's go outside of the 0 - 1 range. There are three options: - * CLAMP, REPEAT, and MIRROR. REPEAT & MIRROR are only available if the texture - * is a power of two size (128, 256, 512, 1024, etc.). - * @method setWrapMode - * @param {String} wrapX Controls the horizontal texture wrapping behavior - * @param {String} wrapY Controls the vertical texture wrapping behavior - */ - _main.default.Texture.prototype.setWrapMode = function (wrapX, wrapY) { - var gl = this._renderer.GL; // for webgl 1 we need to check if the texture is power of two - // if it isn't we will set the wrap mode to CLAMP - // webgl2 will support npot REPEAT and MIRROR but we don't check for it yet - var isPowerOfTwo = function isPowerOfTwo(x) { - return (x & x - 1) === 0; - }; - var textureData = this._getTextureDataFromSource(); - var wrapWidth; - var wrapHeight; - if (textureData.naturalWidth && textureData.naturalHeight) { - wrapWidth = textureData.naturalWidth; - wrapHeight = textureData.naturalHeight; - } else { - wrapWidth = this.width; - wrapHeight = this.height; - } - var widthPowerOfTwo = isPowerOfTwo(wrapWidth); - var heightPowerOfTwo = isPowerOfTwo(wrapHeight); - if (wrapX === constants.REPEAT) { - if (widthPowerOfTwo && heightPowerOfTwo) { - this.glWrapS = gl.REPEAT; - } else { - console.warn('You tried to set the wrap mode to REPEAT but the texture size is not a power of two. Setting to CLAMP instead'); - this.glWrapS = gl.CLAMP_TO_EDGE; + _createClass(Texture, [ + { + key: '_getTextureDataFromSource', + value: function _getTextureDataFromSource() { + var textureData; + if (this.isFramebufferTexture) { + textureData = this.src.rawTexture(); + } else if (this.isSrcP5Image) { + // param is a p5.Image + textureData = this.src.canvas; + } else if (this.isSrcMediaElement || this.isSrcP5Graphics || this.isSrcP5Renderer || this.isSrcHTMLElement) { + // if param is a video HTML element + textureData = this.src.elt; + } else if (this.isImageData) { + textureData = this.src; + } + return textureData; + } /** + * Initializes common texture parameters, creates a gl texture, + * tries to upload the texture for the first time if data is + * already available. + * @private + * @method init + */ + + }, + { + key: 'init', + value: function init(data) { + var gl = this._renderer.GL; + if (!this.isFramebufferTexture) { + this.glTex = gl.createTexture(); + } + this.glWrapS = this._renderer.textureWrapX; + this.glWrapT = this._renderer.textureWrapY; + this.setWrapMode(this.glWrapS, this.glWrapT); + this.bindTexture(); + //gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, this.glMagFilter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this.glMinFilter); + if (this.isFramebufferTexture) { + // Do nothing, the framebuffer manages its own content + } else if (this.width === 0 || this.height === 0 || this.isSrcMediaElement && !this.src.loadedmetadata) { + // assign a 1×1 empty texture initially, because data is not yet ready, + // so that no errors occur in gl console! + var tmpdata = new Uint8Array([1, + 1, + 1, + 1]); + gl.texImage2D(this.glTarget, 0, gl.RGBA, 1, 1, 0, this.glFormat, this.glDataType, tmpdata); + } else { + // data is ready: just push the texture! + gl.texImage2D(this.glTarget, 0, this.glFormat, this.glFormat, this.glDataType, data); + } + } /** + * Checks if the source data for this texture has changed (if it's + * easy to do so) and reuploads the texture if necessary. If it's not + * possible or to expensive to do a calculation to determine wheter or + * not the data has occurred, this method simply re-uploads the texture. + * @method update + */ + + }, + { + key: 'update', + value: function update() { + var data = this.src; + if (data.width === 0 || data.height === 0) { + return false; // nothing to do! + } // FramebufferTexture instances wrap raw WebGL textures already, which + // don't need any extra updating, as they already live on the GPU + + if (this.isFramebufferTexture) { + return false; + } + var textureData = this._getTextureDataFromSource(); + var updated = false; + var gl = this._renderer.GL; + // pull texture from data, make sure width & height are appropriate + if (textureData.width !== this.width || textureData.height !== this.height) { + updated = true; + // make sure that if the width and height of this.src have changed + // for some reason, we update our metadata and upload the texture again + this.width = textureData.width || data.width; + this.height = textureData.height || data.height; + if (this.isSrcP5Image) { + data.setModified(false); + } else if (this.isSrcMediaElement || this.isSrcHTMLElement) { + // on the first frame the metadata comes in, the size will be changed + // from 0 to actual size, but pixels may not be available. + // flag for update in a future frame. + // if we don't do this, a paused video, for example, may not + // send the first frame to texture memory. + data.setModified(true); + } + } else if (this.isSrcP5Image) { + // for an image, we only update if the modified field has been set, + // for example, by a call to p5.Image.set + if (data.isModified()) { + updated = true; + data.setModified(false); + } + } else if (this.isSrcMediaElement) { + // for a media element (video), we'll check if the current time in + // the video frame matches the last time. if it doesn't match, the + // video has advanced or otherwise been taken to a new frame, + // and we need to upload it. + if (data.isModified()) { + // p5.MediaElement may have also had set/updatePixels, etc. called + // on it and should be updated, or may have been set for the first + // time! + updated = true; + data.setModified(false); + } else if (data.loadedmetadata) { + // if the meta data has been loaded, we can ask the video + // what it's current position (in time) is. + if (this._videoPrevUpdateTime !== data.time()) { + // update the texture in gpu mem only if the current + // video timestamp does not match the timestamp of the last + // time we uploaded this texture (and update the time we + // last uploaded, too) + this._videoPrevUpdateTime = data.time(); + updated = true; + } + } + } else if (this.isImageData) { + if (data._dirty) { + data._dirty = false; + updated = true; + } + } else { + /* data instanceof p5.Graphics, probably */ + // there is not enough information to tell if the texture can be + // conditionally updated; so to be safe, we just go ahead and upload it. + updated = true; + } + if (updated) { + this.bindTexture(); + gl.texImage2D(this.glTarget, 0, this.glFormat, this.glFormat, this.glDataType, textureData); + } + return updated; + } /** + * Binds the texture to the appropriate GL target. + * @method bindTexture + */ + + }, + { + key: 'bindTexture', + value: function bindTexture() { + // bind texture using gl context + glTarget and + // generated gl texture object + var gl = this._renderer.GL; + gl.bindTexture(this.glTarget, this.getTexture()); + return this; + } /** + * Unbinds the texture from the appropriate GL target. + * @method unbindTexture + */ + + }, + { + key: 'unbindTexture', + value: function unbindTexture() { + // unbind per above, disable texturing on glTarget + var gl = this._renderer.GL; + gl.bindTexture(this.glTarget, null); + } + }, + { + key: 'getTexture', + value: function getTexture() { + if (this.isFramebufferTexture) { + return this.src.rawTexture(); + } else { + return this.glTex; + } + } /** + * Sets how a texture is be interpolated when upscaled or downscaled. + * Nearest filtering uses nearest neighbor scaling when interpolating + * Linear filtering uses WebGL's linear scaling when interpolating + * @method setInterpolation + * @param {String} downScale Specifies the texture filtering when + * textures are shrunk. Options are LINEAR or NEAREST + * @param {String} upScale Specifies the texture filtering when + * textures are magnified. Options are LINEAR or NEAREST + * @todo implement mipmapping filters + */ + + }, + { + key: 'setInterpolation', + value: function setInterpolation(downScale, upScale) { + var gl = this._renderer.GL; + this.glMinFilter = this.glFilter(downScale); + this.glMagFilter = this.glFilter(upScale); + this.bindTexture(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this.glMinFilter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, this.glMagFilter); + this.unbindTexture(); + } + }, + { + key: 'glFilter', + value: function glFilter(filter) { + var gl = this._renderer.GL; + if (filter === constants.NEAREST) { + return gl.NEAREST; + } else { + return gl.LINEAR; + } + } /** + * Sets the texture wrapping mode. This controls how textures behave + * when their uv's go outside of the 0 - 1 range. There are three options: + * CLAMP, REPEAT, and MIRROR. REPEAT & MIRROR are only available if the texture + * is a power of two size (128, 256, 512, 1024, etc.). + * @method setWrapMode + * @param {String} wrapX Controls the horizontal texture wrapping behavior + * @param {String} wrapY Controls the vertical texture wrapping behavior + */ + + }, + { + key: 'setWrapMode', + value: function setWrapMode(wrapX, wrapY) { + var gl = this._renderer.GL; + // for webgl 1 we need to check if the texture is power of two + // if it isn't we will set the wrap mode to CLAMP + // webgl2 will support npot REPEAT and MIRROR but we don't check for it yet + var isPowerOfTwo = function isPowerOfTwo(x) { + return (x & x - 1) === 0; + }; + var textureData = this._getTextureDataFromSource(); + var wrapWidth; + var wrapHeight; + if (textureData.naturalWidth && textureData.naturalHeight) { + wrapWidth = textureData.naturalWidth; + wrapHeight = textureData.naturalHeight; + } else { + wrapWidth = this.width; + wrapHeight = this.height; + } + var widthPowerOfTwo = isPowerOfTwo(wrapWidth); + var heightPowerOfTwo = isPowerOfTwo(wrapHeight); + if (wrapX === constants.REPEAT) { + if (this._renderer.webglVersion === constants.WEBGL2 || widthPowerOfTwo && heightPowerOfTwo) { + this.glWrapS = gl.REPEAT; + } else { + console.warn('You tried to set the wrap mode to REPEAT but the texture size is not a power of two. Setting to CLAMP instead'); + this.glWrapS = gl.CLAMP_TO_EDGE; + } + } else if (wrapX === constants.MIRROR) { + if (this._renderer.webglVersion === constants.WEBGL2 || widthPowerOfTwo && heightPowerOfTwo) { + this.glWrapS = gl.MIRRORED_REPEAT; + } else { + console.warn('You tried to set the wrap mode to MIRROR but the texture size is not a power of two. Setting to CLAMP instead'); + this.glWrapS = gl.CLAMP_TO_EDGE; + } + } else { + // falling back to default if didn't get a proper mode + this.glWrapS = gl.CLAMP_TO_EDGE; + } + if (wrapY === constants.REPEAT) { + if (this._renderer.webglVersion === constants.WEBGL2 || widthPowerOfTwo && heightPowerOfTwo) { + this.glWrapT = gl.REPEAT; + } else { + console.warn('You tried to set the wrap mode to REPEAT but the texture size is not a power of two. Setting to CLAMP instead'); + this.glWrapT = gl.CLAMP_TO_EDGE; + } + } else if (wrapY === constants.MIRROR) { + if (this._renderer.webglVersion === constants.WEBGL2 || widthPowerOfTwo && heightPowerOfTwo) { + this.glWrapT = gl.MIRRORED_REPEAT; + } else { + console.warn('You tried to set the wrap mode to MIRROR but the texture size is not a power of two. Setting to CLAMP instead'); + this.glWrapT = gl.CLAMP_TO_EDGE; + } + } else { + // falling back to default if didn't get a proper mode + this.glWrapT = gl.CLAMP_TO_EDGE; + } + this.bindTexture(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this.glWrapS); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this.glWrapT); + this.unbindTexture(); + } } - } 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; + ]); + return Texture; + }(); + var MipmapTexture = /*#__PURE__*/ function (_p5$Texture) { + _inherits(MipmapTexture, _p5$Texture); + var _super = _createSuper(MipmapTexture); + function MipmapTexture(renderer, levels, settings) { + var _this; + _classCallCheck(this, MipmapTexture); + _this = _super.call(this, renderer, levels, settings); + var gl = _this._renderer.GL; + if (_this.glMinFilter === gl.LINEAR) { + _this.glMinFilter = gl.LINEAR_MIPMAP_LINEAR; } - } else { - // falling back to default if didn't get a proper mode - this.glWrapS = gl.CLAMP_TO_EDGE; + return _this; } - 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; + _createClass(MipmapTexture, [ + { + key: 'glFilter', + value: function glFilter(_filter) { + var gl = this._renderer.GL; + // TODO: support others + return gl.LINEAR_MIPMAP_LINEAR; + } + }, + { + key: '_getTextureDataFromSource', + value: function _getTextureDataFromSource() { + return this.src; + } + }, + { + key: 'init', + value: function init(levels) { + var gl = this._renderer.GL; + this.glTex = gl.createTexture(); + this.bindTexture(); + for (var level = 0; level < levels.length; level++) { + gl.texImage2D(this.glTarget, level, this.glFormat, this.glFormat, this.glDataType, levels[level]); + } + this.glMinFilter = gl.LINEAR_MIPMAP_LINEAR; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, this.glMagFilter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this.glMinFilter); + this.unbindTexture(); + } + }, + { + key: 'update', + value: function update() { + } } - } else { - // falling back to default if didn't get a proper mode - this.glWrapT = gl.CLAMP_TO_EDGE; - } - this.bindTexture(); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this.glWrapS); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this.glWrapT); - this.unbindTexture(); - }; + ]); + return MipmapTexture; + }(_main.default.Texture); + exports.MipmapTexture = MipmapTexture; + function checkWebGLCapabilities(_ref) { + var GL = _ref.GL, + webglVersion = _ref.webglVersion; + var gl = GL; + var supportsFloat = webglVersion === constants.WEBGL2 ? gl.getExtension('EXT_color_buffer_float') && gl.getExtension('EXT_float_blend') : gl.getExtension('OES_texture_float'); + var supportsFloatLinear = supportsFloat && gl.getExtension('OES_texture_float_linear'); + var supportsHalfFloat = webglVersion === constants.WEBGL2 ? gl.getExtension('EXT_color_buffer_float') : gl.getExtension('OES_texture_half_float'); + var supportsHalfFloatLinear = supportsHalfFloat && gl.getExtension('OES_texture_half_float_linear'); + return { + float: supportsFloat, + floatLinear: supportsFloatLinear, + halfFloat: supportsHalfFloat, + halfFloatLinear: supportsHalfFloatLinear + }; + } var _default = _main.default.Texture; exports.default = _default; }, { - '../core/constants': 278, - '../core/main': 290, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.typed-array.copy-within': 215, - 'core-js/modules/es.typed-array.every': 216, - 'core-js/modules/es.typed-array.fill': 217, - 'core-js/modules/es.typed-array.filter': 218, - 'core-js/modules/es.typed-array.find': 220, - 'core-js/modules/es.typed-array.find-index': 219, - 'core-js/modules/es.typed-array.for-each': 223, - 'core-js/modules/es.typed-array.includes': 224, - 'core-js/modules/es.typed-array.index-of': 225, - 'core-js/modules/es.typed-array.iterator': 228, - 'core-js/modules/es.typed-array.join': 229, - 'core-js/modules/es.typed-array.last-index-of': 230, - 'core-js/modules/es.typed-array.map': 231, - 'core-js/modules/es.typed-array.reduce': 233, - 'core-js/modules/es.typed-array.reduce-right': 232, - 'core-js/modules/es.typed-array.reverse': 234, - 'core-js/modules/es.typed-array.set': 235, - 'core-js/modules/es.typed-array.slice': 236, - 'core-js/modules/es.typed-array.some': 237, - 'core-js/modules/es.typed-array.sort': 238, - 'core-js/modules/es.typed-array.subarray': 239, - 'core-js/modules/es.typed-array.to-locale-string': 240, - 'core-js/modules/es.typed-array.to-string': 241, - 'core-js/modules/es.typed-array.uint8-array': 244, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + '../core/constants': 286, + '../core/main': 298, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.get-prototype-of': 198, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.reflect.construct': 202, + 'core-js/modules/es.regexp.to-string': 206, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.typed-array.copy-within': 223, + 'core-js/modules/es.typed-array.every': 224, + 'core-js/modules/es.typed-array.fill': 225, + 'core-js/modules/es.typed-array.filter': 226, + 'core-js/modules/es.typed-array.find': 228, + 'core-js/modules/es.typed-array.find-index': 227, + 'core-js/modules/es.typed-array.for-each': 231, + 'core-js/modules/es.typed-array.includes': 232, + 'core-js/modules/es.typed-array.index-of': 233, + 'core-js/modules/es.typed-array.iterator': 236, + 'core-js/modules/es.typed-array.join': 237, + 'core-js/modules/es.typed-array.last-index-of': 238, + 'core-js/modules/es.typed-array.map': 239, + 'core-js/modules/es.typed-array.reduce': 241, + 'core-js/modules/es.typed-array.reduce-right': 240, + 'core-js/modules/es.typed-array.reverse': 242, + 'core-js/modules/es.typed-array.set': 243, + 'core-js/modules/es.typed-array.slice': 244, + 'core-js/modules/es.typed-array.some': 245, + 'core-js/modules/es.typed-array.sort': 246, + 'core-js/modules/es.typed-array.subarray': 247, + 'core-js/modules/es.typed-array.to-locale-string': 248, + 'core-js/modules/es.typed-array.to-string': 249, + 'core-js/modules/es.typed-array.uint8-array': 252, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 347: [ + 358: [ function (_dereq_, module, exports) { 'use strict'; _dereq_('core-js/modules/es.symbol'); @@ -106202,10 +120489,30 @@ default: obj }; - } // Text/Typography + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } // Text/Typography // @TODO: - _main.default.RendererGL.prototype._applyTextProperties = function () { //@TODO finish implementation + _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) { @@ -106213,14 +120520,18 @@ return this._textFont._textWidth(s, this._textSize); } return 0; // TODO: error - }; // rendering constants + }; + // 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 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 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 gridImageHeight = 64; + // size of the image holding the offset/length of each row/col stripe var cellImageWidth = 64; var cellImageHeight = 64; /** @@ -106231,75 +120542,86 @@ * * 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; + var ImageInfos = /*#__PURE__*/ function () { + function ImageInfos(width, height) { + _classCallCheck(this, ImageInfos); + this.width = width; + this.height = height; + this.infos = [ + ]; // the list of images + } /** + * + * @method findImage + * @param {Integer} space + * @return {Object} contains the ImageData, and pixel index into that + * ImageData where the free space was allocated. + * + * finds free space of a given size in the ImageData list + */ + + _createClass(ImageInfos, [ + { + key: 'findImage', + value: function findImage(space) { + var imageSize = this.width * this.height; + if (space > imageSize) throw new Error('font is too complex to render in 3D'); + // search through the list of images, looking for one with + // anough unused space. + var imageInfo, + imageData; + for (var ii = this.infos.length - 1; ii >= 0; --ii) { + var imageInfoTest = this.infos[ii]; + if (imageInfoTest.index + space < imageSize) { + // found one + imageInfo = imageInfoTest; + imageData = imageInfoTest.imageData; + break; + } + } + if (!imageInfo) { + try { + // create a new image + imageData = new ImageData(this.width, this.height); + } catch (err) { + // for browsers that don't support ImageData constructors (ie IE11) + // create an ImageData using the old method + var canvas = document.getElementsByTagName('canvas') [0]; + var created = !canvas; + if (!canvas) { + // create a temporary canvas + canvas = document.createElement('canvas'); + canvas.style.display = 'none'; + document.body.appendChild(canvas); + } + var ctx = canvas.getContext('2d'); + if (ctx) { + imageData = ctx.createImageData(this.width, this.height); + } + if (created) { + // distroy the temporary canvas, if necessary + document.body.removeChild(canvas); + } + } // construct & dd the new image info + + imageInfo = { + index: 0, + imageData: imageData + }; + this.infos.push(imageInfo); + } + var index = imageInfo.index; + imageInfo.index += space; // move to the start of the next image + imageData._dirty = true; + return { + imageData: imageData, + index: index + }; } } - if (!imageInfo) { - try { - // create a new image - imageData = new ImageData(this.width, this.height); - } catch (err) { - // for browsers that don't support ImageData constructors (ie IE11) - // create an ImageData using the old method - var canvas = document.getElementsByTagName('canvas') [0]; - var created = !canvas; - if (!canvas) { - // create a temporary canvas - canvas = document.createElement('canvas'); - canvas.style.display = 'none'; - document.body.appendChild(canvas); - } - var ctx = canvas.getContext('2d'); - if (ctx) { - imageData = ctx.createImageData(this.width, this.height); - } - if (created) { - // distroy the temporary canvas, if necessary - document.body.removeChild(canvas); - } - } // construct & dd the new image info - - imageInfo = { - index: 0, - imageData: imageData - }; - this.infos.push(imageInfo); - } - var index = imageInfo.index; - imageInfo.index += space; // move to the start of the next image - imageData._dirty = true; - return { - imageData: imageData, - index: index - }; - }; - } /** + ]); + return ImageInfos; + }(); + /** * @function setPixel * @param {Object} imageInfo * @param {Number} r @@ -106309,7 +120631,6 @@ * * writes the next pixel into an indexed ImageData */ - function setPixel(imageInfo, r, g, b, a) { var imageData = imageInfo.imageData; var pixels = imageData.data; @@ -106327,507 +120648,554 @@ * * 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 + var FontInfo = /*#__PURE__*/ function () { + function FontInfo(font) { + _classCallCheck(this, FontInfo); + this.font = font; + // the bezier curve coordinates + this.strokeImageInfos = new ImageInfos(strokeImageWidth, strokeImageHeight); + // lists of curve indices for each row/column slice + this.colDimImageInfos = new ImageInfos(gridImageWidth, gridImageHeight); + this.rowDimImageInfos = new ImageInfos(gridImageWidth, gridImageHeight); + // the offset & length of each row/col slice in the glyph + this.colCellImageInfos = new ImageInfos(cellImageWidth, cellImageHeight); + this.rowCellImageInfos = new ImageInfos(cellImageWidth, cellImageHeight); + // the cached information for each glyph + this.glyphInfos = { + }; + } /** + * @method getGlyphInfo + * @param {Glyph} glyph the x positions of points in the curve + * @returns {Object} the glyphInfo for that glyph * - * adds a curve to the rows & columns that it intersects with + * calculates rendering info for a glyph, including the curve information, + * row & column stripes compiled into textures. */ - 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; + _createClass(FontInfo, [ + { + key: 'getGlyphInfo', + value: function getGlyphInfo(glyph) { + // check the cache + var gi = this.glyphInfos[glyph.index]; + if (gi) return gi; + // get the bounding box of the glyph from opentype.js + var bb = glyph.getBoundingBox(); + var xMin = bb.x1; + var yMin = bb.y1; + var gWidth = bb.x2 - xMin; + var gHeight = bb.y2 - yMin; + var cmds = glyph.path.commands; + // don't bother rendering invisible glyphs + if (gWidth === 0 || gHeight === 0 || !cmds.length) { + return this.glyphInfos[glyph.index] = { + }; } - return { - min: min, - max: max - }; - } // Expand the bounding box of the glyph by the number of cells below - // before rounding. Curves only partially through a cell won't be added - // to adjacent cells, but ones that are close will be. This helps fix - // small visual glitches that occur when curves are close to grid cell - // boundaries. - - var cellOffset = 0.5; // loop through the rows & columns that the curve intersects - // adding the curve to those slices - var mmX = minMax(xs, 1, 0); - var ixMin = Math.max(Math.floor(mmX.min * charGridWidth - cellOffset), 0); - var ixMax = Math.min(Math.ceil(mmX.max * charGridWidth + cellOffset), charGridWidth); - for (var iCol = ixMin; iCol < ixMax; ++iCol) { - cols[iCol].push(index); - } - var mmY = minMax(ys, 1, 0); - var iyMin = Math.max(Math.floor(mmY.min * charGridHeight - cellOffset), 0); - var iyMax = Math.min(Math.ceil(mmY.max * charGridHeight + cellOffset), charGridHeight); - for (var iRow = iyMin; iRow < iyMax; ++iRow) { - rows[iRow].push(index); - } - } /** - * @function clamp - * @param {Number} v the value to clamp - * @param {Number} min the minimum value - * @param {Number} max the maxmimum value - * - * clamps a value between a minimum & maximum value - */ - - function clamp(v, min, max) { - if (v < min) return min; - if (v > max) return max; - return v; - } /** - * @function byte - * @param {Number} v the value to scale - * - * converts a floating-point number in the range 0-1 to a byte 0-255 - */ - - function byte(v) { - return clamp(255 * v, 0, 255); - } /** - * @private - * @class Cubic - * @param {Number} p0 the start point of the curve - * @param {Number} c0 the first control point - * @param {Number} c1 the second control point - * @param {Number} p1 the end point - * - * a cubic curve - */ - - function Cubic(p0, c0, c1, p1) { - this.p0 = p0; - this.c0 = c0; - this.c1 = c1; - this.p1 = p1; - /** - * @method toQuadratic - * @return {Object} the quadratic approximation - * - * converts the cubic to a quadtratic approximation by - * picking an appropriate quadratic control point - */ - this.toQuadratic = function () { - return { - x: this.p0.x, - y: this.p0.y, - x1: this.p1.x, - y1: this.p1.y, - cx: ((this.c0.x + this.c1.x) * 3 - (this.p0.x + this.p1.x)) / 4, - cy: ((this.c0.y + this.c1.y) * 3 - (this.p0.y + this.p1.y)) / 4 - }; - }; - /** - * @method quadError - * @return {Number} the error - * - * calculates the magnitude of error of this curve's - * quadratic approximation. - */ - this.quadError = function () { - return _main.default.Vector.sub(_main.default.Vector.sub(this.p1, this.p0), _main.default.Vector.mult(_main.default.Vector.sub(this.c1, this.c0), 3)).mag() / 2; - }; - /** - * @method split - * @param {Number} t the value (0-1) at which to split - * @return {Cubic} the second part of the curve - * - * splits the cubic into two parts at a point 't' along the curve. - * this cubic keeps its start point and its end point becomes the - * point at 't'. the 'end half is returned. - */ - this.split = function (t) { - var m1 = _main.default.Vector.lerp(this.p0, this.c0, t); - var m2 = _main.default.Vector.lerp(this.c0, this.c1, t); - var mm1 = _main.default.Vector.lerp(m1, m2, t); - this.c1 = _main.default.Vector.lerp(this.c1, this.p1, t); - this.c0 = _main.default.Vector.lerp(m2, this.c1, t); - var pt = _main.default.Vector.lerp(mm1, this.c0, t); - var part1 = new Cubic(this.p0, m1, mm1, pt); - this.p0 = pt; - return part1; - }; - /** - * @method splitInflections - * @return {Cubic[]} the non-inflecting pieces of this cubic - * - * returns an array containing 0, 1 or 2 cubics split resulting - * from splitting this cubic at its inflection points. - * this cubic is (potentially) altered and returned in the list. - */ - this.splitInflections = function () { - var a = _main.default.Vector.sub(this.c0, this.p0); - var b = _main.default.Vector.sub(_main.default.Vector.sub(this.c1, this.c0), a); - var c = _main.default.Vector.sub(_main.default.Vector.sub(_main.default.Vector.sub(this.p1, this.c1), a), _main.default.Vector.mult(b, 2)); - var cubics = [ - ]; // find the derivative coefficients - var A = b.x * c.y - b.y * c.x; - if (A !== 0) { - var B = a.x * c.y - a.y * c.x; - var C = a.x * b.y - a.y * b.x; - var disc = B * B - 4 * A * C; - if (disc >= 0) { - if (A < 0) { - A = - A; - B = - B; - C = - C; + var 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; } - var Q = Math.sqrt(disc); - var t0 = ( - B - Q) / (2 * A); // the first inflection point - var t1 = ( - B + Q) / (2 * A); // the second inflection point - // test if the first inflection point lies on the curve - if (t0 > 0 && t0 < 1) { - // split at the first inflection point - cubics.push(this.split(t0)); // scale t2 into the second part - t1 = 1 - (1 - t1) / (1 - t0); - } // test if the second inflection point lies on the curve - - if (t1 > 0 && t1 < 1) { - // split at the second inflection point - cubics.push(this.split(t1)); - } - } - } - cubics.push(this); - return cubics; - }; - } /** - * @function cubicToQuadratics - * @param {Number} x0 - * @param {Number} y0 - * @param {Number} cx0 - * @param {Number} cy0 - * @param {Number} cx1 - * @param {Number} cy1 - * @param {Number} x1 - * @param {Number} y1 - * @returns {Cubic[]} an array of cubics whose quadratic approximations - * closely match the civen cubic. - * - * converts a cubic curve to a list of quadratics. - */ - - function cubicToQuadratics(x0, y0, cx0, cy0, cx1, cy1, x1, y1) { - // create the Cubic object and split it at its inflections - var cubics = new Cubic(new _main.default.Vector(x0, y0), new _main.default.Vector(cx0, cy0), new _main.default.Vector(cx1, cy1), new _main.default.Vector(x1, y1)).splitInflections(); - var qs = [ - ]; // the final list of quadratics - var precision = 30 / SQRT3; // for each of the non-inflected pieces of the original cubic - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - try { - for (var _iterator = cubics[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var cubic = _step.value; // the cubic is iteratively split in 3 pieces: - // the first piece is accumulated in 'qs', the result. - // the last piece is accumulated in 'tail', temporarily. - // the middle piece is repeatedly split again, while necessary. - var tail = [ - ]; - var t3 = void 0; - for (; ; ) { - // calculate this cubic's precision - t3 = precision / cubic.quadError(); - if (t3 >= 0.5 * 0.5 * 0.5) { - break; // not too bad, we're done - } // find a split point based on the error - - var t = Math.pow(t3, 1 / 3); // split the cubic in 3 - var start = cubic.split(t); - var middle = cubic.split(1 - t / (1 - t)); - qs.push(start); // the first part - tail.push(cubic); // the last part - cubic = middle; // iterate on the middle piece - } - if (t3 < 1) { - // a little excess error, split the middle in two - qs.push(cubic.split(0.5)); - } // add the middle piece to the result - - qs.push(cubic); // finally add the tail, reversed, onto the result - Array.prototype.push.apply(qs, tail.reverse()); - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return != null) { - _iterator.return(); + return { + min: min, + max: max + }; + } // Expand the bounding box of the glyph by the number of cells below + // before rounding. Curves only partially through a cell won't be added + // to adjacent cells, but ones that are close will be. This helps fix + // small visual glitches that occur when curves are close to grid cell + // boundaries. + + var cellOffset = 0.5; + // loop through the rows & columns that the curve intersects + // adding the curve to those slices + var mmX = minMax(xs, 1, 0); + var ixMin = Math.max(Math.floor(mmX.min * charGridWidth - cellOffset), 0); + var ixMax = Math.min(Math.ceil(mmX.max * charGridWidth + cellOffset), charGridWidth); + for (var iCol = ixMin; iCol < ixMax; ++iCol) { + cols[iCol].push(index); } - } finally { - if (_didIteratorError) { - throw _iteratorError; + var mmY = minMax(ys, 1, 0); + var iyMin = Math.max(Math.floor(mmY.min * charGridHeight - cellOffset), 0); + var iyMax = Math.min(Math.ceil(mmY.max * charGridHeight + cellOffset), charGridHeight); + for (var iRow = iyMin; iRow < iyMax; ++iRow) { + rows[iRow].push(index); } - } - } - 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; + } /** + * @function clamp + * @param {Number} v the value to clamp + * @param {Number} min the minimum value + * @param {Number} max the maxmimum value + * + * clamps a value between a minimum & maximum value + */ + + function clamp(v, min, max) { + if (v < min) return min; + if (v > max) return max; + return v; + } /** + * @function byte + * @param {Number} v the value to scale + * + * converts a floating-point number in the range 0-1 to a byte 0-255 + */ + + function byte(v) { + return clamp(255 * v, 0, 255); + } /** + * @private + * @class Cubic + * @param {Number} p0 the start point of the curve + * @param {Number} c0 the first control point + * @param {Number} c1 the second control point + * @param {Number} p1 the end point + * + * a cubic curve + */ + + var Cubic = /*#__PURE__*/ function () { + function Cubic(p0, c0, c1, p1) { + _classCallCheck(this, Cubic); + this.p0 = p0; + this.c0 = c0; + this.c1 = c1; + this.p1 = p1; + } /** + * @method toQuadratic + * @return {Object} the quadratic approximation + * + * converts the cubic to a quadtratic approximation by + * picking an appropriate quadratic control point + */ + + _createClass(Cubic, [ + { + key: 'toQuadratic', + value: function toQuadratic() { + return { + x: this.p0.x, + y: this.p0.y, + x1: this.p1.x, + y1: this.p1.y, + cx: ((this.c0.x + this.c1.x) * 3 - (this.p0.x + this.p1.x)) / 4, + cy: ((this.c0.y + this.c1.y) * 3 - (this.p0.y + this.p1.y)) / 4 + }; + } /** + * @method quadError + * @return {Number} the error + * + * calculates the magnitude of error of this curve's + * quadratic approximation. + */ + + }, + { + key: 'quadError', + value: function quadError() { + return _main.default.Vector.sub(_main.default.Vector.sub(this.p1, this.p0), _main.default.Vector.mult(_main.default.Vector.sub(this.c1, this.c0), 3)).mag() / 2; + } /** + * @method split + * @param {Number} t the value (0-1) at which to split + * @return {Cubic} the second part of the curve + * + * splits the cubic into two parts at a point 't' along the curve. + * this cubic keeps its start point and its end point becomes the + * point at 't'. the 'end half is returned. + */ + + }, + { + key: 'split', + value: function split(t) { + var m1 = _main.default.Vector.lerp(this.p0, this.c0, t); + var m2 = _main.default.Vector.lerp(this.c0, this.c1, t); + var mm1 = _main.default.Vector.lerp(m1, m2, t); + this.c1 = _main.default.Vector.lerp(this.c1, this.p1, t); + this.c0 = _main.default.Vector.lerp(m2, this.c1, t); + var pt = _main.default.Vector.lerp(mm1, this.c0, t); + var part1 = new Cubic(this.p0, m1, mm1, pt); + this.p0 = pt; + return part1; + } /** + * @method splitInflections + * @return {Cubic[]} the non-inflecting pieces of this cubic + * + * returns an array containing 0, 1 or 2 cubics split resulting + * from splitting this cubic at its inflection points. + * this cubic is (potentially) altered and returned in the list. + */ + + }, + { + key: 'splitInflections', + value: function splitInflections() { + var a = _main.default.Vector.sub(this.c0, this.p0); + var b = _main.default.Vector.sub(_main.default.Vector.sub(this.c1, this.c0), a); + var c = _main.default.Vector.sub(_main.default.Vector.sub(_main.default.Vector.sub(this.p1, this.c1), a), _main.default.Vector.mult(b, 2)); + var cubics = [ + ]; + // find the derivative coefficients + var A = b.x * c.y - b.y * c.x; + if (A !== 0) { + var B = a.x * c.y - a.y * c.x; + var C = a.x * b.y - a.y * b.x; + var disc = B * B - 4 * A * C; + if (disc >= 0) { + if (A < 0) { + A = - A; + B = - B; + C = - C; + } + var Q = Math.sqrt(disc); + var t0 = ( - B - Q) / (2 * A); // the first inflection point + var t1 = ( - B + Q) / (2 * A); // the second inflection point + // test if the first inflection point lies on the curve + if (t0 > 0 && t0 < 1) { + // split at the first inflection point + cubics.push(this.split(t0)); + // scale t2 into the second part + t1 = 1 - (1 - t1) / (1 - t0); + } // test if the second inflection point lies on the curve + + if (t1 > 0 && t1 < 1) { + // split at the second inflection point + cubics.push(this.split(t1)); + } + } + } + cubics.push(this); + return cubics; + } } - 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 - }); + ]); + return Cubic; + }(); + /** + * @function cubicToQuadratics + * @param {Number} x0 + * @param {Number} y0 + * @param {Number} cx0 + * @param {Number} cy0 + * @param {Number} cx1 + * @param {Number} cy1 + * @param {Number} x1 + * @param {Number} y1 + * @returns {Cubic[]} an array of cubics whose quadratic approximations + * closely match the civen cubic. + * + * converts a cubic curve to a list of quadratics. + */ + function cubicToQuadratics(x0, y0, cx0, cy0, cx1, cy1, x1, y1) { + // create the Cubic object and split it at its inflections + var cubics = new Cubic(new _main.default.Vector(x0, y0), new _main.default.Vector(cx0, cy0), new _main.default.Vector(cx1, cy1), new _main.default.Vector(x1, y1)).splitInflections(); + var qs = [ + ]; // the final list of quadratics + var precision = 30 / SQRT3; + // for each of the non-inflected pieces of the original cubic + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = cubics[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var cubic = _step.value; + // the cubic is iteratively split in 3 pieces: + // the first piece is accumulated in 'qs', the result. + // the last piece is accumulated in 'tail', temporarily. + // the middle piece is repeatedly split again, while necessary. + var tail = [ + ]; + var t3 = void 0; + for (; ; ) { + // calculate this cubic's precision + t3 = precision / cubic.quadError(); + if (t3 >= 0.5 * 0.5 * 0.5) { + break; // not too bad, we're done + } // find a split point based on the error + + var t = Math.pow(t3, 1 / 3); + // split the cubic in 3 + var start = cubic.split(t); + var middle = cubic.split(1 - t / (1 - t)); + qs.push(start); // the first part + tail.push(cubic); // the last part + cubic = middle; // iterate on the middle piece } - break; + 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()); } - 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); + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; } - break; } - default: - throw new Error('unknown command type: '.concat(cmd.type)); - } - x0 = x1; - y0 = y1; - } // allocate space for the strokes + } + 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; + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } } + var strokeCount = strokes.length; + var strokeImageInfo = this.strokeImageInfos.findImage(strokeCount); + var strokeOffset = strokeImageInfo.index; + // fill the stroke image + for (var il = 0; il < strokeCount; ++il) { + var s = strokes[il]; + setPixel(strokeImageInfo, byte(s.x), byte(s.y), byte(s.cx), byte(s.cy)); + } /** + * @function layout + * @param {Number[][]} dim + * @param {ImageInfo[]} dimImageInfos + * @param {ImageInfo[]} cellImageInfos + * @return {Object} + * + * lays out the curves in a dimension (row or col) into two + * images, one for the indices of the curves themselves, and + * one containing the offset and length of those index spans. + */ + + function layout(dim, dimImageInfos, cellImageInfos) { + var dimLength = dim.length; // the number of slices in this dimension + var dimImageInfo = dimImageInfos.findImage(dimLength); + var dimOffset = dimImageInfo.index; + // calculate the total number of stroke indices in this dimension + var totalStrokes = 0; + for (var id = 0; id < dimLength; ++id) { + totalStrokes += dim[id].length; + } // allocate space for the stroke indices + + var cellImageInfo = cellImageInfos.findImage(totalStrokes); + // for each slice in the glyph + for (var _i2 = 0; _i2 < dimLength; ++_i2) { + var strokeIndices = dim[_i2]; + var _strokeCount = strokeIndices.length; + var cellLineIndex = cellImageInfo.index; + // write the offset and count into the glyph slice image + setPixel(dimImageInfo, cellLineIndex >> 7, cellLineIndex & 127, _strokeCount >> 7, _strokeCount & 127); + // for each stroke index in that slice + for (var iil = 0; iil < _strokeCount; ++iil) { + // write the stroke index into the slice's image + var strokeIndex = strokeIndices[iil] + strokeOffset; + setPixel(cellImageInfo, strokeIndex >> 7, strokeIndex & 127, 0, 0); + } + } + return { + cellImageInfo: cellImageInfo, + dimOffset: dimOffset, + dimImageInfo: dimImageInfo + }; + } // initialize the info for this glyph + + gi = this.glyphInfos[glyph.index] = { + glyph: glyph, + uGlyphRect: [ + bb.x1, + - bb.y1, + bb.x2, + - bb.y2 + ], + strokeImageInfo: strokeImageInfo, + strokes: strokes, + colInfo: layout(cols, this.colDimImageInfos, this.colCellImageInfos), + rowInfo: layout(rows, this.rowDimImageInfos, this.rowCellImageInfos) + }; + gi.uGridOffset = [ + gi.colInfo.dimOffset, + gi.rowInfo.dimOffset + ]; + return gi; } } - var strokeCount = strokes.length; - var strokeImageInfo = this.strokeImageInfos.findImage(strokeCount); - var strokeOffset = strokeImageInfo.index; // fill the stroke image - for (var il = 0; il < strokeCount; ++il) { - var s = strokes[il]; - setPixel(strokeImageInfo, byte(s.x), byte(s.y), byte(s.cx), byte(s.cy)); - } /** - * @function layout - * @param {Number[][]} dim - * @param {ImageInfo[]} dimImageInfos - * @param {ImageInfo[]} cellImageInfos - * @return {Object} - * - * lays out the curves in a dimension (row or col) into two - * images, one for the indices of the curves themselves, and - * one containing the offset and length of those index spans. - */ - - function layout(dim, dimImageInfos, cellImageInfos) { - var dimLength = dim.length; // the number of slices in this dimension - var dimImageInfo = dimImageInfos.findImage(dimLength); - var dimOffset = dimImageInfo.index; // calculate the total number of stroke indices in this dimension - var totalStrokes = 0; - for (var id = 0; id < dimLength; ++id) { - totalStrokes += dim[id].length; - } // allocate space for the stroke indices - - var cellImageInfo = cellImageInfos.findImage(totalStrokes); // for each slice in the glyph - for (var _i2 = 0; _i2 < dimLength; ++_i2) { - var strokeIndices = dim[_i2]; - var _strokeCount = strokeIndices.length; - var cellLineIndex = cellImageInfo.index; // write the offset and count into the glyph slice image - setPixel(dimImageInfo, cellLineIndex >> 7, cellLineIndex & 127, _strokeCount >> 7, _strokeCount & 127); // for each stroke index in that slice - for (var iil = 0; iil < _strokeCount; ++iil) { - // write the stroke index into the slice's image - var strokeIndex = strokeIndices[iil] + strokeOffset; - setPixel(cellImageInfo, strokeIndex >> 7, strokeIndex & 127, 0, 0); - } - } - return { - cellImageInfo: cellImageInfo, - dimOffset: dimOffset, - dimImageInfo: dimImageInfo - }; - } // initialize the info for this glyph - - gi = this.glyphInfos[glyph.index] = { - glyph: glyph, - uGlyphRect: [ - bb.x1, - - bb.y1, - bb.x2, - - bb.y2 - ], - strokeImageInfo: strokeImageInfo, - strokes: strokes, - colInfo: layout(cols, this.colDimImageInfos, this.colCellImageInfos), - rowInfo: layout(rows, this.rowDimImageInfos, this.rowCellImageInfos) - }; - gi.uGridOffset = [ - gi.colInfo.dimOffset, - gi.rowInfo.dimOffset - ]; - return gi; - }; - }; + ]); + return FontInfo; + }(); _main.default.RendererGL.prototype._renderText = function (p, line, x, y, maxY) { if (!this._textFont || typeof this._textFont === 'string') { console.log('WEBGL: you must load and set a font before drawing text. See `loadFont` and `textFont` for more details.'); @@ -106845,18 +121213,20 @@ var doStroke = this._doStroke; var drawMode = this.drawMode; this._doStroke = false; - this.drawMode = constants.TEXTURE; // get the cached FontInfo object + 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 + } // 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 + this.scale(scale, scale, 1); + // initialize the font shader var gl = this.GL; var initializeShader = !this._defaultFontShader; var sh = this._getFontShader(); @@ -106895,7 +121265,7 @@ }); geom.computeFaces().computeNormals(); g = this.createBuffers('glyph', geom); - } // bind the shader buffers + } // bind the shader buffers var _iteratorNormalCompletion3 = true; var _didIteratorError3 = false; @@ -106919,8 +121289,10 @@ } } } - this._bindBuffer(g.indexBuffer, gl.ELEMENT_ARRAY_BUFFER); // this will have to do for now... + this._bindBuffer(g.indexBuffer, gl.ELEMENT_ARRAY_BUFFER); + // this will have to do for now... sh.setUniform('uMaterialColor', this.curFillColor); + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); try { var dx = 0; // the x position in the line var glyphPrev = null; // the previous glyph, used for kerning @@ -106931,7 +121303,8 @@ var _iteratorError4 = undefined; try { for (var _iterator4 = glyphs[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { - var glyph = _step4.value; // kern + var glyph = _step4.value; + // kern if (glyphPrev) dx += font.getKerningValue(glyphPrev, glyph); var gi = fontInfo.getGlyphInfo(glyph); if (gi.uGlyphRect) { @@ -106971,31 +121344,32 @@ sh.unbindShader(); this._doStroke = doStroke; this.drawMode = drawMode; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true); p.pop(); } return p; }; }, { - '../core/constants': 278, - '../core/main': 290, - './p5.RendererGL.Retained': 343, - './p5.Shader': 345, - 'core-js/modules/es.array.iterator': 176, - 'core-js/modules/es.object.get-own-property-descriptor': 191, - 'core-js/modules/es.object.to-string': 195, - 'core-js/modules/es.regexp.exec': 199, - 'core-js/modules/es.string.iterator': 204, - 'core-js/modules/es.string.split': 209, - 'core-js/modules/es.string.sub': 210, - 'core-js/modules/es.symbol': 214, - 'core-js/modules/es.symbol.description': 212, - 'core-js/modules/es.symbol.iterator': 213, - 'core-js/modules/es.weak-map': 246, - 'core-js/modules/web.dom-collections.iterator': 248 + '../core/constants': 286, + '../core/main': 298, + './p5.RendererGL.Retained': 354, + './p5.Shader': 356, + 'core-js/modules/es.array.iterator': 179, + 'core-js/modules/es.object.get-own-property-descriptor': 196, + 'core-js/modules/es.object.to-string': 200, + 'core-js/modules/es.regexp.exec': 205, + 'core-js/modules/es.string.iterator': 210, + 'core-js/modules/es.string.split': 216, + 'core-js/modules/es.string.sub': 218, + 'core-js/modules/es.symbol': 222, + 'core-js/modules/es.symbol.description': 220, + 'core-js/modules/es.symbol.iterator': 221, + 'core-js/modules/es.weak-map': 254, + 'core-js/modules/web.dom-collections.iterator': 256 } ], - 348: [ + 359: [ function (_dereq_, module, exports) { module.exports = { 'fes': { @@ -107073,7 +121447,7 @@ { } ], - 349: [ + 360: [ function (_dereq_, module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { @@ -107086,7 +121460,7 @@ default: obj }; - } // Only one language is imported above. This is intentional as other languages + } // 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. @@ -107110,16 +121484,18 @@ var languages = [ 'en', 'es', - 'ko' + 'ko', + 'zh', + 'hi' ]; exports.languages = languages; }, { - './en/translation': 348 + './en/translation': 359 } ] }, { }, [ - 273 - ]) (273) + 281 + ]) (281) }); diff --git a/libraries/p5.sound.js b/libraries/p5.sound.js index ca19c19..a8a7e3f 100644 --- a/libraries/p5.sound.js +++ b/libraries/p5.sound.js @@ -218,7 +218,7 @@ function getAudioContext() { * example below. This method utilizes * StartAudioContext * , a library by Yotam Mann (MIT Licence, 2016).

      - * @param {Element|Array} [element(s)] This argument can be an Element, + * @param {Element|Array} [elements] This argument can be an Element, * Selector String, NodeList, p5.Element, * jQuery Element, or an Array of any of those. * @param {Function} [callback] Callback to invoke when the AudioContext