From e0a7646eb55eb76d2c252669f0dd52475273a88c Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Tue, 28 May 2019 14:03:18 -0300 Subject: [PATCH 01/32] Refactor existing compile function transforming it into a class --- pyp5js/compiler.py | 62 +++++++++++++++++++++++++++++++++++----------- 1 file changed, 48 insertions(+), 14 deletions(-) diff --git a/pyp5js/compiler.py b/pyp5js/compiler.py index 0e7da58a..a7ddefc7 100644 --- a/pyp5js/compiler.py +++ b/pyp5js/compiler.py @@ -7,27 +7,61 @@ from watchdog.events import PatternMatchingEventHandler from watchdog.observers import Observer +from pyp5js.fs import Pyp5jsLibFiles -PYP5_DIR = Path(__file__).parent -def compile_sketch_js(sketch_files): - command = ' '.join([str(c) for c in [ - 'transcrypt', '-xp', PYP5_DIR, '-b', '-m', '-n', sketch_files.sketch_py - ]]) +class Pyp5jsCompiler: + + def __init__(self, sketch_files): + self.pyp5js_files = Pyp5jsLibFiles() + self.sketch_files = sketch_files + + def compile_sketch_js(self): + self.run_compiler() + self.clean_up() + + @property + def target_dir(self): + """ + Path to directory with the js and assets files + """ + return self.sketch_files.sketch_dir.child('__target__') - cprint.info(f"Converting Python to P5.js...\nRunning command:\n\t {command}") + @property + def command_line(self): + """ + Builds transcrypt command line with the required parameters and flags + """ + pyp5_dir = self.pyp5js_files.install + return ' '.join([str(c) for c in [ + 'transcrypt', '-xp', pyp5_dir, '-b', '-m', '-n', self.sketch_files.sketch_py + ]]) - proc = subprocess.Popen(shlex.split(command)) - proc.wait() + def run_compiler(self): + """ + Execute transcrypt command to generate the JS files + """ + command = self.command_line + cprint.info(f"Converting Python to P5.js...\nRunning command:\n\t {command}") - __target = sketch_files.sketch_dir.child('__target__') - if not __target.exists(): - cprint.err(f"Error with transcrypt: the {__target} directory wasn't created.", interrupt=True) + proc = subprocess.Popen(shlex.split(command)) + proc.wait() - if sketch_files.target_dir.exists(): - shutil.rmtree(sketch_files.target_dir) - shutil.move(__target, sketch_files.target_dir) + def clean_up(self): + """ + Rename the assets dir from __target__ to target + + This is required because github pages can't deal with assets under a __target__ directory + """ + if self.sketch_files.target_dir.exists(): + shutil.rmtree(self.sketch_files.target_dir) + shutil.move(self.target_dir, self.sketch_files.target_dir) + + +def compile_sketch_js(sketch_files): + compiler = Pyp5jsCompiler(sketch_files) + compiler.compile_sketch_js() def monitor_sketch(sketch_files): From 1c79ca0100588e205950de15119de63dab206ec7 Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Tue, 28 May 2019 14:51:37 -0300 Subject: [PATCH 02/32] Separate monitor from compiler code --- pyp5js/commands.py | 7 ++-- pyp5js/compiler.py | 40 ------------------- pyp5js/monitor.py | 44 +++++++++++++++++++++ tests/test_commands.py | 8 ++-- tests/{test_compiler.py => test_monitor.py} | 6 +-- 5 files changed, 55 insertions(+), 50 deletions(-) create mode 100644 pyp5js/monitor.py rename tests/{test_compiler.py => test_monitor.py} (86%) diff --git a/pyp5js/commands.py b/pyp5js/commands.py index 1a685008..3ab695f4 100644 --- a/pyp5js/commands.py +++ b/pyp5js/commands.py @@ -3,7 +3,8 @@ from cprint import cprint from jinja2 import Environment, FileSystemLoader -from pyp5js import compiler +from pyp5js.compiler import compile_sketch_js +from pyp5js.monitor import monitor_sketch as monitor_sketch_service from pyp5js.fs import Pyp5jsSketchFiles, Pyp5jsLibFiles @@ -71,7 +72,7 @@ def transcrypt_sketch(sketch_name, sketch_dir): if not sketch_files.check_sketch_exists(): cprint.err(f"Couldn't find {sketch_name}", interrupt=True) - compiler.compile_sketch_js(sketch_files) + compile_sketch_js(sketch_files) return sketch_files.index_html @@ -96,6 +97,6 @@ def monitor_sketch(sketch_name, sketch_dir): cprint(f"Monitoring for changes in {sketch_files.sketch_dir.absolute()}...") try: - compiler.monitor_sketch(sketch_files) + monitor_sketch_service(sketch_files) except KeyboardInterrupt: cprint.info("Exiting monitor...") diff --git a/pyp5js/compiler.py b/pyp5js/compiler.py index a7ddefc7..13b99c54 100644 --- a/pyp5js/compiler.py +++ b/pyp5js/compiler.py @@ -1,11 +1,8 @@ import shlex import shutil import subprocess -import time from cprint import cprint from unipath import Path -from watchdog.events import PatternMatchingEventHandler -from watchdog.observers import Observer from pyp5js.fs import Pyp5jsLibFiles @@ -62,40 +59,3 @@ def clean_up(self): def compile_sketch_js(sketch_files): compiler = Pyp5jsCompiler(sketch_files) compiler.compile_sketch_js() - - -def monitor_sketch(sketch_files): - event_handler = TranscryptSketchEventHandler(sketch_files=sketch_files) - observer = Observer() - - observer.schedule(event_handler, sketch_files.sketch_dir) - observer.start() - try: - while True: - time.sleep(1) - except KeyboardInterrupt as e: - observer.stop() - raise e - observer.join() - - -class TranscryptSketchEventHandler(PatternMatchingEventHandler): - patterns = ["*.py"] - - def __init__(self, *args, **kwargs): - self.sketch_files = kwargs.pop('sketch_files') - self._last_event = None - super().__init__(*args, **kwargs) - - def on_modified(self, event): - event_id = id(event) - if event_id == self._last_event: - return - - cprint.info(f"New change in {event.src_path}") - - compile_sketch_js(self.sketch_files) - self._last_event = event_id - - index_file = self.sketch_files.index_html - cprint.ok(f"Your sketch is ready and available at {index_file}") diff --git a/pyp5js/monitor.py b/pyp5js/monitor.py new file mode 100644 index 00000000..4e62c0d8 --- /dev/null +++ b/pyp5js/monitor.py @@ -0,0 +1,44 @@ +import time +from cprint import cprint +from watchdog.events import PatternMatchingEventHandler +from watchdog.observers import Observer + +from pyp5js.compiler import compile_sketch_js + + + +def monitor_sketch(sketch_files): + event_handler = TranscryptSketchEventHandler(sketch_files=sketch_files) + observer = Observer() + + observer.schedule(event_handler, sketch_files.sketch_dir) + observer.start() + try: + while True: + time.sleep(1) + except KeyboardInterrupt as e: + observer.stop() + raise e + observer.join() + + +class TranscryptSketchEventHandler(PatternMatchingEventHandler): + patterns = ["*.py"] + + def __init__(self, *args, **kwargs): + self.sketch_files = kwargs.pop('sketch_files') + self._last_event = None + super().__init__(*args, **kwargs) + + def on_modified(self, event): + event_id = id(event) + if event_id == self._last_event: + return + + cprint.info(f"New change in {event.src_path}") + + compile_sketch_js(self.sketch_files) + self._last_event = event_id + + index_file = self.sketch_files.index_html + cprint.ok(f"Your sketch is ready and available at {index_file}") diff --git a/tests/test_commands.py b/tests/test_commands.py index 23d8ab37..f4277cb2 100644 --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -11,7 +11,7 @@ def test_transcrypt_sketch(MockedFiles): files.check_sketch_exists.return_value = True MockedFiles.return_value = files - with patch('pyp5js.commands.compiler.compile_sketch_js') as compiler: + with patch('pyp5js.commands.compile_sketch_js') as compiler: output = commands.transcrypt_sketch(sketch_name='foo', sketch_dir='bar') assert output == files.index_html @@ -25,7 +25,7 @@ def test_transcrypt_sketch_error_if_sketch_does_not_exist(MockedFiles): files.check_sketch_exists.return_value = False MockedFiles.return_value = files - with patch('pyp5js.commands.compiler.compile_sketch_js') as compiler: + with patch('pyp5js.commands.compile_sketch_js') as compiler: with pytest.raises(SystemExit): commands.transcrypt_sketch(sketch_name='foo', sketch_dir='bar') @@ -36,7 +36,7 @@ def test_monitor_sketch(MockedFiles): files.check_sketch_exists.return_value = True MockedFiles.return_value = files - with patch('pyp5js.commands.compiler.monitor_sketch') as monitor: + with patch('pyp5js.commands.monitor_sketch_service') as monitor: commands.monitor_sketch(sketch_name='foo', sketch_dir='bar') MockedFiles.assert_called_once_with('bar', 'foo') @@ -49,6 +49,6 @@ def test_monitor_sketch_error_if_sketch_does_not_exist(MockedFiles): files.check_sketch_exists.return_value = False MockedFiles.return_value = files - with patch('pyp5js.commands.compiler.monitor_sketch') as monitor: + with patch('pyp5js.commands.monitor_sketch_service') as monitor: with pytest.raises(SystemExit): commands.monitor_sketch(sketch_name='foo', sketch_dir='bar') diff --git a/tests/test_compiler.py b/tests/test_monitor.py similarity index 86% rename from tests/test_compiler.py rename to tests/test_monitor.py index 3f9c5d1c..4e5c8533 100644 --- a/tests/test_compiler.py +++ b/tests/test_monitor.py @@ -1,7 +1,7 @@ from unittest import TestCase from unittest.mock import Mock, patch -from pyp5js.compiler import TranscryptSketchEventHandler +from pyp5js.monitor import TranscryptSketchEventHandler from pyp5js.fs import Pyp5jsSketchFiles @@ -16,7 +16,7 @@ def test_handler_config(self): assert ['*.py'] == self.handler.patterns assert self.handler._last_event is None - @patch('pyp5js.compiler.compile_sketch_js') + @patch('pyp5js.monitor.compile_sketch_js') def test_on_modified(self, mocked_compiler): event = Mock() @@ -25,7 +25,7 @@ def test_on_modified(self, mocked_compiler): mocked_compiler.assert_called_once_with(self.files) assert id(event) == self.handler._last_event - @patch('pyp5js.compiler.compile_sketch_js') + @patch('pyp5js.monitor.compile_sketch_js') def test_on_modified_skip_repeated_event(self, mocked_compiler): event = Mock() self.handler._last_event = id(event) From 66064ef53675994dc09b46eb3ce9c3eaa9346737 Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Tue, 28 May 2019 14:55:02 -0300 Subject: [PATCH 03/32] Add tests to compile sketch service --- tests/test_compiler.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 tests/test_compiler.py diff --git a/tests/test_compiler.py b/tests/test_compiler.py new file mode 100644 index 00000000..e25fa1eb --- /dev/null +++ b/tests/test_compiler.py @@ -0,0 +1,16 @@ +from unittest.mock import Mock, patch + +from pyp5js.compiler import Pyp5jsCompiler, compile_sketch_js +from pyp5js.fs import Pyp5jsSketchFiles + + +@patch('pyp5js.compiler.Pyp5jsCompiler') +def test_compile_sketch_js_service(MockedCompiler): + files = Mock(Pyp5jsSketchFiles) + compiler = Mock(spec=Pyp5jsCompiler) + MockedCompiler.return_value = compiler + + compile_sketch_js(files) + + MockedCompiler.assert_called_once_with(files) + compiler.compile_sketch_js.assert_called_once_with() From cdc5676c2061c455e0f74be6110fbb2aa2c47421 Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Tue, 28 May 2019 19:45:08 -0300 Subject: [PATCH 04/32] Add tests to compiler object --- tests/test_compiler.py | 59 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 57 insertions(+), 2 deletions(-) diff --git a/tests/test_compiler.py b/tests/test_compiler.py index e25fa1eb..cd1f19c6 100644 --- a/tests/test_compiler.py +++ b/tests/test_compiler.py @@ -1,12 +1,17 @@ +import shlex +import shutil +import os +from unittest import TestCase from unittest.mock import Mock, patch +from subprocess import Popen from pyp5js.compiler import Pyp5jsCompiler, compile_sketch_js -from pyp5js.fs import Pyp5jsSketchFiles +from pyp5js.fs import Pyp5jsSketchFiles, Pyp5jsLibFiles @patch('pyp5js.compiler.Pyp5jsCompiler') def test_compile_sketch_js_service(MockedCompiler): - files = Mock(Pyp5jsSketchFiles) + files = Mock(spec=Pyp5jsSketchFiles) compiler = Mock(spec=Pyp5jsCompiler) MockedCompiler.return_value = compiler @@ -14,3 +19,53 @@ def test_compile_sketch_js_service(MockedCompiler): MockedCompiler.assert_called_once_with(files) compiler.compile_sketch_js.assert_called_once_with() + + +class Pyp5jsCompilerTests(TestCase): + + def setUp(self): + self.pyp5js_files = Pyp5jsLibFiles() + self.files = Pyp5jsSketchFiles('dir', 'foo', check_sketch_dir=False) + self.compiler = Pyp5jsCompiler(self.files) + + os.mkdir(self.files.sketch_dir) + with open(self.files.sketch_py, 'w') as fd: + fd.write('hi') + + def tearDown(self): + try: + if self.files.sketch_dir.exists(): + shutil.rmtree(self.files.sketch_dir) + except SystemExit: + pass + + def test_transcrypt_target_dir_path(self): + assert self.files.sketch_dir.child('__target__') == self.compiler.target_dir + + def test_command_line_string(self): + pyp5_dir = self.pyp5js_files.install + + expected = ' '.join([str(c) for c in [ + 'transcrypt', '-xp', pyp5_dir, '-b', '-m', '-n', self.files.sketch_py + ]]) + + assert expected == self.compiler.command_line + + @patch('pyp5js.compiler.subprocess.Popen') + def test_run_compiler_as_expected(self, MockedPopen): + proc = Mock(spec=Popen) + MockedPopen.return_value = proc + + self.compiler.run_compiler() + expected_command_line = shlex.split(self.compiler.command_line) + + MockedPopen.assert_called_once_with(expected_command_line) + proc.wait.assert_called_once_with() + + def test_clean_up(self): + os.mkdir(self.compiler.target_dir) + + self.compiler.clean_up() + + assert not self.compiler.target_dir.exists() + assert self.files.target_dir.exists() From eae3a52cd710238de133755c5e5f4b1ef10721be Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Tue, 28 May 2019 19:46:29 -0300 Subject: [PATCH 05/32] Add new files to the docs --- docs/index.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/index.md b/docs/index.md index dbe93f7b..03eb160d 100644 --- a/docs/index.md +++ b/docs/index.md @@ -140,7 +140,9 @@ After that, you should have the `pyp5js` command enabled and it will respect all - `cli.py`: the entrypoint for `pyp5js` commands such as `new` or `transcrypt` - `commands.py`: just functions responsible for the real implementations for `pyp5js` commands +- `compiler.py`: where all the magic happens! - `fs.py`: classes to abstract the files and directories manipulations from the commands +- `monitor.py`: module with the objects used by the `monitor` command - `pytop5js.py`: module which is imported by the sketches and integrates with P5.js API - `update_pytop5js`: this script is responsible for generating the `pytop5js.py` file From fdcfea3c230e3e1aa7e5d2195306ce709a00fde2 Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Tue, 28 May 2019 19:47:51 -0300 Subject: [PATCH 06/32] Add test to the compiler entry point --- tests/test_compiler.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/test_compiler.py b/tests/test_compiler.py index cd1f19c6..1da282cc 100644 --- a/tests/test_compiler.py +++ b/tests/test_compiler.py @@ -69,3 +69,11 @@ def test_clean_up(self): assert not self.compiler.target_dir.exists() assert self.files.target_dir.exists() + + @patch.object(Pyp5jsCompiler, 'run_compiler', Mock()) + @patch.object(Pyp5jsCompiler, 'clean_up', Mock()) + def test_compile_sketch_js_orchestrate_compiler(self): + self.compiler.compile_sketch_js() + + self.compiler.run_compiler.assert_called_once_with() + self.compiler.clean_up.assert_called_once_with() From 11365106ba9cd2626289f1817b939c4a5fd80615 Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Fri, 31 May 2019 18:31:22 -0300 Subject: [PATCH 07/32] Refactor code by creating a module to encapsulate templates renderization logic --- pyp5js/pytop5js.py | 4 ++-- pyp5js/templates_renderer.py | 17 +++++++++++++++++ pyp5js/update_pytop5js.py | 16 ++-------------- 3 files changed, 21 insertions(+), 16 deletions(-) create mode 100644 pyp5js/templates_renderer.py diff --git a/pyp5js/pytop5js.py b/pyp5js/pytop5js.py index f8f21f3c..282de906 100644 --- a/pyp5js/pytop5js.py +++ b/pyp5js/pytop5js.py @@ -1004,7 +1004,7 @@ def pre_draw(p5_instance, draw_func): mouseIsPressed = p5_instance.mouseIsPressed touches = p5_instance.touches pixels = p5_instance.pixels - + return draw_func() @@ -1048,4 +1048,4 @@ def sketch_setup(p5_sketch): for f_name in [f for f in event_function_names if f in event_functions]: func = event_functions[f_name] event_func = global_p5_injection(instance)(func) - setattr(instance, f_name, event_func) + setattr(instance, f_name, event_func) \ No newline at end of file diff --git a/pyp5js/templates_renderer.py b/pyp5js/templates_renderer.py new file mode 100644 index 00000000..82ca5fb1 --- /dev/null +++ b/pyp5js/templates_renderer.py @@ -0,0 +1,17 @@ +from jinja2 import Environment, FileSystemLoader, select_autoescape + +from pyp5js.fs import Pyp5jsLibFiles + +pyp5js_files = Pyp5jsLibFiles() + +def get_pytop5js_content(variables_names, methods_names, event_function_names): + templates = Environment(loader=FileSystemLoader(pyp5js_files.templates_dir)) + pyp5_template = templates.get_template( + str(pyp5js_files.pytop5js_template.name) + ) + context = { + 'function_names': methods_names, + 'variables_names': variables_names, + 'event_function_names': event_function_names, + } + return pyp5_template.render(context) diff --git a/pyp5js/update_pytop5js.py b/pyp5js/update_pytop5js.py index 32912f73..772f6307 100644 --- a/pyp5js/update_pytop5js.py +++ b/pyp5js/update_pytop5js.py @@ -1,9 +1,8 @@ import yaml -from jinja2 import Environment, FileSystemLoader, select_autoescape -from unipath import Path from cprint import cprint from pyp5js.fs import Pyp5jsLibFiles, Pyp5jsSketchFiles +from pyp5js.templates_renderer import get_pytop5js_content if __name__ == '__main__': pyp5js_files = Pyp5jsLibFiles() @@ -14,18 +13,7 @@ event_function_names = data['events'] variables_names = data['variables'] - - templates = Environment(loader=FileSystemLoader(pyp5js_files.templates_dir)) - pyp5_template = templates.get_template( - str(pyp5js_files.pytop5js_template.name) - ) - context = { - 'function_names': methods_names, - 'variables_names': variables_names, - 'event_function_names': event_function_names, - } - pyp5_content = pyp5_template.render(context) - + pyp5_content = get_pytop5js_content(variables_names, methods_names, event_function_names) with open(pyp5js_files.pytop5js, 'w') as fd: fd.write(pyp5_content) From de99a9d845e46bf9ebfe7f863601f0a667643fd2 Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Fri, 31 May 2019 18:46:12 -0300 Subject: [PATCH 08/32] Render function to generate the base template for target_sketch.py --- pyp5js/templates_renderer.py | 12 ++++++++++++ tests/test_templates_renderer.py | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 tests/test_templates_renderer.py diff --git a/pyp5js/templates_renderer.py b/pyp5js/templates_renderer.py index 82ca5fb1..178571d0 100644 --- a/pyp5js/templates_renderer.py +++ b/pyp5js/templates_renderer.py @@ -15,3 +15,15 @@ def get_pytop5js_content(variables_names, methods_names, event_function_names): 'event_function_names': event_function_names, } return pyp5_template.render(context) + + +def get_target_sketch_template_content(event_function_names): + content = "import {{ sketch_name }} as source_sketch\nfrom pytop5js import *\n\n" + content += "event_functions = {\n" + + for event in event_function_names: + content += f' "{event}": source_sketch.{event},\n' + + content += '}\n\nstart_p5(sketch_source.setup, sketch_source.draw, event_functions)' + + return content diff --git a/tests/test_templates_renderer.py b/tests/test_templates_renderer.py new file mode 100644 index 00000000..e867212c --- /dev/null +++ b/tests/test_templates_renderer.py @@ -0,0 +1,19 @@ +from pyp5js.templates_renderer import get_target_sketch_template_content + + +def test_get_target_sketch_template_content(): + events = ['keyPressed', 'mouseDragged'] + + expected = """ +import {{ sketch_name }} as source_sketch +from pytop5js import * + +event_functions = { + "keyPressed": source_sketch.keyPressed, + "mouseDragged": source_sketch.mouseDragged, +} + +start_p5(sketch_source.setup, sketch_source.draw, event_functions) +""" + + assert expected.strip() == get_target_sketch_template_content(events) From 3f51d49ba3791df543cd2fda2e425f9b33c6571d Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Fri, 31 May 2019 18:52:00 -0300 Subject: [PATCH 09/32] Update target sketch template after updating pytop5js one --- pyp5js/fs.py | 4 ++++ pyp5js/templates/target_sketch.py.template | 24 ++++++++++++++++++++++ pyp5js/update_pytop5js.py | 8 +++++++- tests/test_fs.py | 3 +++ 4 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 pyp5js/templates/target_sketch.py.template diff --git a/pyp5js/fs.py b/pyp5js/fs.py index fe1e3b66..16c6e4f1 100644 --- a/pyp5js/fs.py +++ b/pyp5js/fs.py @@ -91,6 +91,10 @@ def base_sketch(self): def pytop5js_template(self): return self.templates_dir.child('pytop5js.py.template') + @property + def target_sketch_template(self): + return self.templates_dir.child('target_sketch.py.template') + @property def index_html(self): return self.templates_dir.child('index.html') diff --git a/pyp5js/templates/target_sketch.py.template b/pyp5js/templates/target_sketch.py.template new file mode 100644 index 00000000..188aedea --- /dev/null +++ b/pyp5js/templates/target_sketch.py.template @@ -0,0 +1,24 @@ +import {{ sketch_name }} as source_sketch +from pytop5js import * + +event_functions = { + "deviceMoved": source_sketch.deviceMoved, + "deviceTurned": source_sketch.deviceTurned, + "deviceShaken": source_sketch.deviceShaken, + "keyPressed": source_sketch.keyPressed, + "keyReleased": source_sketch.keyReleased, + "keyTyped": source_sketch.keyTyped, + "mouseMoved": source_sketch.mouseMoved, + "mouseDragged": source_sketch.mouseDragged, + "mousePressed": source_sketch.mousePressed, + "mouseReleased": source_sketch.mouseReleased, + "mouseClicked": source_sketch.mouseClicked, + "doubleClicked": source_sketch.doubleClicked, + "mouseWheel": source_sketch.mouseWheel, + "touchStarted": source_sketch.touchStarted, + "touchMoved": source_sketch.touchMoved, + "touchEnded": source_sketch.touchEnded, + "windowResized": source_sketch.windowResized, +} + +start_p5(sketch_source.setup, sketch_source.draw, event_functions) \ No newline at end of file diff --git a/pyp5js/update_pytop5js.py b/pyp5js/update_pytop5js.py index 772f6307..2ad3659f 100644 --- a/pyp5js/update_pytop5js.py +++ b/pyp5js/update_pytop5js.py @@ -2,7 +2,7 @@ from cprint import cprint from pyp5js.fs import Pyp5jsLibFiles, Pyp5jsSketchFiles -from pyp5js.templates_renderer import get_pytop5js_content +from pyp5js.templates_renderer import get_pytop5js_content, get_target_sketch_template_content if __name__ == '__main__': pyp5js_files = Pyp5jsLibFiles() @@ -18,3 +18,9 @@ fd.write(pyp5_content) cprint.ok(f"File {pyp5js_files.pytop5js} was updated with success.") + + target_content = get_target_sketch_template_content(event_function_names) + with open(pyp5js_files.target_sketch_template, 'w') as fd: + fd.write(target_content) + + cprint.ok(f"File {pyp5js_files.target_sketch_template} was updated with success.") diff --git a/tests/test_fs.py b/tests/test_fs.py index 5635ec0d..21a6db87 100644 --- a/tests/test_fs.py +++ b/tests/test_fs.py @@ -35,6 +35,9 @@ def test_files_properties(lib_files): assert lib_files.pytop5js_template == pyp5_dir.child('templates', 'pytop5js.py.template') assert lib_files.pytop5js_template.exists() + assert lib_files.target_sketch_template == pyp5_dir.child('templates', 'target_sketch.py.template') + assert lib_files.target_sketch_template.exists() + assert lib_files.index_html == pyp5_dir.child('templates', 'index.html') assert lib_files.index_html.exists() From 040bc41aa057d65832c462e2f0970185911e4ff8 Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sat, 1 Jun 2019 16:07:50 -0300 Subject: [PATCH 10/32] Refactor new command to use template renderer --- pyp5js/commands.py | 16 +++------------- pyp5js/templates_renderer.py | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/pyp5js/commands.py b/pyp5js/commands.py index 3ab695f4..180b39e9 100644 --- a/pyp5js/commands.py +++ b/pyp5js/commands.py @@ -4,8 +4,9 @@ from jinja2 import Environment, FileSystemLoader from pyp5js.compiler import compile_sketch_js -from pyp5js.monitor import monitor_sketch as monitor_sketch_service from pyp5js.fs import Pyp5jsSketchFiles, Pyp5jsLibFiles +from pyp5js.monitor import monitor_sketch as monitor_sketch_service +from pyp5js.templates_renderer import get_index_content def new_sketch(sketch_name, sketch_dir): @@ -33,23 +34,12 @@ def new_sketch(sketch_name, sketch_dir): (pyp5js_files.p5js, sketch_files.p5js) ] - context = { - "p5_js_url": f"{Pyp5jsSketchFiles.STATIC_NAME}/p5.js", - "sketch_js_url": f"{Pyp5jsSketchFiles.TARGET_NAME}/{sketch_name}.js", - "sketch_name": sketch_name, - } - - templates = Environment(loader=FileSystemLoader(pyp5js_files.templates_dir)) - index_template = templates.get_template( - str(pyp5js_files.index_html.name) - ) - index_contet = index_template.render(context) - os.makedirs(sketch_files.sketch_dir) os.mkdir(sketch_files.static_dir) for src, dest in templates_files: shutil.copyfile(src, dest) + index_contet = get_index_content(sketch_name) with open(sketch_files.index_html, "w") as fd: fd.write(index_contet) diff --git a/pyp5js/templates_renderer.py b/pyp5js/templates_renderer.py index 178571d0..92652534 100644 --- a/pyp5js/templates_renderer.py +++ b/pyp5js/templates_renderer.py @@ -17,6 +17,20 @@ def get_pytop5js_content(variables_names, methods_names, event_function_names): return pyp5_template.render(context) +def get_index_content(sketch_name, p5_js_url=None, sketch_js_url=None): + context = { + "sketch_name": sketch_name, + "p5_js_url": p5_js_url or f"{Pyp5jsSketchFiles.STATIC_NAME}/p5.js", + "sketch_js_url": sketch_js_url or f"{Pyp5jsSketchFiles.STATIC_NAME}/target_sketch.js", + } + templates = Environment(loader=FileSystemLoader(pyp5js_files.templates_dir)) + index_template = templates.get_template( + str(pyp5js_files.index_html.name) + ) + return index_template.render(context) + + + def get_target_sketch_template_content(event_function_names): content = "import {{ sketch_name }} as source_sketch\nfrom pytop5js import *\n\n" content += "event_functions = {\n" From 60e0fbb9a353f41c1b420f00961d81f9a342231d Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sat, 1 Jun 2019 16:09:14 -0300 Subject: [PATCH 11/32] Prepare target_sketch before running compiler --- pyp5js/compiler.py | 12 +++++++++++- pyp5js/fs.py | 4 ++++ pyp5js/templates_renderer.py | 11 ++++++++++- tests/test_compiler.py | 12 ++++++++++++ tests/test_fs.py | 1 + 5 files changed, 38 insertions(+), 2 deletions(-) diff --git a/pyp5js/compiler.py b/pyp5js/compiler.py index 83f37574..693f3f2d 100644 --- a/pyp5js/compiler.py +++ b/pyp5js/compiler.py @@ -5,7 +5,7 @@ from unipath import Path from pyp5js.fs import Pyp5jsLibFiles - +from pyp5js.templates_renderer import get_target_sketch_content class Pyp5jsCompiler: @@ -15,6 +15,7 @@ def __init__(self, sketch_files): self.sketch_files = sketch_files def compile_sketch_js(self): + self.prepare() self.run_compiler() self.clean_up() @@ -55,6 +56,15 @@ def clean_up(self): shutil.rmtree(self.sketch_files.target_dir) shutil.move(self.target_dir, self.sketch_files.target_dir) + + def prepare(self): + """ + Creates target_sketch.py to import the sketch's functions + """ + with open(self.sketch_files.target_sketch, 'w') as fd: + content = get_target_sketch_content(self.sketch_files.sketch_name) + fd.write(content) + def compile_sketch_js(sketch_files): compiler = Pyp5jsCompiler(sketch_files) compiler.compile_sketch_js() diff --git a/pyp5js/fs.py b/pyp5js/fs.py index 16c6e4f1..98de70ad 100644 --- a/pyp5js/fs.py +++ b/pyp5js/fs.py @@ -42,6 +42,10 @@ def index_html(self): def p5js(self): return self.static_dir.child('p5.js') + @property + def target_sketch(self): + return self.sketch_dir.child("target_sketch.py") + @property def sketch_py(self): py_file = self.sketch_dir.child(f'{self.sketch_name}.py') diff --git a/pyp5js/templates_renderer.py b/pyp5js/templates_renderer.py index 92652534..9ef4f6cb 100644 --- a/pyp5js/templates_renderer.py +++ b/pyp5js/templates_renderer.py @@ -1,6 +1,6 @@ from jinja2 import Environment, FileSystemLoader, select_autoescape -from pyp5js.fs import Pyp5jsLibFiles +from pyp5js.fs import Pyp5jsLibFiles, Pyp5jsSketchFiles pyp5js_files = Pyp5jsLibFiles() @@ -41,3 +41,12 @@ def get_target_sketch_template_content(event_function_names): content += '}\n\nstart_p5(sketch_source.setup, sketch_source.draw, event_functions)' return content + + +def get_target_sketch_content(sketch_name): + context = {"sketch_name": sketch_name} + templates = Environment(loader=FileSystemLoader(pyp5js_files.templates_dir)) + index_template = templates.get_template( + str(pyp5js_files.target_sketch_template.name) + ) + return index_template.render(context) diff --git a/tests/test_compiler.py b/tests/test_compiler.py index cd1f19c6..1c5b8ba1 100644 --- a/tests/test_compiler.py +++ b/tests/test_compiler.py @@ -7,6 +7,7 @@ from pyp5js.compiler import Pyp5jsCompiler, compile_sketch_js from pyp5js.fs import Pyp5jsSketchFiles, Pyp5jsLibFiles +from pyp5js.templates_renderer import get_target_sketch_content @patch('pyp5js.compiler.Pyp5jsCompiler') @@ -69,3 +70,14 @@ def test_clean_up(self): assert not self.compiler.target_dir.exists() assert self.files.target_dir.exists() + + def test_prepare_sketch(self): + expected_content = get_target_sketch_content(self.files.sketch_name) + assert not self.files.target_sketch.exists() + + self.compiler.prepare() + + assert self.files.target_sketch.exists() + with open(self.files.target_sketch, 'r') as fd: + content = fd.read() + assert expected_content == content diff --git a/tests/test_fs.py b/tests/test_fs.py index 21a6db87..e893fa90 100644 --- a/tests/test_fs.py +++ b/tests/test_fs.py @@ -87,6 +87,7 @@ def test_sketch_files(self): assert Path(self.sketch_name).child('index.html') == self.files.index_html assert Path(self.sketch_name).child('static', 'p5.js') == self.files.p5js assert Path(self.sketch_name).child('foo.py') == self.files.sketch_py + assert Path(self.sketch_name).child('target_sketch.py') == self.files.target_sketch def test_sketch_exists(self): self.files.check_sketch_dir = False From 4f37699160f6ac57803dee36a15372bbbe22249a Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sat, 1 Jun 2019 16:09:29 -0300 Subject: [PATCH 12/32] Delete target_sketch on clean up --- pyp5js/compiler.py | 5 ++++- tests/test_compiler.py | 3 +++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/pyp5js/compiler.py b/pyp5js/compiler.py index 693f3f2d..0491597b 100644 --- a/pyp5js/compiler.py +++ b/pyp5js/compiler.py @@ -1,3 +1,4 @@ +import os import shlex import shutil import subprocess @@ -48,7 +49,7 @@ def run_compiler(self): def clean_up(self): """ - Rename the assets dir from __target__ to target + Rename the assets dir from __target__ to target and delete target_sketch.py This is required because github pages can't deal with assets under a __target__ directory """ @@ -56,6 +57,8 @@ def clean_up(self): shutil.rmtree(self.sketch_files.target_dir) shutil.move(self.target_dir, self.sketch_files.target_dir) + if self.sketch_files.target_sketch.exists(): + os.remove(self.sketch_files.target_sketch) def prepare(self): """ diff --git a/tests/test_compiler.py b/tests/test_compiler.py index 1c5b8ba1..4e26aa53 100644 --- a/tests/test_compiler.py +++ b/tests/test_compiler.py @@ -65,11 +65,14 @@ def test_run_compiler_as_expected(self, MockedPopen): def test_clean_up(self): os.mkdir(self.compiler.target_dir) + with open(self.files.target_sketch, 'w') as fd: + fd.write('some content') self.compiler.clean_up() assert not self.compiler.target_dir.exists() assert self.files.target_dir.exists() + assert not self.files.target_sketch.exists() def test_prepare_sketch(self): expected_content = get_target_sketch_content(self.files.sketch_name) From 60fd52217f50163d2ac84abb2e1acfa48028f299 Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sat, 1 Jun 2019 16:32:01 -0300 Subject: [PATCH 13/32] Compiler now uses target_sketch as the entry point --- pyp5js/commands.py | 1 + pyp5js/compiler.py | 2 +- tests/test_compiler.py | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/pyp5js/commands.py b/pyp5js/commands.py index 180b39e9..fe6fc772 100644 --- a/pyp5js/commands.py +++ b/pyp5js/commands.py @@ -34,6 +34,7 @@ def new_sketch(sketch_name, sketch_dir): (pyp5js_files.p5js, sketch_files.p5js) ] + os.makedirs(sketch_files.sketch_dir) os.mkdir(sketch_files.static_dir) for src, dest in templates_files: diff --git a/pyp5js/compiler.py b/pyp5js/compiler.py index 0491597b..670a134a 100644 --- a/pyp5js/compiler.py +++ b/pyp5js/compiler.py @@ -34,7 +34,7 @@ def command_line(self): """ pyp5_dir = self.pyp5js_files.install return ' '.join([str(c) for c in [ - 'transcrypt', '-xp', pyp5_dir, '-b', '-m', '-n', self.sketch_files.sketch_py + 'transcrypt', '-xp', pyp5_dir, '-b', '-m', '-n', self.sketch_files.target_sketch ]]) def run_compiler(self): diff --git a/tests/test_compiler.py b/tests/test_compiler.py index 4e26aa53..51b357c1 100644 --- a/tests/test_compiler.py +++ b/tests/test_compiler.py @@ -47,7 +47,7 @@ def test_command_line_string(self): pyp5_dir = self.pyp5js_files.install expected = ' '.join([str(c) for c in [ - 'transcrypt', '-xp', pyp5_dir, '-b', '-m', '-n', self.files.sketch_py + 'transcrypt', '-xp', pyp5_dir, '-b', '-m', '-n', self.files.target_sketch ]]) assert expected == self.compiler.command_line From ec43465fb087707ff4b6db5297088478d8a45a0a Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sat, 1 Jun 2019 16:32:25 -0300 Subject: [PATCH 14/32] Fix variable error in target_sketch --- pyp5js/templates/target_sketch.py.template | 2 +- pyp5js/templates_renderer.py | 4 ++-- tests/test_templates_renderer.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pyp5js/templates/target_sketch.py.template b/pyp5js/templates/target_sketch.py.template index 188aedea..b2627fee 100644 --- a/pyp5js/templates/target_sketch.py.template +++ b/pyp5js/templates/target_sketch.py.template @@ -21,4 +21,4 @@ event_functions = { "windowResized": source_sketch.windowResized, } -start_p5(sketch_source.setup, sketch_source.draw, event_functions) \ No newline at end of file +start_p5(source_sketch.setup, source_sketch.draw, event_functions) \ No newline at end of file diff --git a/pyp5js/templates_renderer.py b/pyp5js/templates_renderer.py index 9ef4f6cb..fc1ddaa2 100644 --- a/pyp5js/templates_renderer.py +++ b/pyp5js/templates_renderer.py @@ -21,7 +21,7 @@ def get_index_content(sketch_name, p5_js_url=None, sketch_js_url=None): context = { "sketch_name": sketch_name, "p5_js_url": p5_js_url or f"{Pyp5jsSketchFiles.STATIC_NAME}/p5.js", - "sketch_js_url": sketch_js_url or f"{Pyp5jsSketchFiles.STATIC_NAME}/target_sketch.js", + "sketch_js_url": sketch_js_url or f"{Pyp5jsSketchFiles.TARGET_NAME}/target_sketch.js", } templates = Environment(loader=FileSystemLoader(pyp5js_files.templates_dir)) index_template = templates.get_template( @@ -38,7 +38,7 @@ def get_target_sketch_template_content(event_function_names): for event in event_function_names: content += f' "{event}": source_sketch.{event},\n' - content += '}\n\nstart_p5(sketch_source.setup, sketch_source.draw, event_functions)' + content += '}\n\nstart_p5(source_sketch.setup, source_sketch.draw, event_functions)' return content diff --git a/tests/test_templates_renderer.py b/tests/test_templates_renderer.py index e867212c..b6a77eec 100644 --- a/tests/test_templates_renderer.py +++ b/tests/test_templates_renderer.py @@ -13,7 +13,7 @@ def test_get_target_sketch_template_content(): "mouseDragged": source_sketch.mouseDragged, } -start_p5(sketch_source.setup, sketch_source.draw, event_functions) +start_p5(source_sketch.setup, source_sketch.draw, event_functions) """ assert expected.strip() == get_target_sketch_template_content(events) From 70e8553d96afa5c4b786e97cefa4f17a766517f5 Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sat, 1 Jun 2019 16:33:07 -0300 Subject: [PATCH 15/32] All events are now present keys with a function or a None value --- pyp5js/pytop5js.py | 2 +- pyp5js/templates/pytop5js.py.template | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pyp5js/pytop5js.py b/pyp5js/pytop5js.py index 282de906..6462430c 100644 --- a/pyp5js/pytop5js.py +++ b/pyp5js/pytop5js.py @@ -1045,7 +1045,7 @@ def sketch_setup(p5_sketch): # inject event functions into p5 event_function_names = ["deviceMoved", "deviceTurned", "deviceShaken", "keyPressed", "keyReleased", "keyTyped", "mouseMoved", "mouseDragged", "mousePressed", "mouseReleased", "mouseClicked", "doubleClicked", "mouseWheel", "touchStarted", "touchMoved", "touchEnded", "windowResized", ] - for f_name in [f for f in event_function_names if f in event_functions]: + for f_name in [f for f in event_function_names if event_functions.get(f, None)]: func = event_functions[f_name] event_func = global_p5_injection(instance)(func) setattr(instance, f_name, event_func) \ No newline at end of file diff --git a/pyp5js/templates/pytop5js.py.template b/pyp5js/templates/pytop5js.py.template index e055fc72..5c2d1494 100644 --- a/pyp5js/templates/pytop5js.py.template +++ b/pyp5js/templates/pytop5js.py.template @@ -69,7 +69,7 @@ def start_p5(setup_func, draw_func, event_functions): # inject event functions into p5 event_function_names = [{% for f in event_function_names %}"{{ f }}", {% endfor %}] - for f_name in [f for f in event_function_names if f in event_functions]: + for f_name in [f for f in event_function_names if event_functions.get(f, None)]: func = event_functions[f_name] event_func = global_p5_injection(instance)(func) setattr(instance, f_name, event_func) From 45dc3b3ab130f938bc3fef62659ef45e6b0d6967 Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sat, 1 Jun 2019 16:33:26 -0300 Subject: [PATCH 16/32] event_functions and start_p5 is no longer required in the sketch file --- pyp5js/templates/base_sketch.py | 9 --------- 1 file changed, 9 deletions(-) diff --git a/pyp5js/templates/base_sketch.py b/pyp5js/templates/base_sketch.py index 9325a2d2..f24d08c8 100644 --- a/pyp5js/templates/base_sketch.py +++ b/pyp5js/templates/base_sketch.py @@ -6,12 +6,3 @@ def setup(): def draw(): pass - - -# ==== This is required by pyp5js to work - -# Register your events functions here -event_functions = { - # "keyPressed": keyPressed, as an example -} -start_p5(setup, draw, event_functions) From 9758f05e77d2e01b6fd5689c6d08d27c06b8b8a7 Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sat, 1 Jun 2019 16:42:38 -0300 Subject: [PATCH 17/32] Update all examples sketches to the new format --- docs/examples/sketch_001/sketch_001.py | 3 - .../target/org.transcrypt.__runtime__.js | 2 +- docs/examples/sketch_001/target/pytop5js.js | 334 +++++++++++++---- docs/examples/sketch_001/target/pytop5js.py | 338 ++++++++++++++---- docs/examples/sketch_001/target/sketch_001.js | 7 +- docs/examples/sketch_001/target/sketch_001.py | 3 - .../sketch_001/target/target_sketch.js | 9 + ...etch_001.options => target_sketch.options} | Bin 604 -> 607 bytes .../sketch_001/target/target_sketch.py | 24 ++ docs/examples/sketch_002/sketch_002.py | 4 - .../target/org.transcrypt.__runtime__.js | 2 +- docs/examples/sketch_002/target/pytop5js.js | 334 +++++++++++++---- docs/examples/sketch_002/target/pytop5js.py | 338 ++++++++++++++---- docs/examples/sketch_002/target/sketch_002.js | 7 +- docs/examples/sketch_002/target/sketch_002.py | 4 - .../sketch_002/target/target_sketch.js | 9 + ...etch_002.options => target_sketch.options} | Bin 604 -> 607 bytes .../sketch_002/target/target_sketch.py | 24 ++ docs/examples/sketch_003/sketch_003.py | 21 +- .../target/org.transcrypt.__runtime__.js | 2 +- docs/examples/sketch_003/target/pytop5js.js | 334 +++++++++++++---- docs/examples/sketch_003/target/pytop5js.py | 338 ++++++++++++++---- docs/examples/sketch_003/target/sketch_003.js | 7 +- docs/examples/sketch_003/target/sketch_003.py | 21 +- .../sketch_003/target/target_sketch.js | 9 + ...etch_003.options => target_sketch.options} | Bin 604 -> 607 bytes .../sketch_003/target/target_sketch.py | 24 ++ docs/examples/sketch_004/sketch_004.py | 4 - .../target/org.transcrypt.__runtime__.js | 2 +- docs/examples/sketch_004/target/pytop5js.js | 334 +++++++++++++---- docs/examples/sketch_004/target/pytop5js.py | 338 ++++++++++++++---- docs/examples/sketch_004/target/sketch_004.js | 9 +- docs/examples/sketch_004/target/sketch_004.py | 4 - .../sketch_004/target/target_sketch.js | 9 + ...etch_004.options => target_sketch.options} | Bin 604 -> 607 bytes .../sketch_004/target/target_sketch.py | 24 ++ docs/examples/sketch_005/sketch_005.py | 4 - .../target/org.transcrypt.__runtime__.js | 2 +- docs/examples/sketch_005/target/pytop5js.js | 334 +++++++++++++---- docs/examples/sketch_005/target/pytop5js.py | 338 ++++++++++++++---- docs/examples/sketch_005/target/sketch_005.js | 7 +- .../sketch_005/target/sketch_005.options | Bin 604 -> 0 bytes docs/examples/sketch_005/target/sketch_005.py | 4 - .../sketch_005/target/target_sketch.js | 9 + .../sketch_005/target/target_sketch.options | Bin 0 -> 607 bytes .../sketch_005/target/target_sketch.py | 24 ++ docs/examples/sketch_006/sketch_006.py | 6 - .../target/org.transcrypt.__runtime__.js | 2 +- docs/examples/sketch_006/target/pytop5js.js | 334 +++++++++++++---- docs/examples/sketch_006/target/pytop5js.py | 338 ++++++++++++++---- docs/examples/sketch_006/target/sketch_006.js | 8 +- .../sketch_006/target/sketch_006.options | Bin 604 -> 0 bytes docs/examples/sketch_006/target/sketch_006.py | 6 - .../sketch_006/target/target_sketch.js | 9 + .../sketch_006/target/target_sketch.options | Bin 0 -> 607 bytes .../sketch_006/target/target_sketch.py | 24 ++ docs/examples/sketch_007/sketch_007.py | 9 - .../target/org.transcrypt.__runtime__.js | 2 +- docs/examples/sketch_007/target/pytop5js.js | 314 ++++++++-------- docs/examples/sketch_007/target/pytop5js.py | 314 ++++++++-------- docs/examples/sketch_007/target/sketch_007.js | 6 +- .../sketch_007/target/sketch_007.options | Bin 604 -> 0 bytes docs/examples/sketch_007/target/sketch_007.py | 9 - .../sketch_007/target/target_sketch.js | 9 + .../sketch_007/target/target_sketch.options | Bin 0 -> 607 bytes .../sketch_007/target/target_sketch.py | 24 ++ 66 files changed, 3756 insertions(+), 1302 deletions(-) create mode 100644 docs/examples/sketch_001/target/target_sketch.js rename docs/examples/sketch_001/target/{sketch_001.options => target_sketch.options} (73%) create mode 100644 docs/examples/sketch_001/target/target_sketch.py create mode 100644 docs/examples/sketch_002/target/target_sketch.js rename docs/examples/sketch_002/target/{sketch_002.options => target_sketch.options} (73%) create mode 100644 docs/examples/sketch_002/target/target_sketch.py create mode 100644 docs/examples/sketch_003/target/target_sketch.js rename docs/examples/sketch_003/target/{sketch_003.options => target_sketch.options} (73%) create mode 100644 docs/examples/sketch_003/target/target_sketch.py create mode 100644 docs/examples/sketch_004/target/target_sketch.js rename docs/examples/sketch_004/target/{sketch_004.options => target_sketch.options} (73%) create mode 100644 docs/examples/sketch_004/target/target_sketch.py delete mode 100644 docs/examples/sketch_005/target/sketch_005.options create mode 100644 docs/examples/sketch_005/target/target_sketch.js create mode 100644 docs/examples/sketch_005/target/target_sketch.options create mode 100644 docs/examples/sketch_005/target/target_sketch.py delete mode 100644 docs/examples/sketch_006/target/sketch_006.options create mode 100644 docs/examples/sketch_006/target/target_sketch.js create mode 100644 docs/examples/sketch_006/target/target_sketch.options create mode 100644 docs/examples/sketch_006/target/target_sketch.py delete mode 100644 docs/examples/sketch_007/target/sketch_007.options create mode 100644 docs/examples/sketch_007/target/target_sketch.js create mode 100644 docs/examples/sketch_007/target/target_sketch.options create mode 100644 docs/examples/sketch_007/target/target_sketch.py diff --git a/docs/examples/sketch_001/sketch_001.py b/docs/examples/sketch_001/sketch_001.py index 22187469..ba40688a 100644 --- a/docs/examples/sketch_001/sketch_001.py +++ b/docs/examples/sketch_001/sketch_001.py @@ -31,6 +31,3 @@ def draw(): t = t + 0.01 console.log(frameRate()) - - -my_p5 = start_p5(setup, draw, {}) diff --git a/docs/examples/sketch_001/target/org.transcrypt.__runtime__.js b/docs/examples/sketch_001/target/org.transcrypt.__runtime__.js index 002b3211..c2a809e9 100644 --- a/docs/examples/sketch_001/target/org.transcrypt.__runtime__.js +++ b/docs/examples/sketch_001/target/org.transcrypt.__runtime__.js @@ -1,4 +1,4 @@ -// Transcrypt'ed from Python, 2019-05-09 00:35:58 +// Transcrypt'ed from Python, 2019-06-01 16:39:00 var __name__ = 'org.transcrypt.__runtime__'; export var __envir__ = {}; __envir__.interpreter_name = 'python'; diff --git a/docs/examples/sketch_001/target/pytop5js.js b/docs/examples/sketch_001/target/pytop5js.js index 9e3f2cb5..895472ea 100644 --- a/docs/examples/sketch_001/target/pytop5js.js +++ b/docs/examples/sketch_001/target/pytop5js.js @@ -1,7 +1,157 @@ -// Transcrypt'ed from Python, 2019-05-09 00:35:58 +// Transcrypt'ed from Python, 2019-06-01 16:39:00 import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, input, isinstance, issubclass, len, list, object, ord, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; var __name__ = 'pytop5js'; export var _P5_INSTANCE = null; +export var _CTX_MIDDLE = null; +export var _DEFAULT_FILL = null; +export var _DEFAULT_LEADMULT = null; +export var _DEFAULT_STROKE = null; +export var _DEFAULT_TEXT_FILL = null; +export var ADD = null; +export var ALT = null; +export var ARROW = null; +export var AUTO = null; +export var AXES = null; +export var BACKSPACE = null; +export var BASELINE = null; +export var BEVEL = null; +export var BEZIER = null; +export var BLEND = null; +export var BLUR = null; +export var BOLD = null; +export var BOLDITALIC = null; +export var BOTTOM = null; +export var BURN = null; +export var CENTER = null; +export var CHORD = null; +export var CLAMP = null; +export var CLOSE = null; +export var CONTROL = null; +export var CORNER = null; +export var CORNERS = null; +export var CROSS = null; +export var CURVE = null; +export var DARKEST = null; +export var DEG_TO_RAD = null; +export var DEGREES = null; +export var DELETE = null; +export var DIFFERENCE = null; +export var DILATE = null; +export var DODGE = null; +export var DOWN_ARROW = null; +export var ENTER = null; +export var ERODE = null; +export var ESCAPE = null; +export var EXCLUSION = null; +export var FILL = null; +export var GRAY = null; +export var GRID = null; +export var HALF_PI = null; +export var HAND = null; +export var HARD_LIGHT = null; +export var HSB = null; +export var HSL = null; +export var IMAGE = null; +export var IMMEDIATE = null; +export var INVERT = null; +export var ITALIC = null; +export var LANDSCAPE = null; +export var LEFT = null; +export var LEFT_ARROW = null; +export var LIGHTEST = null; +export var LINE_LOOP = null; +export var LINE_STRIP = null; +export var LINEAR = null; +export var LINES = null; +export var MIRROR = null; +export var MITER = null; +export var MOVE = null; +export var MULTIPLY = null; +export var NEAREST = null; +export var NORMAL = null; +export var OPAQUE = null; +export var OPEN = null; +export var OPTION = null; +export var OVERLAY = null; +export var PI = null; +export var PIE = null; +export var POINTS = null; +export var PORTRAIT = null; +export var POSTERIZE = null; +export var PROJECT = null; +export var QUAD_STRIP = null; +export var QUADRATIC = null; +export var QUADS = null; +export var QUARTER_PI = null; +export var RAD_TO_DEG = null; +export var RADIANS = null; +export var RADIUS = null; +export var REPEAT = null; +export var REPLACE = null; +export var RETURN = null; +export var RGB = null; +export var RIGHT = null; +export var RIGHT_ARROW = null; +export var ROUND = null; +export var SCREEN = null; +export var SHIFT = null; +export var SOFT_LIGHT = null; +export var SQUARE = null; +export var STROKE = null; +export var SUBTRACT = null; +export var TAB = null; +export var TAU = null; +export var TEXT = null; +export var TEXTURE = null; +export var THRESHOLD = null; +export var TOP = null; +export var TRIANGLE_FAN = null; +export var TRIANGLE_STRIP = null; +export var TRIANGLES = null; +export var TWO_PI = null; +export var UP_ARROW = null; +export var WAIT = null; +export var WEBGL = null; +export var P2D = null; +var PI = null; +export var frameCount = null; +export var focused = null; +export var displayWidth = null; +export var displayHeight = null; +export var windowWidth = null; +export var windowHeight = null; +export var width = null; +export var height = null; +export var disableFriendlyErrors = null; +export var deviceOrientation = null; +export var accelerationX = null; +export var accelerationY = null; +export var accelerationZ = null; +export var pAccelerationX = null; +export var pAccelerationY = null; +export var pAccelerationZ = null; +export var rotationX = null; +export var rotationY = null; +export var rotationZ = null; +export var pRotationX = null; +export var pRotationY = null; +export var pRotationZ = null; +export var turnAxis = null; +export var keyIsPressed = null; +export var key = null; +export var keyCode = null; +export var mouseX = null; +export var mouseY = null; +export var pmouseX = null; +export var pmouseY = null; +export var winMouseX = null; +export var winMouseY = null; +export var pwinMouseX = null; +export var pwinMouseY = null; +export var mouseButton = null; +export var mouseIsPressed = null; +export var touches = null; +export var pixels = null; export var alpha = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.alpha (...args); @@ -310,10 +460,6 @@ export var redraw = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.redraw (...args); }; -export var createCanvas = function () { - var args = tuple ([].slice.apply (arguments).slice (0)); - return _P5_INSTANCE.createCanvas (...args); -}; export var resizeCanvas = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.resizeCanvas (...args); @@ -914,86 +1060,130 @@ export var setCamera = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.setCamera (...args); }; +export var createCanvas = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + var result = _P5_INSTANCE.createCanvas (...args); + width = _P5_INSTANCE.width; + height = _P5_INSTANCE.height; +}; export var py_pop = function () { var args = tuple ([].slice.apply (arguments).slice (0)); var p5_pop = _P5_INSTANCE.pop (...args); return p5_pop; }; -export var HALF_PI = null; -export var PI = null; -export var QUARTER_PI = null; -export var TAU = null; -export var TWO_PI = null; -export var DEGREES = null; -export var RADIANS = null; -export var CLOSE = null; -export var RGB = null; -export var HSB = null; -export var CMYK = null; -export var TOP = null; -export var BOTTOM = null; -export var CENTER = null; -export var LEFT = null; -export var RIGHT = null; -export var SHIFT = null; -export var WEBGL = null; -export var frameCount = null; -export var focused = null; -export var displayWidth = null; -export var displayHeight = null; -export var windowWidth = null; -export var windowHeight = null; -export var width = null; -export var height = null; -export var disableFriendlyErrors = null; -export var deviceOrientation = null; -export var accelerationX = null; -export var accelerationY = null; -export var accelerationZ = null; -export var pAccelerationX = null; -export var pAccelerationY = null; -export var pAccelerationZ = null; -export var rotationX = null; -export var rotationY = null; -export var rotationZ = null; -export var pRotationX = null; -export var pRotationY = null; -export var pRotationZ = null; -export var turnAxis = null; -export var keyIsPressed = null; -export var key = null; -export var keyCode = null; -export var mouseX = null; -export var mouseY = null; -export var pmouseX = null; -export var pmouseY = null; -export var winMouseX = null; -export var winMouseY = null; -export var pwinMouseX = null; -export var pwinMouseY = null; -export var mouseButton = null; -export var mouseIsPressed = null; -export var touches = null; -export var pixels = null; export var pre_draw = function (p5_instance, draw_func) { + _CTX_MIDDLE = p5_instance._CTX_MIDDLE; + _DEFAULT_FILL = p5_instance._DEFAULT_FILL; + _DEFAULT_LEADMULT = p5_instance._DEFAULT_LEADMULT; + _DEFAULT_STROKE = p5_instance._DEFAULT_STROKE; + _DEFAULT_TEXT_FILL = p5_instance._DEFAULT_TEXT_FILL; + ADD = p5_instance.ADD; + ALT = p5_instance.ALT; + ARROW = p5_instance.ARROW; + AUTO = p5_instance.AUTO; + AXES = p5_instance.AXES; + BACKSPACE = p5_instance.BACKSPACE; + BASELINE = p5_instance.BASELINE; + BEVEL = p5_instance.BEVEL; + BEZIER = p5_instance.BEZIER; + BLEND = p5_instance.BLEND; + BLUR = p5_instance.BLUR; + BOLD = p5_instance.BOLD; + BOLDITALIC = p5_instance.BOLDITALIC; + BOTTOM = p5_instance.BOTTOM; + BURN = p5_instance.BURN; + CENTER = p5_instance.CENTER; + CHORD = p5_instance.CHORD; + CLAMP = p5_instance.CLAMP; + CLOSE = p5_instance.CLOSE; + CONTROL = p5_instance.CONTROL; + CORNER = p5_instance.CORNER; + CORNERS = p5_instance.CORNERS; + CROSS = p5_instance.CROSS; + CURVE = p5_instance.CURVE; + DARKEST = p5_instance.DARKEST; + DEG_TO_RAD = p5_instance.DEG_TO_RAD; + DEGREES = p5_instance.DEGREES; + DELETE = p5_instance.DELETE; + DIFFERENCE = p5_instance.DIFFERENCE; + DILATE = p5_instance.DILATE; + DODGE = p5_instance.DODGE; + DOWN_ARROW = p5_instance.DOWN_ARROW; + ENTER = p5_instance.ENTER; + ERODE = p5_instance.ERODE; + ESCAPE = p5_instance.ESCAPE; + EXCLUSION = p5_instance.EXCLUSION; + FILL = p5_instance.FILL; + GRAY = p5_instance.GRAY; + GRID = p5_instance.GRID; HALF_PI = p5_instance.HALF_PI; + HAND = p5_instance.HAND; + HARD_LIGHT = p5_instance.HARD_LIGHT; + HSB = p5_instance.HSB; + HSL = p5_instance.HSL; + IMAGE = p5_instance.IMAGE; + IMMEDIATE = p5_instance.IMMEDIATE; + INVERT = p5_instance.INVERT; + ITALIC = p5_instance.ITALIC; + LANDSCAPE = p5_instance.LANDSCAPE; + LEFT = p5_instance.LEFT; + LEFT_ARROW = p5_instance.LEFT_ARROW; + LIGHTEST = p5_instance.LIGHTEST; + LINE_LOOP = p5_instance.LINE_LOOP; + LINE_STRIP = p5_instance.LINE_STRIP; + LINEAR = p5_instance.LINEAR; + LINES = p5_instance.LINES; + MIRROR = p5_instance.MIRROR; + MITER = p5_instance.MITER; + MOVE = p5_instance.MOVE; + MULTIPLY = p5_instance.MULTIPLY; + NEAREST = p5_instance.NEAREST; + NORMAL = p5_instance.NORMAL; + OPAQUE = p5_instance.OPAQUE; + OPEN = p5_instance.OPEN; + OPTION = p5_instance.OPTION; + OVERLAY = p5_instance.OVERLAY; PI = p5_instance.PI; + PIE = p5_instance.PIE; + POINTS = p5_instance.POINTS; + PORTRAIT = p5_instance.PORTRAIT; + POSTERIZE = p5_instance.POSTERIZE; + PROJECT = p5_instance.PROJECT; + QUAD_STRIP = p5_instance.QUAD_STRIP; + QUADRATIC = p5_instance.QUADRATIC; + QUADS = p5_instance.QUADS; QUARTER_PI = p5_instance.QUARTER_PI; - TAU = p5_instance.TAU; - TWO_PI = p5_instance.TWO_PI; - DEGREES = p5_instance.DEGREES; + RAD_TO_DEG = p5_instance.RAD_TO_DEG; RADIANS = p5_instance.RADIANS; - CLOSE = p5_instance.CLOSE; + RADIUS = p5_instance.RADIUS; + REPEAT = p5_instance.REPEAT; + REPLACE = p5_instance.REPLACE; + RETURN = p5_instance.RETURN; RGB = p5_instance.RGB; - HSB = p5_instance.HSB; - CMYK = p5_instance.CMYK; - TOP = p5_instance.TOP; - BOTTOM = p5_instance.BOTTOM; - CENTER = p5_instance.CENTER; - LEFT = p5_instance.LEFT; RIGHT = p5_instance.RIGHT; + RIGHT_ARROW = p5_instance.RIGHT_ARROW; + ROUND = p5_instance.ROUND; + SCREEN = p5_instance.SCREEN; SHIFT = p5_instance.SHIFT; + SOFT_LIGHT = p5_instance.SOFT_LIGHT; + SQUARE = p5_instance.SQUARE; + STROKE = p5_instance.STROKE; + SUBTRACT = p5_instance.SUBTRACT; + TAB = p5_instance.TAB; + TAU = p5_instance.TAU; + TEXT = p5_instance.TEXT; + TEXTURE = p5_instance.TEXTURE; + THRESHOLD = p5_instance.THRESHOLD; + TOP = p5_instance.TOP; + TRIANGLE_FAN = p5_instance.TRIANGLE_FAN; + TRIANGLE_STRIP = p5_instance.TRIANGLE_STRIP; + TRIANGLES = p5_instance.TRIANGLES; + TWO_PI = p5_instance.TWO_PI; + UP_ARROW = p5_instance.UP_ARROW; + WAIT = p5_instance.WAIT; WEBGL = p5_instance.WEBGL; + P2D = p5_instance.P2D; + PI = p5_instance.PI; frameCount = p5_instance.frameCount; focused = p5_instance.focused; displayWidth = p5_instance.displayWidth; @@ -1054,7 +1244,7 @@ export var start_p5 = function (setup_func, draw_func, event_functions) { for (var f_name of (function () { var __accu0__ = []; for (var f of event_function_names) { - if (__in__ (f, event_functions)) { + if (event_functions.py_get (f, null)) { __accu0__.append (f); } } diff --git a/docs/examples/sketch_001/target/pytop5js.py b/docs/examples/sketch_001/target/pytop5js.py index 59388176..6462430c 100644 --- a/docs/examples/sketch_001/target/pytop5js.py +++ b/docs/examples/sketch_001/target/pytop5js.py @@ -1,4 +1,155 @@ _P5_INSTANCE = None +_CTX_MIDDLE = None +_DEFAULT_FILL = None +_DEFAULT_LEADMULT = None +_DEFAULT_STROKE = None +_DEFAULT_TEXT_FILL = None +ADD = None +ALT = None +ARROW = None +AUTO = None +AXES = None +BACKSPACE = None +BASELINE = None +BEVEL = None +BEZIER = None +BLEND = None +BLUR = None +BOLD = None +BOLDITALIC = None +BOTTOM = None +BURN = None +CENTER = None +CHORD = None +CLAMP = None +CLOSE = None +CONTROL = None +CORNER = None +CORNERS = None +CROSS = None +CURVE = None +DARKEST = None +DEG_TO_RAD = None +DEGREES = None +DELETE = None +DIFFERENCE = None +DILATE = None +DODGE = None +DOWN_ARROW = None +ENTER = None +ERODE = None +ESCAPE = None +EXCLUSION = None +FILL = None +GRAY = None +GRID = None +HALF_PI = None +HAND = None +HARD_LIGHT = None +HSB = None +HSL = None +IMAGE = None +IMMEDIATE = None +INVERT = None +ITALIC = None +LANDSCAPE = None +LEFT = None +LEFT_ARROW = None +LIGHTEST = None +LINE_LOOP = None +LINE_STRIP = None +LINEAR = None +LINES = None +MIRROR = None +MITER = None +MOVE = None +MULTIPLY = None +NEAREST = None +NORMAL = None +OPAQUE = None +OPEN = None +OPTION = None +OVERLAY = None +PI = None +PIE = None +POINTS = None +PORTRAIT = None +POSTERIZE = None +PROJECT = None +QUAD_STRIP = None +QUADRATIC = None +QUADS = None +QUARTER_PI = None +RAD_TO_DEG = None +RADIANS = None +RADIUS = None +REPEAT = None +REPLACE = None +RETURN = None +RGB = None +RIGHT = None +RIGHT_ARROW = None +ROUND = None +SCREEN = None +SHIFT = None +SOFT_LIGHT = None +SQUARE = None +STROKE = None +SUBTRACT = None +TAB = None +TAU = None +TEXT = None +TEXTURE = None +THRESHOLD = None +TOP = None +TRIANGLE_FAN = None +TRIANGLE_STRIP = None +TRIANGLES = None +TWO_PI = None +UP_ARROW = None +WAIT = None +WEBGL = None +P2D = None +PI = None +frameCount = None +focused = None +displayWidth = None +displayHeight = None +windowWidth = None +windowHeight = None +width = None +height = None +disableFriendlyErrors = None +deviceOrientation = None +accelerationX = None +accelerationY = None +accelerationZ = None +pAccelerationX = None +pAccelerationY = None +pAccelerationZ = None +rotationX = None +rotationY = None +rotationZ = None +pRotationX = None +pRotationY = None +pRotationZ = None +turnAxis = None +keyIsPressed = None +key = None +keyCode = None +mouseX = None +mouseY = None +pmouseX = None +pmouseY = None +winMouseX = None +winMouseY = None +pwinMouseX = None +pwinMouseY = None +mouseButton = None +mouseIsPressed = None +touches = None +pixels = None + def alpha(*args): @@ -232,9 +383,6 @@ def push(*args): def redraw(*args): return _P5_INSTANCE.redraw(*args) -def createCanvas(*args): - return _P5_INSTANCE.createCanvas(*args) - def resizeCanvas(*args): return _P5_INSTANCE.resizeCanvas(*args) @@ -686,6 +834,13 @@ def setCamera(*args): return _P5_INSTANCE.setCamera(*args) +def createCanvas(*args): + result = _P5_INSTANCE.createCanvas(*args) + + global width, height + width = _P5_INSTANCE.width + height = _P5_INSTANCE.height + def pop(*args): __pragma__('noalias', 'pop') @@ -693,87 +848,124 @@ def pop(*args): __pragma__('alias', 'pop', 'py_pop') return p5_pop -HALF_PI = None -PI = None -QUARTER_PI = None -TAU = None -TWO_PI = None -DEGREES = None -RADIANS = None -CLOSE = None -RGB = None -HSB = None -CMYK = None -TOP = None -BOTTOM = None -CENTER = None -LEFT = None -RIGHT = None -SHIFT = None -WEBGL = None -frameCount = None -focused = None -displayWidth = None -displayHeight = None -windowWidth = None -windowHeight = None -width = None -height = None -disableFriendlyErrors = None -deviceOrientation = None -accelerationX = None -accelerationY = None -accelerationZ = None -pAccelerationX = None -pAccelerationY = None -pAccelerationZ = None -rotationX = None -rotationY = None -rotationZ = None -pRotationX = None -pRotationY = None -pRotationZ = None -turnAxis = None -keyIsPressed = None -key = None -keyCode = None -mouseX = None -mouseY = None -pmouseX = None -pmouseY = None -winMouseX = None -winMouseY = None -pwinMouseX = None -pwinMouseY = None -mouseButton = None -mouseIsPressed = None -touches = None -pixels = None - def pre_draw(p5_instance, draw_func): """ We need to run this before the actual draw to insert and update p5 env variables """ - global HALF_PI, PI, QUARTER_PI, TAU, TWO_PI, DEGREES, RADIANS, CLOSE, RGB, HSB, CMYK, TOP, BOTTOM, CENTER, LEFT, RIGHT, SHIFT, WEBGL, frameCount, focused, displayWidth, displayHeight, windowWidth, windowHeight, width, height, disableFriendlyErrors, deviceOrientation, accelerationX, accelerationY, accelerationZ, pAccelerationX, pAccelerationY, pAccelerationZ, rotationX, rotationY, rotationZ, pRotationX, pRotationY, pRotationZ, turnAxis, keyIsPressed, key, keyCode, mouseX, mouseY, pmouseX, pmouseY, winMouseX, winMouseY, pwinMouseX, pwinMouseY, mouseButton, mouseIsPressed, touches, pixels - + global _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEG_TO_RAD, DEGREES, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINE_LOOP, LINE_STRIP, LINEAR, LINES, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUAD_STRIP, QUADRATIC, QUADS, QUARTER_PI, RAD_TO_DEG, RADIANS, RADIUS, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLE_FAN, TRIANGLE_STRIP, TRIANGLES, TWO_PI, UP_ARROW, WAIT, WEBGL, P2D, PI, frameCount, focused, displayWidth, displayHeight, windowWidth, windowHeight, width, height, disableFriendlyErrors, deviceOrientation, accelerationX, accelerationY, accelerationZ, pAccelerationX, pAccelerationY, pAccelerationZ, rotationX, rotationY, rotationZ, pRotationX, pRotationY, pRotationZ, turnAxis, keyIsPressed, key, keyCode, mouseX, mouseY, pmouseX, pmouseY, winMouseX, winMouseY, pwinMouseX, pwinMouseY, mouseButton, mouseIsPressed, touches, pixels + + _CTX_MIDDLE = p5_instance._CTX_MIDDLE + _DEFAULT_FILL = p5_instance._DEFAULT_FILL + _DEFAULT_LEADMULT = p5_instance._DEFAULT_LEADMULT + _DEFAULT_STROKE = p5_instance._DEFAULT_STROKE + _DEFAULT_TEXT_FILL = p5_instance._DEFAULT_TEXT_FILL + ADD = p5_instance.ADD + ALT = p5_instance.ALT + ARROW = p5_instance.ARROW + AUTO = p5_instance.AUTO + AXES = p5_instance.AXES + BACKSPACE = p5_instance.BACKSPACE + BASELINE = p5_instance.BASELINE + BEVEL = p5_instance.BEVEL + BEZIER = p5_instance.BEZIER + BLEND = p5_instance.BLEND + BLUR = p5_instance.BLUR + BOLD = p5_instance.BOLD + BOLDITALIC = p5_instance.BOLDITALIC + BOTTOM = p5_instance.BOTTOM + BURN = p5_instance.BURN + CENTER = p5_instance.CENTER + CHORD = p5_instance.CHORD + CLAMP = p5_instance.CLAMP + CLOSE = p5_instance.CLOSE + CONTROL = p5_instance.CONTROL + CORNER = p5_instance.CORNER + CORNERS = p5_instance.CORNERS + CROSS = p5_instance.CROSS + CURVE = p5_instance.CURVE + DARKEST = p5_instance.DARKEST + DEG_TO_RAD = p5_instance.DEG_TO_RAD + DEGREES = p5_instance.DEGREES + DELETE = p5_instance.DELETE + DIFFERENCE = p5_instance.DIFFERENCE + DILATE = p5_instance.DILATE + DODGE = p5_instance.DODGE + DOWN_ARROW = p5_instance.DOWN_ARROW + ENTER = p5_instance.ENTER + ERODE = p5_instance.ERODE + ESCAPE = p5_instance.ESCAPE + EXCLUSION = p5_instance.EXCLUSION + FILL = p5_instance.FILL + GRAY = p5_instance.GRAY + GRID = p5_instance.GRID HALF_PI = p5_instance.HALF_PI + HAND = p5_instance.HAND + HARD_LIGHT = p5_instance.HARD_LIGHT + HSB = p5_instance.HSB + HSL = p5_instance.HSL + IMAGE = p5_instance.IMAGE + IMMEDIATE = p5_instance.IMMEDIATE + INVERT = p5_instance.INVERT + ITALIC = p5_instance.ITALIC + LANDSCAPE = p5_instance.LANDSCAPE + LEFT = p5_instance.LEFT + LEFT_ARROW = p5_instance.LEFT_ARROW + LIGHTEST = p5_instance.LIGHTEST + LINE_LOOP = p5_instance.LINE_LOOP + LINE_STRIP = p5_instance.LINE_STRIP + LINEAR = p5_instance.LINEAR + LINES = p5_instance.LINES + MIRROR = p5_instance.MIRROR + MITER = p5_instance.MITER + MOVE = p5_instance.MOVE + MULTIPLY = p5_instance.MULTIPLY + NEAREST = p5_instance.NEAREST + NORMAL = p5_instance.NORMAL + OPAQUE = p5_instance.OPAQUE + OPEN = p5_instance.OPEN + OPTION = p5_instance.OPTION + OVERLAY = p5_instance.OVERLAY PI = p5_instance.PI + PIE = p5_instance.PIE + POINTS = p5_instance.POINTS + PORTRAIT = p5_instance.PORTRAIT + POSTERIZE = p5_instance.POSTERIZE + PROJECT = p5_instance.PROJECT + QUAD_STRIP = p5_instance.QUAD_STRIP + QUADRATIC = p5_instance.QUADRATIC + QUADS = p5_instance.QUADS QUARTER_PI = p5_instance.QUARTER_PI - TAU = p5_instance.TAU - TWO_PI = p5_instance.TWO_PI - DEGREES = p5_instance.DEGREES + RAD_TO_DEG = p5_instance.RAD_TO_DEG RADIANS = p5_instance.RADIANS - CLOSE = p5_instance.CLOSE + RADIUS = p5_instance.RADIUS + REPEAT = p5_instance.REPEAT + REPLACE = p5_instance.REPLACE + RETURN = p5_instance.RETURN RGB = p5_instance.RGB - HSB = p5_instance.HSB - CMYK = p5_instance.CMYK - TOP = p5_instance.TOP - BOTTOM = p5_instance.BOTTOM - CENTER = p5_instance.CENTER - LEFT = p5_instance.LEFT RIGHT = p5_instance.RIGHT + RIGHT_ARROW = p5_instance.RIGHT_ARROW + ROUND = p5_instance.ROUND + SCREEN = p5_instance.SCREEN SHIFT = p5_instance.SHIFT + SOFT_LIGHT = p5_instance.SOFT_LIGHT + SQUARE = p5_instance.SQUARE + STROKE = p5_instance.STROKE + SUBTRACT = p5_instance.SUBTRACT + TAB = p5_instance.TAB + TAU = p5_instance.TAU + TEXT = p5_instance.TEXT + TEXTURE = p5_instance.TEXTURE + THRESHOLD = p5_instance.THRESHOLD + TOP = p5_instance.TOP + TRIANGLE_FAN = p5_instance.TRIANGLE_FAN + TRIANGLE_STRIP = p5_instance.TRIANGLE_STRIP + TRIANGLES = p5_instance.TRIANGLES + TWO_PI = p5_instance.TWO_PI + UP_ARROW = p5_instance.UP_ARROW + WAIT = p5_instance.WAIT WEBGL = p5_instance.WEBGL + P2D = p5_instance.P2D + PI = p5_instance.PI frameCount = p5_instance.frameCount focused = p5_instance.focused displayWidth = p5_instance.displayWidth @@ -853,7 +1045,7 @@ def sketch_setup(p5_sketch): # inject event functions into p5 event_function_names = ["deviceMoved", "deviceTurned", "deviceShaken", "keyPressed", "keyReleased", "keyTyped", "mouseMoved", "mouseDragged", "mousePressed", "mouseReleased", "mouseClicked", "doubleClicked", "mouseWheel", "touchStarted", "touchMoved", "touchEnded", "windowResized", ] - for f_name in [f for f in event_function_names if f in event_functions]: + for f_name in [f for f in event_function_names if event_functions.get(f, None)]: func = event_functions[f_name] event_func = global_p5_injection(instance)(func) setattr(instance, f_name, event_func) \ No newline at end of file diff --git a/docs/examples/sketch_001/target/sketch_001.js b/docs/examples/sketch_001/target/sketch_001.js index c6fb7c16..2a29c92a 100644 --- a/docs/examples/sketch_001/target/sketch_001.js +++ b/docs/examples/sketch_001/target/sketch_001.js @@ -1,7 +1,7 @@ -// Transcrypt'ed from Python, 2019-05-09 00:35:58 +// Transcrypt'ed from Python, 2019-06-01 16:39:00 import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, input, isinstance, issubclass, len, list, object, ord, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; -import {BOTTOM, CENTER, CLOSE, CMYK, DEGREES, HALF_PI, HSB, LEFT, PI, QUARTER_PI, RADIANS, RGB, RIGHT, SHIFT, TAU, TOP, TWO_PI, WEBGL, _P5_INSTANCE, abs, accelerationX, accelerationY, accelerationZ, acos, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, char, circle, color, colorMode, concat, cone, constrain, copy, cos, createCamera, createCanvas, createGraphics, createImage, createNumberDict, createShader, createStringDict, createVector, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, deviceOrientation, directionalLight, disableFriendlyErrors, displayDensity, displayHeight, displayWidth, dist, ellipse, ellipseMode, ellipsoid, endContour, endShape, exp, fill, filter, float, floor, focused, frameCount, frameRate, fullscreen, getURL, getURLParams, getURLPath, global_p5_injection, green, height, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, int, join, key, keyCode, keyIsDown, keyIsPressed, lerp, lerpColor, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, mouseButton, mouseIsPressed, mouseX, mouseY, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noFill, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normalMaterial, orbitControl, ortho, pAccelerationX, pAccelerationY, pAccelerationZ, pRotationX, pRotationY, pRotationZ, perspective, pixelDensity, pixels, plane, pmouseX, pmouseY, point, pointLight, pow, pre_draw, preload, print, push, pwinMouseX, pwinMouseY, py_clear, py_get, py_pop, py_sort, py_split, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, remove, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, rotationX, rotationY, rotationZ, round, saturation, save, saveCanvas, saveFrames, saveJSON, saveStrings, saveTable, scale, second, set, setAttributes, setCamera, setMoveThreshold, setShakeThreshold, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, specularMaterial, sphere, splice, splitTokens, sq, sqrt, square, start_p5, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, touches, translate, triangle, trim, turnAxis, unchar, unhex, updatePixels, vertex, width, winMouseX, winMouseY, windowHeight, windowWidth, year} from './pytop5js.js'; -var __name__ = '__main__'; +import {ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEGREES, DEG_TO_RAD, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINEAR, LINES, LINE_LOOP, LINE_STRIP, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, P2D, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUADRATIC, QUADS, QUAD_STRIP, QUARTER_PI, RADIANS, RADIUS, RAD_TO_DEG, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, TWO_PI, UP_ARROW, WAIT, WEBGL, _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, _P5_INSTANCE, abs, accelerationX, accelerationY, accelerationZ, acos, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, char, circle, color, colorMode, concat, cone, constrain, copy, cos, createCamera, createCanvas, createGraphics, createImage, createNumberDict, createShader, createStringDict, createVector, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, deviceOrientation, directionalLight, disableFriendlyErrors, displayDensity, displayHeight, displayWidth, dist, ellipse, ellipseMode, ellipsoid, endContour, endShape, exp, fill, filter, float, floor, focused, frameCount, frameRate, fullscreen, getURL, getURLParams, getURLPath, global_p5_injection, green, height, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, int, join, key, keyCode, keyIsDown, keyIsPressed, lerp, lerpColor, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, mouseButton, mouseIsPressed, mouseX, mouseY, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noFill, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normalMaterial, orbitControl, ortho, pAccelerationX, pAccelerationY, pAccelerationZ, pRotationX, pRotationY, pRotationZ, perspective, pixelDensity, pixels, plane, pmouseX, pmouseY, point, pointLight, pow, pre_draw, preload, print, push, pwinMouseX, pwinMouseY, py_clear, py_get, py_pop, py_sort, py_split, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, remove, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, rotationX, rotationY, rotationZ, round, saturation, save, saveCanvas, saveFrames, saveJSON, saveStrings, saveTable, scale, second, set, setAttributes, setCamera, setMoveThreshold, setShakeThreshold, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, specularMaterial, sphere, splice, splitTokens, sq, sqrt, square, start_p5, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, touches, translate, triangle, trim, turnAxis, unchar, unhex, updatePixels, vertex, width, winMouseX, winMouseY, windowHeight, windowWidth, year} from './pytop5js.js'; +var __name__ = 'sketch_001'; export var t = 0; export var setup = function () { createCanvas (600, 600); @@ -24,6 +24,5 @@ export var draw = function () { t = t + 0.01; console.log (frameRate ()); }; -export var my_p5 = start_p5 (setup, draw, dict ({})); //# sourceMappingURL=sketch_001.map \ No newline at end of file diff --git a/docs/examples/sketch_001/target/sketch_001.py b/docs/examples/sketch_001/target/sketch_001.py index 22187469..ba40688a 100644 --- a/docs/examples/sketch_001/target/sketch_001.py +++ b/docs/examples/sketch_001/target/sketch_001.py @@ -31,6 +31,3 @@ def draw(): t = t + 0.01 console.log(frameRate()) - - -my_p5 = start_p5(setup, draw, {}) diff --git a/docs/examples/sketch_001/target/target_sketch.js b/docs/examples/sketch_001/target/target_sketch.js new file mode 100644 index 00000000..ab1f48a5 --- /dev/null +++ b/docs/examples/sketch_001/target/target_sketch.js @@ -0,0 +1,9 @@ +// Transcrypt'ed from Python, 2019-06-01 16:39:00 +import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, input, isinstance, issubclass, len, list, object, ord, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; +import {ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEGREES, DEG_TO_RAD, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINEAR, LINES, LINE_LOOP, LINE_STRIP, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, P2D, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUADRATIC, QUADS, QUAD_STRIP, QUARTER_PI, RADIANS, RADIUS, RAD_TO_DEG, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, TWO_PI, UP_ARROW, WAIT, WEBGL, _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, _P5_INSTANCE, abs, accelerationX, accelerationY, accelerationZ, acos, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, char, circle, color, colorMode, concat, cone, constrain, copy, cos, createCamera, createCanvas, createGraphics, createImage, createNumberDict, createShader, createStringDict, createVector, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, deviceOrientation, directionalLight, disableFriendlyErrors, displayDensity, displayHeight, displayWidth, dist, draw, ellipse, ellipseMode, ellipsoid, endContour, endShape, exp, fill, filter, float, floor, focused, frameCount, frameRate, fullscreen, getURL, getURLParams, getURLPath, global_p5_injection, green, height, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, int, join, key, keyCode, keyIsDown, keyIsPressed, lerp, lerpColor, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, mouseButton, mouseIsPressed, mouseX, mouseY, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noFill, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normalMaterial, orbitControl, ortho, pAccelerationX, pAccelerationY, pAccelerationZ, pRotationX, pRotationY, pRotationZ, perspective, pixelDensity, pixels, plane, pmouseX, pmouseY, point, pointLight, pow, pre_draw, preload, print, push, pwinMouseX, pwinMouseY, py_clear, py_get, py_pop, py_sort, py_split, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, remove, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, rotationX, rotationY, rotationZ, round, saturation, save, saveCanvas, saveFrames, saveJSON, saveStrings, saveTable, scale, second, set, setAttributes, setCamera, setMoveThreshold, setShakeThreshold, setup, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, specularMaterial, sphere, splice, splitTokens, sq, sqrt, square, start_p5, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, touches, translate, triangle, trim, turnAxis, unchar, unhex, updatePixels, vertex, width, winMouseX, winMouseY, windowHeight, windowWidth, year} from './pytop5js.js'; +import * as source_sketch from './sketch_001.js'; +var __name__ = '__main__'; +export var event_functions = dict ({'deviceMoved': source_sketch.deviceMoved, 'deviceTurned': source_sketch.deviceTurned, 'deviceShaken': source_sketch.deviceShaken, 'keyPressed': source_sketch.keyPressed, 'keyReleased': source_sketch.keyReleased, 'keyTyped': source_sketch.keyTyped, 'mouseMoved': source_sketch.mouseMoved, 'mouseDragged': source_sketch.mouseDragged, 'mousePressed': source_sketch.mousePressed, 'mouseReleased': source_sketch.mouseReleased, 'mouseClicked': source_sketch.mouseClicked, 'doubleClicked': source_sketch.doubleClicked, 'mouseWheel': source_sketch.mouseWheel, 'touchStarted': source_sketch.touchStarted, 'touchMoved': source_sketch.touchMoved, 'touchEnded': source_sketch.touchEnded, 'windowResized': source_sketch.windowResized}); +start_p5 (source_sketch.setup, source_sketch.draw, event_functions); + +//# sourceMappingURL=target_sketch.map \ No newline at end of file diff --git a/docs/examples/sketch_001/target/sketch_001.options b/docs/examples/sketch_001/target/target_sketch.options similarity index 73% rename from docs/examples/sketch_001/target/sketch_001.options rename to docs/examples/sketch_001/target/target_sketch.options index 17bcdf8f0b24ea9158f1e6bbb204e11ee64ed3b1..e251721a95222811092136791ec9ec3e1d0c129b 100644 GIT binary patch delta 39 qcmcb^a-U^_h>SD?14D6kYDscNyn%tCeo10cdTL2LL}a6`J`(`;lnl23 delta 36 jcmcc5a))Jth@=Dq14D6kYDscNyn%tCK7zT?K%WT!%H0aS diff --git a/docs/examples/sketch_001/target/target_sketch.py b/docs/examples/sketch_001/target/target_sketch.py new file mode 100644 index 00000000..7cf98994 --- /dev/null +++ b/docs/examples/sketch_001/target/target_sketch.py @@ -0,0 +1,24 @@ +import sketch_001 as source_sketch +from pytop5js import * + +event_functions = { + "deviceMoved": source_sketch.deviceMoved, + "deviceTurned": source_sketch.deviceTurned, + "deviceShaken": source_sketch.deviceShaken, + "keyPressed": source_sketch.keyPressed, + "keyReleased": source_sketch.keyReleased, + "keyTyped": source_sketch.keyTyped, + "mouseMoved": source_sketch.mouseMoved, + "mouseDragged": source_sketch.mouseDragged, + "mousePressed": source_sketch.mousePressed, + "mouseReleased": source_sketch.mouseReleased, + "mouseClicked": source_sketch.mouseClicked, + "doubleClicked": source_sketch.doubleClicked, + "mouseWheel": source_sketch.mouseWheel, + "touchStarted": source_sketch.touchStarted, + "touchMoved": source_sketch.touchMoved, + "touchEnded": source_sketch.touchEnded, + "windowResized": source_sketch.windowResized, +} + +start_p5(source_sketch.setup, source_sketch.draw, event_functions) \ No newline at end of file diff --git a/docs/examples/sketch_002/sketch_002.py b/docs/examples/sketch_002/sketch_002.py index 251ff9b7..50285aa0 100644 --- a/docs/examples/sketch_002/sketch_002.py +++ b/docs/examples/sketch_002/sketch_002.py @@ -27,7 +27,3 @@ def draw(): line(-100, 0, 0, 100, 0, 0) line(0, -100, 0, 0, 100, 0) line(0, 0, -100, 0, 0, 100) - - -# This is required by pyp5js to work -start_p5(setup, draw, {}) diff --git a/docs/examples/sketch_002/target/org.transcrypt.__runtime__.js b/docs/examples/sketch_002/target/org.transcrypt.__runtime__.js index 60166e16..4d1226cf 100644 --- a/docs/examples/sketch_002/target/org.transcrypt.__runtime__.js +++ b/docs/examples/sketch_002/target/org.transcrypt.__runtime__.js @@ -1,4 +1,4 @@ -// Transcrypt'ed from Python, 2019-05-09 00:36:14 +// Transcrypt'ed from Python, 2019-06-01 16:39:02 var __name__ = 'org.transcrypt.__runtime__'; export var __envir__ = {}; __envir__.interpreter_name = 'python'; diff --git a/docs/examples/sketch_002/target/pytop5js.js b/docs/examples/sketch_002/target/pytop5js.js index 514aa31e..18165948 100644 --- a/docs/examples/sketch_002/target/pytop5js.js +++ b/docs/examples/sketch_002/target/pytop5js.js @@ -1,7 +1,157 @@ -// Transcrypt'ed from Python, 2019-05-09 00:36:14 +// Transcrypt'ed from Python, 2019-06-01 16:39:02 import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, input, isinstance, issubclass, len, list, object, ord, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; var __name__ = 'pytop5js'; export var _P5_INSTANCE = null; +export var _CTX_MIDDLE = null; +export var _DEFAULT_FILL = null; +export var _DEFAULT_LEADMULT = null; +export var _DEFAULT_STROKE = null; +export var _DEFAULT_TEXT_FILL = null; +export var ADD = null; +export var ALT = null; +export var ARROW = null; +export var AUTO = null; +export var AXES = null; +export var BACKSPACE = null; +export var BASELINE = null; +export var BEVEL = null; +export var BEZIER = null; +export var BLEND = null; +export var BLUR = null; +export var BOLD = null; +export var BOLDITALIC = null; +export var BOTTOM = null; +export var BURN = null; +export var CENTER = null; +export var CHORD = null; +export var CLAMP = null; +export var CLOSE = null; +export var CONTROL = null; +export var CORNER = null; +export var CORNERS = null; +export var CROSS = null; +export var CURVE = null; +export var DARKEST = null; +export var DEG_TO_RAD = null; +export var DEGREES = null; +export var DELETE = null; +export var DIFFERENCE = null; +export var DILATE = null; +export var DODGE = null; +export var DOWN_ARROW = null; +export var ENTER = null; +export var ERODE = null; +export var ESCAPE = null; +export var EXCLUSION = null; +export var FILL = null; +export var GRAY = null; +export var GRID = null; +export var HALF_PI = null; +export var HAND = null; +export var HARD_LIGHT = null; +export var HSB = null; +export var HSL = null; +export var IMAGE = null; +export var IMMEDIATE = null; +export var INVERT = null; +export var ITALIC = null; +export var LANDSCAPE = null; +export var LEFT = null; +export var LEFT_ARROW = null; +export var LIGHTEST = null; +export var LINE_LOOP = null; +export var LINE_STRIP = null; +export var LINEAR = null; +export var LINES = null; +export var MIRROR = null; +export var MITER = null; +export var MOVE = null; +export var MULTIPLY = null; +export var NEAREST = null; +export var NORMAL = null; +export var OPAQUE = null; +export var OPEN = null; +export var OPTION = null; +export var OVERLAY = null; +export var PI = null; +export var PIE = null; +export var POINTS = null; +export var PORTRAIT = null; +export var POSTERIZE = null; +export var PROJECT = null; +export var QUAD_STRIP = null; +export var QUADRATIC = null; +export var QUADS = null; +export var QUARTER_PI = null; +export var RAD_TO_DEG = null; +export var RADIANS = null; +export var RADIUS = null; +export var REPEAT = null; +export var REPLACE = null; +export var RETURN = null; +export var RGB = null; +export var RIGHT = null; +export var RIGHT_ARROW = null; +export var ROUND = null; +export var SCREEN = null; +export var SHIFT = null; +export var SOFT_LIGHT = null; +export var SQUARE = null; +export var STROKE = null; +export var SUBTRACT = null; +export var TAB = null; +export var TAU = null; +export var TEXT = null; +export var TEXTURE = null; +export var THRESHOLD = null; +export var TOP = null; +export var TRIANGLE_FAN = null; +export var TRIANGLE_STRIP = null; +export var TRIANGLES = null; +export var TWO_PI = null; +export var UP_ARROW = null; +export var WAIT = null; +export var WEBGL = null; +export var P2D = null; +var PI = null; +export var frameCount = null; +export var focused = null; +export var displayWidth = null; +export var displayHeight = null; +export var windowWidth = null; +export var windowHeight = null; +export var width = null; +export var height = null; +export var disableFriendlyErrors = null; +export var deviceOrientation = null; +export var accelerationX = null; +export var accelerationY = null; +export var accelerationZ = null; +export var pAccelerationX = null; +export var pAccelerationY = null; +export var pAccelerationZ = null; +export var rotationX = null; +export var rotationY = null; +export var rotationZ = null; +export var pRotationX = null; +export var pRotationY = null; +export var pRotationZ = null; +export var turnAxis = null; +export var keyIsPressed = null; +export var key = null; +export var keyCode = null; +export var mouseX = null; +export var mouseY = null; +export var pmouseX = null; +export var pmouseY = null; +export var winMouseX = null; +export var winMouseY = null; +export var pwinMouseX = null; +export var pwinMouseY = null; +export var mouseButton = null; +export var mouseIsPressed = null; +export var touches = null; +export var pixels = null; export var alpha = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.alpha (...args); @@ -310,10 +460,6 @@ export var redraw = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.redraw (...args); }; -export var createCanvas = function () { - var args = tuple ([].slice.apply (arguments).slice (0)); - return _P5_INSTANCE.createCanvas (...args); -}; export var resizeCanvas = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.resizeCanvas (...args); @@ -914,86 +1060,130 @@ export var setCamera = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.setCamera (...args); }; +export var createCanvas = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + var result = _P5_INSTANCE.createCanvas (...args); + width = _P5_INSTANCE.width; + height = _P5_INSTANCE.height; +}; export var py_pop = function () { var args = tuple ([].slice.apply (arguments).slice (0)); var p5_pop = _P5_INSTANCE.pop (...args); return p5_pop; }; -export var HALF_PI = null; -export var PI = null; -export var QUARTER_PI = null; -export var TAU = null; -export var TWO_PI = null; -export var DEGREES = null; -export var RADIANS = null; -export var CLOSE = null; -export var RGB = null; -export var HSB = null; -export var CMYK = null; -export var TOP = null; -export var BOTTOM = null; -export var CENTER = null; -export var LEFT = null; -export var RIGHT = null; -export var SHIFT = null; -export var WEBGL = null; -export var frameCount = null; -export var focused = null; -export var displayWidth = null; -export var displayHeight = null; -export var windowWidth = null; -export var windowHeight = null; -export var width = null; -export var height = null; -export var disableFriendlyErrors = null; -export var deviceOrientation = null; -export var accelerationX = null; -export var accelerationY = null; -export var accelerationZ = null; -export var pAccelerationX = null; -export var pAccelerationY = null; -export var pAccelerationZ = null; -export var rotationX = null; -export var rotationY = null; -export var rotationZ = null; -export var pRotationX = null; -export var pRotationY = null; -export var pRotationZ = null; -export var turnAxis = null; -export var keyIsPressed = null; -export var key = null; -export var keyCode = null; -export var mouseX = null; -export var mouseY = null; -export var pmouseX = null; -export var pmouseY = null; -export var winMouseX = null; -export var winMouseY = null; -export var pwinMouseX = null; -export var pwinMouseY = null; -export var mouseButton = null; -export var mouseIsPressed = null; -export var touches = null; -export var pixels = null; export var pre_draw = function (p5_instance, draw_func) { + _CTX_MIDDLE = p5_instance._CTX_MIDDLE; + _DEFAULT_FILL = p5_instance._DEFAULT_FILL; + _DEFAULT_LEADMULT = p5_instance._DEFAULT_LEADMULT; + _DEFAULT_STROKE = p5_instance._DEFAULT_STROKE; + _DEFAULT_TEXT_FILL = p5_instance._DEFAULT_TEXT_FILL; + ADD = p5_instance.ADD; + ALT = p5_instance.ALT; + ARROW = p5_instance.ARROW; + AUTO = p5_instance.AUTO; + AXES = p5_instance.AXES; + BACKSPACE = p5_instance.BACKSPACE; + BASELINE = p5_instance.BASELINE; + BEVEL = p5_instance.BEVEL; + BEZIER = p5_instance.BEZIER; + BLEND = p5_instance.BLEND; + BLUR = p5_instance.BLUR; + BOLD = p5_instance.BOLD; + BOLDITALIC = p5_instance.BOLDITALIC; + BOTTOM = p5_instance.BOTTOM; + BURN = p5_instance.BURN; + CENTER = p5_instance.CENTER; + CHORD = p5_instance.CHORD; + CLAMP = p5_instance.CLAMP; + CLOSE = p5_instance.CLOSE; + CONTROL = p5_instance.CONTROL; + CORNER = p5_instance.CORNER; + CORNERS = p5_instance.CORNERS; + CROSS = p5_instance.CROSS; + CURVE = p5_instance.CURVE; + DARKEST = p5_instance.DARKEST; + DEG_TO_RAD = p5_instance.DEG_TO_RAD; + DEGREES = p5_instance.DEGREES; + DELETE = p5_instance.DELETE; + DIFFERENCE = p5_instance.DIFFERENCE; + DILATE = p5_instance.DILATE; + DODGE = p5_instance.DODGE; + DOWN_ARROW = p5_instance.DOWN_ARROW; + ENTER = p5_instance.ENTER; + ERODE = p5_instance.ERODE; + ESCAPE = p5_instance.ESCAPE; + EXCLUSION = p5_instance.EXCLUSION; + FILL = p5_instance.FILL; + GRAY = p5_instance.GRAY; + GRID = p5_instance.GRID; HALF_PI = p5_instance.HALF_PI; + HAND = p5_instance.HAND; + HARD_LIGHT = p5_instance.HARD_LIGHT; + HSB = p5_instance.HSB; + HSL = p5_instance.HSL; + IMAGE = p5_instance.IMAGE; + IMMEDIATE = p5_instance.IMMEDIATE; + INVERT = p5_instance.INVERT; + ITALIC = p5_instance.ITALIC; + LANDSCAPE = p5_instance.LANDSCAPE; + LEFT = p5_instance.LEFT; + LEFT_ARROW = p5_instance.LEFT_ARROW; + LIGHTEST = p5_instance.LIGHTEST; + LINE_LOOP = p5_instance.LINE_LOOP; + LINE_STRIP = p5_instance.LINE_STRIP; + LINEAR = p5_instance.LINEAR; + LINES = p5_instance.LINES; + MIRROR = p5_instance.MIRROR; + MITER = p5_instance.MITER; + MOVE = p5_instance.MOVE; + MULTIPLY = p5_instance.MULTIPLY; + NEAREST = p5_instance.NEAREST; + NORMAL = p5_instance.NORMAL; + OPAQUE = p5_instance.OPAQUE; + OPEN = p5_instance.OPEN; + OPTION = p5_instance.OPTION; + OVERLAY = p5_instance.OVERLAY; PI = p5_instance.PI; + PIE = p5_instance.PIE; + POINTS = p5_instance.POINTS; + PORTRAIT = p5_instance.PORTRAIT; + POSTERIZE = p5_instance.POSTERIZE; + PROJECT = p5_instance.PROJECT; + QUAD_STRIP = p5_instance.QUAD_STRIP; + QUADRATIC = p5_instance.QUADRATIC; + QUADS = p5_instance.QUADS; QUARTER_PI = p5_instance.QUARTER_PI; - TAU = p5_instance.TAU; - TWO_PI = p5_instance.TWO_PI; - DEGREES = p5_instance.DEGREES; + RAD_TO_DEG = p5_instance.RAD_TO_DEG; RADIANS = p5_instance.RADIANS; - CLOSE = p5_instance.CLOSE; + RADIUS = p5_instance.RADIUS; + REPEAT = p5_instance.REPEAT; + REPLACE = p5_instance.REPLACE; + RETURN = p5_instance.RETURN; RGB = p5_instance.RGB; - HSB = p5_instance.HSB; - CMYK = p5_instance.CMYK; - TOP = p5_instance.TOP; - BOTTOM = p5_instance.BOTTOM; - CENTER = p5_instance.CENTER; - LEFT = p5_instance.LEFT; RIGHT = p5_instance.RIGHT; + RIGHT_ARROW = p5_instance.RIGHT_ARROW; + ROUND = p5_instance.ROUND; + SCREEN = p5_instance.SCREEN; SHIFT = p5_instance.SHIFT; + SOFT_LIGHT = p5_instance.SOFT_LIGHT; + SQUARE = p5_instance.SQUARE; + STROKE = p5_instance.STROKE; + SUBTRACT = p5_instance.SUBTRACT; + TAB = p5_instance.TAB; + TAU = p5_instance.TAU; + TEXT = p5_instance.TEXT; + TEXTURE = p5_instance.TEXTURE; + THRESHOLD = p5_instance.THRESHOLD; + TOP = p5_instance.TOP; + TRIANGLE_FAN = p5_instance.TRIANGLE_FAN; + TRIANGLE_STRIP = p5_instance.TRIANGLE_STRIP; + TRIANGLES = p5_instance.TRIANGLES; + TWO_PI = p5_instance.TWO_PI; + UP_ARROW = p5_instance.UP_ARROW; + WAIT = p5_instance.WAIT; WEBGL = p5_instance.WEBGL; + P2D = p5_instance.P2D; + PI = p5_instance.PI; frameCount = p5_instance.frameCount; focused = p5_instance.focused; displayWidth = p5_instance.displayWidth; @@ -1054,7 +1244,7 @@ export var start_p5 = function (setup_func, draw_func, event_functions) { for (var f_name of (function () { var __accu0__ = []; for (var f of event_function_names) { - if (__in__ (f, event_functions)) { + if (event_functions.py_get (f, null)) { __accu0__.append (f); } } diff --git a/docs/examples/sketch_002/target/pytop5js.py b/docs/examples/sketch_002/target/pytop5js.py index 59388176..6462430c 100644 --- a/docs/examples/sketch_002/target/pytop5js.py +++ b/docs/examples/sketch_002/target/pytop5js.py @@ -1,4 +1,155 @@ _P5_INSTANCE = None +_CTX_MIDDLE = None +_DEFAULT_FILL = None +_DEFAULT_LEADMULT = None +_DEFAULT_STROKE = None +_DEFAULT_TEXT_FILL = None +ADD = None +ALT = None +ARROW = None +AUTO = None +AXES = None +BACKSPACE = None +BASELINE = None +BEVEL = None +BEZIER = None +BLEND = None +BLUR = None +BOLD = None +BOLDITALIC = None +BOTTOM = None +BURN = None +CENTER = None +CHORD = None +CLAMP = None +CLOSE = None +CONTROL = None +CORNER = None +CORNERS = None +CROSS = None +CURVE = None +DARKEST = None +DEG_TO_RAD = None +DEGREES = None +DELETE = None +DIFFERENCE = None +DILATE = None +DODGE = None +DOWN_ARROW = None +ENTER = None +ERODE = None +ESCAPE = None +EXCLUSION = None +FILL = None +GRAY = None +GRID = None +HALF_PI = None +HAND = None +HARD_LIGHT = None +HSB = None +HSL = None +IMAGE = None +IMMEDIATE = None +INVERT = None +ITALIC = None +LANDSCAPE = None +LEFT = None +LEFT_ARROW = None +LIGHTEST = None +LINE_LOOP = None +LINE_STRIP = None +LINEAR = None +LINES = None +MIRROR = None +MITER = None +MOVE = None +MULTIPLY = None +NEAREST = None +NORMAL = None +OPAQUE = None +OPEN = None +OPTION = None +OVERLAY = None +PI = None +PIE = None +POINTS = None +PORTRAIT = None +POSTERIZE = None +PROJECT = None +QUAD_STRIP = None +QUADRATIC = None +QUADS = None +QUARTER_PI = None +RAD_TO_DEG = None +RADIANS = None +RADIUS = None +REPEAT = None +REPLACE = None +RETURN = None +RGB = None +RIGHT = None +RIGHT_ARROW = None +ROUND = None +SCREEN = None +SHIFT = None +SOFT_LIGHT = None +SQUARE = None +STROKE = None +SUBTRACT = None +TAB = None +TAU = None +TEXT = None +TEXTURE = None +THRESHOLD = None +TOP = None +TRIANGLE_FAN = None +TRIANGLE_STRIP = None +TRIANGLES = None +TWO_PI = None +UP_ARROW = None +WAIT = None +WEBGL = None +P2D = None +PI = None +frameCount = None +focused = None +displayWidth = None +displayHeight = None +windowWidth = None +windowHeight = None +width = None +height = None +disableFriendlyErrors = None +deviceOrientation = None +accelerationX = None +accelerationY = None +accelerationZ = None +pAccelerationX = None +pAccelerationY = None +pAccelerationZ = None +rotationX = None +rotationY = None +rotationZ = None +pRotationX = None +pRotationY = None +pRotationZ = None +turnAxis = None +keyIsPressed = None +key = None +keyCode = None +mouseX = None +mouseY = None +pmouseX = None +pmouseY = None +winMouseX = None +winMouseY = None +pwinMouseX = None +pwinMouseY = None +mouseButton = None +mouseIsPressed = None +touches = None +pixels = None + def alpha(*args): @@ -232,9 +383,6 @@ def push(*args): def redraw(*args): return _P5_INSTANCE.redraw(*args) -def createCanvas(*args): - return _P5_INSTANCE.createCanvas(*args) - def resizeCanvas(*args): return _P5_INSTANCE.resizeCanvas(*args) @@ -686,6 +834,13 @@ def setCamera(*args): return _P5_INSTANCE.setCamera(*args) +def createCanvas(*args): + result = _P5_INSTANCE.createCanvas(*args) + + global width, height + width = _P5_INSTANCE.width + height = _P5_INSTANCE.height + def pop(*args): __pragma__('noalias', 'pop') @@ -693,87 +848,124 @@ def pop(*args): __pragma__('alias', 'pop', 'py_pop') return p5_pop -HALF_PI = None -PI = None -QUARTER_PI = None -TAU = None -TWO_PI = None -DEGREES = None -RADIANS = None -CLOSE = None -RGB = None -HSB = None -CMYK = None -TOP = None -BOTTOM = None -CENTER = None -LEFT = None -RIGHT = None -SHIFT = None -WEBGL = None -frameCount = None -focused = None -displayWidth = None -displayHeight = None -windowWidth = None -windowHeight = None -width = None -height = None -disableFriendlyErrors = None -deviceOrientation = None -accelerationX = None -accelerationY = None -accelerationZ = None -pAccelerationX = None -pAccelerationY = None -pAccelerationZ = None -rotationX = None -rotationY = None -rotationZ = None -pRotationX = None -pRotationY = None -pRotationZ = None -turnAxis = None -keyIsPressed = None -key = None -keyCode = None -mouseX = None -mouseY = None -pmouseX = None -pmouseY = None -winMouseX = None -winMouseY = None -pwinMouseX = None -pwinMouseY = None -mouseButton = None -mouseIsPressed = None -touches = None -pixels = None - def pre_draw(p5_instance, draw_func): """ We need to run this before the actual draw to insert and update p5 env variables """ - global HALF_PI, PI, QUARTER_PI, TAU, TWO_PI, DEGREES, RADIANS, CLOSE, RGB, HSB, CMYK, TOP, BOTTOM, CENTER, LEFT, RIGHT, SHIFT, WEBGL, frameCount, focused, displayWidth, displayHeight, windowWidth, windowHeight, width, height, disableFriendlyErrors, deviceOrientation, accelerationX, accelerationY, accelerationZ, pAccelerationX, pAccelerationY, pAccelerationZ, rotationX, rotationY, rotationZ, pRotationX, pRotationY, pRotationZ, turnAxis, keyIsPressed, key, keyCode, mouseX, mouseY, pmouseX, pmouseY, winMouseX, winMouseY, pwinMouseX, pwinMouseY, mouseButton, mouseIsPressed, touches, pixels - + global _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEG_TO_RAD, DEGREES, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINE_LOOP, LINE_STRIP, LINEAR, LINES, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUAD_STRIP, QUADRATIC, QUADS, QUARTER_PI, RAD_TO_DEG, RADIANS, RADIUS, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLE_FAN, TRIANGLE_STRIP, TRIANGLES, TWO_PI, UP_ARROW, WAIT, WEBGL, P2D, PI, frameCount, focused, displayWidth, displayHeight, windowWidth, windowHeight, width, height, disableFriendlyErrors, deviceOrientation, accelerationX, accelerationY, accelerationZ, pAccelerationX, pAccelerationY, pAccelerationZ, rotationX, rotationY, rotationZ, pRotationX, pRotationY, pRotationZ, turnAxis, keyIsPressed, key, keyCode, mouseX, mouseY, pmouseX, pmouseY, winMouseX, winMouseY, pwinMouseX, pwinMouseY, mouseButton, mouseIsPressed, touches, pixels + + _CTX_MIDDLE = p5_instance._CTX_MIDDLE + _DEFAULT_FILL = p5_instance._DEFAULT_FILL + _DEFAULT_LEADMULT = p5_instance._DEFAULT_LEADMULT + _DEFAULT_STROKE = p5_instance._DEFAULT_STROKE + _DEFAULT_TEXT_FILL = p5_instance._DEFAULT_TEXT_FILL + ADD = p5_instance.ADD + ALT = p5_instance.ALT + ARROW = p5_instance.ARROW + AUTO = p5_instance.AUTO + AXES = p5_instance.AXES + BACKSPACE = p5_instance.BACKSPACE + BASELINE = p5_instance.BASELINE + BEVEL = p5_instance.BEVEL + BEZIER = p5_instance.BEZIER + BLEND = p5_instance.BLEND + BLUR = p5_instance.BLUR + BOLD = p5_instance.BOLD + BOLDITALIC = p5_instance.BOLDITALIC + BOTTOM = p5_instance.BOTTOM + BURN = p5_instance.BURN + CENTER = p5_instance.CENTER + CHORD = p5_instance.CHORD + CLAMP = p5_instance.CLAMP + CLOSE = p5_instance.CLOSE + CONTROL = p5_instance.CONTROL + CORNER = p5_instance.CORNER + CORNERS = p5_instance.CORNERS + CROSS = p5_instance.CROSS + CURVE = p5_instance.CURVE + DARKEST = p5_instance.DARKEST + DEG_TO_RAD = p5_instance.DEG_TO_RAD + DEGREES = p5_instance.DEGREES + DELETE = p5_instance.DELETE + DIFFERENCE = p5_instance.DIFFERENCE + DILATE = p5_instance.DILATE + DODGE = p5_instance.DODGE + DOWN_ARROW = p5_instance.DOWN_ARROW + ENTER = p5_instance.ENTER + ERODE = p5_instance.ERODE + ESCAPE = p5_instance.ESCAPE + EXCLUSION = p5_instance.EXCLUSION + FILL = p5_instance.FILL + GRAY = p5_instance.GRAY + GRID = p5_instance.GRID HALF_PI = p5_instance.HALF_PI + HAND = p5_instance.HAND + HARD_LIGHT = p5_instance.HARD_LIGHT + HSB = p5_instance.HSB + HSL = p5_instance.HSL + IMAGE = p5_instance.IMAGE + IMMEDIATE = p5_instance.IMMEDIATE + INVERT = p5_instance.INVERT + ITALIC = p5_instance.ITALIC + LANDSCAPE = p5_instance.LANDSCAPE + LEFT = p5_instance.LEFT + LEFT_ARROW = p5_instance.LEFT_ARROW + LIGHTEST = p5_instance.LIGHTEST + LINE_LOOP = p5_instance.LINE_LOOP + LINE_STRIP = p5_instance.LINE_STRIP + LINEAR = p5_instance.LINEAR + LINES = p5_instance.LINES + MIRROR = p5_instance.MIRROR + MITER = p5_instance.MITER + MOVE = p5_instance.MOVE + MULTIPLY = p5_instance.MULTIPLY + NEAREST = p5_instance.NEAREST + NORMAL = p5_instance.NORMAL + OPAQUE = p5_instance.OPAQUE + OPEN = p5_instance.OPEN + OPTION = p5_instance.OPTION + OVERLAY = p5_instance.OVERLAY PI = p5_instance.PI + PIE = p5_instance.PIE + POINTS = p5_instance.POINTS + PORTRAIT = p5_instance.PORTRAIT + POSTERIZE = p5_instance.POSTERIZE + PROJECT = p5_instance.PROJECT + QUAD_STRIP = p5_instance.QUAD_STRIP + QUADRATIC = p5_instance.QUADRATIC + QUADS = p5_instance.QUADS QUARTER_PI = p5_instance.QUARTER_PI - TAU = p5_instance.TAU - TWO_PI = p5_instance.TWO_PI - DEGREES = p5_instance.DEGREES + RAD_TO_DEG = p5_instance.RAD_TO_DEG RADIANS = p5_instance.RADIANS - CLOSE = p5_instance.CLOSE + RADIUS = p5_instance.RADIUS + REPEAT = p5_instance.REPEAT + REPLACE = p5_instance.REPLACE + RETURN = p5_instance.RETURN RGB = p5_instance.RGB - HSB = p5_instance.HSB - CMYK = p5_instance.CMYK - TOP = p5_instance.TOP - BOTTOM = p5_instance.BOTTOM - CENTER = p5_instance.CENTER - LEFT = p5_instance.LEFT RIGHT = p5_instance.RIGHT + RIGHT_ARROW = p5_instance.RIGHT_ARROW + ROUND = p5_instance.ROUND + SCREEN = p5_instance.SCREEN SHIFT = p5_instance.SHIFT + SOFT_LIGHT = p5_instance.SOFT_LIGHT + SQUARE = p5_instance.SQUARE + STROKE = p5_instance.STROKE + SUBTRACT = p5_instance.SUBTRACT + TAB = p5_instance.TAB + TAU = p5_instance.TAU + TEXT = p5_instance.TEXT + TEXTURE = p5_instance.TEXTURE + THRESHOLD = p5_instance.THRESHOLD + TOP = p5_instance.TOP + TRIANGLE_FAN = p5_instance.TRIANGLE_FAN + TRIANGLE_STRIP = p5_instance.TRIANGLE_STRIP + TRIANGLES = p5_instance.TRIANGLES + TWO_PI = p5_instance.TWO_PI + UP_ARROW = p5_instance.UP_ARROW + WAIT = p5_instance.WAIT WEBGL = p5_instance.WEBGL + P2D = p5_instance.P2D + PI = p5_instance.PI frameCount = p5_instance.frameCount focused = p5_instance.focused displayWidth = p5_instance.displayWidth @@ -853,7 +1045,7 @@ def sketch_setup(p5_sketch): # inject event functions into p5 event_function_names = ["deviceMoved", "deviceTurned", "deviceShaken", "keyPressed", "keyReleased", "keyTyped", "mouseMoved", "mouseDragged", "mousePressed", "mouseReleased", "mouseClicked", "doubleClicked", "mouseWheel", "touchStarted", "touchMoved", "touchEnded", "windowResized", ] - for f_name in [f for f in event_function_names if f in event_functions]: + for f_name in [f for f in event_function_names if event_functions.get(f, None)]: func = event_functions[f_name] event_func = global_p5_injection(instance)(func) setattr(instance, f_name, event_func) \ No newline at end of file diff --git a/docs/examples/sketch_002/target/sketch_002.js b/docs/examples/sketch_002/target/sketch_002.js index 8e0e1165..c894c28b 100644 --- a/docs/examples/sketch_002/target/sketch_002.js +++ b/docs/examples/sketch_002/target/sketch_002.js @@ -1,7 +1,7 @@ -// Transcrypt'ed from Python, 2019-05-09 00:36:14 +// Transcrypt'ed from Python, 2019-06-01 16:39:02 import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, input, isinstance, issubclass, len, list, object, ord, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; -import {BOTTOM, CENTER, CLOSE, CMYK, DEGREES, HALF_PI, HSB, LEFT, PI, QUARTER_PI, RADIANS, RGB, RIGHT, SHIFT, TAU, TOP, TWO_PI, WEBGL, _P5_INSTANCE, abs, accelerationX, accelerationY, accelerationZ, acos, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, char, circle, color, colorMode, concat, cone, constrain, copy, cos, createCamera, createCanvas, createGraphics, createImage, createNumberDict, createShader, createStringDict, createVector, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, deviceOrientation, directionalLight, disableFriendlyErrors, displayDensity, displayHeight, displayWidth, dist, ellipse, ellipseMode, ellipsoid, endContour, endShape, exp, fill, filter, float, floor, focused, frameCount, frameRate, fullscreen, getURL, getURLParams, getURLPath, global_p5_injection, green, height, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, int, join, key, keyCode, keyIsDown, keyIsPressed, lerp, lerpColor, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, mouseButton, mouseIsPressed, mouseX, mouseY, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noFill, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normalMaterial, orbitControl, ortho, pAccelerationX, pAccelerationY, pAccelerationZ, pRotationX, pRotationY, pRotationZ, perspective, pixelDensity, pixels, plane, pmouseX, pmouseY, point, pointLight, pow, pre_draw, preload, print, push, pwinMouseX, pwinMouseY, py_clear, py_get, py_pop, py_sort, py_split, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, remove, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, rotationX, rotationY, rotationZ, round, saturation, save, saveCanvas, saveFrames, saveJSON, saveStrings, saveTable, scale, second, set, setAttributes, setCamera, setMoveThreshold, setShakeThreshold, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, specularMaterial, sphere, splice, splitTokens, sq, sqrt, square, start_p5, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, touches, translate, triangle, trim, turnAxis, unchar, unhex, updatePixels, vertex, width, winMouseX, winMouseY, windowHeight, windowWidth, year} from './pytop5js.js'; -var __name__ = '__main__'; +import {ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEGREES, DEG_TO_RAD, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINEAR, LINES, LINE_LOOP, LINE_STRIP, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, P2D, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUADRATIC, QUADS, QUAD_STRIP, QUARTER_PI, RADIANS, RADIUS, RAD_TO_DEG, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, TWO_PI, UP_ARROW, WAIT, WEBGL, _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, _P5_INSTANCE, abs, accelerationX, accelerationY, accelerationZ, acos, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, char, circle, color, colorMode, concat, cone, constrain, copy, cos, createCamera, createCanvas, createGraphics, createImage, createNumberDict, createShader, createStringDict, createVector, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, deviceOrientation, directionalLight, disableFriendlyErrors, displayDensity, displayHeight, displayWidth, dist, ellipse, ellipseMode, ellipsoid, endContour, endShape, exp, fill, filter, float, floor, focused, frameCount, frameRate, fullscreen, getURL, getURLParams, getURLPath, global_p5_injection, green, height, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, int, join, key, keyCode, keyIsDown, keyIsPressed, lerp, lerpColor, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, mouseButton, mouseIsPressed, mouseX, mouseY, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noFill, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normalMaterial, orbitControl, ortho, pAccelerationX, pAccelerationY, pAccelerationZ, pRotationX, pRotationY, pRotationZ, perspective, pixelDensity, pixels, plane, pmouseX, pmouseY, point, pointLight, pow, pre_draw, preload, print, push, pwinMouseX, pwinMouseY, py_clear, py_get, py_pop, py_sort, py_split, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, remove, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, rotationX, rotationY, rotationZ, round, saturation, save, saveCanvas, saveFrames, saveJSON, saveStrings, saveTable, scale, second, set, setAttributes, setCamera, setMoveThreshold, setShakeThreshold, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, specularMaterial, sphere, splice, splitTokens, sq, sqrt, square, start_p5, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, touches, translate, triangle, trim, turnAxis, unchar, unhex, updatePixels, vertex, width, winMouseX, winMouseY, windowHeight, windowWidth, year} from './pytop5js.js'; +var __name__ = 'sketch_002'; export var setup = function () { createCanvas (640, 360, _P5_INSTANCE.WEBGL); fill (204); @@ -18,6 +18,5 @@ export var draw = function () { line (0, -(100), 0, 0, 100, 0); line (0, 0, -(100), 0, 0, 100); }; -start_p5 (setup, draw, dict ({})); //# sourceMappingURL=sketch_002.map \ No newline at end of file diff --git a/docs/examples/sketch_002/target/sketch_002.py b/docs/examples/sketch_002/target/sketch_002.py index 251ff9b7..50285aa0 100644 --- a/docs/examples/sketch_002/target/sketch_002.py +++ b/docs/examples/sketch_002/target/sketch_002.py @@ -27,7 +27,3 @@ def draw(): line(-100, 0, 0, 100, 0, 0) line(0, -100, 0, 0, 100, 0) line(0, 0, -100, 0, 0, 100) - - -# This is required by pyp5js to work -start_p5(setup, draw, {}) diff --git a/docs/examples/sketch_002/target/target_sketch.js b/docs/examples/sketch_002/target/target_sketch.js new file mode 100644 index 00000000..0bc3b564 --- /dev/null +++ b/docs/examples/sketch_002/target/target_sketch.js @@ -0,0 +1,9 @@ +// Transcrypt'ed from Python, 2019-06-01 16:39:02 +import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, input, isinstance, issubclass, len, list, object, ord, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; +import {ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEGREES, DEG_TO_RAD, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINEAR, LINES, LINE_LOOP, LINE_STRIP, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, P2D, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUADRATIC, QUADS, QUAD_STRIP, QUARTER_PI, RADIANS, RADIUS, RAD_TO_DEG, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, TWO_PI, UP_ARROW, WAIT, WEBGL, _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, _P5_INSTANCE, abs, accelerationX, accelerationY, accelerationZ, acos, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, char, circle, color, colorMode, concat, cone, constrain, copy, cos, createCamera, createCanvas, createGraphics, createImage, createNumberDict, createShader, createStringDict, createVector, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, deviceOrientation, directionalLight, disableFriendlyErrors, displayDensity, displayHeight, displayWidth, dist, draw, ellipse, ellipseMode, ellipsoid, endContour, endShape, exp, fill, filter, float, floor, focused, frameCount, frameRate, fullscreen, getURL, getURLParams, getURLPath, global_p5_injection, green, height, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, int, join, key, keyCode, keyIsDown, keyIsPressed, lerp, lerpColor, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, mouseButton, mouseIsPressed, mouseX, mouseY, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noFill, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normalMaterial, orbitControl, ortho, pAccelerationX, pAccelerationY, pAccelerationZ, pRotationX, pRotationY, pRotationZ, perspective, pixelDensity, pixels, plane, pmouseX, pmouseY, point, pointLight, pow, pre_draw, preload, print, push, pwinMouseX, pwinMouseY, py_clear, py_get, py_pop, py_sort, py_split, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, remove, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, rotationX, rotationY, rotationZ, round, saturation, save, saveCanvas, saveFrames, saveJSON, saveStrings, saveTable, scale, second, set, setAttributes, setCamera, setMoveThreshold, setShakeThreshold, setup, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, specularMaterial, sphere, splice, splitTokens, sq, sqrt, square, start_p5, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, touches, translate, triangle, trim, turnAxis, unchar, unhex, updatePixels, vertex, width, winMouseX, winMouseY, windowHeight, windowWidth, year} from './pytop5js.js'; +import * as source_sketch from './sketch_002.js'; +var __name__ = '__main__'; +export var event_functions = dict ({'deviceMoved': source_sketch.deviceMoved, 'deviceTurned': source_sketch.deviceTurned, 'deviceShaken': source_sketch.deviceShaken, 'keyPressed': source_sketch.keyPressed, 'keyReleased': source_sketch.keyReleased, 'keyTyped': source_sketch.keyTyped, 'mouseMoved': source_sketch.mouseMoved, 'mouseDragged': source_sketch.mouseDragged, 'mousePressed': source_sketch.mousePressed, 'mouseReleased': source_sketch.mouseReleased, 'mouseClicked': source_sketch.mouseClicked, 'doubleClicked': source_sketch.doubleClicked, 'mouseWheel': source_sketch.mouseWheel, 'touchStarted': source_sketch.touchStarted, 'touchMoved': source_sketch.touchMoved, 'touchEnded': source_sketch.touchEnded, 'windowResized': source_sketch.windowResized}); +start_p5 (source_sketch.setup, source_sketch.draw, event_functions); + +//# sourceMappingURL=target_sketch.map \ No newline at end of file diff --git a/docs/examples/sketch_002/target/sketch_002.options b/docs/examples/sketch_002/target/target_sketch.options similarity index 73% rename from docs/examples/sketch_002/target/sketch_002.options rename to docs/examples/sketch_002/target/target_sketch.options index 92f959596532910d7e69f65557b5f35436f967e1..150b5c2fa41ef593a32dcf03d0674da2ac16d461 100644 GIT binary patch delta 39 qcmcb^a-U^_h>SD?14D6kYDscNyn%s{eo10cdTL2LL}a6`J`(`;rwq6N delta 36 jcmcc5a))Jth@=Dq14D6kYDscNyn%s{K7zT?K%WT!%JK@p diff --git a/docs/examples/sketch_002/target/target_sketch.py b/docs/examples/sketch_002/target/target_sketch.py new file mode 100644 index 00000000..7b761ecb --- /dev/null +++ b/docs/examples/sketch_002/target/target_sketch.py @@ -0,0 +1,24 @@ +import sketch_002 as source_sketch +from pytop5js import * + +event_functions = { + "deviceMoved": source_sketch.deviceMoved, + "deviceTurned": source_sketch.deviceTurned, + "deviceShaken": source_sketch.deviceShaken, + "keyPressed": source_sketch.keyPressed, + "keyReleased": source_sketch.keyReleased, + "keyTyped": source_sketch.keyTyped, + "mouseMoved": source_sketch.mouseMoved, + "mouseDragged": source_sketch.mouseDragged, + "mousePressed": source_sketch.mousePressed, + "mouseReleased": source_sketch.mouseReleased, + "mouseClicked": source_sketch.mouseClicked, + "doubleClicked": source_sketch.doubleClicked, + "mouseWheel": source_sketch.mouseWheel, + "touchStarted": source_sketch.touchStarted, + "touchMoved": source_sketch.touchMoved, + "touchEnded": source_sketch.touchEnded, + "windowResized": source_sketch.windowResized, +} + +start_p5(source_sketch.setup, source_sketch.draw, event_functions) \ No newline at end of file diff --git a/docs/examples/sketch_003/sketch_003.py b/docs/examples/sketch_003/sketch_003.py index 917638e6..12843781 100644 --- a/docs/examples/sketch_003/sketch_003.py +++ b/docs/examples/sketch_003/sketch_003.py @@ -6,15 +6,12 @@ def setup(): createCanvas(600, 600, WEBGL) def draw(): - background(200) - translate(-100, -100, 0) - push() - normalMaterial() - rotateZ(frameCount * 0.01) - rotateX(frameCount * 0.01) - rotateY(frameCount * 0.01) - box(50, 70, 100) - pop() - - -start_p5(setup, draw, {}) + background(200) + translate(-100, -100, 0) + push() + normalMaterial() + rotateZ(frameCount * 0.01) + rotateX(frameCount * 0.01) + rotateY(frameCount * 0.01) + box(50, 70, 100) + pop() diff --git a/docs/examples/sketch_003/target/org.transcrypt.__runtime__.js b/docs/examples/sketch_003/target/org.transcrypt.__runtime__.js index 5ec089c3..6dc6f748 100644 --- a/docs/examples/sketch_003/target/org.transcrypt.__runtime__.js +++ b/docs/examples/sketch_003/target/org.transcrypt.__runtime__.js @@ -1,4 +1,4 @@ -// Transcrypt'ed from Python, 2019-05-09 00:36:26 +// Transcrypt'ed from Python, 2019-06-01 16:39:04 var __name__ = 'org.transcrypt.__runtime__'; export var __envir__ = {}; __envir__.interpreter_name = 'python'; diff --git a/docs/examples/sketch_003/target/pytop5js.js b/docs/examples/sketch_003/target/pytop5js.js index 123b8401..32617fd6 100644 --- a/docs/examples/sketch_003/target/pytop5js.js +++ b/docs/examples/sketch_003/target/pytop5js.js @@ -1,7 +1,157 @@ -// Transcrypt'ed from Python, 2019-05-09 00:36:26 +// Transcrypt'ed from Python, 2019-06-01 16:39:04 import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, input, isinstance, issubclass, len, list, object, ord, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; var __name__ = 'pytop5js'; export var _P5_INSTANCE = null; +export var _CTX_MIDDLE = null; +export var _DEFAULT_FILL = null; +export var _DEFAULT_LEADMULT = null; +export var _DEFAULT_STROKE = null; +export var _DEFAULT_TEXT_FILL = null; +export var ADD = null; +export var ALT = null; +export var ARROW = null; +export var AUTO = null; +export var AXES = null; +export var BACKSPACE = null; +export var BASELINE = null; +export var BEVEL = null; +export var BEZIER = null; +export var BLEND = null; +export var BLUR = null; +export var BOLD = null; +export var BOLDITALIC = null; +export var BOTTOM = null; +export var BURN = null; +export var CENTER = null; +export var CHORD = null; +export var CLAMP = null; +export var CLOSE = null; +export var CONTROL = null; +export var CORNER = null; +export var CORNERS = null; +export var CROSS = null; +export var CURVE = null; +export var DARKEST = null; +export var DEG_TO_RAD = null; +export var DEGREES = null; +export var DELETE = null; +export var DIFFERENCE = null; +export var DILATE = null; +export var DODGE = null; +export var DOWN_ARROW = null; +export var ENTER = null; +export var ERODE = null; +export var ESCAPE = null; +export var EXCLUSION = null; +export var FILL = null; +export var GRAY = null; +export var GRID = null; +export var HALF_PI = null; +export var HAND = null; +export var HARD_LIGHT = null; +export var HSB = null; +export var HSL = null; +export var IMAGE = null; +export var IMMEDIATE = null; +export var INVERT = null; +export var ITALIC = null; +export var LANDSCAPE = null; +export var LEFT = null; +export var LEFT_ARROW = null; +export var LIGHTEST = null; +export var LINE_LOOP = null; +export var LINE_STRIP = null; +export var LINEAR = null; +export var LINES = null; +export var MIRROR = null; +export var MITER = null; +export var MOVE = null; +export var MULTIPLY = null; +export var NEAREST = null; +export var NORMAL = null; +export var OPAQUE = null; +export var OPEN = null; +export var OPTION = null; +export var OVERLAY = null; +export var PI = null; +export var PIE = null; +export var POINTS = null; +export var PORTRAIT = null; +export var POSTERIZE = null; +export var PROJECT = null; +export var QUAD_STRIP = null; +export var QUADRATIC = null; +export var QUADS = null; +export var QUARTER_PI = null; +export var RAD_TO_DEG = null; +export var RADIANS = null; +export var RADIUS = null; +export var REPEAT = null; +export var REPLACE = null; +export var RETURN = null; +export var RGB = null; +export var RIGHT = null; +export var RIGHT_ARROW = null; +export var ROUND = null; +export var SCREEN = null; +export var SHIFT = null; +export var SOFT_LIGHT = null; +export var SQUARE = null; +export var STROKE = null; +export var SUBTRACT = null; +export var TAB = null; +export var TAU = null; +export var TEXT = null; +export var TEXTURE = null; +export var THRESHOLD = null; +export var TOP = null; +export var TRIANGLE_FAN = null; +export var TRIANGLE_STRIP = null; +export var TRIANGLES = null; +export var TWO_PI = null; +export var UP_ARROW = null; +export var WAIT = null; +export var WEBGL = null; +export var P2D = null; +var PI = null; +export var frameCount = null; +export var focused = null; +export var displayWidth = null; +export var displayHeight = null; +export var windowWidth = null; +export var windowHeight = null; +export var width = null; +export var height = null; +export var disableFriendlyErrors = null; +export var deviceOrientation = null; +export var accelerationX = null; +export var accelerationY = null; +export var accelerationZ = null; +export var pAccelerationX = null; +export var pAccelerationY = null; +export var pAccelerationZ = null; +export var rotationX = null; +export var rotationY = null; +export var rotationZ = null; +export var pRotationX = null; +export var pRotationY = null; +export var pRotationZ = null; +export var turnAxis = null; +export var keyIsPressed = null; +export var key = null; +export var keyCode = null; +export var mouseX = null; +export var mouseY = null; +export var pmouseX = null; +export var pmouseY = null; +export var winMouseX = null; +export var winMouseY = null; +export var pwinMouseX = null; +export var pwinMouseY = null; +export var mouseButton = null; +export var mouseIsPressed = null; +export var touches = null; +export var pixels = null; export var alpha = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.alpha (...args); @@ -310,10 +460,6 @@ export var redraw = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.redraw (...args); }; -export var createCanvas = function () { - var args = tuple ([].slice.apply (arguments).slice (0)); - return _P5_INSTANCE.createCanvas (...args); -}; export var resizeCanvas = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.resizeCanvas (...args); @@ -914,86 +1060,130 @@ export var setCamera = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.setCamera (...args); }; +export var createCanvas = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + var result = _P5_INSTANCE.createCanvas (...args); + width = _P5_INSTANCE.width; + height = _P5_INSTANCE.height; +}; export var py_pop = function () { var args = tuple ([].slice.apply (arguments).slice (0)); var p5_pop = _P5_INSTANCE.pop (...args); return p5_pop; }; -export var HALF_PI = null; -export var PI = null; -export var QUARTER_PI = null; -export var TAU = null; -export var TWO_PI = null; -export var DEGREES = null; -export var RADIANS = null; -export var CLOSE = null; -export var RGB = null; -export var HSB = null; -export var CMYK = null; -export var TOP = null; -export var BOTTOM = null; -export var CENTER = null; -export var LEFT = null; -export var RIGHT = null; -export var SHIFT = null; -export var WEBGL = null; -export var frameCount = null; -export var focused = null; -export var displayWidth = null; -export var displayHeight = null; -export var windowWidth = null; -export var windowHeight = null; -export var width = null; -export var height = null; -export var disableFriendlyErrors = null; -export var deviceOrientation = null; -export var accelerationX = null; -export var accelerationY = null; -export var accelerationZ = null; -export var pAccelerationX = null; -export var pAccelerationY = null; -export var pAccelerationZ = null; -export var rotationX = null; -export var rotationY = null; -export var rotationZ = null; -export var pRotationX = null; -export var pRotationY = null; -export var pRotationZ = null; -export var turnAxis = null; -export var keyIsPressed = null; -export var key = null; -export var keyCode = null; -export var mouseX = null; -export var mouseY = null; -export var pmouseX = null; -export var pmouseY = null; -export var winMouseX = null; -export var winMouseY = null; -export var pwinMouseX = null; -export var pwinMouseY = null; -export var mouseButton = null; -export var mouseIsPressed = null; -export var touches = null; -export var pixels = null; export var pre_draw = function (p5_instance, draw_func) { + _CTX_MIDDLE = p5_instance._CTX_MIDDLE; + _DEFAULT_FILL = p5_instance._DEFAULT_FILL; + _DEFAULT_LEADMULT = p5_instance._DEFAULT_LEADMULT; + _DEFAULT_STROKE = p5_instance._DEFAULT_STROKE; + _DEFAULT_TEXT_FILL = p5_instance._DEFAULT_TEXT_FILL; + ADD = p5_instance.ADD; + ALT = p5_instance.ALT; + ARROW = p5_instance.ARROW; + AUTO = p5_instance.AUTO; + AXES = p5_instance.AXES; + BACKSPACE = p5_instance.BACKSPACE; + BASELINE = p5_instance.BASELINE; + BEVEL = p5_instance.BEVEL; + BEZIER = p5_instance.BEZIER; + BLEND = p5_instance.BLEND; + BLUR = p5_instance.BLUR; + BOLD = p5_instance.BOLD; + BOLDITALIC = p5_instance.BOLDITALIC; + BOTTOM = p5_instance.BOTTOM; + BURN = p5_instance.BURN; + CENTER = p5_instance.CENTER; + CHORD = p5_instance.CHORD; + CLAMP = p5_instance.CLAMP; + CLOSE = p5_instance.CLOSE; + CONTROL = p5_instance.CONTROL; + CORNER = p5_instance.CORNER; + CORNERS = p5_instance.CORNERS; + CROSS = p5_instance.CROSS; + CURVE = p5_instance.CURVE; + DARKEST = p5_instance.DARKEST; + DEG_TO_RAD = p5_instance.DEG_TO_RAD; + DEGREES = p5_instance.DEGREES; + DELETE = p5_instance.DELETE; + DIFFERENCE = p5_instance.DIFFERENCE; + DILATE = p5_instance.DILATE; + DODGE = p5_instance.DODGE; + DOWN_ARROW = p5_instance.DOWN_ARROW; + ENTER = p5_instance.ENTER; + ERODE = p5_instance.ERODE; + ESCAPE = p5_instance.ESCAPE; + EXCLUSION = p5_instance.EXCLUSION; + FILL = p5_instance.FILL; + GRAY = p5_instance.GRAY; + GRID = p5_instance.GRID; HALF_PI = p5_instance.HALF_PI; + HAND = p5_instance.HAND; + HARD_LIGHT = p5_instance.HARD_LIGHT; + HSB = p5_instance.HSB; + HSL = p5_instance.HSL; + IMAGE = p5_instance.IMAGE; + IMMEDIATE = p5_instance.IMMEDIATE; + INVERT = p5_instance.INVERT; + ITALIC = p5_instance.ITALIC; + LANDSCAPE = p5_instance.LANDSCAPE; + LEFT = p5_instance.LEFT; + LEFT_ARROW = p5_instance.LEFT_ARROW; + LIGHTEST = p5_instance.LIGHTEST; + LINE_LOOP = p5_instance.LINE_LOOP; + LINE_STRIP = p5_instance.LINE_STRIP; + LINEAR = p5_instance.LINEAR; + LINES = p5_instance.LINES; + MIRROR = p5_instance.MIRROR; + MITER = p5_instance.MITER; + MOVE = p5_instance.MOVE; + MULTIPLY = p5_instance.MULTIPLY; + NEAREST = p5_instance.NEAREST; + NORMAL = p5_instance.NORMAL; + OPAQUE = p5_instance.OPAQUE; + OPEN = p5_instance.OPEN; + OPTION = p5_instance.OPTION; + OVERLAY = p5_instance.OVERLAY; PI = p5_instance.PI; + PIE = p5_instance.PIE; + POINTS = p5_instance.POINTS; + PORTRAIT = p5_instance.PORTRAIT; + POSTERIZE = p5_instance.POSTERIZE; + PROJECT = p5_instance.PROJECT; + QUAD_STRIP = p5_instance.QUAD_STRIP; + QUADRATIC = p5_instance.QUADRATIC; + QUADS = p5_instance.QUADS; QUARTER_PI = p5_instance.QUARTER_PI; - TAU = p5_instance.TAU; - TWO_PI = p5_instance.TWO_PI; - DEGREES = p5_instance.DEGREES; + RAD_TO_DEG = p5_instance.RAD_TO_DEG; RADIANS = p5_instance.RADIANS; - CLOSE = p5_instance.CLOSE; + RADIUS = p5_instance.RADIUS; + REPEAT = p5_instance.REPEAT; + REPLACE = p5_instance.REPLACE; + RETURN = p5_instance.RETURN; RGB = p5_instance.RGB; - HSB = p5_instance.HSB; - CMYK = p5_instance.CMYK; - TOP = p5_instance.TOP; - BOTTOM = p5_instance.BOTTOM; - CENTER = p5_instance.CENTER; - LEFT = p5_instance.LEFT; RIGHT = p5_instance.RIGHT; + RIGHT_ARROW = p5_instance.RIGHT_ARROW; + ROUND = p5_instance.ROUND; + SCREEN = p5_instance.SCREEN; SHIFT = p5_instance.SHIFT; + SOFT_LIGHT = p5_instance.SOFT_LIGHT; + SQUARE = p5_instance.SQUARE; + STROKE = p5_instance.STROKE; + SUBTRACT = p5_instance.SUBTRACT; + TAB = p5_instance.TAB; + TAU = p5_instance.TAU; + TEXT = p5_instance.TEXT; + TEXTURE = p5_instance.TEXTURE; + THRESHOLD = p5_instance.THRESHOLD; + TOP = p5_instance.TOP; + TRIANGLE_FAN = p5_instance.TRIANGLE_FAN; + TRIANGLE_STRIP = p5_instance.TRIANGLE_STRIP; + TRIANGLES = p5_instance.TRIANGLES; + TWO_PI = p5_instance.TWO_PI; + UP_ARROW = p5_instance.UP_ARROW; + WAIT = p5_instance.WAIT; WEBGL = p5_instance.WEBGL; + P2D = p5_instance.P2D; + PI = p5_instance.PI; frameCount = p5_instance.frameCount; focused = p5_instance.focused; displayWidth = p5_instance.displayWidth; @@ -1054,7 +1244,7 @@ export var start_p5 = function (setup_func, draw_func, event_functions) { for (var f_name of (function () { var __accu0__ = []; for (var f of event_function_names) { - if (__in__ (f, event_functions)) { + if (event_functions.py_get (f, null)) { __accu0__.append (f); } } diff --git a/docs/examples/sketch_003/target/pytop5js.py b/docs/examples/sketch_003/target/pytop5js.py index 59388176..6462430c 100644 --- a/docs/examples/sketch_003/target/pytop5js.py +++ b/docs/examples/sketch_003/target/pytop5js.py @@ -1,4 +1,155 @@ _P5_INSTANCE = None +_CTX_MIDDLE = None +_DEFAULT_FILL = None +_DEFAULT_LEADMULT = None +_DEFAULT_STROKE = None +_DEFAULT_TEXT_FILL = None +ADD = None +ALT = None +ARROW = None +AUTO = None +AXES = None +BACKSPACE = None +BASELINE = None +BEVEL = None +BEZIER = None +BLEND = None +BLUR = None +BOLD = None +BOLDITALIC = None +BOTTOM = None +BURN = None +CENTER = None +CHORD = None +CLAMP = None +CLOSE = None +CONTROL = None +CORNER = None +CORNERS = None +CROSS = None +CURVE = None +DARKEST = None +DEG_TO_RAD = None +DEGREES = None +DELETE = None +DIFFERENCE = None +DILATE = None +DODGE = None +DOWN_ARROW = None +ENTER = None +ERODE = None +ESCAPE = None +EXCLUSION = None +FILL = None +GRAY = None +GRID = None +HALF_PI = None +HAND = None +HARD_LIGHT = None +HSB = None +HSL = None +IMAGE = None +IMMEDIATE = None +INVERT = None +ITALIC = None +LANDSCAPE = None +LEFT = None +LEFT_ARROW = None +LIGHTEST = None +LINE_LOOP = None +LINE_STRIP = None +LINEAR = None +LINES = None +MIRROR = None +MITER = None +MOVE = None +MULTIPLY = None +NEAREST = None +NORMAL = None +OPAQUE = None +OPEN = None +OPTION = None +OVERLAY = None +PI = None +PIE = None +POINTS = None +PORTRAIT = None +POSTERIZE = None +PROJECT = None +QUAD_STRIP = None +QUADRATIC = None +QUADS = None +QUARTER_PI = None +RAD_TO_DEG = None +RADIANS = None +RADIUS = None +REPEAT = None +REPLACE = None +RETURN = None +RGB = None +RIGHT = None +RIGHT_ARROW = None +ROUND = None +SCREEN = None +SHIFT = None +SOFT_LIGHT = None +SQUARE = None +STROKE = None +SUBTRACT = None +TAB = None +TAU = None +TEXT = None +TEXTURE = None +THRESHOLD = None +TOP = None +TRIANGLE_FAN = None +TRIANGLE_STRIP = None +TRIANGLES = None +TWO_PI = None +UP_ARROW = None +WAIT = None +WEBGL = None +P2D = None +PI = None +frameCount = None +focused = None +displayWidth = None +displayHeight = None +windowWidth = None +windowHeight = None +width = None +height = None +disableFriendlyErrors = None +deviceOrientation = None +accelerationX = None +accelerationY = None +accelerationZ = None +pAccelerationX = None +pAccelerationY = None +pAccelerationZ = None +rotationX = None +rotationY = None +rotationZ = None +pRotationX = None +pRotationY = None +pRotationZ = None +turnAxis = None +keyIsPressed = None +key = None +keyCode = None +mouseX = None +mouseY = None +pmouseX = None +pmouseY = None +winMouseX = None +winMouseY = None +pwinMouseX = None +pwinMouseY = None +mouseButton = None +mouseIsPressed = None +touches = None +pixels = None + def alpha(*args): @@ -232,9 +383,6 @@ def push(*args): def redraw(*args): return _P5_INSTANCE.redraw(*args) -def createCanvas(*args): - return _P5_INSTANCE.createCanvas(*args) - def resizeCanvas(*args): return _P5_INSTANCE.resizeCanvas(*args) @@ -686,6 +834,13 @@ def setCamera(*args): return _P5_INSTANCE.setCamera(*args) +def createCanvas(*args): + result = _P5_INSTANCE.createCanvas(*args) + + global width, height + width = _P5_INSTANCE.width + height = _P5_INSTANCE.height + def pop(*args): __pragma__('noalias', 'pop') @@ -693,87 +848,124 @@ def pop(*args): __pragma__('alias', 'pop', 'py_pop') return p5_pop -HALF_PI = None -PI = None -QUARTER_PI = None -TAU = None -TWO_PI = None -DEGREES = None -RADIANS = None -CLOSE = None -RGB = None -HSB = None -CMYK = None -TOP = None -BOTTOM = None -CENTER = None -LEFT = None -RIGHT = None -SHIFT = None -WEBGL = None -frameCount = None -focused = None -displayWidth = None -displayHeight = None -windowWidth = None -windowHeight = None -width = None -height = None -disableFriendlyErrors = None -deviceOrientation = None -accelerationX = None -accelerationY = None -accelerationZ = None -pAccelerationX = None -pAccelerationY = None -pAccelerationZ = None -rotationX = None -rotationY = None -rotationZ = None -pRotationX = None -pRotationY = None -pRotationZ = None -turnAxis = None -keyIsPressed = None -key = None -keyCode = None -mouseX = None -mouseY = None -pmouseX = None -pmouseY = None -winMouseX = None -winMouseY = None -pwinMouseX = None -pwinMouseY = None -mouseButton = None -mouseIsPressed = None -touches = None -pixels = None - def pre_draw(p5_instance, draw_func): """ We need to run this before the actual draw to insert and update p5 env variables """ - global HALF_PI, PI, QUARTER_PI, TAU, TWO_PI, DEGREES, RADIANS, CLOSE, RGB, HSB, CMYK, TOP, BOTTOM, CENTER, LEFT, RIGHT, SHIFT, WEBGL, frameCount, focused, displayWidth, displayHeight, windowWidth, windowHeight, width, height, disableFriendlyErrors, deviceOrientation, accelerationX, accelerationY, accelerationZ, pAccelerationX, pAccelerationY, pAccelerationZ, rotationX, rotationY, rotationZ, pRotationX, pRotationY, pRotationZ, turnAxis, keyIsPressed, key, keyCode, mouseX, mouseY, pmouseX, pmouseY, winMouseX, winMouseY, pwinMouseX, pwinMouseY, mouseButton, mouseIsPressed, touches, pixels - + global _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEG_TO_RAD, DEGREES, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINE_LOOP, LINE_STRIP, LINEAR, LINES, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUAD_STRIP, QUADRATIC, QUADS, QUARTER_PI, RAD_TO_DEG, RADIANS, RADIUS, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLE_FAN, TRIANGLE_STRIP, TRIANGLES, TWO_PI, UP_ARROW, WAIT, WEBGL, P2D, PI, frameCount, focused, displayWidth, displayHeight, windowWidth, windowHeight, width, height, disableFriendlyErrors, deviceOrientation, accelerationX, accelerationY, accelerationZ, pAccelerationX, pAccelerationY, pAccelerationZ, rotationX, rotationY, rotationZ, pRotationX, pRotationY, pRotationZ, turnAxis, keyIsPressed, key, keyCode, mouseX, mouseY, pmouseX, pmouseY, winMouseX, winMouseY, pwinMouseX, pwinMouseY, mouseButton, mouseIsPressed, touches, pixels + + _CTX_MIDDLE = p5_instance._CTX_MIDDLE + _DEFAULT_FILL = p5_instance._DEFAULT_FILL + _DEFAULT_LEADMULT = p5_instance._DEFAULT_LEADMULT + _DEFAULT_STROKE = p5_instance._DEFAULT_STROKE + _DEFAULT_TEXT_FILL = p5_instance._DEFAULT_TEXT_FILL + ADD = p5_instance.ADD + ALT = p5_instance.ALT + ARROW = p5_instance.ARROW + AUTO = p5_instance.AUTO + AXES = p5_instance.AXES + BACKSPACE = p5_instance.BACKSPACE + BASELINE = p5_instance.BASELINE + BEVEL = p5_instance.BEVEL + BEZIER = p5_instance.BEZIER + BLEND = p5_instance.BLEND + BLUR = p5_instance.BLUR + BOLD = p5_instance.BOLD + BOLDITALIC = p5_instance.BOLDITALIC + BOTTOM = p5_instance.BOTTOM + BURN = p5_instance.BURN + CENTER = p5_instance.CENTER + CHORD = p5_instance.CHORD + CLAMP = p5_instance.CLAMP + CLOSE = p5_instance.CLOSE + CONTROL = p5_instance.CONTROL + CORNER = p5_instance.CORNER + CORNERS = p5_instance.CORNERS + CROSS = p5_instance.CROSS + CURVE = p5_instance.CURVE + DARKEST = p5_instance.DARKEST + DEG_TO_RAD = p5_instance.DEG_TO_RAD + DEGREES = p5_instance.DEGREES + DELETE = p5_instance.DELETE + DIFFERENCE = p5_instance.DIFFERENCE + DILATE = p5_instance.DILATE + DODGE = p5_instance.DODGE + DOWN_ARROW = p5_instance.DOWN_ARROW + ENTER = p5_instance.ENTER + ERODE = p5_instance.ERODE + ESCAPE = p5_instance.ESCAPE + EXCLUSION = p5_instance.EXCLUSION + FILL = p5_instance.FILL + GRAY = p5_instance.GRAY + GRID = p5_instance.GRID HALF_PI = p5_instance.HALF_PI + HAND = p5_instance.HAND + HARD_LIGHT = p5_instance.HARD_LIGHT + HSB = p5_instance.HSB + HSL = p5_instance.HSL + IMAGE = p5_instance.IMAGE + IMMEDIATE = p5_instance.IMMEDIATE + INVERT = p5_instance.INVERT + ITALIC = p5_instance.ITALIC + LANDSCAPE = p5_instance.LANDSCAPE + LEFT = p5_instance.LEFT + LEFT_ARROW = p5_instance.LEFT_ARROW + LIGHTEST = p5_instance.LIGHTEST + LINE_LOOP = p5_instance.LINE_LOOP + LINE_STRIP = p5_instance.LINE_STRIP + LINEAR = p5_instance.LINEAR + LINES = p5_instance.LINES + MIRROR = p5_instance.MIRROR + MITER = p5_instance.MITER + MOVE = p5_instance.MOVE + MULTIPLY = p5_instance.MULTIPLY + NEAREST = p5_instance.NEAREST + NORMAL = p5_instance.NORMAL + OPAQUE = p5_instance.OPAQUE + OPEN = p5_instance.OPEN + OPTION = p5_instance.OPTION + OVERLAY = p5_instance.OVERLAY PI = p5_instance.PI + PIE = p5_instance.PIE + POINTS = p5_instance.POINTS + PORTRAIT = p5_instance.PORTRAIT + POSTERIZE = p5_instance.POSTERIZE + PROJECT = p5_instance.PROJECT + QUAD_STRIP = p5_instance.QUAD_STRIP + QUADRATIC = p5_instance.QUADRATIC + QUADS = p5_instance.QUADS QUARTER_PI = p5_instance.QUARTER_PI - TAU = p5_instance.TAU - TWO_PI = p5_instance.TWO_PI - DEGREES = p5_instance.DEGREES + RAD_TO_DEG = p5_instance.RAD_TO_DEG RADIANS = p5_instance.RADIANS - CLOSE = p5_instance.CLOSE + RADIUS = p5_instance.RADIUS + REPEAT = p5_instance.REPEAT + REPLACE = p5_instance.REPLACE + RETURN = p5_instance.RETURN RGB = p5_instance.RGB - HSB = p5_instance.HSB - CMYK = p5_instance.CMYK - TOP = p5_instance.TOP - BOTTOM = p5_instance.BOTTOM - CENTER = p5_instance.CENTER - LEFT = p5_instance.LEFT RIGHT = p5_instance.RIGHT + RIGHT_ARROW = p5_instance.RIGHT_ARROW + ROUND = p5_instance.ROUND + SCREEN = p5_instance.SCREEN SHIFT = p5_instance.SHIFT + SOFT_LIGHT = p5_instance.SOFT_LIGHT + SQUARE = p5_instance.SQUARE + STROKE = p5_instance.STROKE + SUBTRACT = p5_instance.SUBTRACT + TAB = p5_instance.TAB + TAU = p5_instance.TAU + TEXT = p5_instance.TEXT + TEXTURE = p5_instance.TEXTURE + THRESHOLD = p5_instance.THRESHOLD + TOP = p5_instance.TOP + TRIANGLE_FAN = p5_instance.TRIANGLE_FAN + TRIANGLE_STRIP = p5_instance.TRIANGLE_STRIP + TRIANGLES = p5_instance.TRIANGLES + TWO_PI = p5_instance.TWO_PI + UP_ARROW = p5_instance.UP_ARROW + WAIT = p5_instance.WAIT WEBGL = p5_instance.WEBGL + P2D = p5_instance.P2D + PI = p5_instance.PI frameCount = p5_instance.frameCount focused = p5_instance.focused displayWidth = p5_instance.displayWidth @@ -853,7 +1045,7 @@ def sketch_setup(p5_sketch): # inject event functions into p5 event_function_names = ["deviceMoved", "deviceTurned", "deviceShaken", "keyPressed", "keyReleased", "keyTyped", "mouseMoved", "mouseDragged", "mousePressed", "mouseReleased", "mouseClicked", "doubleClicked", "mouseWheel", "touchStarted", "touchMoved", "touchEnded", "windowResized", ] - for f_name in [f for f in event_function_names if f in event_functions]: + for f_name in [f for f in event_function_names if event_functions.get(f, None)]: func = event_functions[f_name] event_func = global_p5_injection(instance)(func) setattr(instance, f_name, event_func) \ No newline at end of file diff --git a/docs/examples/sketch_003/target/sketch_003.js b/docs/examples/sketch_003/target/sketch_003.js index 1b337abb..ae6f937c 100644 --- a/docs/examples/sketch_003/target/sketch_003.js +++ b/docs/examples/sketch_003/target/sketch_003.js @@ -1,7 +1,7 @@ -// Transcrypt'ed from Python, 2019-05-09 00:36:26 +// Transcrypt'ed from Python, 2019-06-01 16:39:04 import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, input, isinstance, issubclass, len, list, object, ord, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; -import {BOTTOM, CENTER, CLOSE, CMYK, DEGREES, HALF_PI, HSB, LEFT, PI, QUARTER_PI, RADIANS, RGB, RIGHT, SHIFT, TAU, TOP, TWO_PI, WEBGL, _P5_INSTANCE, abs, accelerationX, accelerationY, accelerationZ, acos, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, char, circle, color, colorMode, concat, cone, constrain, copy, cos, createCamera, createCanvas, createGraphics, createImage, createNumberDict, createShader, createStringDict, createVector, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, deviceOrientation, directionalLight, disableFriendlyErrors, displayDensity, displayHeight, displayWidth, dist, ellipse, ellipseMode, ellipsoid, endContour, endShape, exp, fill, filter, float, floor, focused, frameCount, frameRate, fullscreen, getURL, getURLParams, getURLPath, global_p5_injection, green, height, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, int, join, key, keyCode, keyIsDown, keyIsPressed, lerp, lerpColor, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, mouseButton, mouseIsPressed, mouseX, mouseY, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noFill, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normalMaterial, orbitControl, ortho, pAccelerationX, pAccelerationY, pAccelerationZ, pRotationX, pRotationY, pRotationZ, perspective, pixelDensity, pixels, plane, pmouseX, pmouseY, point, pointLight, pow, pre_draw, preload, print, push, pwinMouseX, pwinMouseY, py_clear, py_get, py_pop, py_sort, py_split, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, remove, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, rotationX, rotationY, rotationZ, round, saturation, save, saveCanvas, saveFrames, saveJSON, saveStrings, saveTable, scale, second, set, setAttributes, setCamera, setMoveThreshold, setShakeThreshold, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, specularMaterial, sphere, splice, splitTokens, sq, sqrt, square, start_p5, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, touches, translate, triangle, trim, turnAxis, unchar, unhex, updatePixels, vertex, width, winMouseX, winMouseY, windowHeight, windowWidth, year} from './pytop5js.js'; -var __name__ = '__main__'; +import {ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEGREES, DEG_TO_RAD, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINEAR, LINES, LINE_LOOP, LINE_STRIP, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, P2D, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUADRATIC, QUADS, QUAD_STRIP, QUARTER_PI, RADIANS, RADIUS, RAD_TO_DEG, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, TWO_PI, UP_ARROW, WAIT, WEBGL, _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, _P5_INSTANCE, abs, accelerationX, accelerationY, accelerationZ, acos, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, char, circle, color, colorMode, concat, cone, constrain, copy, cos, createCamera, createCanvas, createGraphics, createImage, createNumberDict, createShader, createStringDict, createVector, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, deviceOrientation, directionalLight, disableFriendlyErrors, displayDensity, displayHeight, displayWidth, dist, ellipse, ellipseMode, ellipsoid, endContour, endShape, exp, fill, filter, float, floor, focused, frameCount, frameRate, fullscreen, getURL, getURLParams, getURLPath, global_p5_injection, green, height, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, int, join, key, keyCode, keyIsDown, keyIsPressed, lerp, lerpColor, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, mouseButton, mouseIsPressed, mouseX, mouseY, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noFill, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normalMaterial, orbitControl, ortho, pAccelerationX, pAccelerationY, pAccelerationZ, pRotationX, pRotationY, pRotationZ, perspective, pixelDensity, pixels, plane, pmouseX, pmouseY, point, pointLight, pow, pre_draw, preload, print, push, pwinMouseX, pwinMouseY, py_clear, py_get, py_pop, py_sort, py_split, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, remove, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, rotationX, rotationY, rotationZ, round, saturation, save, saveCanvas, saveFrames, saveJSON, saveStrings, saveTable, scale, second, set, setAttributes, setCamera, setMoveThreshold, setShakeThreshold, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, specularMaterial, sphere, splice, splitTokens, sq, sqrt, square, start_p5, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, touches, translate, triangle, trim, turnAxis, unchar, unhex, updatePixels, vertex, width, winMouseX, winMouseY, windowHeight, windowWidth, year} from './pytop5js.js'; +var __name__ = 'sketch_003'; export var setup = function () { createCanvas (600, 600, WEBGL); }; @@ -16,6 +16,5 @@ export var draw = function () { box (50, 70, 100); py_pop (); }; -start_p5 (setup, draw, dict ({})); //# sourceMappingURL=sketch_003.map \ No newline at end of file diff --git a/docs/examples/sketch_003/target/sketch_003.py b/docs/examples/sketch_003/target/sketch_003.py index 917638e6..12843781 100644 --- a/docs/examples/sketch_003/target/sketch_003.py +++ b/docs/examples/sketch_003/target/sketch_003.py @@ -6,15 +6,12 @@ def setup(): createCanvas(600, 600, WEBGL) def draw(): - background(200) - translate(-100, -100, 0) - push() - normalMaterial() - rotateZ(frameCount * 0.01) - rotateX(frameCount * 0.01) - rotateY(frameCount * 0.01) - box(50, 70, 100) - pop() - - -start_p5(setup, draw, {}) + background(200) + translate(-100, -100, 0) + push() + normalMaterial() + rotateZ(frameCount * 0.01) + rotateX(frameCount * 0.01) + rotateY(frameCount * 0.01) + box(50, 70, 100) + pop() diff --git a/docs/examples/sketch_003/target/target_sketch.js b/docs/examples/sketch_003/target/target_sketch.js new file mode 100644 index 00000000..893a145d --- /dev/null +++ b/docs/examples/sketch_003/target/target_sketch.js @@ -0,0 +1,9 @@ +// Transcrypt'ed from Python, 2019-06-01 16:39:04 +import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, input, isinstance, issubclass, len, list, object, ord, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; +import {ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEGREES, DEG_TO_RAD, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINEAR, LINES, LINE_LOOP, LINE_STRIP, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, P2D, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUADRATIC, QUADS, QUAD_STRIP, QUARTER_PI, RADIANS, RADIUS, RAD_TO_DEG, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, TWO_PI, UP_ARROW, WAIT, WEBGL, _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, _P5_INSTANCE, abs, accelerationX, accelerationY, accelerationZ, acos, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, char, circle, color, colorMode, concat, cone, constrain, copy, cos, createCamera, createCanvas, createGraphics, createImage, createNumberDict, createShader, createStringDict, createVector, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, deviceOrientation, directionalLight, disableFriendlyErrors, displayDensity, displayHeight, displayWidth, dist, draw, ellipse, ellipseMode, ellipsoid, endContour, endShape, exp, fill, filter, float, floor, focused, frameCount, frameRate, fullscreen, getURL, getURLParams, getURLPath, global_p5_injection, green, height, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, int, join, key, keyCode, keyIsDown, keyIsPressed, lerp, lerpColor, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, mouseButton, mouseIsPressed, mouseX, mouseY, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noFill, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normalMaterial, orbitControl, ortho, pAccelerationX, pAccelerationY, pAccelerationZ, pRotationX, pRotationY, pRotationZ, perspective, pixelDensity, pixels, plane, pmouseX, pmouseY, point, pointLight, pow, pre_draw, preload, print, push, pwinMouseX, pwinMouseY, py_clear, py_get, py_pop, py_sort, py_split, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, remove, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, rotationX, rotationY, rotationZ, round, saturation, save, saveCanvas, saveFrames, saveJSON, saveStrings, saveTable, scale, second, set, setAttributes, setCamera, setMoveThreshold, setShakeThreshold, setup, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, specularMaterial, sphere, splice, splitTokens, sq, sqrt, square, start_p5, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, touches, translate, triangle, trim, turnAxis, unchar, unhex, updatePixels, vertex, width, winMouseX, winMouseY, windowHeight, windowWidth, year} from './pytop5js.js'; +import * as source_sketch from './sketch_003.js'; +var __name__ = '__main__'; +export var event_functions = dict ({'deviceMoved': source_sketch.deviceMoved, 'deviceTurned': source_sketch.deviceTurned, 'deviceShaken': source_sketch.deviceShaken, 'keyPressed': source_sketch.keyPressed, 'keyReleased': source_sketch.keyReleased, 'keyTyped': source_sketch.keyTyped, 'mouseMoved': source_sketch.mouseMoved, 'mouseDragged': source_sketch.mouseDragged, 'mousePressed': source_sketch.mousePressed, 'mouseReleased': source_sketch.mouseReleased, 'mouseClicked': source_sketch.mouseClicked, 'doubleClicked': source_sketch.doubleClicked, 'mouseWheel': source_sketch.mouseWheel, 'touchStarted': source_sketch.touchStarted, 'touchMoved': source_sketch.touchMoved, 'touchEnded': source_sketch.touchEnded, 'windowResized': source_sketch.windowResized}); +start_p5 (source_sketch.setup, source_sketch.draw, event_functions); + +//# sourceMappingURL=target_sketch.map \ No newline at end of file diff --git a/docs/examples/sketch_003/target/sketch_003.options b/docs/examples/sketch_003/target/target_sketch.options similarity index 73% rename from docs/examples/sketch_003/target/sketch_003.options rename to docs/examples/sketch_003/target/target_sketch.options index 2f6e32dde00cb232f7861e6b1cfa9d4b39ce8fc7..4e0e8b3c04719adbdc66d4e39a8709b092d2f2f6 100644 GIT binary patch delta 39 qcmcb^a-U^_h>SD?14D6kYDscNyn%tSeo10cdTL2LL}a6`J`(`;x(vAh delta 36 jcmcc5a))Jth@=Dq14D6kYDscNyn%tSK7zT?K%WT!%LfX= diff --git a/docs/examples/sketch_003/target/target_sketch.py b/docs/examples/sketch_003/target/target_sketch.py new file mode 100644 index 00000000..b12224d8 --- /dev/null +++ b/docs/examples/sketch_003/target/target_sketch.py @@ -0,0 +1,24 @@ +import sketch_003 as source_sketch +from pytop5js import * + +event_functions = { + "deviceMoved": source_sketch.deviceMoved, + "deviceTurned": source_sketch.deviceTurned, + "deviceShaken": source_sketch.deviceShaken, + "keyPressed": source_sketch.keyPressed, + "keyReleased": source_sketch.keyReleased, + "keyTyped": source_sketch.keyTyped, + "mouseMoved": source_sketch.mouseMoved, + "mouseDragged": source_sketch.mouseDragged, + "mousePressed": source_sketch.mousePressed, + "mouseReleased": source_sketch.mouseReleased, + "mouseClicked": source_sketch.mouseClicked, + "doubleClicked": source_sketch.doubleClicked, + "mouseWheel": source_sketch.mouseWheel, + "touchStarted": source_sketch.touchStarted, + "touchMoved": source_sketch.touchMoved, + "touchEnded": source_sketch.touchEnded, + "windowResized": source_sketch.windowResized, +} + +start_p5(source_sketch.setup, source_sketch.draw, event_functions) \ No newline at end of file diff --git a/docs/examples/sketch_004/sketch_004.py b/docs/examples/sketch_004/sketch_004.py index 159440fc..d34ade2c 100644 --- a/docs/examples/sketch_004/sketch_004.py +++ b/docs/examples/sketch_004/sketch_004.py @@ -162,7 +162,3 @@ def cohesion (self, boids) : return self.seek(sum); # Steer towards the location else: return createVector(0, 0); - - -# This is required by pyp5js to work -start_p5(setup, draw, {}) diff --git a/docs/examples/sketch_004/target/org.transcrypt.__runtime__.js b/docs/examples/sketch_004/target/org.transcrypt.__runtime__.js index e976da7e..de1ceb76 100644 --- a/docs/examples/sketch_004/target/org.transcrypt.__runtime__.js +++ b/docs/examples/sketch_004/target/org.transcrypt.__runtime__.js @@ -1,4 +1,4 @@ -// Transcrypt'ed from Python, 2019-05-09 00:36:34 +// Transcrypt'ed from Python, 2019-06-01 16:39:05 var __name__ = 'org.transcrypt.__runtime__'; export var __envir__ = {}; __envir__.interpreter_name = 'python'; diff --git a/docs/examples/sketch_004/target/pytop5js.js b/docs/examples/sketch_004/target/pytop5js.js index 0b9df45c..05ce1ac2 100644 --- a/docs/examples/sketch_004/target/pytop5js.js +++ b/docs/examples/sketch_004/target/pytop5js.js @@ -1,7 +1,157 @@ -// Transcrypt'ed from Python, 2019-05-09 00:36:34 +// Transcrypt'ed from Python, 2019-06-01 16:39:06 import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, input, isinstance, issubclass, len, list, object, ord, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; var __name__ = 'pytop5js'; export var _P5_INSTANCE = null; +export var _CTX_MIDDLE = null; +export var _DEFAULT_FILL = null; +export var _DEFAULT_LEADMULT = null; +export var _DEFAULT_STROKE = null; +export var _DEFAULT_TEXT_FILL = null; +export var ADD = null; +export var ALT = null; +export var ARROW = null; +export var AUTO = null; +export var AXES = null; +export var BACKSPACE = null; +export var BASELINE = null; +export var BEVEL = null; +export var BEZIER = null; +export var BLEND = null; +export var BLUR = null; +export var BOLD = null; +export var BOLDITALIC = null; +export var BOTTOM = null; +export var BURN = null; +export var CENTER = null; +export var CHORD = null; +export var CLAMP = null; +export var CLOSE = null; +export var CONTROL = null; +export var CORNER = null; +export var CORNERS = null; +export var CROSS = null; +export var CURVE = null; +export var DARKEST = null; +export var DEG_TO_RAD = null; +export var DEGREES = null; +export var DELETE = null; +export var DIFFERENCE = null; +export var DILATE = null; +export var DODGE = null; +export var DOWN_ARROW = null; +export var ENTER = null; +export var ERODE = null; +export var ESCAPE = null; +export var EXCLUSION = null; +export var FILL = null; +export var GRAY = null; +export var GRID = null; +export var HALF_PI = null; +export var HAND = null; +export var HARD_LIGHT = null; +export var HSB = null; +export var HSL = null; +export var IMAGE = null; +export var IMMEDIATE = null; +export var INVERT = null; +export var ITALIC = null; +export var LANDSCAPE = null; +export var LEFT = null; +export var LEFT_ARROW = null; +export var LIGHTEST = null; +export var LINE_LOOP = null; +export var LINE_STRIP = null; +export var LINEAR = null; +export var LINES = null; +export var MIRROR = null; +export var MITER = null; +export var MOVE = null; +export var MULTIPLY = null; +export var NEAREST = null; +export var NORMAL = null; +export var OPAQUE = null; +export var OPEN = null; +export var OPTION = null; +export var OVERLAY = null; +export var PI = null; +export var PIE = null; +export var POINTS = null; +export var PORTRAIT = null; +export var POSTERIZE = null; +export var PROJECT = null; +export var QUAD_STRIP = null; +export var QUADRATIC = null; +export var QUADS = null; +export var QUARTER_PI = null; +export var RAD_TO_DEG = null; +export var RADIANS = null; +export var RADIUS = null; +export var REPEAT = null; +export var REPLACE = null; +export var RETURN = null; +export var RGB = null; +export var RIGHT = null; +export var RIGHT_ARROW = null; +export var ROUND = null; +export var SCREEN = null; +export var SHIFT = null; +export var SOFT_LIGHT = null; +export var SQUARE = null; +export var STROKE = null; +export var SUBTRACT = null; +export var TAB = null; +export var TAU = null; +export var TEXT = null; +export var TEXTURE = null; +export var THRESHOLD = null; +export var TOP = null; +export var TRIANGLE_FAN = null; +export var TRIANGLE_STRIP = null; +export var TRIANGLES = null; +export var TWO_PI = null; +export var UP_ARROW = null; +export var WAIT = null; +export var WEBGL = null; +export var P2D = null; +var PI = null; +export var frameCount = null; +export var focused = null; +export var displayWidth = null; +export var displayHeight = null; +export var windowWidth = null; +export var windowHeight = null; +export var width = null; +export var height = null; +export var disableFriendlyErrors = null; +export var deviceOrientation = null; +export var accelerationX = null; +export var accelerationY = null; +export var accelerationZ = null; +export var pAccelerationX = null; +export var pAccelerationY = null; +export var pAccelerationZ = null; +export var rotationX = null; +export var rotationY = null; +export var rotationZ = null; +export var pRotationX = null; +export var pRotationY = null; +export var pRotationZ = null; +export var turnAxis = null; +export var keyIsPressed = null; +export var key = null; +export var keyCode = null; +export var mouseX = null; +export var mouseY = null; +export var pmouseX = null; +export var pmouseY = null; +export var winMouseX = null; +export var winMouseY = null; +export var pwinMouseX = null; +export var pwinMouseY = null; +export var mouseButton = null; +export var mouseIsPressed = null; +export var touches = null; +export var pixels = null; export var alpha = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.alpha (...args); @@ -310,10 +460,6 @@ export var redraw = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.redraw (...args); }; -export var createCanvas = function () { - var args = tuple ([].slice.apply (arguments).slice (0)); - return _P5_INSTANCE.createCanvas (...args); -}; export var resizeCanvas = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.resizeCanvas (...args); @@ -914,86 +1060,130 @@ export var setCamera = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.setCamera (...args); }; +export var createCanvas = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + var result = _P5_INSTANCE.createCanvas (...args); + width = _P5_INSTANCE.width; + height = _P5_INSTANCE.height; +}; export var py_pop = function () { var args = tuple ([].slice.apply (arguments).slice (0)); var p5_pop = _P5_INSTANCE.pop (...args); return p5_pop; }; -export var HALF_PI = null; -export var PI = null; -export var QUARTER_PI = null; -export var TAU = null; -export var TWO_PI = null; -export var DEGREES = null; -export var RADIANS = null; -export var CLOSE = null; -export var RGB = null; -export var HSB = null; -export var CMYK = null; -export var TOP = null; -export var BOTTOM = null; -export var CENTER = null; -export var LEFT = null; -export var RIGHT = null; -export var SHIFT = null; -export var WEBGL = null; -export var frameCount = null; -export var focused = null; -export var displayWidth = null; -export var displayHeight = null; -export var windowWidth = null; -export var windowHeight = null; -export var width = null; -export var height = null; -export var disableFriendlyErrors = null; -export var deviceOrientation = null; -export var accelerationX = null; -export var accelerationY = null; -export var accelerationZ = null; -export var pAccelerationX = null; -export var pAccelerationY = null; -export var pAccelerationZ = null; -export var rotationX = null; -export var rotationY = null; -export var rotationZ = null; -export var pRotationX = null; -export var pRotationY = null; -export var pRotationZ = null; -export var turnAxis = null; -export var keyIsPressed = null; -export var key = null; -export var keyCode = null; -export var mouseX = null; -export var mouseY = null; -export var pmouseX = null; -export var pmouseY = null; -export var winMouseX = null; -export var winMouseY = null; -export var pwinMouseX = null; -export var pwinMouseY = null; -export var mouseButton = null; -export var mouseIsPressed = null; -export var touches = null; -export var pixels = null; export var pre_draw = function (p5_instance, draw_func) { + _CTX_MIDDLE = p5_instance._CTX_MIDDLE; + _DEFAULT_FILL = p5_instance._DEFAULT_FILL; + _DEFAULT_LEADMULT = p5_instance._DEFAULT_LEADMULT; + _DEFAULT_STROKE = p5_instance._DEFAULT_STROKE; + _DEFAULT_TEXT_FILL = p5_instance._DEFAULT_TEXT_FILL; + ADD = p5_instance.ADD; + ALT = p5_instance.ALT; + ARROW = p5_instance.ARROW; + AUTO = p5_instance.AUTO; + AXES = p5_instance.AXES; + BACKSPACE = p5_instance.BACKSPACE; + BASELINE = p5_instance.BASELINE; + BEVEL = p5_instance.BEVEL; + BEZIER = p5_instance.BEZIER; + BLEND = p5_instance.BLEND; + BLUR = p5_instance.BLUR; + BOLD = p5_instance.BOLD; + BOLDITALIC = p5_instance.BOLDITALIC; + BOTTOM = p5_instance.BOTTOM; + BURN = p5_instance.BURN; + CENTER = p5_instance.CENTER; + CHORD = p5_instance.CHORD; + CLAMP = p5_instance.CLAMP; + CLOSE = p5_instance.CLOSE; + CONTROL = p5_instance.CONTROL; + CORNER = p5_instance.CORNER; + CORNERS = p5_instance.CORNERS; + CROSS = p5_instance.CROSS; + CURVE = p5_instance.CURVE; + DARKEST = p5_instance.DARKEST; + DEG_TO_RAD = p5_instance.DEG_TO_RAD; + DEGREES = p5_instance.DEGREES; + DELETE = p5_instance.DELETE; + DIFFERENCE = p5_instance.DIFFERENCE; + DILATE = p5_instance.DILATE; + DODGE = p5_instance.DODGE; + DOWN_ARROW = p5_instance.DOWN_ARROW; + ENTER = p5_instance.ENTER; + ERODE = p5_instance.ERODE; + ESCAPE = p5_instance.ESCAPE; + EXCLUSION = p5_instance.EXCLUSION; + FILL = p5_instance.FILL; + GRAY = p5_instance.GRAY; + GRID = p5_instance.GRID; HALF_PI = p5_instance.HALF_PI; + HAND = p5_instance.HAND; + HARD_LIGHT = p5_instance.HARD_LIGHT; + HSB = p5_instance.HSB; + HSL = p5_instance.HSL; + IMAGE = p5_instance.IMAGE; + IMMEDIATE = p5_instance.IMMEDIATE; + INVERT = p5_instance.INVERT; + ITALIC = p5_instance.ITALIC; + LANDSCAPE = p5_instance.LANDSCAPE; + LEFT = p5_instance.LEFT; + LEFT_ARROW = p5_instance.LEFT_ARROW; + LIGHTEST = p5_instance.LIGHTEST; + LINE_LOOP = p5_instance.LINE_LOOP; + LINE_STRIP = p5_instance.LINE_STRIP; + LINEAR = p5_instance.LINEAR; + LINES = p5_instance.LINES; + MIRROR = p5_instance.MIRROR; + MITER = p5_instance.MITER; + MOVE = p5_instance.MOVE; + MULTIPLY = p5_instance.MULTIPLY; + NEAREST = p5_instance.NEAREST; + NORMAL = p5_instance.NORMAL; + OPAQUE = p5_instance.OPAQUE; + OPEN = p5_instance.OPEN; + OPTION = p5_instance.OPTION; + OVERLAY = p5_instance.OVERLAY; PI = p5_instance.PI; + PIE = p5_instance.PIE; + POINTS = p5_instance.POINTS; + PORTRAIT = p5_instance.PORTRAIT; + POSTERIZE = p5_instance.POSTERIZE; + PROJECT = p5_instance.PROJECT; + QUAD_STRIP = p5_instance.QUAD_STRIP; + QUADRATIC = p5_instance.QUADRATIC; + QUADS = p5_instance.QUADS; QUARTER_PI = p5_instance.QUARTER_PI; - TAU = p5_instance.TAU; - TWO_PI = p5_instance.TWO_PI; - DEGREES = p5_instance.DEGREES; + RAD_TO_DEG = p5_instance.RAD_TO_DEG; RADIANS = p5_instance.RADIANS; - CLOSE = p5_instance.CLOSE; + RADIUS = p5_instance.RADIUS; + REPEAT = p5_instance.REPEAT; + REPLACE = p5_instance.REPLACE; + RETURN = p5_instance.RETURN; RGB = p5_instance.RGB; - HSB = p5_instance.HSB; - CMYK = p5_instance.CMYK; - TOP = p5_instance.TOP; - BOTTOM = p5_instance.BOTTOM; - CENTER = p5_instance.CENTER; - LEFT = p5_instance.LEFT; RIGHT = p5_instance.RIGHT; + RIGHT_ARROW = p5_instance.RIGHT_ARROW; + ROUND = p5_instance.ROUND; + SCREEN = p5_instance.SCREEN; SHIFT = p5_instance.SHIFT; + SOFT_LIGHT = p5_instance.SOFT_LIGHT; + SQUARE = p5_instance.SQUARE; + STROKE = p5_instance.STROKE; + SUBTRACT = p5_instance.SUBTRACT; + TAB = p5_instance.TAB; + TAU = p5_instance.TAU; + TEXT = p5_instance.TEXT; + TEXTURE = p5_instance.TEXTURE; + THRESHOLD = p5_instance.THRESHOLD; + TOP = p5_instance.TOP; + TRIANGLE_FAN = p5_instance.TRIANGLE_FAN; + TRIANGLE_STRIP = p5_instance.TRIANGLE_STRIP; + TRIANGLES = p5_instance.TRIANGLES; + TWO_PI = p5_instance.TWO_PI; + UP_ARROW = p5_instance.UP_ARROW; + WAIT = p5_instance.WAIT; WEBGL = p5_instance.WEBGL; + P2D = p5_instance.P2D; + PI = p5_instance.PI; frameCount = p5_instance.frameCount; focused = p5_instance.focused; displayWidth = p5_instance.displayWidth; @@ -1054,7 +1244,7 @@ export var start_p5 = function (setup_func, draw_func, event_functions) { for (var f_name of (function () { var __accu0__ = []; for (var f of event_function_names) { - if (__in__ (f, event_functions)) { + if (event_functions.py_get (f, null)) { __accu0__.append (f); } } diff --git a/docs/examples/sketch_004/target/pytop5js.py b/docs/examples/sketch_004/target/pytop5js.py index 59388176..6462430c 100644 --- a/docs/examples/sketch_004/target/pytop5js.py +++ b/docs/examples/sketch_004/target/pytop5js.py @@ -1,4 +1,155 @@ _P5_INSTANCE = None +_CTX_MIDDLE = None +_DEFAULT_FILL = None +_DEFAULT_LEADMULT = None +_DEFAULT_STROKE = None +_DEFAULT_TEXT_FILL = None +ADD = None +ALT = None +ARROW = None +AUTO = None +AXES = None +BACKSPACE = None +BASELINE = None +BEVEL = None +BEZIER = None +BLEND = None +BLUR = None +BOLD = None +BOLDITALIC = None +BOTTOM = None +BURN = None +CENTER = None +CHORD = None +CLAMP = None +CLOSE = None +CONTROL = None +CORNER = None +CORNERS = None +CROSS = None +CURVE = None +DARKEST = None +DEG_TO_RAD = None +DEGREES = None +DELETE = None +DIFFERENCE = None +DILATE = None +DODGE = None +DOWN_ARROW = None +ENTER = None +ERODE = None +ESCAPE = None +EXCLUSION = None +FILL = None +GRAY = None +GRID = None +HALF_PI = None +HAND = None +HARD_LIGHT = None +HSB = None +HSL = None +IMAGE = None +IMMEDIATE = None +INVERT = None +ITALIC = None +LANDSCAPE = None +LEFT = None +LEFT_ARROW = None +LIGHTEST = None +LINE_LOOP = None +LINE_STRIP = None +LINEAR = None +LINES = None +MIRROR = None +MITER = None +MOVE = None +MULTIPLY = None +NEAREST = None +NORMAL = None +OPAQUE = None +OPEN = None +OPTION = None +OVERLAY = None +PI = None +PIE = None +POINTS = None +PORTRAIT = None +POSTERIZE = None +PROJECT = None +QUAD_STRIP = None +QUADRATIC = None +QUADS = None +QUARTER_PI = None +RAD_TO_DEG = None +RADIANS = None +RADIUS = None +REPEAT = None +REPLACE = None +RETURN = None +RGB = None +RIGHT = None +RIGHT_ARROW = None +ROUND = None +SCREEN = None +SHIFT = None +SOFT_LIGHT = None +SQUARE = None +STROKE = None +SUBTRACT = None +TAB = None +TAU = None +TEXT = None +TEXTURE = None +THRESHOLD = None +TOP = None +TRIANGLE_FAN = None +TRIANGLE_STRIP = None +TRIANGLES = None +TWO_PI = None +UP_ARROW = None +WAIT = None +WEBGL = None +P2D = None +PI = None +frameCount = None +focused = None +displayWidth = None +displayHeight = None +windowWidth = None +windowHeight = None +width = None +height = None +disableFriendlyErrors = None +deviceOrientation = None +accelerationX = None +accelerationY = None +accelerationZ = None +pAccelerationX = None +pAccelerationY = None +pAccelerationZ = None +rotationX = None +rotationY = None +rotationZ = None +pRotationX = None +pRotationY = None +pRotationZ = None +turnAxis = None +keyIsPressed = None +key = None +keyCode = None +mouseX = None +mouseY = None +pmouseX = None +pmouseY = None +winMouseX = None +winMouseY = None +pwinMouseX = None +pwinMouseY = None +mouseButton = None +mouseIsPressed = None +touches = None +pixels = None + def alpha(*args): @@ -232,9 +383,6 @@ def push(*args): def redraw(*args): return _P5_INSTANCE.redraw(*args) -def createCanvas(*args): - return _P5_INSTANCE.createCanvas(*args) - def resizeCanvas(*args): return _P5_INSTANCE.resizeCanvas(*args) @@ -686,6 +834,13 @@ def setCamera(*args): return _P5_INSTANCE.setCamera(*args) +def createCanvas(*args): + result = _P5_INSTANCE.createCanvas(*args) + + global width, height + width = _P5_INSTANCE.width + height = _P5_INSTANCE.height + def pop(*args): __pragma__('noalias', 'pop') @@ -693,87 +848,124 @@ def pop(*args): __pragma__('alias', 'pop', 'py_pop') return p5_pop -HALF_PI = None -PI = None -QUARTER_PI = None -TAU = None -TWO_PI = None -DEGREES = None -RADIANS = None -CLOSE = None -RGB = None -HSB = None -CMYK = None -TOP = None -BOTTOM = None -CENTER = None -LEFT = None -RIGHT = None -SHIFT = None -WEBGL = None -frameCount = None -focused = None -displayWidth = None -displayHeight = None -windowWidth = None -windowHeight = None -width = None -height = None -disableFriendlyErrors = None -deviceOrientation = None -accelerationX = None -accelerationY = None -accelerationZ = None -pAccelerationX = None -pAccelerationY = None -pAccelerationZ = None -rotationX = None -rotationY = None -rotationZ = None -pRotationX = None -pRotationY = None -pRotationZ = None -turnAxis = None -keyIsPressed = None -key = None -keyCode = None -mouseX = None -mouseY = None -pmouseX = None -pmouseY = None -winMouseX = None -winMouseY = None -pwinMouseX = None -pwinMouseY = None -mouseButton = None -mouseIsPressed = None -touches = None -pixels = None - def pre_draw(p5_instance, draw_func): """ We need to run this before the actual draw to insert and update p5 env variables """ - global HALF_PI, PI, QUARTER_PI, TAU, TWO_PI, DEGREES, RADIANS, CLOSE, RGB, HSB, CMYK, TOP, BOTTOM, CENTER, LEFT, RIGHT, SHIFT, WEBGL, frameCount, focused, displayWidth, displayHeight, windowWidth, windowHeight, width, height, disableFriendlyErrors, deviceOrientation, accelerationX, accelerationY, accelerationZ, pAccelerationX, pAccelerationY, pAccelerationZ, rotationX, rotationY, rotationZ, pRotationX, pRotationY, pRotationZ, turnAxis, keyIsPressed, key, keyCode, mouseX, mouseY, pmouseX, pmouseY, winMouseX, winMouseY, pwinMouseX, pwinMouseY, mouseButton, mouseIsPressed, touches, pixels - + global _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEG_TO_RAD, DEGREES, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINE_LOOP, LINE_STRIP, LINEAR, LINES, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUAD_STRIP, QUADRATIC, QUADS, QUARTER_PI, RAD_TO_DEG, RADIANS, RADIUS, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLE_FAN, TRIANGLE_STRIP, TRIANGLES, TWO_PI, UP_ARROW, WAIT, WEBGL, P2D, PI, frameCount, focused, displayWidth, displayHeight, windowWidth, windowHeight, width, height, disableFriendlyErrors, deviceOrientation, accelerationX, accelerationY, accelerationZ, pAccelerationX, pAccelerationY, pAccelerationZ, rotationX, rotationY, rotationZ, pRotationX, pRotationY, pRotationZ, turnAxis, keyIsPressed, key, keyCode, mouseX, mouseY, pmouseX, pmouseY, winMouseX, winMouseY, pwinMouseX, pwinMouseY, mouseButton, mouseIsPressed, touches, pixels + + _CTX_MIDDLE = p5_instance._CTX_MIDDLE + _DEFAULT_FILL = p5_instance._DEFAULT_FILL + _DEFAULT_LEADMULT = p5_instance._DEFAULT_LEADMULT + _DEFAULT_STROKE = p5_instance._DEFAULT_STROKE + _DEFAULT_TEXT_FILL = p5_instance._DEFAULT_TEXT_FILL + ADD = p5_instance.ADD + ALT = p5_instance.ALT + ARROW = p5_instance.ARROW + AUTO = p5_instance.AUTO + AXES = p5_instance.AXES + BACKSPACE = p5_instance.BACKSPACE + BASELINE = p5_instance.BASELINE + BEVEL = p5_instance.BEVEL + BEZIER = p5_instance.BEZIER + BLEND = p5_instance.BLEND + BLUR = p5_instance.BLUR + BOLD = p5_instance.BOLD + BOLDITALIC = p5_instance.BOLDITALIC + BOTTOM = p5_instance.BOTTOM + BURN = p5_instance.BURN + CENTER = p5_instance.CENTER + CHORD = p5_instance.CHORD + CLAMP = p5_instance.CLAMP + CLOSE = p5_instance.CLOSE + CONTROL = p5_instance.CONTROL + CORNER = p5_instance.CORNER + CORNERS = p5_instance.CORNERS + CROSS = p5_instance.CROSS + CURVE = p5_instance.CURVE + DARKEST = p5_instance.DARKEST + DEG_TO_RAD = p5_instance.DEG_TO_RAD + DEGREES = p5_instance.DEGREES + DELETE = p5_instance.DELETE + DIFFERENCE = p5_instance.DIFFERENCE + DILATE = p5_instance.DILATE + DODGE = p5_instance.DODGE + DOWN_ARROW = p5_instance.DOWN_ARROW + ENTER = p5_instance.ENTER + ERODE = p5_instance.ERODE + ESCAPE = p5_instance.ESCAPE + EXCLUSION = p5_instance.EXCLUSION + FILL = p5_instance.FILL + GRAY = p5_instance.GRAY + GRID = p5_instance.GRID HALF_PI = p5_instance.HALF_PI + HAND = p5_instance.HAND + HARD_LIGHT = p5_instance.HARD_LIGHT + HSB = p5_instance.HSB + HSL = p5_instance.HSL + IMAGE = p5_instance.IMAGE + IMMEDIATE = p5_instance.IMMEDIATE + INVERT = p5_instance.INVERT + ITALIC = p5_instance.ITALIC + LANDSCAPE = p5_instance.LANDSCAPE + LEFT = p5_instance.LEFT + LEFT_ARROW = p5_instance.LEFT_ARROW + LIGHTEST = p5_instance.LIGHTEST + LINE_LOOP = p5_instance.LINE_LOOP + LINE_STRIP = p5_instance.LINE_STRIP + LINEAR = p5_instance.LINEAR + LINES = p5_instance.LINES + MIRROR = p5_instance.MIRROR + MITER = p5_instance.MITER + MOVE = p5_instance.MOVE + MULTIPLY = p5_instance.MULTIPLY + NEAREST = p5_instance.NEAREST + NORMAL = p5_instance.NORMAL + OPAQUE = p5_instance.OPAQUE + OPEN = p5_instance.OPEN + OPTION = p5_instance.OPTION + OVERLAY = p5_instance.OVERLAY PI = p5_instance.PI + PIE = p5_instance.PIE + POINTS = p5_instance.POINTS + PORTRAIT = p5_instance.PORTRAIT + POSTERIZE = p5_instance.POSTERIZE + PROJECT = p5_instance.PROJECT + QUAD_STRIP = p5_instance.QUAD_STRIP + QUADRATIC = p5_instance.QUADRATIC + QUADS = p5_instance.QUADS QUARTER_PI = p5_instance.QUARTER_PI - TAU = p5_instance.TAU - TWO_PI = p5_instance.TWO_PI - DEGREES = p5_instance.DEGREES + RAD_TO_DEG = p5_instance.RAD_TO_DEG RADIANS = p5_instance.RADIANS - CLOSE = p5_instance.CLOSE + RADIUS = p5_instance.RADIUS + REPEAT = p5_instance.REPEAT + REPLACE = p5_instance.REPLACE + RETURN = p5_instance.RETURN RGB = p5_instance.RGB - HSB = p5_instance.HSB - CMYK = p5_instance.CMYK - TOP = p5_instance.TOP - BOTTOM = p5_instance.BOTTOM - CENTER = p5_instance.CENTER - LEFT = p5_instance.LEFT RIGHT = p5_instance.RIGHT + RIGHT_ARROW = p5_instance.RIGHT_ARROW + ROUND = p5_instance.ROUND + SCREEN = p5_instance.SCREEN SHIFT = p5_instance.SHIFT + SOFT_LIGHT = p5_instance.SOFT_LIGHT + SQUARE = p5_instance.SQUARE + STROKE = p5_instance.STROKE + SUBTRACT = p5_instance.SUBTRACT + TAB = p5_instance.TAB + TAU = p5_instance.TAU + TEXT = p5_instance.TEXT + TEXTURE = p5_instance.TEXTURE + THRESHOLD = p5_instance.THRESHOLD + TOP = p5_instance.TOP + TRIANGLE_FAN = p5_instance.TRIANGLE_FAN + TRIANGLE_STRIP = p5_instance.TRIANGLE_STRIP + TRIANGLES = p5_instance.TRIANGLES + TWO_PI = p5_instance.TWO_PI + UP_ARROW = p5_instance.UP_ARROW + WAIT = p5_instance.WAIT WEBGL = p5_instance.WEBGL + P2D = p5_instance.P2D + PI = p5_instance.PI frameCount = p5_instance.frameCount focused = p5_instance.focused displayWidth = p5_instance.displayWidth @@ -853,7 +1045,7 @@ def sketch_setup(p5_sketch): # inject event functions into p5 event_function_names = ["deviceMoved", "deviceTurned", "deviceShaken", "keyPressed", "keyReleased", "keyTyped", "mouseMoved", "mouseDragged", "mousePressed", "mouseReleased", "mouseClicked", "doubleClicked", "mouseWheel", "touchStarted", "touchMoved", "touchEnded", "windowResized", ] - for f_name in [f for f in event_function_names if f in event_functions]: + for f_name in [f for f in event_function_names if event_functions.get(f, None)]: func = event_functions[f_name] event_func = global_p5_injection(instance)(func) setattr(instance, f_name, event_func) \ No newline at end of file diff --git a/docs/examples/sketch_004/target/sketch_004.js b/docs/examples/sketch_004/target/sketch_004.js index 427615c1..641aed0f 100644 --- a/docs/examples/sketch_004/target/sketch_004.js +++ b/docs/examples/sketch_004/target/sketch_004.js @@ -1,7 +1,7 @@ -// Transcrypt'ed from Python, 2019-05-09 00:36:34 +// Transcrypt'ed from Python, 2019-06-01 16:39:06 import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, input, isinstance, issubclass, len, list, object, ord, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; -import {BOTTOM, CENTER, CLOSE, CMYK, DEGREES, HALF_PI, HSB, LEFT, PI, QUARTER_PI, RADIANS, RGB, RIGHT, SHIFT, TAU, TOP, TWO_PI, WEBGL, _P5_INSTANCE, abs, accelerationX, accelerationY, accelerationZ, acos, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, char, circle, color, colorMode, concat, cone, constrain, copy, cos, createCamera, createCanvas, createGraphics, createImage, createNumberDict, createShader, createStringDict, createVector, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, deviceOrientation, directionalLight, disableFriendlyErrors, displayDensity, displayHeight, displayWidth, dist, ellipse, ellipseMode, ellipsoid, endContour, endShape, exp, fill, filter, float, floor, focused, frameCount, frameRate, fullscreen, getURL, getURLParams, getURLPath, global_p5_injection, green, height, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, int, join, key, keyCode, keyIsDown, keyIsPressed, lerp, lerpColor, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, mouseButton, mouseIsPressed, mouseX, mouseY, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noFill, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normalMaterial, orbitControl, ortho, pAccelerationX, pAccelerationY, pAccelerationZ, pRotationX, pRotationY, pRotationZ, perspective, pixelDensity, pixels, plane, pmouseX, pmouseY, point, pointLight, pow, pre_draw, preload, print, push, pwinMouseX, pwinMouseY, py_clear, py_get, py_pop, py_sort, py_split, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, remove, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, rotationX, rotationY, rotationZ, round, saturation, save, saveCanvas, saveFrames, saveJSON, saveStrings, saveTable, scale, second, set, setAttributes, setCamera, setMoveThreshold, setShakeThreshold, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, specularMaterial, sphere, splice, splitTokens, sq, sqrt, square, start_p5, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, touches, translate, triangle, trim, turnAxis, unchar, unhex, updatePixels, vertex, width, winMouseX, winMouseY, windowHeight, windowWidth, year} from './pytop5js.js'; -var __name__ = '__main__'; +import {ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEGREES, DEG_TO_RAD, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINEAR, LINES, LINE_LOOP, LINE_STRIP, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, P2D, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUADRATIC, QUADS, QUAD_STRIP, QUARTER_PI, RADIANS, RADIUS, RAD_TO_DEG, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, TWO_PI, UP_ARROW, WAIT, WEBGL, _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, _P5_INSTANCE, abs, accelerationX, accelerationY, accelerationZ, acos, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, char, circle, color, colorMode, concat, cone, constrain, copy, cos, createCamera, createCanvas, createGraphics, createImage, createNumberDict, createShader, createStringDict, createVector, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, deviceOrientation, directionalLight, disableFriendlyErrors, displayDensity, displayHeight, displayWidth, dist, ellipse, ellipseMode, ellipsoid, endContour, endShape, exp, fill, filter, float, floor, focused, frameCount, frameRate, fullscreen, getURL, getURLParams, getURLPath, global_p5_injection, green, height, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, int, join, key, keyCode, keyIsDown, keyIsPressed, lerp, lerpColor, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, mouseButton, mouseIsPressed, mouseX, mouseY, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noFill, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normalMaterial, orbitControl, ortho, pAccelerationX, pAccelerationY, pAccelerationZ, pRotationX, pRotationY, pRotationZ, perspective, pixelDensity, pixels, plane, pmouseX, pmouseY, point, pointLight, pow, pre_draw, preload, print, push, pwinMouseX, pwinMouseY, py_clear, py_get, py_pop, py_sort, py_split, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, remove, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, rotationX, rotationY, rotationZ, round, saturation, save, saveCanvas, saveFrames, saveJSON, saveStrings, saveTable, scale, second, set, setAttributes, setCamera, setMoveThreshold, setShakeThreshold, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, specularMaterial, sphere, splice, splitTokens, sq, sqrt, square, start_p5, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, touches, translate, triangle, trim, turnAxis, unchar, unhex, updatePixels, vertex, width, winMouseX, winMouseY, windowHeight, windowWidth, year} from './pytop5js.js'; +var __name__ = 'sketch_004'; export var boids = list ([]); export var setup = function () { createCanvas (720, 400); @@ -146,6 +146,5 @@ export var Boid = __class__ ('Boid', [object], { } });} }); -start_p5 (setup, draw, dict ({})); -//# sourceMappingURL=sketch_004.map +//# sourceMappingURL=sketch_004.map \ No newline at end of file diff --git a/docs/examples/sketch_004/target/sketch_004.py b/docs/examples/sketch_004/target/sketch_004.py index 159440fc..d34ade2c 100644 --- a/docs/examples/sketch_004/target/sketch_004.py +++ b/docs/examples/sketch_004/target/sketch_004.py @@ -162,7 +162,3 @@ def cohesion (self, boids) : return self.seek(sum); # Steer towards the location else: return createVector(0, 0); - - -# This is required by pyp5js to work -start_p5(setup, draw, {}) diff --git a/docs/examples/sketch_004/target/target_sketch.js b/docs/examples/sketch_004/target/target_sketch.js new file mode 100644 index 00000000..86797bc7 --- /dev/null +++ b/docs/examples/sketch_004/target/target_sketch.js @@ -0,0 +1,9 @@ +// Transcrypt'ed from Python, 2019-06-01 16:39:06 +import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, input, isinstance, issubclass, len, list, object, ord, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; +import {ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEGREES, DEG_TO_RAD, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINEAR, LINES, LINE_LOOP, LINE_STRIP, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, P2D, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUADRATIC, QUADS, QUAD_STRIP, QUARTER_PI, RADIANS, RADIUS, RAD_TO_DEG, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, TWO_PI, UP_ARROW, WAIT, WEBGL, _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, _P5_INSTANCE, abs, accelerationX, accelerationY, accelerationZ, acos, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, char, circle, color, colorMode, concat, cone, constrain, copy, cos, createCamera, createCanvas, createGraphics, createImage, createNumberDict, createShader, createStringDict, createVector, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, deviceOrientation, directionalLight, disableFriendlyErrors, displayDensity, displayHeight, displayWidth, dist, draw, ellipse, ellipseMode, ellipsoid, endContour, endShape, exp, fill, filter, float, floor, focused, frameCount, frameRate, fullscreen, getURL, getURLParams, getURLPath, global_p5_injection, green, height, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, int, join, key, keyCode, keyIsDown, keyIsPressed, lerp, lerpColor, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, mouseButton, mouseIsPressed, mouseX, mouseY, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noFill, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normalMaterial, orbitControl, ortho, pAccelerationX, pAccelerationY, pAccelerationZ, pRotationX, pRotationY, pRotationZ, perspective, pixelDensity, pixels, plane, pmouseX, pmouseY, point, pointLight, pow, pre_draw, preload, print, push, pwinMouseX, pwinMouseY, py_clear, py_get, py_pop, py_sort, py_split, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, remove, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, rotationX, rotationY, rotationZ, round, saturation, save, saveCanvas, saveFrames, saveJSON, saveStrings, saveTable, scale, second, set, setAttributes, setCamera, setMoveThreshold, setShakeThreshold, setup, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, specularMaterial, sphere, splice, splitTokens, sq, sqrt, square, start_p5, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, touches, translate, triangle, trim, turnAxis, unchar, unhex, updatePixels, vertex, width, winMouseX, winMouseY, windowHeight, windowWidth, year} from './pytop5js.js'; +import * as source_sketch from './sketch_004.js'; +var __name__ = '__main__'; +export var event_functions = dict ({'deviceMoved': source_sketch.deviceMoved, 'deviceTurned': source_sketch.deviceTurned, 'deviceShaken': source_sketch.deviceShaken, 'keyPressed': source_sketch.keyPressed, 'keyReleased': source_sketch.keyReleased, 'keyTyped': source_sketch.keyTyped, 'mouseMoved': source_sketch.mouseMoved, 'mouseDragged': source_sketch.mouseDragged, 'mousePressed': source_sketch.mousePressed, 'mouseReleased': source_sketch.mouseReleased, 'mouseClicked': source_sketch.mouseClicked, 'doubleClicked': source_sketch.doubleClicked, 'mouseWheel': source_sketch.mouseWheel, 'touchStarted': source_sketch.touchStarted, 'touchMoved': source_sketch.touchMoved, 'touchEnded': source_sketch.touchEnded, 'windowResized': source_sketch.windowResized}); +start_p5 (source_sketch.setup, source_sketch.draw, event_functions); + +//# sourceMappingURL=target_sketch.map \ No newline at end of file diff --git a/docs/examples/sketch_004/target/sketch_004.options b/docs/examples/sketch_004/target/target_sketch.options similarity index 73% rename from docs/examples/sketch_004/target/sketch_004.options rename to docs/examples/sketch_004/target/target_sketch.options index 22f492feddd950af648931682cd6299422befab9..812253dbfd8a45f4aa0f82b20dcfd663c9c0d2fa 100644 GIT binary patch delta 39 qcmcb^a-U^_h>SD?14D6kYDscNyn%sC diff --git a/docs/examples/sketch_004/target/target_sketch.py b/docs/examples/sketch_004/target/target_sketch.py new file mode 100644 index 00000000..87be4dff --- /dev/null +++ b/docs/examples/sketch_004/target/target_sketch.py @@ -0,0 +1,24 @@ +import sketch_004 as source_sketch +from pytop5js import * + +event_functions = { + "deviceMoved": source_sketch.deviceMoved, + "deviceTurned": source_sketch.deviceTurned, + "deviceShaken": source_sketch.deviceShaken, + "keyPressed": source_sketch.keyPressed, + "keyReleased": source_sketch.keyReleased, + "keyTyped": source_sketch.keyTyped, + "mouseMoved": source_sketch.mouseMoved, + "mouseDragged": source_sketch.mouseDragged, + "mousePressed": source_sketch.mousePressed, + "mouseReleased": source_sketch.mouseReleased, + "mouseClicked": source_sketch.mouseClicked, + "doubleClicked": source_sketch.doubleClicked, + "mouseWheel": source_sketch.mouseWheel, + "touchStarted": source_sketch.touchStarted, + "touchMoved": source_sketch.touchMoved, + "touchEnded": source_sketch.touchEnded, + "windowResized": source_sketch.windowResized, +} + +start_p5(source_sketch.setup, source_sketch.draw, event_functions) \ No newline at end of file diff --git a/docs/examples/sketch_005/sketch_005.py b/docs/examples/sketch_005/sketch_005.py index 2059e0aa..7f3b815e 100644 --- a/docs/examples/sketch_005/sketch_005.py +++ b/docs/examples/sketch_005/sketch_005.py @@ -13,7 +13,3 @@ def draw(): background(h,100,100) fill(100-h,100,100) rect(300,300,mouseX+1,mouseX+1) - - -# This is required by pyp5js to work -start_p5(setup, draw, {}) diff --git a/docs/examples/sketch_005/target/org.transcrypt.__runtime__.js b/docs/examples/sketch_005/target/org.transcrypt.__runtime__.js index 353ff397..1efa0277 100644 --- a/docs/examples/sketch_005/target/org.transcrypt.__runtime__.js +++ b/docs/examples/sketch_005/target/org.transcrypt.__runtime__.js @@ -1,4 +1,4 @@ -// Transcrypt'ed from Python, 2019-05-09 00:36:43 +// Transcrypt'ed from Python, 2019-06-01 16:39:07 var __name__ = 'org.transcrypt.__runtime__'; export var __envir__ = {}; __envir__.interpreter_name = 'python'; diff --git a/docs/examples/sketch_005/target/pytop5js.js b/docs/examples/sketch_005/target/pytop5js.js index 03690b4a..06b1fcc3 100644 --- a/docs/examples/sketch_005/target/pytop5js.js +++ b/docs/examples/sketch_005/target/pytop5js.js @@ -1,7 +1,157 @@ -// Transcrypt'ed from Python, 2019-05-09 00:36:43 +// Transcrypt'ed from Python, 2019-06-01 16:39:08 import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, input, isinstance, issubclass, len, list, object, ord, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; var __name__ = 'pytop5js'; export var _P5_INSTANCE = null; +export var _CTX_MIDDLE = null; +export var _DEFAULT_FILL = null; +export var _DEFAULT_LEADMULT = null; +export var _DEFAULT_STROKE = null; +export var _DEFAULT_TEXT_FILL = null; +export var ADD = null; +export var ALT = null; +export var ARROW = null; +export var AUTO = null; +export var AXES = null; +export var BACKSPACE = null; +export var BASELINE = null; +export var BEVEL = null; +export var BEZIER = null; +export var BLEND = null; +export var BLUR = null; +export var BOLD = null; +export var BOLDITALIC = null; +export var BOTTOM = null; +export var BURN = null; +export var CENTER = null; +export var CHORD = null; +export var CLAMP = null; +export var CLOSE = null; +export var CONTROL = null; +export var CORNER = null; +export var CORNERS = null; +export var CROSS = null; +export var CURVE = null; +export var DARKEST = null; +export var DEG_TO_RAD = null; +export var DEGREES = null; +export var DELETE = null; +export var DIFFERENCE = null; +export var DILATE = null; +export var DODGE = null; +export var DOWN_ARROW = null; +export var ENTER = null; +export var ERODE = null; +export var ESCAPE = null; +export var EXCLUSION = null; +export var FILL = null; +export var GRAY = null; +export var GRID = null; +export var HALF_PI = null; +export var HAND = null; +export var HARD_LIGHT = null; +export var HSB = null; +export var HSL = null; +export var IMAGE = null; +export var IMMEDIATE = null; +export var INVERT = null; +export var ITALIC = null; +export var LANDSCAPE = null; +export var LEFT = null; +export var LEFT_ARROW = null; +export var LIGHTEST = null; +export var LINE_LOOP = null; +export var LINE_STRIP = null; +export var LINEAR = null; +export var LINES = null; +export var MIRROR = null; +export var MITER = null; +export var MOVE = null; +export var MULTIPLY = null; +export var NEAREST = null; +export var NORMAL = null; +export var OPAQUE = null; +export var OPEN = null; +export var OPTION = null; +export var OVERLAY = null; +export var PI = null; +export var PIE = null; +export var POINTS = null; +export var PORTRAIT = null; +export var POSTERIZE = null; +export var PROJECT = null; +export var QUAD_STRIP = null; +export var QUADRATIC = null; +export var QUADS = null; +export var QUARTER_PI = null; +export var RAD_TO_DEG = null; +export var RADIANS = null; +export var RADIUS = null; +export var REPEAT = null; +export var REPLACE = null; +export var RETURN = null; +export var RGB = null; +export var RIGHT = null; +export var RIGHT_ARROW = null; +export var ROUND = null; +export var SCREEN = null; +export var SHIFT = null; +export var SOFT_LIGHT = null; +export var SQUARE = null; +export var STROKE = null; +export var SUBTRACT = null; +export var TAB = null; +export var TAU = null; +export var TEXT = null; +export var TEXTURE = null; +export var THRESHOLD = null; +export var TOP = null; +export var TRIANGLE_FAN = null; +export var TRIANGLE_STRIP = null; +export var TRIANGLES = null; +export var TWO_PI = null; +export var UP_ARROW = null; +export var WAIT = null; +export var WEBGL = null; +export var P2D = null; +var PI = null; +export var frameCount = null; +export var focused = null; +export var displayWidth = null; +export var displayHeight = null; +export var windowWidth = null; +export var windowHeight = null; +export var width = null; +export var height = null; +export var disableFriendlyErrors = null; +export var deviceOrientation = null; +export var accelerationX = null; +export var accelerationY = null; +export var accelerationZ = null; +export var pAccelerationX = null; +export var pAccelerationY = null; +export var pAccelerationZ = null; +export var rotationX = null; +export var rotationY = null; +export var rotationZ = null; +export var pRotationX = null; +export var pRotationY = null; +export var pRotationZ = null; +export var turnAxis = null; +export var keyIsPressed = null; +export var key = null; +export var keyCode = null; +export var mouseX = null; +export var mouseY = null; +export var pmouseX = null; +export var pmouseY = null; +export var winMouseX = null; +export var winMouseY = null; +export var pwinMouseX = null; +export var pwinMouseY = null; +export var mouseButton = null; +export var mouseIsPressed = null; +export var touches = null; +export var pixels = null; export var alpha = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.alpha (...args); @@ -310,10 +460,6 @@ export var redraw = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.redraw (...args); }; -export var createCanvas = function () { - var args = tuple ([].slice.apply (arguments).slice (0)); - return _P5_INSTANCE.createCanvas (...args); -}; export var resizeCanvas = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.resizeCanvas (...args); @@ -914,86 +1060,130 @@ export var setCamera = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.setCamera (...args); }; +export var createCanvas = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + var result = _P5_INSTANCE.createCanvas (...args); + width = _P5_INSTANCE.width; + height = _P5_INSTANCE.height; +}; export var py_pop = function () { var args = tuple ([].slice.apply (arguments).slice (0)); var p5_pop = _P5_INSTANCE.pop (...args); return p5_pop; }; -export var HALF_PI = null; -export var PI = null; -export var QUARTER_PI = null; -export var TAU = null; -export var TWO_PI = null; -export var DEGREES = null; -export var RADIANS = null; -export var CLOSE = null; -export var RGB = null; -export var HSB = null; -export var CMYK = null; -export var TOP = null; -export var BOTTOM = null; -export var CENTER = null; -export var LEFT = null; -export var RIGHT = null; -export var SHIFT = null; -export var WEBGL = null; -export var frameCount = null; -export var focused = null; -export var displayWidth = null; -export var displayHeight = null; -export var windowWidth = null; -export var windowHeight = null; -export var width = null; -export var height = null; -export var disableFriendlyErrors = null; -export var deviceOrientation = null; -export var accelerationX = null; -export var accelerationY = null; -export var accelerationZ = null; -export var pAccelerationX = null; -export var pAccelerationY = null; -export var pAccelerationZ = null; -export var rotationX = null; -export var rotationY = null; -export var rotationZ = null; -export var pRotationX = null; -export var pRotationY = null; -export var pRotationZ = null; -export var turnAxis = null; -export var keyIsPressed = null; -export var key = null; -export var keyCode = null; -export var mouseX = null; -export var mouseY = null; -export var pmouseX = null; -export var pmouseY = null; -export var winMouseX = null; -export var winMouseY = null; -export var pwinMouseX = null; -export var pwinMouseY = null; -export var mouseButton = null; -export var mouseIsPressed = null; -export var touches = null; -export var pixels = null; export var pre_draw = function (p5_instance, draw_func) { + _CTX_MIDDLE = p5_instance._CTX_MIDDLE; + _DEFAULT_FILL = p5_instance._DEFAULT_FILL; + _DEFAULT_LEADMULT = p5_instance._DEFAULT_LEADMULT; + _DEFAULT_STROKE = p5_instance._DEFAULT_STROKE; + _DEFAULT_TEXT_FILL = p5_instance._DEFAULT_TEXT_FILL; + ADD = p5_instance.ADD; + ALT = p5_instance.ALT; + ARROW = p5_instance.ARROW; + AUTO = p5_instance.AUTO; + AXES = p5_instance.AXES; + BACKSPACE = p5_instance.BACKSPACE; + BASELINE = p5_instance.BASELINE; + BEVEL = p5_instance.BEVEL; + BEZIER = p5_instance.BEZIER; + BLEND = p5_instance.BLEND; + BLUR = p5_instance.BLUR; + BOLD = p5_instance.BOLD; + BOLDITALIC = p5_instance.BOLDITALIC; + BOTTOM = p5_instance.BOTTOM; + BURN = p5_instance.BURN; + CENTER = p5_instance.CENTER; + CHORD = p5_instance.CHORD; + CLAMP = p5_instance.CLAMP; + CLOSE = p5_instance.CLOSE; + CONTROL = p5_instance.CONTROL; + CORNER = p5_instance.CORNER; + CORNERS = p5_instance.CORNERS; + CROSS = p5_instance.CROSS; + CURVE = p5_instance.CURVE; + DARKEST = p5_instance.DARKEST; + DEG_TO_RAD = p5_instance.DEG_TO_RAD; + DEGREES = p5_instance.DEGREES; + DELETE = p5_instance.DELETE; + DIFFERENCE = p5_instance.DIFFERENCE; + DILATE = p5_instance.DILATE; + DODGE = p5_instance.DODGE; + DOWN_ARROW = p5_instance.DOWN_ARROW; + ENTER = p5_instance.ENTER; + ERODE = p5_instance.ERODE; + ESCAPE = p5_instance.ESCAPE; + EXCLUSION = p5_instance.EXCLUSION; + FILL = p5_instance.FILL; + GRAY = p5_instance.GRAY; + GRID = p5_instance.GRID; HALF_PI = p5_instance.HALF_PI; + HAND = p5_instance.HAND; + HARD_LIGHT = p5_instance.HARD_LIGHT; + HSB = p5_instance.HSB; + HSL = p5_instance.HSL; + IMAGE = p5_instance.IMAGE; + IMMEDIATE = p5_instance.IMMEDIATE; + INVERT = p5_instance.INVERT; + ITALIC = p5_instance.ITALIC; + LANDSCAPE = p5_instance.LANDSCAPE; + LEFT = p5_instance.LEFT; + LEFT_ARROW = p5_instance.LEFT_ARROW; + LIGHTEST = p5_instance.LIGHTEST; + LINE_LOOP = p5_instance.LINE_LOOP; + LINE_STRIP = p5_instance.LINE_STRIP; + LINEAR = p5_instance.LINEAR; + LINES = p5_instance.LINES; + MIRROR = p5_instance.MIRROR; + MITER = p5_instance.MITER; + MOVE = p5_instance.MOVE; + MULTIPLY = p5_instance.MULTIPLY; + NEAREST = p5_instance.NEAREST; + NORMAL = p5_instance.NORMAL; + OPAQUE = p5_instance.OPAQUE; + OPEN = p5_instance.OPEN; + OPTION = p5_instance.OPTION; + OVERLAY = p5_instance.OVERLAY; PI = p5_instance.PI; + PIE = p5_instance.PIE; + POINTS = p5_instance.POINTS; + PORTRAIT = p5_instance.PORTRAIT; + POSTERIZE = p5_instance.POSTERIZE; + PROJECT = p5_instance.PROJECT; + QUAD_STRIP = p5_instance.QUAD_STRIP; + QUADRATIC = p5_instance.QUADRATIC; + QUADS = p5_instance.QUADS; QUARTER_PI = p5_instance.QUARTER_PI; - TAU = p5_instance.TAU; - TWO_PI = p5_instance.TWO_PI; - DEGREES = p5_instance.DEGREES; + RAD_TO_DEG = p5_instance.RAD_TO_DEG; RADIANS = p5_instance.RADIANS; - CLOSE = p5_instance.CLOSE; + RADIUS = p5_instance.RADIUS; + REPEAT = p5_instance.REPEAT; + REPLACE = p5_instance.REPLACE; + RETURN = p5_instance.RETURN; RGB = p5_instance.RGB; - HSB = p5_instance.HSB; - CMYK = p5_instance.CMYK; - TOP = p5_instance.TOP; - BOTTOM = p5_instance.BOTTOM; - CENTER = p5_instance.CENTER; - LEFT = p5_instance.LEFT; RIGHT = p5_instance.RIGHT; + RIGHT_ARROW = p5_instance.RIGHT_ARROW; + ROUND = p5_instance.ROUND; + SCREEN = p5_instance.SCREEN; SHIFT = p5_instance.SHIFT; + SOFT_LIGHT = p5_instance.SOFT_LIGHT; + SQUARE = p5_instance.SQUARE; + STROKE = p5_instance.STROKE; + SUBTRACT = p5_instance.SUBTRACT; + TAB = p5_instance.TAB; + TAU = p5_instance.TAU; + TEXT = p5_instance.TEXT; + TEXTURE = p5_instance.TEXTURE; + THRESHOLD = p5_instance.THRESHOLD; + TOP = p5_instance.TOP; + TRIANGLE_FAN = p5_instance.TRIANGLE_FAN; + TRIANGLE_STRIP = p5_instance.TRIANGLE_STRIP; + TRIANGLES = p5_instance.TRIANGLES; + TWO_PI = p5_instance.TWO_PI; + UP_ARROW = p5_instance.UP_ARROW; + WAIT = p5_instance.WAIT; WEBGL = p5_instance.WEBGL; + P2D = p5_instance.P2D; + PI = p5_instance.PI; frameCount = p5_instance.frameCount; focused = p5_instance.focused; displayWidth = p5_instance.displayWidth; @@ -1054,7 +1244,7 @@ export var start_p5 = function (setup_func, draw_func, event_functions) { for (var f_name of (function () { var __accu0__ = []; for (var f of event_function_names) { - if (__in__ (f, event_functions)) { + if (event_functions.py_get (f, null)) { __accu0__.append (f); } } diff --git a/docs/examples/sketch_005/target/pytop5js.py b/docs/examples/sketch_005/target/pytop5js.py index 59388176..6462430c 100644 --- a/docs/examples/sketch_005/target/pytop5js.py +++ b/docs/examples/sketch_005/target/pytop5js.py @@ -1,4 +1,155 @@ _P5_INSTANCE = None +_CTX_MIDDLE = None +_DEFAULT_FILL = None +_DEFAULT_LEADMULT = None +_DEFAULT_STROKE = None +_DEFAULT_TEXT_FILL = None +ADD = None +ALT = None +ARROW = None +AUTO = None +AXES = None +BACKSPACE = None +BASELINE = None +BEVEL = None +BEZIER = None +BLEND = None +BLUR = None +BOLD = None +BOLDITALIC = None +BOTTOM = None +BURN = None +CENTER = None +CHORD = None +CLAMP = None +CLOSE = None +CONTROL = None +CORNER = None +CORNERS = None +CROSS = None +CURVE = None +DARKEST = None +DEG_TO_RAD = None +DEGREES = None +DELETE = None +DIFFERENCE = None +DILATE = None +DODGE = None +DOWN_ARROW = None +ENTER = None +ERODE = None +ESCAPE = None +EXCLUSION = None +FILL = None +GRAY = None +GRID = None +HALF_PI = None +HAND = None +HARD_LIGHT = None +HSB = None +HSL = None +IMAGE = None +IMMEDIATE = None +INVERT = None +ITALIC = None +LANDSCAPE = None +LEFT = None +LEFT_ARROW = None +LIGHTEST = None +LINE_LOOP = None +LINE_STRIP = None +LINEAR = None +LINES = None +MIRROR = None +MITER = None +MOVE = None +MULTIPLY = None +NEAREST = None +NORMAL = None +OPAQUE = None +OPEN = None +OPTION = None +OVERLAY = None +PI = None +PIE = None +POINTS = None +PORTRAIT = None +POSTERIZE = None +PROJECT = None +QUAD_STRIP = None +QUADRATIC = None +QUADS = None +QUARTER_PI = None +RAD_TO_DEG = None +RADIANS = None +RADIUS = None +REPEAT = None +REPLACE = None +RETURN = None +RGB = None +RIGHT = None +RIGHT_ARROW = None +ROUND = None +SCREEN = None +SHIFT = None +SOFT_LIGHT = None +SQUARE = None +STROKE = None +SUBTRACT = None +TAB = None +TAU = None +TEXT = None +TEXTURE = None +THRESHOLD = None +TOP = None +TRIANGLE_FAN = None +TRIANGLE_STRIP = None +TRIANGLES = None +TWO_PI = None +UP_ARROW = None +WAIT = None +WEBGL = None +P2D = None +PI = None +frameCount = None +focused = None +displayWidth = None +displayHeight = None +windowWidth = None +windowHeight = None +width = None +height = None +disableFriendlyErrors = None +deviceOrientation = None +accelerationX = None +accelerationY = None +accelerationZ = None +pAccelerationX = None +pAccelerationY = None +pAccelerationZ = None +rotationX = None +rotationY = None +rotationZ = None +pRotationX = None +pRotationY = None +pRotationZ = None +turnAxis = None +keyIsPressed = None +key = None +keyCode = None +mouseX = None +mouseY = None +pmouseX = None +pmouseY = None +winMouseX = None +winMouseY = None +pwinMouseX = None +pwinMouseY = None +mouseButton = None +mouseIsPressed = None +touches = None +pixels = None + def alpha(*args): @@ -232,9 +383,6 @@ def push(*args): def redraw(*args): return _P5_INSTANCE.redraw(*args) -def createCanvas(*args): - return _P5_INSTANCE.createCanvas(*args) - def resizeCanvas(*args): return _P5_INSTANCE.resizeCanvas(*args) @@ -686,6 +834,13 @@ def setCamera(*args): return _P5_INSTANCE.setCamera(*args) +def createCanvas(*args): + result = _P5_INSTANCE.createCanvas(*args) + + global width, height + width = _P5_INSTANCE.width + height = _P5_INSTANCE.height + def pop(*args): __pragma__('noalias', 'pop') @@ -693,87 +848,124 @@ def pop(*args): __pragma__('alias', 'pop', 'py_pop') return p5_pop -HALF_PI = None -PI = None -QUARTER_PI = None -TAU = None -TWO_PI = None -DEGREES = None -RADIANS = None -CLOSE = None -RGB = None -HSB = None -CMYK = None -TOP = None -BOTTOM = None -CENTER = None -LEFT = None -RIGHT = None -SHIFT = None -WEBGL = None -frameCount = None -focused = None -displayWidth = None -displayHeight = None -windowWidth = None -windowHeight = None -width = None -height = None -disableFriendlyErrors = None -deviceOrientation = None -accelerationX = None -accelerationY = None -accelerationZ = None -pAccelerationX = None -pAccelerationY = None -pAccelerationZ = None -rotationX = None -rotationY = None -rotationZ = None -pRotationX = None -pRotationY = None -pRotationZ = None -turnAxis = None -keyIsPressed = None -key = None -keyCode = None -mouseX = None -mouseY = None -pmouseX = None -pmouseY = None -winMouseX = None -winMouseY = None -pwinMouseX = None -pwinMouseY = None -mouseButton = None -mouseIsPressed = None -touches = None -pixels = None - def pre_draw(p5_instance, draw_func): """ We need to run this before the actual draw to insert and update p5 env variables """ - global HALF_PI, PI, QUARTER_PI, TAU, TWO_PI, DEGREES, RADIANS, CLOSE, RGB, HSB, CMYK, TOP, BOTTOM, CENTER, LEFT, RIGHT, SHIFT, WEBGL, frameCount, focused, displayWidth, displayHeight, windowWidth, windowHeight, width, height, disableFriendlyErrors, deviceOrientation, accelerationX, accelerationY, accelerationZ, pAccelerationX, pAccelerationY, pAccelerationZ, rotationX, rotationY, rotationZ, pRotationX, pRotationY, pRotationZ, turnAxis, keyIsPressed, key, keyCode, mouseX, mouseY, pmouseX, pmouseY, winMouseX, winMouseY, pwinMouseX, pwinMouseY, mouseButton, mouseIsPressed, touches, pixels - + global _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEG_TO_RAD, DEGREES, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINE_LOOP, LINE_STRIP, LINEAR, LINES, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUAD_STRIP, QUADRATIC, QUADS, QUARTER_PI, RAD_TO_DEG, RADIANS, RADIUS, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLE_FAN, TRIANGLE_STRIP, TRIANGLES, TWO_PI, UP_ARROW, WAIT, WEBGL, P2D, PI, frameCount, focused, displayWidth, displayHeight, windowWidth, windowHeight, width, height, disableFriendlyErrors, deviceOrientation, accelerationX, accelerationY, accelerationZ, pAccelerationX, pAccelerationY, pAccelerationZ, rotationX, rotationY, rotationZ, pRotationX, pRotationY, pRotationZ, turnAxis, keyIsPressed, key, keyCode, mouseX, mouseY, pmouseX, pmouseY, winMouseX, winMouseY, pwinMouseX, pwinMouseY, mouseButton, mouseIsPressed, touches, pixels + + _CTX_MIDDLE = p5_instance._CTX_MIDDLE + _DEFAULT_FILL = p5_instance._DEFAULT_FILL + _DEFAULT_LEADMULT = p5_instance._DEFAULT_LEADMULT + _DEFAULT_STROKE = p5_instance._DEFAULT_STROKE + _DEFAULT_TEXT_FILL = p5_instance._DEFAULT_TEXT_FILL + ADD = p5_instance.ADD + ALT = p5_instance.ALT + ARROW = p5_instance.ARROW + AUTO = p5_instance.AUTO + AXES = p5_instance.AXES + BACKSPACE = p5_instance.BACKSPACE + BASELINE = p5_instance.BASELINE + BEVEL = p5_instance.BEVEL + BEZIER = p5_instance.BEZIER + BLEND = p5_instance.BLEND + BLUR = p5_instance.BLUR + BOLD = p5_instance.BOLD + BOLDITALIC = p5_instance.BOLDITALIC + BOTTOM = p5_instance.BOTTOM + BURN = p5_instance.BURN + CENTER = p5_instance.CENTER + CHORD = p5_instance.CHORD + CLAMP = p5_instance.CLAMP + CLOSE = p5_instance.CLOSE + CONTROL = p5_instance.CONTROL + CORNER = p5_instance.CORNER + CORNERS = p5_instance.CORNERS + CROSS = p5_instance.CROSS + CURVE = p5_instance.CURVE + DARKEST = p5_instance.DARKEST + DEG_TO_RAD = p5_instance.DEG_TO_RAD + DEGREES = p5_instance.DEGREES + DELETE = p5_instance.DELETE + DIFFERENCE = p5_instance.DIFFERENCE + DILATE = p5_instance.DILATE + DODGE = p5_instance.DODGE + DOWN_ARROW = p5_instance.DOWN_ARROW + ENTER = p5_instance.ENTER + ERODE = p5_instance.ERODE + ESCAPE = p5_instance.ESCAPE + EXCLUSION = p5_instance.EXCLUSION + FILL = p5_instance.FILL + GRAY = p5_instance.GRAY + GRID = p5_instance.GRID HALF_PI = p5_instance.HALF_PI + HAND = p5_instance.HAND + HARD_LIGHT = p5_instance.HARD_LIGHT + HSB = p5_instance.HSB + HSL = p5_instance.HSL + IMAGE = p5_instance.IMAGE + IMMEDIATE = p5_instance.IMMEDIATE + INVERT = p5_instance.INVERT + ITALIC = p5_instance.ITALIC + LANDSCAPE = p5_instance.LANDSCAPE + LEFT = p5_instance.LEFT + LEFT_ARROW = p5_instance.LEFT_ARROW + LIGHTEST = p5_instance.LIGHTEST + LINE_LOOP = p5_instance.LINE_LOOP + LINE_STRIP = p5_instance.LINE_STRIP + LINEAR = p5_instance.LINEAR + LINES = p5_instance.LINES + MIRROR = p5_instance.MIRROR + MITER = p5_instance.MITER + MOVE = p5_instance.MOVE + MULTIPLY = p5_instance.MULTIPLY + NEAREST = p5_instance.NEAREST + NORMAL = p5_instance.NORMAL + OPAQUE = p5_instance.OPAQUE + OPEN = p5_instance.OPEN + OPTION = p5_instance.OPTION + OVERLAY = p5_instance.OVERLAY PI = p5_instance.PI + PIE = p5_instance.PIE + POINTS = p5_instance.POINTS + PORTRAIT = p5_instance.PORTRAIT + POSTERIZE = p5_instance.POSTERIZE + PROJECT = p5_instance.PROJECT + QUAD_STRIP = p5_instance.QUAD_STRIP + QUADRATIC = p5_instance.QUADRATIC + QUADS = p5_instance.QUADS QUARTER_PI = p5_instance.QUARTER_PI - TAU = p5_instance.TAU - TWO_PI = p5_instance.TWO_PI - DEGREES = p5_instance.DEGREES + RAD_TO_DEG = p5_instance.RAD_TO_DEG RADIANS = p5_instance.RADIANS - CLOSE = p5_instance.CLOSE + RADIUS = p5_instance.RADIUS + REPEAT = p5_instance.REPEAT + REPLACE = p5_instance.REPLACE + RETURN = p5_instance.RETURN RGB = p5_instance.RGB - HSB = p5_instance.HSB - CMYK = p5_instance.CMYK - TOP = p5_instance.TOP - BOTTOM = p5_instance.BOTTOM - CENTER = p5_instance.CENTER - LEFT = p5_instance.LEFT RIGHT = p5_instance.RIGHT + RIGHT_ARROW = p5_instance.RIGHT_ARROW + ROUND = p5_instance.ROUND + SCREEN = p5_instance.SCREEN SHIFT = p5_instance.SHIFT + SOFT_LIGHT = p5_instance.SOFT_LIGHT + SQUARE = p5_instance.SQUARE + STROKE = p5_instance.STROKE + SUBTRACT = p5_instance.SUBTRACT + TAB = p5_instance.TAB + TAU = p5_instance.TAU + TEXT = p5_instance.TEXT + TEXTURE = p5_instance.TEXTURE + THRESHOLD = p5_instance.THRESHOLD + TOP = p5_instance.TOP + TRIANGLE_FAN = p5_instance.TRIANGLE_FAN + TRIANGLE_STRIP = p5_instance.TRIANGLE_STRIP + TRIANGLES = p5_instance.TRIANGLES + TWO_PI = p5_instance.TWO_PI + UP_ARROW = p5_instance.UP_ARROW + WAIT = p5_instance.WAIT WEBGL = p5_instance.WEBGL + P2D = p5_instance.P2D + PI = p5_instance.PI frameCount = p5_instance.frameCount focused = p5_instance.focused displayWidth = p5_instance.displayWidth @@ -853,7 +1045,7 @@ def sketch_setup(p5_sketch): # inject event functions into p5 event_function_names = ["deviceMoved", "deviceTurned", "deviceShaken", "keyPressed", "keyReleased", "keyTyped", "mouseMoved", "mouseDragged", "mousePressed", "mouseReleased", "mouseClicked", "doubleClicked", "mouseWheel", "touchStarted", "touchMoved", "touchEnded", "windowResized", ] - for f_name in [f for f in event_function_names if f in event_functions]: + for f_name in [f for f in event_function_names if event_functions.get(f, None)]: func = event_functions[f_name] event_func = global_p5_injection(instance)(func) setattr(instance, f_name, event_func) \ No newline at end of file diff --git a/docs/examples/sketch_005/target/sketch_005.js b/docs/examples/sketch_005/target/sketch_005.js index f62fcd4b..2a86818d 100644 --- a/docs/examples/sketch_005/target/sketch_005.js +++ b/docs/examples/sketch_005/target/sketch_005.js @@ -1,7 +1,7 @@ -// Transcrypt'ed from Python, 2019-05-09 00:36:43 +// Transcrypt'ed from Python, 2019-06-01 16:39:08 import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, input, isinstance, issubclass, len, list, object, ord, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; -import {BOTTOM, CENTER, CLOSE, CMYK, DEGREES, HALF_PI, HSB, LEFT, PI, QUARTER_PI, RADIANS, RGB, RIGHT, SHIFT, TAU, TOP, TWO_PI, WEBGL, _P5_INSTANCE, abs, accelerationX, accelerationY, accelerationZ, acos, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, char, circle, color, colorMode, concat, cone, constrain, copy, cos, createCamera, createCanvas, createGraphics, createImage, createNumberDict, createShader, createStringDict, createVector, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, deviceOrientation, directionalLight, disableFriendlyErrors, displayDensity, displayHeight, displayWidth, dist, ellipse, ellipseMode, ellipsoid, endContour, endShape, exp, fill, filter, float, floor, focused, frameCount, frameRate, fullscreen, getURL, getURLParams, getURLPath, global_p5_injection, green, height, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, int, join, key, keyCode, keyIsDown, keyIsPressed, lerp, lerpColor, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, mouseButton, mouseIsPressed, mouseX, mouseY, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noFill, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normalMaterial, orbitControl, ortho, pAccelerationX, pAccelerationY, pAccelerationZ, pRotationX, pRotationY, pRotationZ, perspective, pixelDensity, pixels, plane, pmouseX, pmouseY, point, pointLight, pow, pre_draw, preload, print, push, pwinMouseX, pwinMouseY, py_clear, py_get, py_pop, py_sort, py_split, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, remove, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, rotationX, rotationY, rotationZ, round, saturation, save, saveCanvas, saveFrames, saveJSON, saveStrings, saveTable, scale, second, set, setAttributes, setCamera, setMoveThreshold, setShakeThreshold, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, specularMaterial, sphere, splice, splitTokens, sq, sqrt, square, start_p5, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, touches, translate, triangle, trim, turnAxis, unchar, unhex, updatePixels, vertex, width, winMouseX, winMouseY, windowHeight, windowWidth, year} from './pytop5js.js'; -var __name__ = '__main__'; +import {ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEGREES, DEG_TO_RAD, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINEAR, LINES, LINE_LOOP, LINE_STRIP, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, P2D, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUADRATIC, QUADS, QUAD_STRIP, QUARTER_PI, RADIANS, RADIUS, RAD_TO_DEG, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, TWO_PI, UP_ARROW, WAIT, WEBGL, _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, _P5_INSTANCE, abs, accelerationX, accelerationY, accelerationZ, acos, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, char, circle, color, colorMode, concat, cone, constrain, copy, cos, createCamera, createCanvas, createGraphics, createImage, createNumberDict, createShader, createStringDict, createVector, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, deviceOrientation, directionalLight, disableFriendlyErrors, displayDensity, displayHeight, displayWidth, dist, ellipse, ellipseMode, ellipsoid, endContour, endShape, exp, fill, filter, float, floor, focused, frameCount, frameRate, fullscreen, getURL, getURLParams, getURLPath, global_p5_injection, green, height, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, int, join, key, keyCode, keyIsDown, keyIsPressed, lerp, lerpColor, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, mouseButton, mouseIsPressed, mouseX, mouseY, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noFill, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normalMaterial, orbitControl, ortho, pAccelerationX, pAccelerationY, pAccelerationZ, pRotationX, pRotationY, pRotationZ, perspective, pixelDensity, pixels, plane, pmouseX, pmouseY, point, pointLight, pow, pre_draw, preload, print, push, pwinMouseX, pwinMouseY, py_clear, py_get, py_pop, py_sort, py_split, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, remove, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, rotationX, rotationY, rotationZ, round, saturation, save, saveCanvas, saveFrames, saveJSON, saveStrings, saveTable, scale, second, set, setAttributes, setCamera, setMoveThreshold, setShakeThreshold, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, specularMaterial, sphere, splice, splitTokens, sq, sqrt, square, start_p5, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, touches, translate, triangle, trim, turnAxis, unchar, unhex, updatePixels, vertex, width, winMouseX, winMouseY, windowHeight, windowWidth, year} from './pytop5js.js'; +var __name__ = 'sketch_005'; export var setup = function () { createCanvas (600, 600); noStroke (); @@ -14,6 +14,5 @@ export var draw = function () { fill (100 - h, 100, 100); rect (300, 300, mouseX + 1, mouseX + 1); }; -start_p5 (setup, draw, dict ({})); //# sourceMappingURL=sketch_005.map \ No newline at end of file diff --git a/docs/examples/sketch_005/target/sketch_005.options b/docs/examples/sketch_005/target/sketch_005.options deleted file mode 100644 index 4211ba33a8c15c1e8edf962d5295666cfdfd9421..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 604 zcmYLG%XZT+5KT#6yrJb$-jo(vSk&G0H?r1_Bg@moi7e?#vauIEhh_ZND4O)Jl16jq zK1P41cbHs?{mEn!Z0i+aN1SYm6-Bl9eSLjX{J&ng0T0A(YD;4*remIyx^8TR-BIkN zPTAJF!rodOq(a%oY3i}hy~-*XaWLjyB|{(|amXx{T98`d;kKearnyIBR;#p~TSQNU=cAY=B!vzyX4&Aal3L>>zt73wi1D?uro%Do zFGEJXy02C=1iWV8GHl|$;nwPp^z(qXY$(Av#tCQCwIUM;?^tbP{rx(-Ft(`;KCE*- z>uiUQOz5O16Y*)5ef!qnGjoNZDXk9p!ZE_F^$otVrI@{+@`hSdM|_**C3oaYn+%+d zVkfPk$2m{;X*WH-vt&QlwhZ{eT)mTVfeUe(@WsM5RFve6^p!2hbfIvAyII~JxXfw# RSepSqSwDS($FH%y`UfCsrzZda diff --git a/docs/examples/sketch_005/target/sketch_005.py b/docs/examples/sketch_005/target/sketch_005.py index 2059e0aa..7f3b815e 100644 --- a/docs/examples/sketch_005/target/sketch_005.py +++ b/docs/examples/sketch_005/target/sketch_005.py @@ -13,7 +13,3 @@ def draw(): background(h,100,100) fill(100-h,100,100) rect(300,300,mouseX+1,mouseX+1) - - -# This is required by pyp5js to work -start_p5(setup, draw, {}) diff --git a/docs/examples/sketch_005/target/target_sketch.js b/docs/examples/sketch_005/target/target_sketch.js new file mode 100644 index 00000000..2ec8015b --- /dev/null +++ b/docs/examples/sketch_005/target/target_sketch.js @@ -0,0 +1,9 @@ +// Transcrypt'ed from Python, 2019-06-01 16:39:08 +import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, input, isinstance, issubclass, len, list, object, ord, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; +import {ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEGREES, DEG_TO_RAD, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINEAR, LINES, LINE_LOOP, LINE_STRIP, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, P2D, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUADRATIC, QUADS, QUAD_STRIP, QUARTER_PI, RADIANS, RADIUS, RAD_TO_DEG, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, TWO_PI, UP_ARROW, WAIT, WEBGL, _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, _P5_INSTANCE, abs, accelerationX, accelerationY, accelerationZ, acos, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, char, circle, color, colorMode, concat, cone, constrain, copy, cos, createCamera, createCanvas, createGraphics, createImage, createNumberDict, createShader, createStringDict, createVector, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, deviceOrientation, directionalLight, disableFriendlyErrors, displayDensity, displayHeight, displayWidth, dist, draw, ellipse, ellipseMode, ellipsoid, endContour, endShape, exp, fill, filter, float, floor, focused, frameCount, frameRate, fullscreen, getURL, getURLParams, getURLPath, global_p5_injection, green, height, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, int, join, key, keyCode, keyIsDown, keyIsPressed, lerp, lerpColor, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, mouseButton, mouseIsPressed, mouseX, mouseY, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noFill, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normalMaterial, orbitControl, ortho, pAccelerationX, pAccelerationY, pAccelerationZ, pRotationX, pRotationY, pRotationZ, perspective, pixelDensity, pixels, plane, pmouseX, pmouseY, point, pointLight, pow, pre_draw, preload, print, push, pwinMouseX, pwinMouseY, py_clear, py_get, py_pop, py_sort, py_split, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, remove, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, rotationX, rotationY, rotationZ, round, saturation, save, saveCanvas, saveFrames, saveJSON, saveStrings, saveTable, scale, second, set, setAttributes, setCamera, setMoveThreshold, setShakeThreshold, setup, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, specularMaterial, sphere, splice, splitTokens, sq, sqrt, square, start_p5, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, touches, translate, triangle, trim, turnAxis, unchar, unhex, updatePixels, vertex, width, winMouseX, winMouseY, windowHeight, windowWidth, year} from './pytop5js.js'; +import * as source_sketch from './sketch_005.js'; +var __name__ = '__main__'; +export var event_functions = dict ({'deviceMoved': source_sketch.deviceMoved, 'deviceTurned': source_sketch.deviceTurned, 'deviceShaken': source_sketch.deviceShaken, 'keyPressed': source_sketch.keyPressed, 'keyReleased': source_sketch.keyReleased, 'keyTyped': source_sketch.keyTyped, 'mouseMoved': source_sketch.mouseMoved, 'mouseDragged': source_sketch.mouseDragged, 'mousePressed': source_sketch.mousePressed, 'mouseReleased': source_sketch.mouseReleased, 'mouseClicked': source_sketch.mouseClicked, 'doubleClicked': source_sketch.doubleClicked, 'mouseWheel': source_sketch.mouseWheel, 'touchStarted': source_sketch.touchStarted, 'touchMoved': source_sketch.touchMoved, 'touchEnded': source_sketch.touchEnded, 'windowResized': source_sketch.windowResized}); +start_p5 (source_sketch.setup, source_sketch.draw, event_functions); + +//# sourceMappingURL=target_sketch.map \ No newline at end of file diff --git a/docs/examples/sketch_005/target/target_sketch.options b/docs/examples/sketch_005/target/target_sketch.options new file mode 100644 index 0000000000000000000000000000000000000000..6d6d6f3cfa655c0f83769317e24de1f67ef26781 GIT binary patch literal 607 zcmXw0%U0Vk5Dg8lzFX*1nlS{EbnM{Ihy&~+0lTERrs1~=^*EdC!eopb0U#{GMM`AZ2q%juLF^@`JH@3p= zDE3mPY-?R%Z!Hc|p={$c_1NcLWtEIL7;~?ZA&`$aWR^-TNUiXATTvg=+>zvOz+u<`4I_b$oe3@n6zBTyDTw!QRs{_7qjBsatgYRr9X78uGq1Mz9KW2H!9r@BG z181YyNo(kF&eMI`O^=@}+0V5t1AZ}A?_^xyLYyXiv9JvlC3z!#WeYN0DBR#~mJbIm UbDBQZX25UOPoLoNXKb(j1CpJo8~^|S literal 0 HcmV?d00001 diff --git a/docs/examples/sketch_005/target/target_sketch.py b/docs/examples/sketch_005/target/target_sketch.py new file mode 100644 index 00000000..5e09b202 --- /dev/null +++ b/docs/examples/sketch_005/target/target_sketch.py @@ -0,0 +1,24 @@ +import sketch_005 as source_sketch +from pytop5js import * + +event_functions = { + "deviceMoved": source_sketch.deviceMoved, + "deviceTurned": source_sketch.deviceTurned, + "deviceShaken": source_sketch.deviceShaken, + "keyPressed": source_sketch.keyPressed, + "keyReleased": source_sketch.keyReleased, + "keyTyped": source_sketch.keyTyped, + "mouseMoved": source_sketch.mouseMoved, + "mouseDragged": source_sketch.mouseDragged, + "mousePressed": source_sketch.mousePressed, + "mouseReleased": source_sketch.mouseReleased, + "mouseClicked": source_sketch.mouseClicked, + "doubleClicked": source_sketch.doubleClicked, + "mouseWheel": source_sketch.mouseWheel, + "touchStarted": source_sketch.touchStarted, + "touchMoved": source_sketch.touchMoved, + "touchEnded": source_sketch.touchEnded, + "windowResized": source_sketch.windowResized, +} + +start_p5(source_sketch.setup, source_sketch.draw, event_functions) \ No newline at end of file diff --git a/docs/examples/sketch_006/sketch_006.py b/docs/examples/sketch_006/sketch_006.py index 1d403d76..9a6e7e97 100644 --- a/docs/examples/sketch_006/sketch_006.py +++ b/docs/examples/sketch_006/sketch_006.py @@ -27,9 +27,3 @@ def mouseDragged(): global r r = random(100, 700) redraw() - -event_functions = { - 'keyPressed': keyPressed, - 'mouseDragged': mouseDragged, -} -start_p5(setup, draw, event_functions) diff --git a/docs/examples/sketch_006/target/org.transcrypt.__runtime__.js b/docs/examples/sketch_006/target/org.transcrypt.__runtime__.js index 35e90f08..7a6a14d4 100644 --- a/docs/examples/sketch_006/target/org.transcrypt.__runtime__.js +++ b/docs/examples/sketch_006/target/org.transcrypt.__runtime__.js @@ -1,4 +1,4 @@ -// Transcrypt'ed from Python, 2019-05-09 00:40:46 +// Transcrypt'ed from Python, 2019-06-01 16:39:09 var __name__ = 'org.transcrypt.__runtime__'; export var __envir__ = {}; __envir__.interpreter_name = 'python'; diff --git a/docs/examples/sketch_006/target/pytop5js.js b/docs/examples/sketch_006/target/pytop5js.js index 1edb2342..4638aabb 100644 --- a/docs/examples/sketch_006/target/pytop5js.js +++ b/docs/examples/sketch_006/target/pytop5js.js @@ -1,7 +1,157 @@ -// Transcrypt'ed from Python, 2019-05-09 00:40:46 +// Transcrypt'ed from Python, 2019-06-01 16:39:10 import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, input, isinstance, issubclass, len, list, object, ord, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; var __name__ = 'pytop5js'; export var _P5_INSTANCE = null; +export var _CTX_MIDDLE = null; +export var _DEFAULT_FILL = null; +export var _DEFAULT_LEADMULT = null; +export var _DEFAULT_STROKE = null; +export var _DEFAULT_TEXT_FILL = null; +export var ADD = null; +export var ALT = null; +export var ARROW = null; +export var AUTO = null; +export var AXES = null; +export var BACKSPACE = null; +export var BASELINE = null; +export var BEVEL = null; +export var BEZIER = null; +export var BLEND = null; +export var BLUR = null; +export var BOLD = null; +export var BOLDITALIC = null; +export var BOTTOM = null; +export var BURN = null; +export var CENTER = null; +export var CHORD = null; +export var CLAMP = null; +export var CLOSE = null; +export var CONTROL = null; +export var CORNER = null; +export var CORNERS = null; +export var CROSS = null; +export var CURVE = null; +export var DARKEST = null; +export var DEG_TO_RAD = null; +export var DEGREES = null; +export var DELETE = null; +export var DIFFERENCE = null; +export var DILATE = null; +export var DODGE = null; +export var DOWN_ARROW = null; +export var ENTER = null; +export var ERODE = null; +export var ESCAPE = null; +export var EXCLUSION = null; +export var FILL = null; +export var GRAY = null; +export var GRID = null; +export var HALF_PI = null; +export var HAND = null; +export var HARD_LIGHT = null; +export var HSB = null; +export var HSL = null; +export var IMAGE = null; +export var IMMEDIATE = null; +export var INVERT = null; +export var ITALIC = null; +export var LANDSCAPE = null; +export var LEFT = null; +export var LEFT_ARROW = null; +export var LIGHTEST = null; +export var LINE_LOOP = null; +export var LINE_STRIP = null; +export var LINEAR = null; +export var LINES = null; +export var MIRROR = null; +export var MITER = null; +export var MOVE = null; +export var MULTIPLY = null; +export var NEAREST = null; +export var NORMAL = null; +export var OPAQUE = null; +export var OPEN = null; +export var OPTION = null; +export var OVERLAY = null; +export var PI = null; +export var PIE = null; +export var POINTS = null; +export var PORTRAIT = null; +export var POSTERIZE = null; +export var PROJECT = null; +export var QUAD_STRIP = null; +export var QUADRATIC = null; +export var QUADS = null; +export var QUARTER_PI = null; +export var RAD_TO_DEG = null; +export var RADIANS = null; +export var RADIUS = null; +export var REPEAT = null; +export var REPLACE = null; +export var RETURN = null; +export var RGB = null; +export var RIGHT = null; +export var RIGHT_ARROW = null; +export var ROUND = null; +export var SCREEN = null; +export var SHIFT = null; +export var SOFT_LIGHT = null; +export var SQUARE = null; +export var STROKE = null; +export var SUBTRACT = null; +export var TAB = null; +export var TAU = null; +export var TEXT = null; +export var TEXTURE = null; +export var THRESHOLD = null; +export var TOP = null; +export var TRIANGLE_FAN = null; +export var TRIANGLE_STRIP = null; +export var TRIANGLES = null; +export var TWO_PI = null; +export var UP_ARROW = null; +export var WAIT = null; +export var WEBGL = null; +export var P2D = null; +var PI = null; +export var frameCount = null; +export var focused = null; +export var displayWidth = null; +export var displayHeight = null; +export var windowWidth = null; +export var windowHeight = null; +export var width = null; +export var height = null; +export var disableFriendlyErrors = null; +export var deviceOrientation = null; +export var accelerationX = null; +export var accelerationY = null; +export var accelerationZ = null; +export var pAccelerationX = null; +export var pAccelerationY = null; +export var pAccelerationZ = null; +export var rotationX = null; +export var rotationY = null; +export var rotationZ = null; +export var pRotationX = null; +export var pRotationY = null; +export var pRotationZ = null; +export var turnAxis = null; +export var keyIsPressed = null; +export var key = null; +export var keyCode = null; +export var mouseX = null; +export var mouseY = null; +export var pmouseX = null; +export var pmouseY = null; +export var winMouseX = null; +export var winMouseY = null; +export var pwinMouseX = null; +export var pwinMouseY = null; +export var mouseButton = null; +export var mouseIsPressed = null; +export var touches = null; +export var pixels = null; export var alpha = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.alpha (...args); @@ -310,10 +460,6 @@ export var redraw = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.redraw (...args); }; -export var createCanvas = function () { - var args = tuple ([].slice.apply (arguments).slice (0)); - return _P5_INSTANCE.createCanvas (...args); -}; export var resizeCanvas = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.resizeCanvas (...args); @@ -914,86 +1060,130 @@ export var setCamera = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.setCamera (...args); }; +export var createCanvas = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + var result = _P5_INSTANCE.createCanvas (...args); + width = _P5_INSTANCE.width; + height = _P5_INSTANCE.height; +}; export var py_pop = function () { var args = tuple ([].slice.apply (arguments).slice (0)); var p5_pop = _P5_INSTANCE.pop (...args); return p5_pop; }; -export var HALF_PI = null; -export var PI = null; -export var QUARTER_PI = null; -export var TAU = null; -export var TWO_PI = null; -export var DEGREES = null; -export var RADIANS = null; -export var CLOSE = null; -export var RGB = null; -export var HSB = null; -export var CMYK = null; -export var TOP = null; -export var BOTTOM = null; -export var CENTER = null; -export var LEFT = null; -export var RIGHT = null; -export var SHIFT = null; -export var WEBGL = null; -export var frameCount = null; -export var focused = null; -export var displayWidth = null; -export var displayHeight = null; -export var windowWidth = null; -export var windowHeight = null; -export var width = null; -export var height = null; -export var disableFriendlyErrors = null; -export var deviceOrientation = null; -export var accelerationX = null; -export var accelerationY = null; -export var accelerationZ = null; -export var pAccelerationX = null; -export var pAccelerationY = null; -export var pAccelerationZ = null; -export var rotationX = null; -export var rotationY = null; -export var rotationZ = null; -export var pRotationX = null; -export var pRotationY = null; -export var pRotationZ = null; -export var turnAxis = null; -export var keyIsPressed = null; -export var key = null; -export var keyCode = null; -export var mouseX = null; -export var mouseY = null; -export var pmouseX = null; -export var pmouseY = null; -export var winMouseX = null; -export var winMouseY = null; -export var pwinMouseX = null; -export var pwinMouseY = null; -export var mouseButton = null; -export var mouseIsPressed = null; -export var touches = null; -export var pixels = null; export var pre_draw = function (p5_instance, draw_func) { + _CTX_MIDDLE = p5_instance._CTX_MIDDLE; + _DEFAULT_FILL = p5_instance._DEFAULT_FILL; + _DEFAULT_LEADMULT = p5_instance._DEFAULT_LEADMULT; + _DEFAULT_STROKE = p5_instance._DEFAULT_STROKE; + _DEFAULT_TEXT_FILL = p5_instance._DEFAULT_TEXT_FILL; + ADD = p5_instance.ADD; + ALT = p5_instance.ALT; + ARROW = p5_instance.ARROW; + AUTO = p5_instance.AUTO; + AXES = p5_instance.AXES; + BACKSPACE = p5_instance.BACKSPACE; + BASELINE = p5_instance.BASELINE; + BEVEL = p5_instance.BEVEL; + BEZIER = p5_instance.BEZIER; + BLEND = p5_instance.BLEND; + BLUR = p5_instance.BLUR; + BOLD = p5_instance.BOLD; + BOLDITALIC = p5_instance.BOLDITALIC; + BOTTOM = p5_instance.BOTTOM; + BURN = p5_instance.BURN; + CENTER = p5_instance.CENTER; + CHORD = p5_instance.CHORD; + CLAMP = p5_instance.CLAMP; + CLOSE = p5_instance.CLOSE; + CONTROL = p5_instance.CONTROL; + CORNER = p5_instance.CORNER; + CORNERS = p5_instance.CORNERS; + CROSS = p5_instance.CROSS; + CURVE = p5_instance.CURVE; + DARKEST = p5_instance.DARKEST; + DEG_TO_RAD = p5_instance.DEG_TO_RAD; + DEGREES = p5_instance.DEGREES; + DELETE = p5_instance.DELETE; + DIFFERENCE = p5_instance.DIFFERENCE; + DILATE = p5_instance.DILATE; + DODGE = p5_instance.DODGE; + DOWN_ARROW = p5_instance.DOWN_ARROW; + ENTER = p5_instance.ENTER; + ERODE = p5_instance.ERODE; + ESCAPE = p5_instance.ESCAPE; + EXCLUSION = p5_instance.EXCLUSION; + FILL = p5_instance.FILL; + GRAY = p5_instance.GRAY; + GRID = p5_instance.GRID; HALF_PI = p5_instance.HALF_PI; + HAND = p5_instance.HAND; + HARD_LIGHT = p5_instance.HARD_LIGHT; + HSB = p5_instance.HSB; + HSL = p5_instance.HSL; + IMAGE = p5_instance.IMAGE; + IMMEDIATE = p5_instance.IMMEDIATE; + INVERT = p5_instance.INVERT; + ITALIC = p5_instance.ITALIC; + LANDSCAPE = p5_instance.LANDSCAPE; + LEFT = p5_instance.LEFT; + LEFT_ARROW = p5_instance.LEFT_ARROW; + LIGHTEST = p5_instance.LIGHTEST; + LINE_LOOP = p5_instance.LINE_LOOP; + LINE_STRIP = p5_instance.LINE_STRIP; + LINEAR = p5_instance.LINEAR; + LINES = p5_instance.LINES; + MIRROR = p5_instance.MIRROR; + MITER = p5_instance.MITER; + MOVE = p5_instance.MOVE; + MULTIPLY = p5_instance.MULTIPLY; + NEAREST = p5_instance.NEAREST; + NORMAL = p5_instance.NORMAL; + OPAQUE = p5_instance.OPAQUE; + OPEN = p5_instance.OPEN; + OPTION = p5_instance.OPTION; + OVERLAY = p5_instance.OVERLAY; PI = p5_instance.PI; + PIE = p5_instance.PIE; + POINTS = p5_instance.POINTS; + PORTRAIT = p5_instance.PORTRAIT; + POSTERIZE = p5_instance.POSTERIZE; + PROJECT = p5_instance.PROJECT; + QUAD_STRIP = p5_instance.QUAD_STRIP; + QUADRATIC = p5_instance.QUADRATIC; + QUADS = p5_instance.QUADS; QUARTER_PI = p5_instance.QUARTER_PI; - TAU = p5_instance.TAU; - TWO_PI = p5_instance.TWO_PI; - DEGREES = p5_instance.DEGREES; + RAD_TO_DEG = p5_instance.RAD_TO_DEG; RADIANS = p5_instance.RADIANS; - CLOSE = p5_instance.CLOSE; + RADIUS = p5_instance.RADIUS; + REPEAT = p5_instance.REPEAT; + REPLACE = p5_instance.REPLACE; + RETURN = p5_instance.RETURN; RGB = p5_instance.RGB; - HSB = p5_instance.HSB; - CMYK = p5_instance.CMYK; - TOP = p5_instance.TOP; - BOTTOM = p5_instance.BOTTOM; - CENTER = p5_instance.CENTER; - LEFT = p5_instance.LEFT; RIGHT = p5_instance.RIGHT; + RIGHT_ARROW = p5_instance.RIGHT_ARROW; + ROUND = p5_instance.ROUND; + SCREEN = p5_instance.SCREEN; SHIFT = p5_instance.SHIFT; + SOFT_LIGHT = p5_instance.SOFT_LIGHT; + SQUARE = p5_instance.SQUARE; + STROKE = p5_instance.STROKE; + SUBTRACT = p5_instance.SUBTRACT; + TAB = p5_instance.TAB; + TAU = p5_instance.TAU; + TEXT = p5_instance.TEXT; + TEXTURE = p5_instance.TEXTURE; + THRESHOLD = p5_instance.THRESHOLD; + TOP = p5_instance.TOP; + TRIANGLE_FAN = p5_instance.TRIANGLE_FAN; + TRIANGLE_STRIP = p5_instance.TRIANGLE_STRIP; + TRIANGLES = p5_instance.TRIANGLES; + TWO_PI = p5_instance.TWO_PI; + UP_ARROW = p5_instance.UP_ARROW; + WAIT = p5_instance.WAIT; WEBGL = p5_instance.WEBGL; + P2D = p5_instance.P2D; + PI = p5_instance.PI; frameCount = p5_instance.frameCount; focused = p5_instance.focused; displayWidth = p5_instance.displayWidth; @@ -1054,7 +1244,7 @@ export var start_p5 = function (setup_func, draw_func, event_functions) { for (var f_name of (function () { var __accu0__ = []; for (var f of event_function_names) { - if (__in__ (f, event_functions)) { + if (event_functions.py_get (f, null)) { __accu0__.append (f); } } diff --git a/docs/examples/sketch_006/target/pytop5js.py b/docs/examples/sketch_006/target/pytop5js.py index 59388176..6462430c 100644 --- a/docs/examples/sketch_006/target/pytop5js.py +++ b/docs/examples/sketch_006/target/pytop5js.py @@ -1,4 +1,155 @@ _P5_INSTANCE = None +_CTX_MIDDLE = None +_DEFAULT_FILL = None +_DEFAULT_LEADMULT = None +_DEFAULT_STROKE = None +_DEFAULT_TEXT_FILL = None +ADD = None +ALT = None +ARROW = None +AUTO = None +AXES = None +BACKSPACE = None +BASELINE = None +BEVEL = None +BEZIER = None +BLEND = None +BLUR = None +BOLD = None +BOLDITALIC = None +BOTTOM = None +BURN = None +CENTER = None +CHORD = None +CLAMP = None +CLOSE = None +CONTROL = None +CORNER = None +CORNERS = None +CROSS = None +CURVE = None +DARKEST = None +DEG_TO_RAD = None +DEGREES = None +DELETE = None +DIFFERENCE = None +DILATE = None +DODGE = None +DOWN_ARROW = None +ENTER = None +ERODE = None +ESCAPE = None +EXCLUSION = None +FILL = None +GRAY = None +GRID = None +HALF_PI = None +HAND = None +HARD_LIGHT = None +HSB = None +HSL = None +IMAGE = None +IMMEDIATE = None +INVERT = None +ITALIC = None +LANDSCAPE = None +LEFT = None +LEFT_ARROW = None +LIGHTEST = None +LINE_LOOP = None +LINE_STRIP = None +LINEAR = None +LINES = None +MIRROR = None +MITER = None +MOVE = None +MULTIPLY = None +NEAREST = None +NORMAL = None +OPAQUE = None +OPEN = None +OPTION = None +OVERLAY = None +PI = None +PIE = None +POINTS = None +PORTRAIT = None +POSTERIZE = None +PROJECT = None +QUAD_STRIP = None +QUADRATIC = None +QUADS = None +QUARTER_PI = None +RAD_TO_DEG = None +RADIANS = None +RADIUS = None +REPEAT = None +REPLACE = None +RETURN = None +RGB = None +RIGHT = None +RIGHT_ARROW = None +ROUND = None +SCREEN = None +SHIFT = None +SOFT_LIGHT = None +SQUARE = None +STROKE = None +SUBTRACT = None +TAB = None +TAU = None +TEXT = None +TEXTURE = None +THRESHOLD = None +TOP = None +TRIANGLE_FAN = None +TRIANGLE_STRIP = None +TRIANGLES = None +TWO_PI = None +UP_ARROW = None +WAIT = None +WEBGL = None +P2D = None +PI = None +frameCount = None +focused = None +displayWidth = None +displayHeight = None +windowWidth = None +windowHeight = None +width = None +height = None +disableFriendlyErrors = None +deviceOrientation = None +accelerationX = None +accelerationY = None +accelerationZ = None +pAccelerationX = None +pAccelerationY = None +pAccelerationZ = None +rotationX = None +rotationY = None +rotationZ = None +pRotationX = None +pRotationY = None +pRotationZ = None +turnAxis = None +keyIsPressed = None +key = None +keyCode = None +mouseX = None +mouseY = None +pmouseX = None +pmouseY = None +winMouseX = None +winMouseY = None +pwinMouseX = None +pwinMouseY = None +mouseButton = None +mouseIsPressed = None +touches = None +pixels = None + def alpha(*args): @@ -232,9 +383,6 @@ def push(*args): def redraw(*args): return _P5_INSTANCE.redraw(*args) -def createCanvas(*args): - return _P5_INSTANCE.createCanvas(*args) - def resizeCanvas(*args): return _P5_INSTANCE.resizeCanvas(*args) @@ -686,6 +834,13 @@ def setCamera(*args): return _P5_INSTANCE.setCamera(*args) +def createCanvas(*args): + result = _P5_INSTANCE.createCanvas(*args) + + global width, height + width = _P5_INSTANCE.width + height = _P5_INSTANCE.height + def pop(*args): __pragma__('noalias', 'pop') @@ -693,87 +848,124 @@ def pop(*args): __pragma__('alias', 'pop', 'py_pop') return p5_pop -HALF_PI = None -PI = None -QUARTER_PI = None -TAU = None -TWO_PI = None -DEGREES = None -RADIANS = None -CLOSE = None -RGB = None -HSB = None -CMYK = None -TOP = None -BOTTOM = None -CENTER = None -LEFT = None -RIGHT = None -SHIFT = None -WEBGL = None -frameCount = None -focused = None -displayWidth = None -displayHeight = None -windowWidth = None -windowHeight = None -width = None -height = None -disableFriendlyErrors = None -deviceOrientation = None -accelerationX = None -accelerationY = None -accelerationZ = None -pAccelerationX = None -pAccelerationY = None -pAccelerationZ = None -rotationX = None -rotationY = None -rotationZ = None -pRotationX = None -pRotationY = None -pRotationZ = None -turnAxis = None -keyIsPressed = None -key = None -keyCode = None -mouseX = None -mouseY = None -pmouseX = None -pmouseY = None -winMouseX = None -winMouseY = None -pwinMouseX = None -pwinMouseY = None -mouseButton = None -mouseIsPressed = None -touches = None -pixels = None - def pre_draw(p5_instance, draw_func): """ We need to run this before the actual draw to insert and update p5 env variables """ - global HALF_PI, PI, QUARTER_PI, TAU, TWO_PI, DEGREES, RADIANS, CLOSE, RGB, HSB, CMYK, TOP, BOTTOM, CENTER, LEFT, RIGHT, SHIFT, WEBGL, frameCount, focused, displayWidth, displayHeight, windowWidth, windowHeight, width, height, disableFriendlyErrors, deviceOrientation, accelerationX, accelerationY, accelerationZ, pAccelerationX, pAccelerationY, pAccelerationZ, rotationX, rotationY, rotationZ, pRotationX, pRotationY, pRotationZ, turnAxis, keyIsPressed, key, keyCode, mouseX, mouseY, pmouseX, pmouseY, winMouseX, winMouseY, pwinMouseX, pwinMouseY, mouseButton, mouseIsPressed, touches, pixels - + global _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEG_TO_RAD, DEGREES, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINE_LOOP, LINE_STRIP, LINEAR, LINES, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUAD_STRIP, QUADRATIC, QUADS, QUARTER_PI, RAD_TO_DEG, RADIANS, RADIUS, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLE_FAN, TRIANGLE_STRIP, TRIANGLES, TWO_PI, UP_ARROW, WAIT, WEBGL, P2D, PI, frameCount, focused, displayWidth, displayHeight, windowWidth, windowHeight, width, height, disableFriendlyErrors, deviceOrientation, accelerationX, accelerationY, accelerationZ, pAccelerationX, pAccelerationY, pAccelerationZ, rotationX, rotationY, rotationZ, pRotationX, pRotationY, pRotationZ, turnAxis, keyIsPressed, key, keyCode, mouseX, mouseY, pmouseX, pmouseY, winMouseX, winMouseY, pwinMouseX, pwinMouseY, mouseButton, mouseIsPressed, touches, pixels + + _CTX_MIDDLE = p5_instance._CTX_MIDDLE + _DEFAULT_FILL = p5_instance._DEFAULT_FILL + _DEFAULT_LEADMULT = p5_instance._DEFAULT_LEADMULT + _DEFAULT_STROKE = p5_instance._DEFAULT_STROKE + _DEFAULT_TEXT_FILL = p5_instance._DEFAULT_TEXT_FILL + ADD = p5_instance.ADD + ALT = p5_instance.ALT + ARROW = p5_instance.ARROW + AUTO = p5_instance.AUTO + AXES = p5_instance.AXES + BACKSPACE = p5_instance.BACKSPACE + BASELINE = p5_instance.BASELINE + BEVEL = p5_instance.BEVEL + BEZIER = p5_instance.BEZIER + BLEND = p5_instance.BLEND + BLUR = p5_instance.BLUR + BOLD = p5_instance.BOLD + BOLDITALIC = p5_instance.BOLDITALIC + BOTTOM = p5_instance.BOTTOM + BURN = p5_instance.BURN + CENTER = p5_instance.CENTER + CHORD = p5_instance.CHORD + CLAMP = p5_instance.CLAMP + CLOSE = p5_instance.CLOSE + CONTROL = p5_instance.CONTROL + CORNER = p5_instance.CORNER + CORNERS = p5_instance.CORNERS + CROSS = p5_instance.CROSS + CURVE = p5_instance.CURVE + DARKEST = p5_instance.DARKEST + DEG_TO_RAD = p5_instance.DEG_TO_RAD + DEGREES = p5_instance.DEGREES + DELETE = p5_instance.DELETE + DIFFERENCE = p5_instance.DIFFERENCE + DILATE = p5_instance.DILATE + DODGE = p5_instance.DODGE + DOWN_ARROW = p5_instance.DOWN_ARROW + ENTER = p5_instance.ENTER + ERODE = p5_instance.ERODE + ESCAPE = p5_instance.ESCAPE + EXCLUSION = p5_instance.EXCLUSION + FILL = p5_instance.FILL + GRAY = p5_instance.GRAY + GRID = p5_instance.GRID HALF_PI = p5_instance.HALF_PI + HAND = p5_instance.HAND + HARD_LIGHT = p5_instance.HARD_LIGHT + HSB = p5_instance.HSB + HSL = p5_instance.HSL + IMAGE = p5_instance.IMAGE + IMMEDIATE = p5_instance.IMMEDIATE + INVERT = p5_instance.INVERT + ITALIC = p5_instance.ITALIC + LANDSCAPE = p5_instance.LANDSCAPE + LEFT = p5_instance.LEFT + LEFT_ARROW = p5_instance.LEFT_ARROW + LIGHTEST = p5_instance.LIGHTEST + LINE_LOOP = p5_instance.LINE_LOOP + LINE_STRIP = p5_instance.LINE_STRIP + LINEAR = p5_instance.LINEAR + LINES = p5_instance.LINES + MIRROR = p5_instance.MIRROR + MITER = p5_instance.MITER + MOVE = p5_instance.MOVE + MULTIPLY = p5_instance.MULTIPLY + NEAREST = p5_instance.NEAREST + NORMAL = p5_instance.NORMAL + OPAQUE = p5_instance.OPAQUE + OPEN = p5_instance.OPEN + OPTION = p5_instance.OPTION + OVERLAY = p5_instance.OVERLAY PI = p5_instance.PI + PIE = p5_instance.PIE + POINTS = p5_instance.POINTS + PORTRAIT = p5_instance.PORTRAIT + POSTERIZE = p5_instance.POSTERIZE + PROJECT = p5_instance.PROJECT + QUAD_STRIP = p5_instance.QUAD_STRIP + QUADRATIC = p5_instance.QUADRATIC + QUADS = p5_instance.QUADS QUARTER_PI = p5_instance.QUARTER_PI - TAU = p5_instance.TAU - TWO_PI = p5_instance.TWO_PI - DEGREES = p5_instance.DEGREES + RAD_TO_DEG = p5_instance.RAD_TO_DEG RADIANS = p5_instance.RADIANS - CLOSE = p5_instance.CLOSE + RADIUS = p5_instance.RADIUS + REPEAT = p5_instance.REPEAT + REPLACE = p5_instance.REPLACE + RETURN = p5_instance.RETURN RGB = p5_instance.RGB - HSB = p5_instance.HSB - CMYK = p5_instance.CMYK - TOP = p5_instance.TOP - BOTTOM = p5_instance.BOTTOM - CENTER = p5_instance.CENTER - LEFT = p5_instance.LEFT RIGHT = p5_instance.RIGHT + RIGHT_ARROW = p5_instance.RIGHT_ARROW + ROUND = p5_instance.ROUND + SCREEN = p5_instance.SCREEN SHIFT = p5_instance.SHIFT + SOFT_LIGHT = p5_instance.SOFT_LIGHT + SQUARE = p5_instance.SQUARE + STROKE = p5_instance.STROKE + SUBTRACT = p5_instance.SUBTRACT + TAB = p5_instance.TAB + TAU = p5_instance.TAU + TEXT = p5_instance.TEXT + TEXTURE = p5_instance.TEXTURE + THRESHOLD = p5_instance.THRESHOLD + TOP = p5_instance.TOP + TRIANGLE_FAN = p5_instance.TRIANGLE_FAN + TRIANGLE_STRIP = p5_instance.TRIANGLE_STRIP + TRIANGLES = p5_instance.TRIANGLES + TWO_PI = p5_instance.TWO_PI + UP_ARROW = p5_instance.UP_ARROW + WAIT = p5_instance.WAIT WEBGL = p5_instance.WEBGL + P2D = p5_instance.P2D + PI = p5_instance.PI frameCount = p5_instance.frameCount focused = p5_instance.focused displayWidth = p5_instance.displayWidth @@ -853,7 +1045,7 @@ def sketch_setup(p5_sketch): # inject event functions into p5 event_function_names = ["deviceMoved", "deviceTurned", "deviceShaken", "keyPressed", "keyReleased", "keyTyped", "mouseMoved", "mouseDragged", "mousePressed", "mouseReleased", "mouseClicked", "doubleClicked", "mouseWheel", "touchStarted", "touchMoved", "touchEnded", "windowResized", ] - for f_name in [f for f in event_function_names if f in event_functions]: + for f_name in [f for f in event_function_names if event_functions.get(f, None)]: func = event_functions[f_name] event_func = global_p5_injection(instance)(func) setattr(instance, f_name, event_func) \ No newline at end of file diff --git a/docs/examples/sketch_006/target/sketch_006.js b/docs/examples/sketch_006/target/sketch_006.js index d34176dd..4bd7bc80 100644 --- a/docs/examples/sketch_006/target/sketch_006.js +++ b/docs/examples/sketch_006/target/sketch_006.js @@ -1,7 +1,7 @@ -// Transcrypt'ed from Python, 2019-05-09 00:40:46 +// Transcrypt'ed from Python, 2019-06-01 16:39:10 import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, input, isinstance, issubclass, len, list, object, ord, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; -import {BOTTOM, CENTER, CLOSE, CMYK, DEGREES, HALF_PI, HSB, LEFT, PI, QUARTER_PI, RADIANS, RGB, RIGHT, SHIFT, TAU, TOP, TWO_PI, WEBGL, _P5_INSTANCE, abs, accelerationX, accelerationY, accelerationZ, acos, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, char, circle, color, colorMode, concat, cone, constrain, copy, cos, createCamera, createCanvas, createGraphics, createImage, createNumberDict, createShader, createStringDict, createVector, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, deviceOrientation, directionalLight, disableFriendlyErrors, displayDensity, displayHeight, displayWidth, dist, ellipse, ellipseMode, ellipsoid, endContour, endShape, exp, fill, filter, float, floor, focused, frameCount, frameRate, fullscreen, getURL, getURLParams, getURLPath, global_p5_injection, green, height, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, int, join, key, keyCode, keyIsDown, keyIsPressed, lerp, lerpColor, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, mouseButton, mouseIsPressed, mouseX, mouseY, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noFill, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normalMaterial, orbitControl, ortho, pAccelerationX, pAccelerationY, pAccelerationZ, pRotationX, pRotationY, pRotationZ, perspective, pixelDensity, pixels, plane, pmouseX, pmouseY, point, pointLight, pow, pre_draw, preload, print, push, pwinMouseX, pwinMouseY, py_clear, py_get, py_pop, py_sort, py_split, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, remove, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, rotationX, rotationY, rotationZ, round, saturation, save, saveCanvas, saveFrames, saveJSON, saveStrings, saveTable, scale, second, set, setAttributes, setCamera, setMoveThreshold, setShakeThreshold, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, specularMaterial, sphere, splice, splitTokens, sq, sqrt, square, start_p5, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, touches, translate, triangle, trim, turnAxis, unchar, unhex, updatePixels, vertex, width, winMouseX, winMouseY, windowHeight, windowWidth, year} from './pytop5js.js'; -var __name__ = '__main__'; +import {ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEGREES, DEG_TO_RAD, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINEAR, LINES, LINE_LOOP, LINE_STRIP, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, P2D, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUADRATIC, QUADS, QUAD_STRIP, QUARTER_PI, RADIANS, RADIUS, RAD_TO_DEG, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, TWO_PI, UP_ARROW, WAIT, WEBGL, _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, _P5_INSTANCE, abs, accelerationX, accelerationY, accelerationZ, acos, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, char, circle, color, colorMode, concat, cone, constrain, copy, cos, createCamera, createCanvas, createGraphics, createImage, createNumberDict, createShader, createStringDict, createVector, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, deviceOrientation, directionalLight, disableFriendlyErrors, displayDensity, displayHeight, displayWidth, dist, ellipse, ellipseMode, ellipsoid, endContour, endShape, exp, fill, filter, float, floor, focused, frameCount, frameRate, fullscreen, getURL, getURLParams, getURLPath, global_p5_injection, green, height, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, int, join, key, keyCode, keyIsDown, keyIsPressed, lerp, lerpColor, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, mouseButton, mouseIsPressed, mouseX, mouseY, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noFill, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normalMaterial, orbitControl, ortho, pAccelerationX, pAccelerationY, pAccelerationZ, pRotationX, pRotationY, pRotationZ, perspective, pixelDensity, pixels, plane, pmouseX, pmouseY, point, pointLight, pow, pre_draw, preload, print, push, pwinMouseX, pwinMouseY, py_clear, py_get, py_pop, py_sort, py_split, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, remove, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, rotationX, rotationY, rotationZ, round, saturation, save, saveCanvas, saveFrames, saveJSON, saveStrings, saveTable, scale, second, set, setAttributes, setCamera, setMoveThreshold, setShakeThreshold, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, specularMaterial, sphere, splice, splitTokens, sq, sqrt, square, start_p5, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, touches, translate, triangle, trim, turnAxis, unchar, unhex, updatePixels, vertex, width, winMouseX, winMouseY, windowHeight, windowWidth, year} from './pytop5js.js'; +var __name__ = 'sketch_006'; export var r = null; export var setup = function () { createCanvas (900, 900); @@ -25,7 +25,5 @@ export var mouseDragged = function () { r = random (100, 700); redraw (); }; -export var event_functions = dict ({'keyPressed': keyPressed, 'mouseDragged': mouseDragged}); -start_p5 (setup, draw, event_functions); //# sourceMappingURL=sketch_006.map \ No newline at end of file diff --git a/docs/examples/sketch_006/target/sketch_006.options b/docs/examples/sketch_006/target/sketch_006.options deleted file mode 100644 index 213bf2f0e1c2b985291dbaad0ceaa25eca737561..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 604 zcmYLG%XZT+5KT#6yrJb$-V_RLS=8OYXJoA%N0z6F6Is%gWY=DB4$JtjQ8ejcC5`6J zeT@E2|6p<<_9v4`u&q~w9dWWLRut9Z_x1I!;{Wx^4Y((EQ(GEiF&*=q)OBMk?2ckD zb;`EZ753KRAQj3sPE(J4?p0RFh=VcrDj5R#h(l(n)PmFs_qP@GG0i;~vs$I?91pkm zMmjti#bKhaj1AG(4v)9|AtwGO+ah`*JRQX}At`itHp>QYl++r}`F&0XM~ttPH64yw ze;G3B#a*?cA>btgmthn46}MKm($524v!Mjz7$=-j*NRLaykWJC^|$Nn!q}!Zc(=~^ ztg{{7Goh27OvHy-_U&7PkIWT@rnEZX6UPWQ);IXfmSXmP${T7;9r0zBm)wyrZ8Gq6 z6gz1RJyjV1fJwq?L~=IWh{3!ID7gfAAhp`s*jq_1p2rVE7|+|T9Rfs34` RkF^5n;DOjp2x*MPbj+ht*Nv^P zJBq#3Dcf3C*jtN(R4CgxO+EIxS6L+^4#wQ8WC-LV4wF{I}hl##2Hbh@LJl*n#nE0P18xbp4B$iKdiG0W1HIG zWS#R_XFGgkLMJ_$h)=WZ+qVXvnJWxUX?4ICjuCFHZ}62Z#q9l*H`JOs;@d1Qxg%fN zWZ?TKcG4Ppobhy@cGKerOZIbZ%YdKE)jJs%I2Wf0Uo31xMM>UBU)h387YaAH-^=?0 U7dcHIYct@I_0uPK{2JS<|CHOQ9RL6T literal 0 HcmV?d00001 diff --git a/docs/examples/sketch_006/target/target_sketch.py b/docs/examples/sketch_006/target/target_sketch.py new file mode 100644 index 00000000..0125a76d --- /dev/null +++ b/docs/examples/sketch_006/target/target_sketch.py @@ -0,0 +1,24 @@ +import sketch_006 as source_sketch +from pytop5js import * + +event_functions = { + "deviceMoved": source_sketch.deviceMoved, + "deviceTurned": source_sketch.deviceTurned, + "deviceShaken": source_sketch.deviceShaken, + "keyPressed": source_sketch.keyPressed, + "keyReleased": source_sketch.keyReleased, + "keyTyped": source_sketch.keyTyped, + "mouseMoved": source_sketch.mouseMoved, + "mouseDragged": source_sketch.mouseDragged, + "mousePressed": source_sketch.mousePressed, + "mouseReleased": source_sketch.mouseReleased, + "mouseClicked": source_sketch.mouseClicked, + "doubleClicked": source_sketch.doubleClicked, + "mouseWheel": source_sketch.mouseWheel, + "touchStarted": source_sketch.touchStarted, + "touchMoved": source_sketch.touchMoved, + "touchEnded": source_sketch.touchEnded, + "windowResized": source_sketch.windowResized, +} + +start_p5(source_sketch.setup, source_sketch.draw, event_functions) \ No newline at end of file diff --git a/docs/examples/sketch_007/sketch_007.py b/docs/examples/sketch_007/sketch_007.py index 2b1205ee..1974a20a 100644 --- a/docs/examples/sketch_007/sketch_007.py +++ b/docs/examples/sketch_007/sketch_007.py @@ -17,12 +17,3 @@ def draw(): line(0, 0, v.x, v.y) pop() - - -# ==== This is required by pyp5js to work - -# Register your events functions here -event_functions = { - # "keyPressed": keyPressed, as an example -} -start_p5(setup, draw, event_functions) diff --git a/docs/examples/sketch_007/target/org.transcrypt.__runtime__.js b/docs/examples/sketch_007/target/org.transcrypt.__runtime__.js index af0ffc3d..ae8d3722 100644 --- a/docs/examples/sketch_007/target/org.transcrypt.__runtime__.js +++ b/docs/examples/sketch_007/target/org.transcrypt.__runtime__.js @@ -1,4 +1,4 @@ -// Transcrypt'ed from Python, 2019-05-21 18:55:45 +// Transcrypt'ed from Python, 2019-06-01 16:39:11 var __name__ = 'org.transcrypt.__runtime__'; export var __envir__ = {}; __envir__.interpreter_name = 'python'; diff --git a/docs/examples/sketch_007/target/pytop5js.js b/docs/examples/sketch_007/target/pytop5js.js index 39fa7f88..9c558ab7 100644 --- a/docs/examples/sketch_007/target/pytop5js.js +++ b/docs/examples/sketch_007/target/pytop5js.js @@ -1,7 +1,157 @@ -// Transcrypt'ed from Python, 2019-05-21 18:55:45 +// Transcrypt'ed from Python, 2019-06-01 16:39:12 import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, input, isinstance, issubclass, len, list, object, ord, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; var __name__ = 'pytop5js'; export var _P5_INSTANCE = null; +export var _CTX_MIDDLE = null; +export var _DEFAULT_FILL = null; +export var _DEFAULT_LEADMULT = null; +export var _DEFAULT_STROKE = null; +export var _DEFAULT_TEXT_FILL = null; +export var ADD = null; +export var ALT = null; +export var ARROW = null; +export var AUTO = null; +export var AXES = null; +export var BACKSPACE = null; +export var BASELINE = null; +export var BEVEL = null; +export var BEZIER = null; +export var BLEND = null; +export var BLUR = null; +export var BOLD = null; +export var BOLDITALIC = null; +export var BOTTOM = null; +export var BURN = null; +export var CENTER = null; +export var CHORD = null; +export var CLAMP = null; +export var CLOSE = null; +export var CONTROL = null; +export var CORNER = null; +export var CORNERS = null; +export var CROSS = null; +export var CURVE = null; +export var DARKEST = null; +export var DEG_TO_RAD = null; +export var DEGREES = null; +export var DELETE = null; +export var DIFFERENCE = null; +export var DILATE = null; +export var DODGE = null; +export var DOWN_ARROW = null; +export var ENTER = null; +export var ERODE = null; +export var ESCAPE = null; +export var EXCLUSION = null; +export var FILL = null; +export var GRAY = null; +export var GRID = null; +export var HALF_PI = null; +export var HAND = null; +export var HARD_LIGHT = null; +export var HSB = null; +export var HSL = null; +export var IMAGE = null; +export var IMMEDIATE = null; +export var INVERT = null; +export var ITALIC = null; +export var LANDSCAPE = null; +export var LEFT = null; +export var LEFT_ARROW = null; +export var LIGHTEST = null; +export var LINE_LOOP = null; +export var LINE_STRIP = null; +export var LINEAR = null; +export var LINES = null; +export var MIRROR = null; +export var MITER = null; +export var MOVE = null; +export var MULTIPLY = null; +export var NEAREST = null; +export var NORMAL = null; +export var OPAQUE = null; +export var OPEN = null; +export var OPTION = null; +export var OVERLAY = null; +export var PI = null; +export var PIE = null; +export var POINTS = null; +export var PORTRAIT = null; +export var POSTERIZE = null; +export var PROJECT = null; +export var QUAD_STRIP = null; +export var QUADRATIC = null; +export var QUADS = null; +export var QUARTER_PI = null; +export var RAD_TO_DEG = null; +export var RADIANS = null; +export var RADIUS = null; +export var REPEAT = null; +export var REPLACE = null; +export var RETURN = null; +export var RGB = null; +export var RIGHT = null; +export var RIGHT_ARROW = null; +export var ROUND = null; +export var SCREEN = null; +export var SHIFT = null; +export var SOFT_LIGHT = null; +export var SQUARE = null; +export var STROKE = null; +export var SUBTRACT = null; +export var TAB = null; +export var TAU = null; +export var TEXT = null; +export var TEXTURE = null; +export var THRESHOLD = null; +export var TOP = null; +export var TRIANGLE_FAN = null; +export var TRIANGLE_STRIP = null; +export var TRIANGLES = null; +export var TWO_PI = null; +export var UP_ARROW = null; +export var WAIT = null; +export var WEBGL = null; +export var P2D = null; +var PI = null; +export var frameCount = null; +export var focused = null; +export var displayWidth = null; +export var displayHeight = null; +export var windowWidth = null; +export var windowHeight = null; +export var width = null; +export var height = null; +export var disableFriendlyErrors = null; +export var deviceOrientation = null; +export var accelerationX = null; +export var accelerationY = null; +export var accelerationZ = null; +export var pAccelerationX = null; +export var pAccelerationY = null; +export var pAccelerationZ = null; +export var rotationX = null; +export var rotationY = null; +export var rotationZ = null; +export var pRotationX = null; +export var pRotationY = null; +export var pRotationZ = null; +export var turnAxis = null; +export var keyIsPressed = null; +export var key = null; +export var keyCode = null; +export var mouseX = null; +export var mouseY = null; +export var pmouseX = null; +export var pmouseY = null; +export var winMouseX = null; +export var winMouseY = null; +export var pwinMouseX = null; +export var pwinMouseY = null; +export var mouseButton = null; +export var mouseIsPressed = null; +export var touches = null; +export var pixels = null; export var alpha = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.alpha (...args); @@ -310,10 +460,6 @@ export var redraw = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.redraw (...args); }; -export var createCanvas = function () { - var args = tuple ([].slice.apply (arguments).slice (0)); - return _P5_INSTANCE.createCanvas (...args); -}; export var resizeCanvas = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.resizeCanvas (...args); @@ -914,161 +1060,17 @@ export var setCamera = function () { var args = tuple ([].slice.apply (arguments).slice (0)); return _P5_INSTANCE.setCamera (...args); }; +export var createCanvas = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + var result = _P5_INSTANCE.createCanvas (...args); + width = _P5_INSTANCE.width; + height = _P5_INSTANCE.height; +}; export var py_pop = function () { var args = tuple ([].slice.apply (arguments).slice (0)); var p5_pop = _P5_INSTANCE.pop (...args); return p5_pop; }; -export var _CTX_MIDDLE = null; -export var _DEFAULT_FILL = null; -export var _DEFAULT_LEADMULT = null; -export var _DEFAULT_STROKE = null; -export var _DEFAULT_TEXT_FILL = null; -export var ADD = null; -export var ALT = null; -export var ARROW = null; -export var AUTO = null; -export var AXES = null; -export var BACKSPACE = null; -export var BASELINE = null; -export var BEVEL = null; -export var BEZIER = null; -export var BLEND = null; -export var BLUR = null; -export var BOLD = null; -export var BOLDITALIC = null; -export var BOTTOM = null; -export var BURN = null; -export var CENTER = null; -export var CHORD = null; -export var CLAMP = null; -export var CLOSE = null; -export var CONTROL = null; -export var CORNER = null; -export var CORNERS = null; -export var CROSS = null; -export var CURVE = null; -export var DARKEST = null; -export var DEG_TO_RAD = null; -export var DEGREES = null; -export var DELETE = null; -export var DIFFERENCE = null; -export var DILATE = null; -export var DODGE = null; -export var DOWN_ARROW = null; -export var ENTER = null; -export var ERODE = null; -export var ESCAPE = null; -export var EXCLUSION = null; -export var FILL = null; -export var GRAY = null; -export var GRID = null; -export var HALF_PI = null; -export var HAND = null; -export var HARD_LIGHT = null; -export var HSB = null; -export var HSL = null; -export var IMAGE = null; -export var IMMEDIATE = null; -export var INVERT = null; -export var ITALIC = null; -export var LANDSCAPE = null; -export var LEFT = null; -export var LEFT_ARROW = null; -export var LIGHTEST = null; -export var LINE_LOOP = null; -export var LINE_STRIP = null; -export var LINEAR = null; -export var LINES = null; -export var MIRROR = null; -export var MITER = null; -export var MOVE = null; -export var MULTIPLY = null; -export var NEAREST = null; -export var NORMAL = null; -export var OPAQUE = null; -export var OPEN = null; -export var OPTION = null; -export var OVERLAY = null; -export var PI = null; -export var PIE = null; -export var POINTS = null; -export var PORTRAIT = null; -export var POSTERIZE = null; -export var PROJECT = null; -export var QUAD_STRIP = null; -export var QUADRATIC = null; -export var QUADS = null; -export var QUARTER_PI = null; -export var RAD_TO_DEG = null; -export var RADIANS = null; -export var RADIUS = null; -export var REPEAT = null; -export var REPLACE = null; -export var RETURN = null; -export var RGB = null; -export var RIGHT = null; -export var RIGHT_ARROW = null; -export var ROUND = null; -export var SCREEN = null; -export var SHIFT = null; -export var SOFT_LIGHT = null; -export var SQUARE = null; -export var STROKE = null; -export var SUBTRACT = null; -export var TAB = null; -export var TAU = null; -export var TEXT = null; -export var TEXTURE = null; -export var THRESHOLD = null; -export var TOP = null; -export var TRIANGLE_FAN = null; -export var TRIANGLE_STRIP = null; -export var TRIANGLES = null; -export var TWO_PI = null; -export var UP_ARROW = null; -export var WAIT = null; -export var WEBGL = null; -export var P2D = null; -var PI = null; -export var frameCount = null; -export var focused = null; -export var displayWidth = null; -export var displayHeight = null; -export var windowWidth = null; -export var windowHeight = null; -export var width = null; -export var height = null; -export var disableFriendlyErrors = null; -export var deviceOrientation = null; -export var accelerationX = null; -export var accelerationY = null; -export var accelerationZ = null; -export var pAccelerationX = null; -export var pAccelerationY = null; -export var pAccelerationZ = null; -export var rotationX = null; -export var rotationY = null; -export var rotationZ = null; -export var pRotationX = null; -export var pRotationY = null; -export var pRotationZ = null; -export var turnAxis = null; -export var keyIsPressed = null; -export var key = null; -export var keyCode = null; -export var mouseX = null; -export var mouseY = null; -export var pmouseX = null; -export var pmouseY = null; -export var winMouseX = null; -export var winMouseY = null; -export var pwinMouseX = null; -export var pwinMouseY = null; -export var mouseButton = null; -export var mouseIsPressed = null; -export var touches = null; -export var pixels = null; export var pre_draw = function (p5_instance, draw_func) { _CTX_MIDDLE = p5_instance._CTX_MIDDLE; _DEFAULT_FILL = p5_instance._DEFAULT_FILL; @@ -1242,7 +1244,7 @@ export var start_p5 = function (setup_func, draw_func, event_functions) { for (var f_name of (function () { var __accu0__ = []; for (var f of event_function_names) { - if (__in__ (f, event_functions)) { + if (event_functions.py_get (f, null)) { __accu0__.append (f); } } diff --git a/docs/examples/sketch_007/target/pytop5js.py b/docs/examples/sketch_007/target/pytop5js.py index 6e5d2d85..6462430c 100644 --- a/docs/examples/sketch_007/target/pytop5js.py +++ b/docs/examples/sketch_007/target/pytop5js.py @@ -1,4 +1,155 @@ _P5_INSTANCE = None +_CTX_MIDDLE = None +_DEFAULT_FILL = None +_DEFAULT_LEADMULT = None +_DEFAULT_STROKE = None +_DEFAULT_TEXT_FILL = None +ADD = None +ALT = None +ARROW = None +AUTO = None +AXES = None +BACKSPACE = None +BASELINE = None +BEVEL = None +BEZIER = None +BLEND = None +BLUR = None +BOLD = None +BOLDITALIC = None +BOTTOM = None +BURN = None +CENTER = None +CHORD = None +CLAMP = None +CLOSE = None +CONTROL = None +CORNER = None +CORNERS = None +CROSS = None +CURVE = None +DARKEST = None +DEG_TO_RAD = None +DEGREES = None +DELETE = None +DIFFERENCE = None +DILATE = None +DODGE = None +DOWN_ARROW = None +ENTER = None +ERODE = None +ESCAPE = None +EXCLUSION = None +FILL = None +GRAY = None +GRID = None +HALF_PI = None +HAND = None +HARD_LIGHT = None +HSB = None +HSL = None +IMAGE = None +IMMEDIATE = None +INVERT = None +ITALIC = None +LANDSCAPE = None +LEFT = None +LEFT_ARROW = None +LIGHTEST = None +LINE_LOOP = None +LINE_STRIP = None +LINEAR = None +LINES = None +MIRROR = None +MITER = None +MOVE = None +MULTIPLY = None +NEAREST = None +NORMAL = None +OPAQUE = None +OPEN = None +OPTION = None +OVERLAY = None +PI = None +PIE = None +POINTS = None +PORTRAIT = None +POSTERIZE = None +PROJECT = None +QUAD_STRIP = None +QUADRATIC = None +QUADS = None +QUARTER_PI = None +RAD_TO_DEG = None +RADIANS = None +RADIUS = None +REPEAT = None +REPLACE = None +RETURN = None +RGB = None +RIGHT = None +RIGHT_ARROW = None +ROUND = None +SCREEN = None +SHIFT = None +SOFT_LIGHT = None +SQUARE = None +STROKE = None +SUBTRACT = None +TAB = None +TAU = None +TEXT = None +TEXTURE = None +THRESHOLD = None +TOP = None +TRIANGLE_FAN = None +TRIANGLE_STRIP = None +TRIANGLES = None +TWO_PI = None +UP_ARROW = None +WAIT = None +WEBGL = None +P2D = None +PI = None +frameCount = None +focused = None +displayWidth = None +displayHeight = None +windowWidth = None +windowHeight = None +width = None +height = None +disableFriendlyErrors = None +deviceOrientation = None +accelerationX = None +accelerationY = None +accelerationZ = None +pAccelerationX = None +pAccelerationY = None +pAccelerationZ = None +rotationX = None +rotationY = None +rotationZ = None +pRotationX = None +pRotationY = None +pRotationZ = None +turnAxis = None +keyIsPressed = None +key = None +keyCode = None +mouseX = None +mouseY = None +pmouseX = None +pmouseY = None +winMouseX = None +winMouseY = None +pwinMouseX = None +pwinMouseY = None +mouseButton = None +mouseIsPressed = None +touches = None +pixels = None + def alpha(*args): @@ -232,9 +383,6 @@ def push(*args): def redraw(*args): return _P5_INSTANCE.redraw(*args) -def createCanvas(*args): - return _P5_INSTANCE.createCanvas(*args) - def resizeCanvas(*args): return _P5_INSTANCE.resizeCanvas(*args) @@ -686,6 +834,13 @@ def setCamera(*args): return _P5_INSTANCE.setCamera(*args) +def createCanvas(*args): + result = _P5_INSTANCE.createCanvas(*args) + + global width, height + width = _P5_INSTANCE.width + height = _P5_INSTANCE.height + def pop(*args): __pragma__('noalias', 'pop') @@ -693,157 +848,6 @@ def pop(*args): __pragma__('alias', 'pop', 'py_pop') return p5_pop -_CTX_MIDDLE = None -_DEFAULT_FILL = None -_DEFAULT_LEADMULT = None -_DEFAULT_STROKE = None -_DEFAULT_TEXT_FILL = None -ADD = None -ALT = None -ARROW = None -AUTO = None -AXES = None -BACKSPACE = None -BASELINE = None -BEVEL = None -BEZIER = None -BLEND = None -BLUR = None -BOLD = None -BOLDITALIC = None -BOTTOM = None -BURN = None -CENTER = None -CHORD = None -CLAMP = None -CLOSE = None -CONTROL = None -CORNER = None -CORNERS = None -CROSS = None -CURVE = None -DARKEST = None -DEG_TO_RAD = None -DEGREES = None -DELETE = None -DIFFERENCE = None -DILATE = None -DODGE = None -DOWN_ARROW = None -ENTER = None -ERODE = None -ESCAPE = None -EXCLUSION = None -FILL = None -GRAY = None -GRID = None -HALF_PI = None -HAND = None -HARD_LIGHT = None -HSB = None -HSL = None -IMAGE = None -IMMEDIATE = None -INVERT = None -ITALIC = None -LANDSCAPE = None -LEFT = None -LEFT_ARROW = None -LIGHTEST = None -LINE_LOOP = None -LINE_STRIP = None -LINEAR = None -LINES = None -MIRROR = None -MITER = None -MOVE = None -MULTIPLY = None -NEAREST = None -NORMAL = None -OPAQUE = None -OPEN = None -OPTION = None -OVERLAY = None -PI = None -PIE = None -POINTS = None -PORTRAIT = None -POSTERIZE = None -PROJECT = None -QUAD_STRIP = None -QUADRATIC = None -QUADS = None -QUARTER_PI = None -RAD_TO_DEG = None -RADIANS = None -RADIUS = None -REPEAT = None -REPLACE = None -RETURN = None -RGB = None -RIGHT = None -RIGHT_ARROW = None -ROUND = None -SCREEN = None -SHIFT = None -SOFT_LIGHT = None -SQUARE = None -STROKE = None -SUBTRACT = None -TAB = None -TAU = None -TEXT = None -TEXTURE = None -THRESHOLD = None -TOP = None -TRIANGLE_FAN = None -TRIANGLE_STRIP = None -TRIANGLES = None -TWO_PI = None -UP_ARROW = None -WAIT = None -WEBGL = None -P2D = None -PI = None -frameCount = None -focused = None -displayWidth = None -displayHeight = None -windowWidth = None -windowHeight = None -width = None -height = None -disableFriendlyErrors = None -deviceOrientation = None -accelerationX = None -accelerationY = None -accelerationZ = None -pAccelerationX = None -pAccelerationY = None -pAccelerationZ = None -rotationX = None -rotationY = None -rotationZ = None -pRotationX = None -pRotationY = None -pRotationZ = None -turnAxis = None -keyIsPressed = None -key = None -keyCode = None -mouseX = None -mouseY = None -pmouseX = None -pmouseY = None -winMouseX = None -winMouseY = None -pwinMouseX = None -pwinMouseY = None -mouseButton = None -mouseIsPressed = None -touches = None -pixels = None - def pre_draw(p5_instance, draw_func): """ We need to run this before the actual draw to insert and update p5 env variables @@ -1041,7 +1045,7 @@ def sketch_setup(p5_sketch): # inject event functions into p5 event_function_names = ["deviceMoved", "deviceTurned", "deviceShaken", "keyPressed", "keyReleased", "keyTyped", "mouseMoved", "mouseDragged", "mousePressed", "mouseReleased", "mouseClicked", "doubleClicked", "mouseWheel", "touchStarted", "touchMoved", "touchEnded", "windowResized", ] - for f_name in [f for f in event_function_names if f in event_functions]: + for f_name in [f for f in event_function_names if event_functions.get(f, None)]: func = event_functions[f_name] event_func = global_p5_injection(instance)(func) setattr(instance, f_name, event_func) \ No newline at end of file diff --git a/docs/examples/sketch_007/target/sketch_007.js b/docs/examples/sketch_007/target/sketch_007.js index b5d28e70..e984ca8c 100644 --- a/docs/examples/sketch_007/target/sketch_007.js +++ b/docs/examples/sketch_007/target/sketch_007.js @@ -1,7 +1,7 @@ -// Transcrypt'ed from Python, 2019-05-21 18:55:45 +// Transcrypt'ed from Python, 2019-06-01 16:39:12 import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, input, isinstance, issubclass, len, list, object, ord, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; import {ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEGREES, DEG_TO_RAD, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINEAR, LINES, LINE_LOOP, LINE_STRIP, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, P2D, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUADRATIC, QUADS, QUAD_STRIP, QUARTER_PI, RADIANS, RADIUS, RAD_TO_DEG, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, TWO_PI, UP_ARROW, WAIT, WEBGL, _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, _P5_INSTANCE, abs, accelerationX, accelerationY, accelerationZ, acos, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, char, circle, color, colorMode, concat, cone, constrain, copy, cos, createCamera, createCanvas, createGraphics, createImage, createNumberDict, createShader, createStringDict, createVector, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, deviceOrientation, directionalLight, disableFriendlyErrors, displayDensity, displayHeight, displayWidth, dist, ellipse, ellipseMode, ellipsoid, endContour, endShape, exp, fill, filter, float, floor, focused, frameCount, frameRate, fullscreen, getURL, getURLParams, getURLPath, global_p5_injection, green, height, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, int, join, key, keyCode, keyIsDown, keyIsPressed, lerp, lerpColor, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, mouseButton, mouseIsPressed, mouseX, mouseY, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noFill, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normalMaterial, orbitControl, ortho, pAccelerationX, pAccelerationY, pAccelerationZ, pRotationX, pRotationY, pRotationZ, perspective, pixelDensity, pixels, plane, pmouseX, pmouseY, point, pointLight, pow, pre_draw, preload, print, push, pwinMouseX, pwinMouseY, py_clear, py_get, py_pop, py_sort, py_split, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, remove, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, rotationX, rotationY, rotationZ, round, saturation, save, saveCanvas, saveFrames, saveJSON, saveStrings, saveTable, scale, second, set, setAttributes, setCamera, setMoveThreshold, setShakeThreshold, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, specularMaterial, sphere, splice, splitTokens, sq, sqrt, square, start_p5, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, touches, translate, triangle, trim, turnAxis, unchar, unhex, updatePixels, vertex, width, winMouseX, winMouseY, windowHeight, windowWidth, year} from './pytop5js.js'; -var __name__ = '__main__'; +var __name__ = 'sketch_007'; export var setup = function () { createCanvas (900, 900); stroke (27, 27, 27, 10); @@ -16,7 +16,5 @@ export var draw = function () { line (0, 0, v.x, v.y); py_pop (); }; -export var event_functions = dict ({}); -start_p5 (setup, draw, event_functions); //# sourceMappingURL=sketch_007.map \ No newline at end of file diff --git a/docs/examples/sketch_007/target/sketch_007.options b/docs/examples/sketch_007/target/sketch_007.options deleted file mode 100644 index 44dafc579be7783da3fdc040ac0da2498e6192b6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 604 zcmYLG$#T>%5S=jD*dbvFJAptF4sk9Ne=%p>C|T~zct)1=B-ybKRB;^tH5&D#I7zL3 z{g&3>=^sok#QtP53AXi$up>@3#fqX@{Jy^aRs6qRxdHdYZfZ+oET&_gle%tfh22r? zrB2z_y29RC9Hc_o#%b!Y&%Mej8F4V?UL`{yA92Vmm0FNm;r_OwKBl<`V^*uQo#Wy5 z-bjZ>qc}|Tm9ZiE+Trn*Kg7iUWLrc}gr}pJCM1Op&t}=+jgng9Ils@z;E3_HvZli^ z>n}q_y|}AZGz7e4;4*CDzT(#ER{D9sYc`Z%9OHyD>ROQrgg30VvHo_QT^QTc2JhB6 zpLMpwdnRJ8+TH S^szPrE?GZ)g2#`sz4`|!Kc_1I diff --git a/docs/examples/sketch_007/target/sketch_007.py b/docs/examples/sketch_007/target/sketch_007.py index 2b1205ee..1974a20a 100644 --- a/docs/examples/sketch_007/target/sketch_007.py +++ b/docs/examples/sketch_007/target/sketch_007.py @@ -17,12 +17,3 @@ def draw(): line(0, 0, v.x, v.y) pop() - - -# ==== This is required by pyp5js to work - -# Register your events functions here -event_functions = { - # "keyPressed": keyPressed, as an example -} -start_p5(setup, draw, event_functions) diff --git a/docs/examples/sketch_007/target/target_sketch.js b/docs/examples/sketch_007/target/target_sketch.js new file mode 100644 index 00000000..0aaf0470 --- /dev/null +++ b/docs/examples/sketch_007/target/target_sketch.js @@ -0,0 +1,9 @@ +// Transcrypt'ed from Python, 2019-06-01 16:39:11 +import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, input, isinstance, issubclass, len, list, object, ord, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; +import {ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEGREES, DEG_TO_RAD, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINEAR, LINES, LINE_LOOP, LINE_STRIP, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, P2D, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUADRATIC, QUADS, QUAD_STRIP, QUARTER_PI, RADIANS, RADIUS, RAD_TO_DEG, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, TWO_PI, UP_ARROW, WAIT, WEBGL, _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, _P5_INSTANCE, abs, accelerationX, accelerationY, accelerationZ, acos, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, char, circle, color, colorMode, concat, cone, constrain, copy, cos, createCamera, createCanvas, createGraphics, createImage, createNumberDict, createShader, createStringDict, createVector, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, deviceOrientation, directionalLight, disableFriendlyErrors, displayDensity, displayHeight, displayWidth, dist, draw, ellipse, ellipseMode, ellipsoid, endContour, endShape, exp, fill, filter, float, floor, focused, frameCount, frameRate, fullscreen, getURL, getURLParams, getURLPath, global_p5_injection, green, height, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, int, join, key, keyCode, keyIsDown, keyIsPressed, lerp, lerpColor, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, mouseButton, mouseIsPressed, mouseX, mouseY, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noFill, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normalMaterial, orbitControl, ortho, pAccelerationX, pAccelerationY, pAccelerationZ, pRotationX, pRotationY, pRotationZ, perspective, pixelDensity, pixels, plane, pmouseX, pmouseY, point, pointLight, pow, pre_draw, preload, print, push, pwinMouseX, pwinMouseY, py_clear, py_get, py_pop, py_sort, py_split, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, remove, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, rotationX, rotationY, rotationZ, round, saturation, save, saveCanvas, saveFrames, saveJSON, saveStrings, saveTable, scale, second, set, setAttributes, setCamera, setMoveThreshold, setShakeThreshold, setup, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, specularMaterial, sphere, splice, splitTokens, sq, sqrt, square, start_p5, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, touches, translate, triangle, trim, turnAxis, unchar, unhex, updatePixels, vertex, width, winMouseX, winMouseY, windowHeight, windowWidth, year} from './pytop5js.js'; +import * as source_sketch from './sketch_007.js'; +var __name__ = '__main__'; +export var event_functions = dict ({'deviceMoved': source_sketch.deviceMoved, 'deviceTurned': source_sketch.deviceTurned, 'deviceShaken': source_sketch.deviceShaken, 'keyPressed': source_sketch.keyPressed, 'keyReleased': source_sketch.keyReleased, 'keyTyped': source_sketch.keyTyped, 'mouseMoved': source_sketch.mouseMoved, 'mouseDragged': source_sketch.mouseDragged, 'mousePressed': source_sketch.mousePressed, 'mouseReleased': source_sketch.mouseReleased, 'mouseClicked': source_sketch.mouseClicked, 'doubleClicked': source_sketch.doubleClicked, 'mouseWheel': source_sketch.mouseWheel, 'touchStarted': source_sketch.touchStarted, 'touchMoved': source_sketch.touchMoved, 'touchEnded': source_sketch.touchEnded, 'windowResized': source_sketch.windowResized}); +start_p5 (source_sketch.setup, source_sketch.draw, event_functions); + +//# sourceMappingURL=target_sketch.map \ No newline at end of file diff --git a/docs/examples/sketch_007/target/target_sketch.options b/docs/examples/sketch_007/target/target_sketch.options new file mode 100644 index 0000000000000000000000000000000000000000..54c96fd656b3c78ce02aaf2beede076f0b375dd8 GIT binary patch literal 607 zcmXw0xpLbu5S1fexf46Lb2)KhJB8^clfO`n&I5vLi4q9l0U%8lnMo=Bbs(%<0gHY6 zj>W&}Ura8<{$w%bkKN zc1N+7I%Qky3VUmDkP2lRr>Vz2_bRJo#KD+*l?;J=#38d(YC&p+huez!nC2dhS*_A` zj>p@3BORWM;xN%y#)jx?ho@Wq5EK8iZ4o^Yo{wUhkQ6$+m}P^vN@|Ul{5~gxBgWUt znhwXTzYH1m>b_dh5b&CT%dm<2hFhzuiUQOz5O16Y*)5ef!qnGjoNZDXk9p!ZE_F^$otVrI@{+@`hSdM|_**C3oaY zn+$v(#ZFp7k29X`({6hFV99>2Z5i;Bxq2t#0_Wm1;fsZBs3^%B=_^~1=|bTK_j`GN V;3B8#V{HapvVQsmk6&YZ^&giRsU83T literal 0 HcmV?d00001 diff --git a/docs/examples/sketch_007/target/target_sketch.py b/docs/examples/sketch_007/target/target_sketch.py new file mode 100644 index 00000000..a1adafa0 --- /dev/null +++ b/docs/examples/sketch_007/target/target_sketch.py @@ -0,0 +1,24 @@ +import sketch_007 as source_sketch +from pytop5js import * + +event_functions = { + "deviceMoved": source_sketch.deviceMoved, + "deviceTurned": source_sketch.deviceTurned, + "deviceShaken": source_sketch.deviceShaken, + "keyPressed": source_sketch.keyPressed, + "keyReleased": source_sketch.keyReleased, + "keyTyped": source_sketch.keyTyped, + "mouseMoved": source_sketch.mouseMoved, + "mouseDragged": source_sketch.mouseDragged, + "mousePressed": source_sketch.mousePressed, + "mouseReleased": source_sketch.mouseReleased, + "mouseClicked": source_sketch.mouseClicked, + "doubleClicked": source_sketch.doubleClicked, + "mouseWheel": source_sketch.mouseWheel, + "touchStarted": source_sketch.touchStarted, + "touchMoved": source_sketch.touchMoved, + "touchEnded": source_sketch.touchEnded, + "windowResized": source_sketch.windowResized, +} + +start_p5(source_sketch.setup, source_sketch.draw, event_functions) \ No newline at end of file From ca9548528a9ea1db62cf72eb0dd5e3890fd399a5 Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sat, 1 Jun 2019 16:46:26 -0300 Subject: [PATCH 18/32] Update all the examples index.html --- docs/examples/sketch_001/index.html | 5 +---- docs/examples/sketch_002/index.html | 6 +----- docs/examples/sketch_003/index.html | 5 +---- docs/examples/sketch_004/index.html | 6 +----- docs/examples/sketch_005/index.html | 6 +----- docs/examples/sketch_006/index.html | 8 +------- docs/examples/sketch_007/index.html | 10 +--------- 7 files changed, 7 insertions(+), 39 deletions(-) diff --git a/docs/examples/sketch_001/index.html b/docs/examples/sketch_001/index.html index 46987897..672a57b5 100644 --- a/docs/examples/sketch_001/index.html +++ b/docs/examples/sketch_001/index.html @@ -10,7 +10,7 @@ - + @@ -76,9 +76,6 @@ t = t + 0.01 console.log(frameRate()) - - -my_p5 = start_p5(setup, draw, {}) diff --git a/docs/examples/sketch_002/index.html b/docs/examples/sketch_002/index.html index c71565a9..4e27ca9e 100644 --- a/docs/examples/sketch_002/index.html +++ b/docs/examples/sketch_002/index.html @@ -10,7 +10,7 @@ - + @@ -76,10 +76,6 @@ line(-100, 0, 0, 100, 0, 0) line(0, -100, 0, 0, 100, 0) line(0, 0, -100, 0, 0, 100) - - -# This is required by pyp5js to work -start_p5(setup, draw, {}) diff --git a/docs/examples/sketch_003/index.html b/docs/examples/sketch_003/index.html index 47ec23a3..0df954c5 100644 --- a/docs/examples/sketch_003/index.html +++ b/docs/examples/sketch_003/index.html @@ -10,7 +10,7 @@ - + @@ -62,9 +62,6 @@ rotateY(frameCount * 0.01) box(50, 70, 100) pop() - - -start_p5(setup, draw, {}) diff --git a/docs/examples/sketch_004/index.html b/docs/examples/sketch_004/index.html index 5a127c2c..40439cc6 100644 --- a/docs/examples/sketch_004/index.html +++ b/docs/examples/sketch_004/index.html @@ -10,7 +10,7 @@ - + @@ -212,10 +212,6 @@ return self.seek(sum); # Steer towards the location else: return createVector(0, 0); - - -# This is required by pyp5js to work -start_p5(setup, draw, {}) diff --git a/docs/examples/sketch_005/index.html b/docs/examples/sketch_005/index.html index eb47ff39..eff138d2 100644 --- a/docs/examples/sketch_005/index.html +++ b/docs/examples/sketch_005/index.html @@ -10,7 +10,7 @@ - + @@ -60,10 +60,6 @@ background(h,100,100) fill(100-h,100,100) rect(300,300,mouseX+1,mouseX+1) - - -# This is required by pyp5js to work -start_p5(setup, draw, {}) diff --git a/docs/examples/sketch_006/index.html b/docs/examples/sketch_006/index.html index 9124caea..0d0ce20d 100644 --- a/docs/examples/sketch_006/index.html +++ b/docs/examples/sketch_006/index.html @@ -10,7 +10,7 @@ - + @@ -75,12 +75,6 @@ global r r = random(100, 700) redraw() - -event_functions = { - 'keyPressed': keyPressed, - 'mouseDragged': mouseDragged, -} -start_p5(setup, draw, event_functions) diff --git a/docs/examples/sketch_007/index.html b/docs/examples/sketch_007/index.html index 0cc620f9..988bf625 100644 --- a/docs/examples/sketch_007/index.html +++ b/docs/examples/sketch_007/index.html @@ -10,7 +10,7 @@ - + @@ -63,14 +63,6 @@ line(0, 0, v.x, v.y) pop() - -# ==== This is required by pyp5js to work - -# Register your events functions here -event_functions = { - # "keyPressed": keyPressed, as an example -} -start_p5(setup, draw, event_functions) From f284565723f0381b06aa9045b4766efb38c12916 Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sat, 1 Jun 2019 16:47:31 -0300 Subject: [PATCH 19/32] Update the docs --- README.md | 3 --- docs/index.md | 21 +-------------------- 2 files changed, 1 insertion(+), 23 deletions(-) diff --git a/README.md b/README.md index 891ec917..e98cca36 100644 --- a/README.md +++ b/README.md @@ -17,9 +17,6 @@ def draw(): background(200) r = sin(frameCount / 60) * 50 + 50 ellipse(100, 100, r, r) - - -start_p5(setup, draw, {}) ``` ### [Documentation](https://berinhard.github.io/pyp5js) diff --git a/docs/index.md b/docs/index.md index 03eb160d..879c4f57 100644 --- a/docs/index.md +++ b/docs/index.md @@ -21,9 +21,6 @@ def draw(): background(200) r = sin(frameCount / 60) * 50 + 50 ellipse(100, 100, r, r) - - -start_p5(setup, draw, {}) ``` ### More Examples [Click here](https://berinhard.github.io/pyp5js/examples/) to see a list of examples generated with `pyp5js`. @@ -88,23 +85,6 @@ $ pyp5js --help - Remember to use **P5.js** method names & conventions for most things. -- To use event functions such as `keyPressed`, `mouseDragged`, `deviceMoved`, `touchMoved`, `windowResized` and others listed in [P5.js reference manual](https://p5js.org/reference/), you have to pass more values to `start_p5` like the following snippet of code. You can check this [live demo](https://berinhard.github.io/pyp5js/examples/sketch_006/index.html) here and also the [Python code](https://github.com/berinhard/pyp5js/blob/master/docs/examples/sketch_006/index.html) for a more expressive example. - -``` -def keyPressed(): - ### your keyPressed implementation - - -def mouseDragged(): - ### your mouseDragged implementation - -event_functions = { - 'keyPressed': keyPressed, - 'mouseDragged': mouseDragged, -} -start_p5(setup, draw, event_functions) -``` - - The `p5.dom.js` library can be used, but you'll have to add it to the `index.html` yourself, and then it's methods and objects will be available with the `p5.` prefix. - There are no Py.Processing `with` context facilities for `push/pop` or `beginShape/endShape`. @@ -144,6 +124,7 @@ After that, you should have the `pyp5js` command enabled and it will respect all - `fs.py`: classes to abstract the files and directories manipulations from the commands - `monitor.py`: module with the objects used by the `monitor` command - `pytop5js.py`: module which is imported by the sketches and integrates with P5.js API +- `template_renderer.py`: simple module with the renderization logic for the code templates like `target_sketch.py` - `update_pytop5js`: this script is responsible for generating the `pytop5js.py` file I still have to add some tests to pyp5js, so I'd love help on that as well. From 9c1505d8d6bfb68d7fed7824eed7ba7385124716 Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sat, 1 Jun 2019 17:51:58 -0300 Subject: [PATCH 20/32] Change monitor to ignore changes introduced by pyp5js --- pyp5js/monitor.py | 12 +++++++++++- tests/test_monitor.py | 20 ++++++++++++++++++-- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/pyp5js/monitor.py b/pyp5js/monitor.py index 449a7eb9..3af3ccff 100644 --- a/pyp5js/monitor.py +++ b/pyp5js/monitor.py @@ -8,9 +8,10 @@ def monitor_sketch(sketch_files): - event_handler = TranscryptSketchEventHandler(sketch_files=sketch_files) observer = Observer() + event_handler = TranscryptSketchEventHandler(sketch_files=sketch_files, observer=observer) + observer.schedule(event_handler, sketch_files.sketch_dir) observer.start() try: @@ -27,13 +28,22 @@ class TranscryptSketchEventHandler(PatternMatchingEventHandler): def __init__(self, *args, **kwargs): self.sketch_files = kwargs.pop('sketch_files') + self.observer = kwargs.pop('observer') self._last_event = None super().__init__(*args, **kwargs) def on_modified(self, event): cprint.info(f"New change in {event.src_path}") + # monkey patch on the observer handlers to avoid recursion + handlers_config = self.observer._handlers.copy() + handlers_copy = {} + compile_sketch_js(self.sketch_files) + queue = self.observer.event_queue + while queue.qsize(): + queue.get() + index_file = self.sketch_files.index_html cprint.ok(f"Your sketch is ready and available at {index_file}") diff --git a/tests/test_monitor.py b/tests/test_monitor.py index 86607833..7782522b 100644 --- a/tests/test_monitor.py +++ b/tests/test_monitor.py @@ -1,3 +1,4 @@ +from queue import Queue from unittest import TestCase from unittest.mock import Mock, patch @@ -9,17 +10,32 @@ class TranscryptSketchEventHandlerTests(TestCase): def setUp(self): self.files = Mock(spec=Pyp5jsSketchFiles) - self.handler = TranscryptSketchEventHandler(sketch_files=self.files) + self.queue = Mock(spec=Queue) + self.observer = Mock(event_queue=self.queue) + self.handler = TranscryptSketchEventHandler(sketch_files=self.files, observer=self.observer) def test_handler_config(self): assert self.files == self.handler.sketch_files assert ['*.py'] == self.handler.patterns - assert self.handler._last_event is None + assert self.observer == self.handler.observer @patch('pyp5js.monitor.compile_sketch_js') def test_on_modified(self, mocked_compiler): + self.queue.qsize.return_value = 0 event = Mock() self.handler.on_modified(event) mocked_compiler.assert_called_once_with(self.files) + self.queue.qsize.assert_called_once_with() + + @patch('pyp5js.monitor.compile_sketch_js') + def test_on_modified_cleans_event_queue_from_changes_introduced_by_pyp5(self, mocked_compiler): + self.queue.qsize.side_effect = sorted(range(11), reverse=True) + event = Mock() + + self.handler.on_modified(event) + + mocked_compiler.assert_called_once_with(self.files) + assert self.queue.qsize.call_count == 11 + assert 10 == self.queue.get.call_count From 188ae3bcbf766821a2f9dc1edc6c4f2f08774e72 Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sun, 2 Jun 2019 12:56:05 -0300 Subject: [PATCH 21/32] Add dom.js methods and variables to pytop5js --- pyp5js/assets/p5_reference.yml | 989 +++++++++++++++++---------------- pyp5js/pytop5js.py | 72 ++- pyp5js/update_pytop5js.py | 7 +- 3 files changed, 584 insertions(+), 484 deletions(-) diff --git a/pyp5js/assets/p5_reference.yml b/pyp5js/assets/p5_reference.yml index c581fb8a..83556719 100644 --- a/pyp5js/assets/p5_reference.yml +++ b/pyp5js/assets/p5_reference.yml @@ -1,480 +1,509 @@ -methods: - - alpha - - blue - - brightness - - color - - green - - hue - - lerpColor - - lightness - - red - - saturation - - background - - clear - - colorMode - - fill - - noFill - - noStroke - - stroke - - # 2D Primitives - - arc - - ellipse - - circle - - line - - point - - quad - - rect - - square - - triangle - - # 3D Primitives - - plane - - box - - sphere - - cylinder - - cone - - ellipsoid - - torus - - # 3D Models - - loadModel - - model - - # Attributes - - ellipseMode - - noSmooth - - rectMode - - smooth - - strokeCap - - strokeJoin - - strokeWeight - - # Curves - - bezier - - bezierDetail - - bezierPoint - - bezierTangent - - curve - - curveDetail - - curveTightness - - curvePoint - - curveTangent - - # Vertex - - beginContour - - beginShape - - bezierVertex - - curveVertex - - endContour - - endShape - - quadraticVertex - - vertex - - # Environment - - print - - cursor - - frameRate - - noCursor - - fullscreen - - pixelDensity - - displayDensity - - getURL - - getURLPath - - getURLParams - - # Structure - - preload - - setup - - draw - - remove - - noLoop - - loop - - push - - redraw - - # Rendering - - resizeCanvas - - noCanvas - - createGraphics - - blendMode - - setAttributes - - # Transform - - applyMatrix - - resetMatrix - - rotate - - rotateX - - rotateY - - rotateZ - - scale - - shearX - - shearY - - translate - - # Dictionary - - createStringDict - - createNumberDict - - # Array Functions - - append - - arrayCopy - - concat - - reverse - - shorten - - shuffle - - sort - - splice - - subset - - # Conversion - - float - - int - - str - - boolean - - byte - - char - - unchar - - hex - - unhex - - # String Functions - - join - - match - - matchAll - - nf - - nfc - - nfp - - nfs - - split - - splitTokens - - trim - - # Acceleration - - setMoveThreshold - - setShakeThreshold - - # Keyboard - - keyIsDown - - # Image - - createImage - - saveCanvas - - saveFrames - - # Loading & Displaying - - loadImage - - image - - tint - - noTint - - imageMode - - # Pixels - - blend - - copy - - filter - - get - - loadPixels - - set - - updatePixels - - # Input - - loadJSON - - loadStrings - - loadTable - - loadXML - - loadBytes - - httpGet - - httpPost - - httpDo - - # Output - - createWriter - - save - - saveJSON - - saveStrings - - saveTable - - # Time & Date - - day - - hour - - minute - - millis - - month - - second - - year - - # Math - - createVector - - # Calculation - - abs - - ceil - - constrain - - dist - - exp - - floor - - lerp - - log - - mag - - map - - max - - min - - norm - - pow - - round - - sq - - sqrt - - # Noise - - noise - - noiseDetail - - noiseSeed - - # Random - - randomSeed - - random - - randomGaussian - - # Trigonometry - - acos - - asin - - atan - - atan2 - - cos - - sin - - tan - - degrees - - radians - - angleMode - - # Attributes - - textAlign - - textLeading - - textSize - - textStyle - - textWidth - - textAscent - - textDescent - - # Loading & Displaying - - loadFont - - text - - textFont - - # Interaction - - orbitControl - - debugMode - - noDebugMode - - # Lights - - ambientLight - - directionalLight - - pointLight - - lights - - # Material - - loadShader - - createShader - - shader - - resetShader - - normalMaterial - - texture - - textureMode - - textureWrap - - ambientMaterial - - specularMaterial - - shininess - - # Camera - - camera - - perspective - - ortho - - createCamera - - setCamera - -events: - # Devicce - - deviceMoved - - deviceTurned - - deviceShaken - # Keyboard - - keyPressed - - keyReleased - - keyTyped - # Mouse - - mouseMoved - - mouseDragged - - mousePressed - - mouseReleased - - mouseClicked - - doubleClicked - - mouseWheel - # Touch - - touchStarted - - touchMoved - - touchEnded - # Window - - windowResized - -variables: - # Constants - - _CTX_MIDDLE - - _DEFAULT_FILL - - _DEFAULT_LEADMULT - - _DEFAULT_STROKE - - _DEFAULT_TEXT_FILL - - ADD - - ALT - - ARROW - - AUTO - - AXES - - BACKSPACE - - BASELINE - - BEVEL - - BEZIER - - BLEND - - BLUR - - BOLD - - BOLDITALIC - - BOTTOM - - BURN - - CENTER - - CHORD - - CLAMP - - CLOSE - - CONTROL - - CORNER - - CORNERS - - CROSS - - CURVE - - DARKEST - - DEG_TO_RAD - - DEGREES - - DELETE - - DIFFERENCE - - DILATE - - DODGE - - DOWN_ARROW - - ENTER - - ERODE - - ESCAPE - - EXCLUSION - - FILL - - GRAY - - GRID - - HALF_PI - - HAND - - HARD_LIGHT - - HSB - - HSL - - IMAGE - - IMMEDIATE - - INVERT - - ITALIC - - LANDSCAPE - - LEFT - - LEFT_ARROW - - LIGHTEST - - LINE_LOOP - - LINE_STRIP - - LINEAR - - LINES - - MIRROR - - MITER - - MOVE - - MULTIPLY - - NEAREST - - NORMAL - - OPAQUE - - OPEN - - OPTION - - OVERLAY - - PI - - PIE - - POINTS - - PORTRAIT - - POSTERIZE - - PROJECT - - QUAD_STRIP - - QUADRATIC - - QUADS - - QUARTER_PI - - RAD_TO_DEG - - RADIANS - - RADIUS - - REPEAT - - REPLACE - - RETURN - - RGB - - RIGHT - - RIGHT_ARROW - - ROUND - - SCREEN - - SHIFT - - SOFT_LIGHT - - SQUARE - - STROKE - - SUBTRACT - - TAB - - TAU - - TEXT - - TEXTURE - - THRESHOLD - - TOP - - TRIANGLE_FAN - - TRIANGLE_STRIP - - TRIANGLES - - TWO_PI - - UP_ARROW - - WAIT - - WEBGL - - P2D - - PI - - # Environment - - frameCount - - focused - - displayWidth - - displayHeight - - windowWidth - - windowHeight - - width - - height - - disableFriendlyErrors - # Acceleration - - deviceOrientation - - accelerationX - - accelerationY - - accelerationZ - - pAccelerationX - - pAccelerationY - - pAccelerationZ - - rotationX - - rotationY - - rotationZ - - pRotationX - - pRotationY - - pRotationZ - - turnAxis - # Keyboard - - keyIsPressed - - key - - keyCode - # Mouse - - mouseX - - mouseY - - pmouseX - - pmouseY - - winMouseX - - winMouseY - - pwinMouseX - - pwinMouseY - - mouseButton - - mouseIsPressed - - # Touch - - touches - - # Pixels - - pixels +p5: + methods: + - alpha + - blue + - brightness + - color + - green + - hue + - lerpColor + - lightness + - red + - saturation + - background + - clear + - colorMode + - fill + - noFill + - noStroke + - stroke + + # 2D Primitives + - arc + - ellipse + - circle + - line + - point + - quad + - rect + - square + - triangle + + # 3D Primitives + - plane + - box + - sphere + - cylinder + - cone + - ellipsoid + - torus + + # 3D Models + - loadModel + - model + + # Attributes + - ellipseMode + - noSmooth + - rectMode + - smooth + - strokeCap + - strokeJoin + - strokeWeight + + # Curves + - bezier + - bezierDetail + - bezierPoint + - bezierTangent + - curve + - curveDetail + - curveTightness + - curvePoint + - curveTangent + + # Vertex + - beginContour + - beginShape + - bezierVertex + - curveVertex + - endContour + - endShape + - quadraticVertex + - vertex + + # Environment + - print + - cursor + - frameRate + - noCursor + - fullscreen + - pixelDensity + - displayDensity + - getURL + - getURLPath + - getURLParams + + # Structure + - preload + - setup + - draw + - remove + - noLoop + - loop + - push + - redraw + + # Rendering + - resizeCanvas + - noCanvas + - createGraphics + - blendMode + - setAttributes + + # Transform + - applyMatrix + - resetMatrix + - rotate + - rotateX + - rotateY + - rotateZ + - scale + - shearX + - shearY + - translate + + # Dictionary + - createStringDict + - createNumberDict + + # Array Functions + - append + - arrayCopy + - concat + - reverse + - shorten + - shuffle + - sort + - splice + - subset + + # Conversion + - float + - int + - str + - boolean + - byte + - char + - unchar + - hex + - unhex + + # String Functions + - join + - match + - matchAll + - nf + - nfc + - nfp + - nfs + - split + - splitTokens + - trim + + # Acceleration + - setMoveThreshold + - setShakeThreshold + + # Keyboard + - keyIsDown + + # Image + - createImage + - saveCanvas + - saveFrames + + # Loading & Displaying + - loadImage + - image + - tint + - noTint + - imageMode + + # Pixels + - blend + - copy + - filter + - get + - loadPixels + - set + - updatePixels + + # Input + - loadJSON + - loadStrings + - loadTable + - loadXML + - loadBytes + - httpGet + - httpPost + - httpDo + + # Output + - createWriter + - save + - saveJSON + - saveStrings + - saveTable + + # Time & Date + - day + - hour + - minute + - millis + - month + - second + - year + + # Math + - createVector + + # Calculation + - abs + - ceil + - constrain + - dist + - exp + - floor + - lerp + - log + - mag + - map + - max + - min + - norm + - pow + - round + - sq + - sqrt + + # Noise + - noise + - noiseDetail + - noiseSeed + + # Random + - randomSeed + - random + - randomGaussian + + # Trigonometry + - acos + - asin + - atan + - atan2 + - cos + - sin + - tan + - degrees + - radians + - angleMode + + # Attributes + - textAlign + - textLeading + - textSize + - textStyle + - textWidth + - textAscent + - textDescent + + # Loading & Displaying + - loadFont + - text + - textFont + + # Interaction + - orbitControl + - debugMode + - noDebugMode + + # Lights + - ambientLight + - directionalLight + - pointLight + - lights + + # Material + - loadShader + - createShader + - shader + - resetShader + - normalMaterial + - texture + - textureMode + - textureWrap + - ambientMaterial + - specularMaterial + - shininess + + # Camera + - camera + - perspective + - ortho + - createCamera + - setCamera + + events: + # Devicce + - deviceMoved + - deviceTurned + - deviceShaken + # Keyboard + - keyPressed + - keyReleased + - keyTyped + # Mouse + - mouseMoved + - mouseDragged + - mousePressed + - mouseReleased + - mouseClicked + - doubleClicked + - mouseWheel + # Touch + - touchStarted + - touchMoved + - touchEnded + # Window + - windowResized + + variables: + # Constants + - _CTX_MIDDLE + - _DEFAULT_FILL + - _DEFAULT_LEADMULT + - _DEFAULT_STROKE + - _DEFAULT_TEXT_FILL + - ADD + - ALT + - ARROW + - AUTO + - AXES + - BACKSPACE + - BASELINE + - BEVEL + - BEZIER + - BLEND + - BLUR + - BOLD + - BOLDITALIC + - BOTTOM + - BURN + - CENTER + - CHORD + - CLAMP + - CLOSE + - CONTROL + - CORNER + - CORNERS + - CROSS + - CURVE + - DARKEST + - DEG_TO_RAD + - DEGREES + - DELETE + - DIFFERENCE + - DILATE + - DODGE + - DOWN_ARROW + - ENTER + - ERODE + - ESCAPE + - EXCLUSION + - FILL + - GRAY + - GRID + - HALF_PI + - HAND + - HARD_LIGHT + - HSB + - HSL + - IMAGE + - IMMEDIATE + - INVERT + - ITALIC + - LANDSCAPE + - LEFT + - LEFT_ARROW + - LIGHTEST + - LINE_LOOP + - LINE_STRIP + - LINEAR + - LINES + - MIRROR + - MITER + - MOVE + - MULTIPLY + - NEAREST + - NORMAL + - OPAQUE + - OPEN + - OPTION + - OVERLAY + - PI + - PIE + - POINTS + - PORTRAIT + - POSTERIZE + - PROJECT + - QUAD_STRIP + - QUADRATIC + - QUADS + - QUARTER_PI + - RAD_TO_DEG + - RADIANS + - RADIUS + - REPEAT + - REPLACE + - RETURN + - RGB + - RIGHT + - RIGHT_ARROW + - ROUND + - SCREEN + - SHIFT + - SOFT_LIGHT + - SQUARE + - STROKE + - SUBTRACT + - TAB + - TAU + - TEXT + - TEXTURE + - THRESHOLD + - TOP + - TRIANGLE_FAN + - TRIANGLE_STRIP + - TRIANGLES + - TWO_PI + - UP_ARROW + - WAIT + - WEBGL + - P2D + - PI + + # Environment + - frameCount + - focused + - displayWidth + - displayHeight + - windowWidth + - windowHeight + - width + - height + - disableFriendlyErrors + # Acceleration + - deviceOrientation + - accelerationX + - accelerationY + - accelerationZ + - pAccelerationX + - pAccelerationY + - pAccelerationZ + - rotationX + - rotationY + - rotationZ + - pRotationX + - pRotationY + - pRotationZ + - turnAxis + # Keyboard + - keyIsPressed + - key + - keyCode + # Mouse + - mouseX + - mouseY + - pmouseX + - pmouseY + - winMouseX + - winMouseY + - pwinMouseX + - pwinMouseY + - mouseButton + - mouseIsPressed + + # Touch + - touches + + # Pixels + - pixels + +dom: + methods: + - select + - selectAll + - removeElements + - changed + - input + - createDiv + - createP + - createSpan + - createImg + - createA + - createSlider + - createButton + - createCheckbox + - createSelect + - createRadio + - createColorPicker + - createInput + - createFileInput + - createVideo + - createAudio + - createCapture + - createElement + variables: + - VIDEO + - AUDIO diff --git a/pyp5js/pytop5js.py b/pyp5js/pytop5js.py index 6462430c..50904995 100644 --- a/pyp5js/pytop5js.py +++ b/pyp5js/pytop5js.py @@ -149,6 +149,8 @@ mouseIsPressed = None touches = None pixels = None +VIDEO = None +AUDIO = None @@ -833,6 +835,72 @@ def createCamera(*args): def setCamera(*args): return _P5_INSTANCE.setCamera(*args) +def select(*args): + return _P5_INSTANCE.select(*args) + +def selectAll(*args): + return _P5_INSTANCE.selectAll(*args) + +def removeElements(*args): + return _P5_INSTANCE.removeElements(*args) + +def changed(*args): + return _P5_INSTANCE.changed(*args) + +def input(*args): + return _P5_INSTANCE.input(*args) + +def createDiv(*args): + return _P5_INSTANCE.createDiv(*args) + +def createP(*args): + return _P5_INSTANCE.createP(*args) + +def createSpan(*args): + return _P5_INSTANCE.createSpan(*args) + +def createImg(*args): + return _P5_INSTANCE.createImg(*args) + +def createA(*args): + return _P5_INSTANCE.createA(*args) + +def createSlider(*args): + return _P5_INSTANCE.createSlider(*args) + +def createButton(*args): + return _P5_INSTANCE.createButton(*args) + +def createCheckbox(*args): + return _P5_INSTANCE.createCheckbox(*args) + +def createSelect(*args): + return _P5_INSTANCE.createSelect(*args) + +def createRadio(*args): + return _P5_INSTANCE.createRadio(*args) + +def createColorPicker(*args): + return _P5_INSTANCE.createColorPicker(*args) + +def createInput(*args): + return _P5_INSTANCE.createInput(*args) + +def createFileInput(*args): + return _P5_INSTANCE.createFileInput(*args) + +def createVideo(*args): + return _P5_INSTANCE.createVideo(*args) + +def createAudio(*args): + return _P5_INSTANCE.createAudio(*args) + +def createCapture(*args): + return _P5_INSTANCE.createCapture(*args) + +def createElement(*args): + return _P5_INSTANCE.createElement(*args) + def createCanvas(*args): result = _P5_INSTANCE.createCanvas(*args) @@ -852,7 +920,7 @@ def pre_draw(p5_instance, draw_func): """ We need to run this before the actual draw to insert and update p5 env variables """ - global _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEG_TO_RAD, DEGREES, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINE_LOOP, LINE_STRIP, LINEAR, LINES, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUAD_STRIP, QUADRATIC, QUADS, QUARTER_PI, RAD_TO_DEG, RADIANS, RADIUS, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLE_FAN, TRIANGLE_STRIP, TRIANGLES, TWO_PI, UP_ARROW, WAIT, WEBGL, P2D, PI, frameCount, focused, displayWidth, displayHeight, windowWidth, windowHeight, width, height, disableFriendlyErrors, deviceOrientation, accelerationX, accelerationY, accelerationZ, pAccelerationX, pAccelerationY, pAccelerationZ, rotationX, rotationY, rotationZ, pRotationX, pRotationY, pRotationZ, turnAxis, keyIsPressed, key, keyCode, mouseX, mouseY, pmouseX, pmouseY, winMouseX, winMouseY, pwinMouseX, pwinMouseY, mouseButton, mouseIsPressed, touches, pixels + global _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEG_TO_RAD, DEGREES, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINE_LOOP, LINE_STRIP, LINEAR, LINES, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUAD_STRIP, QUADRATIC, QUADS, QUARTER_PI, RAD_TO_DEG, RADIANS, RADIUS, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLE_FAN, TRIANGLE_STRIP, TRIANGLES, TWO_PI, UP_ARROW, WAIT, WEBGL, P2D, PI, frameCount, focused, displayWidth, displayHeight, windowWidth, windowHeight, width, height, disableFriendlyErrors, deviceOrientation, accelerationX, accelerationY, accelerationZ, pAccelerationX, pAccelerationY, pAccelerationZ, rotationX, rotationY, rotationZ, pRotationX, pRotationY, pRotationZ, turnAxis, keyIsPressed, key, keyCode, mouseX, mouseY, pmouseX, pmouseY, winMouseX, winMouseY, pwinMouseX, pwinMouseY, mouseButton, mouseIsPressed, touches, pixels, VIDEO, AUDIO _CTX_MIDDLE = p5_instance._CTX_MIDDLE _DEFAULT_FILL = p5_instance._DEFAULT_FILL @@ -1004,6 +1072,8 @@ def pre_draw(p5_instance, draw_func): mouseIsPressed = p5_instance.mouseIsPressed touches = p5_instance.touches pixels = p5_instance.pixels + VIDEO = p5_instance.VIDEO + AUDIO = p5_instance.AUDIO return draw_func() diff --git a/pyp5js/update_pytop5js.py b/pyp5js/update_pytop5js.py index 2ad3659f..bbb195fb 100644 --- a/pyp5js/update_pytop5js.py +++ b/pyp5js/update_pytop5js.py @@ -9,9 +9,10 @@ with open(pyp5js_files.p5_yml) as fd: data = yaml.load(fd.read()) - methods_names = data['methods'] - event_function_names = data['events'] - variables_names = data['variables'] + p5_data, dom_data = data['p5'], data['dom'] + methods_names = p5_data['methods'] + dom_data['methods'] + event_function_names = p5_data['events'] + variables_names = p5_data['variables'] + dom_data['variables'] pyp5_content = get_pytop5js_content(variables_names, methods_names, event_function_names) with open(pyp5js_files.pytop5js, 'w') as fd: From e956d68505dc0e17b5cc20dbb4440750115856cb Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sun, 2 Jun 2019 15:38:47 -0300 Subject: [PATCH 22/32] Remove print to do not overrrides python's print --- pyp5js/assets/p5_reference.yml | 1 - pyp5js/pytop5js.py | 3 --- 2 files changed, 4 deletions(-) diff --git a/pyp5js/assets/p5_reference.yml b/pyp5js/assets/p5_reference.yml index 83556719..99655943 100644 --- a/pyp5js/assets/p5_reference.yml +++ b/pyp5js/assets/p5_reference.yml @@ -73,7 +73,6 @@ p5: - vertex # Environment - - print - cursor - frameRate - noCursor diff --git a/pyp5js/pytop5js.py b/pyp5js/pytop5js.py index 50904995..fbabc1ee 100644 --- a/pyp5js/pytop5js.py +++ b/pyp5js/pytop5js.py @@ -331,9 +331,6 @@ def quadraticVertex(*args): def vertex(*args): return _P5_INSTANCE.vertex(*args) -def print(*args): - return _P5_INSTANCE.print(*args) - def cursor(*args): return _P5_INSTANCE.cursor(*args) From 66799c96f1ed4c2f65de86b3fc0853268723ff36 Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sun, 2 Jun 2019 15:40:02 -0300 Subject: [PATCH 23/32] Update p5.js to version 0.8.0 --- pyp5js/static/p5/addons/p5.dom.js | 3408 ++++++ pyp5js/static/p5/addons/p5.dom.min.js | 3 + pyp5js/static/p5/addons/p5.sound.js | 12879 ++++++++++++++++++++ pyp5js/static/p5/addons/p5.sound.min.js | 28 + pyp5js/static/p5/empty-example/index.html | 15 + pyp5js/static/p5/empty-example/sketch.js | 7 + pyp5js/static/{ => p5}/p5.js | 12045 ++++++++++-------- pyp5js/static/p5/p5.min.js | 3 + 8 files changed, 23330 insertions(+), 5058 deletions(-) create mode 100644 pyp5js/static/p5/addons/p5.dom.js create mode 100644 pyp5js/static/p5/addons/p5.dom.min.js create mode 100644 pyp5js/static/p5/addons/p5.sound.js create mode 100644 pyp5js/static/p5/addons/p5.sound.min.js create mode 100644 pyp5js/static/p5/empty-example/index.html create mode 100644 pyp5js/static/p5/empty-example/sketch.js rename pyp5js/static/{ => p5}/p5.js (90%) create mode 100644 pyp5js/static/p5/p5.min.js diff --git a/pyp5js/static/p5/addons/p5.dom.js b/pyp5js/static/p5/addons/p5.dom.js new file mode 100644 index 00000000..a8743e29 --- /dev/null +++ b/pyp5js/static/p5/addons/p5.dom.js @@ -0,0 +1,3408 @@ +/*! p5.dom.js v0.4.0 August 9, 2018 */ +/** + *

The web is much more than just canvas and p5.dom 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. + * + *

Methods and properties shown in black are part of the p5.js core, items in + * blue are part of the p5.dom library. You will need to include an extra file + * in order to access the blue functions. See the + * using a library + * section for information on how to include this library. p5.dom comes with + * p5 complete or you can download the single file + * + * here.

+ *

See tutorial: beyond the canvas + * for more info on how to use this library. + * + * @module p5.dom + * @submodule p5.dom + * @for p5 + * @main + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) + define('p5.dom', ['p5'], function(p5) { + factory(p5); + }); + else if (typeof exports === 'object') factory(require('../p5')); + else factory(root['p5']); +})(this, function(p5) { + // ============================================================================= + // p5 additions + // ============================================================================= + + /** + * Searches the page for an element with the given ID, class, or tag name (using the '#' or '.' + * prefixes to specify an ID or class respectively, and none for a tag) and returns it as + * a p5.Element. If a class or tag name is given with more than 1 element, + * only the first element will be returned. + * The DOM node itself can be accessed with .elt. + * Returns null if none found. You can also specify a container to search within. + * + * @method select + * @param {String} name id, class, or tag name of element to search for + * @param {String|p5.Element|HTMLElement} [container] id, p5.Element, or + * HTML element to search within + * @return {p5.Element|null} p5.Element containing node found + * @example + *

+ * function setup() { + * createCanvas(100, 100); + * //translates canvas 50px down + * select('canvas').position(100, 100); + * } + *
+ *
+ * // these are all valid calls to select() + * var a = select('#moo'); + * var b = select('#blah', '#myContainer'); + * var c, e; + * if (b) { + * c = select('#foo', b); + * } + * var d = document.getElementById('beep'); + * if (d) { + * e = select('p', d); + * } + * [a, b, c, d, e]; // unused + *
+ * + */ + p5.prototype.select = function(e, p) { + p5._validateParameters('select', arguments); + var res = null; + var container = getContainer(p); + if (e[0] === '.') { + e = e.slice(1); + res = container.getElementsByClassName(e); + if (res.length) { + res = res[0]; + } else { + res = null; + } + } else if (e[0] === '#') { + e = e.slice(1); + res = container.getElementById(e); + } else { + res = container.getElementsByTagName(e); + if (res.length) { + res = res[0]; + } else { + res = null; + } + } + if (res) { + return this._wrapElement(res); + } else { + return null; + } + }; + + /** + * Searches the page for elements with the given class or tag name (using the '.' prefix + * to specify a class and no prefix for a tag) and returns them as p5.Elements + * in an array. + * The DOM node itself can be accessed with .elt. + * Returns an empty array if none found. + * You can also specify a container to search within. + * + * @method selectAll + * @param {String} name class or tag name of elements to search for + * @param {String} [container] id, p5.Element, or HTML element to search within + * @return {p5.Element[]} Array of p5.Elements containing nodes found + * @example + *
+ * function setup() { + * createButton('btn'); + * createButton('2nd btn'); + * createButton('3rd btn'); + * var buttons = selectAll('button'); + * + * for (var i = 0; i < buttons.length; i++) { + * buttons[i].size(100, 100); + * } + * } + *
+ *
+ * // these are all valid calls to selectAll() + * var a = selectAll('.moo'); + * a = selectAll('div'); + * a = selectAll('button', '#myContainer'); + * + * var d = select('#container'); + * a = selectAll('p', d); + * + * var f = document.getElementById('beep'); + * a = select('.blah', f); + * + * a; // unused + *
+ * + */ + p5.prototype.selectAll = function(e, p) { + p5._validateParameters('selectAll', arguments); + var arr = []; + var res; + var container = getContainer(p); + if (e[0] === '.') { + e = e.slice(1); + res = container.getElementsByClassName(e); + } else { + res = container.getElementsByTagName(e); + } + if (res) { + for (var j = 0; j < res.length; j++) { + var obj = this._wrapElement(res[j]); + arr.push(obj); + } + } + return arr; + }; + + /** + * Helper function for select and selectAll + */ + function getContainer(p) { + var container = document; + if (typeof p === 'string' && p[0] === '#') { + p = p.slice(1); + container = document.getElementById(p) || document; + } else if (p instanceof p5.Element) { + container = p.elt; + } else if (p instanceof HTMLElement) { + container = p; + } + return container; + } + + /** + * Helper function for getElement and getElements. + */ + p5.prototype._wrapElement = function(elt) { + var children = Array.prototype.slice.call(elt.children); + if (elt.tagName === 'INPUT' && elt.type === 'checkbox') { + var converted = new p5.Element(elt, this); + converted.checked = function() { + if (arguments.length === 0) { + return this.elt.checked; + } else if (arguments[0]) { + this.elt.checked = true; + } else { + this.elt.checked = false; + } + return this; + }; + return converted; + } else if (elt.tagName === 'VIDEO' || elt.tagName === 'AUDIO') { + return new p5.MediaElement(elt, this); + } else if (elt.tagName === 'SELECT') { + return this.createSelect(new p5.Element(elt, this)); + } else if ( + children.length > 0 && + children.every(function(c) { + return c.tagName === 'INPUT' || c.tagName === 'LABEL'; + }) + ) { + return this.createRadio(new p5.Element(elt, this)); + } else { + return new p5.Element(elt, this); + } + }; + + /** + * Removes all elements created by p5, except any canvas / graphics + * elements created by createCanvas or createGraphics. + * Event handlers are removed, and element is removed from the DOM. + * @method removeElements + * @example + *
+ * function setup() { + * createCanvas(100, 100); + * createDiv('this is some text'); + * createP('this is a paragraph'); + * } + * function mousePressed() { + * removeElements(); // this will remove the div and p, not canvas + * } + *
+ * + */ + p5.prototype.removeElements = function(e) { + p5._validateParameters('removeElements', arguments); + for (var i = 0; i < this._elements.length; i++) { + if (!(this._elements[i].elt instanceof HTMLCanvasElement)) { + this._elements[i].remove(); + } + } + }; + + /** + * The .changed() function is called when the value of an + * element changes. + * This can be used to attach an element specific event listener. + * + * @method changed + * @param {Function|Boolean} fxn function to be fired when the value of + * an element changes. + * if `false` is passed instead, the previously + * firing function will no longer fire. + * @chainable + * @example + *
+ * var 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() { + * var item = sel.value(); + * background(200); + * text("it's a " + item + '!', 50, 50); + * } + *
+ * + *
+ * var checkbox; + * var cnv; + * + * function setup() { + * checkbox = createCheckbox(' fill'); + * checkbox.changed(changeFill); + * cnv = createCanvas(100, 100); + * cnv.position(0, 30); + * noFill(); + * } + * + * function draw() { + * background(200); + * ellipse(50, 50, 50, 50); + * } + * + * function changeFill() { + * if (checkbox.checked()) { + * fill(0); + * } else { + * noFill(); + * } + * } + *
+ * + * @alt + * dropdown: pear, kiwi, grape. When selected text "its a" + selection shown. + * + */ + p5.Element.prototype.changed = function(fxn) { + p5.Element._adjustListener('change', fxn, this); + return this; + }; + + /** + * The .input() function is called when any user input is + * detected with an element. The input event is often used + * to detect keystrokes in a input element, or changes on a + * slider element. This can be used to attach an element specific + * event listener. + * + * @method input + * @param {Function|Boolean} fxn function to be fired when any user input is + * detected within the element. + * if `false` is passed instead, the previously + * firing function will no longer fire. + * @chainable + * @example + *
+ * // Open your console to see the output + * function setup() { + * var inp = createInput(''); + * inp.input(myInputEvent); + * } + * + * function myInputEvent() { + * console.log('you are typing: ', this.value()); + * } + *
+ * + * @alt + * no display. + * + */ + p5.Element.prototype.input = function(fxn) { + p5.Element._adjustListener('input', fxn, this); + return this; + }; + + /** + * Helpers for create methods. + */ + function addElement(elt, pInst, media) { + var node = pInst._userNode ? pInst._userNode : document.body; + node.appendChild(elt); + var c = media + ? new p5.MediaElement(elt, pInst) + : new p5.Element(elt, pInst); + pInst._elements.push(c); + return c; + } + + /** + * Creates a <div></div> element in the DOM with given inner HTML. + * Appends to the container node if one is specified, otherwise + * appends to body. + * + * @method createDiv + * @param {String} [html] inner HTML for element created + * @return {p5.Element} pointer to p5.Element holding created node + * @example + *
+ * createDiv('this is some text'); + *
+ */ + + /** + * Creates a <p></p> element in the DOM with given inner HTML. Used + * for paragraph length text. + * Appends to the container node if one is specified, otherwise + * appends to body. + * + * @method createP + * @param {String} [html] inner HTML for element created + * @return {p5.Element} pointer to p5.Element holding created node + * @example + *
+ * createP('this is some text'); + *
+ */ + + /** + * Creates a <span></span> element in the DOM with given inner HTML. + * Appends to the container node if one is specified, otherwise + * appends to body. + * + * @method createSpan + * @param {String} [html] inner HTML for element created + * @return {p5.Element} pointer to p5.Element holding created node + * @example + *
+ * createSpan('this is some text'); + *
+ */ + var tags = ['div', 'p', 'span']; + tags.forEach(function(tag) { + var method = 'create' + tag.charAt(0).toUpperCase() + tag.slice(1); + p5.prototype[method] = function(html) { + var elt = document.createElement(tag); + elt.innerHTML = typeof html === 'undefined' ? '' : html; + return addElement(elt, this); + }; + }); + + /** + * Creates an <img> element in the DOM with given src and + * alternate text. + * Appends to the container node if one is specified, otherwise + * appends to body. + * + * @method createImg + * @param {String} src src path or url for image + * @param {String} [alt] alternate text to be used if image does not load + * @param {Function} [successCallback] callback to be called once image data is loaded + * @return {p5.Element} pointer to p5.Element holding created node + * @example + *
+ * createImg('http://p5js.org/img/asterisk-01.png'); + *
+ */ + /** + * @method createImg + * @param {String} src + * @param {Function} successCallback + * @return {Object|p5.Element} + */ + p5.prototype.createImg = function() { + p5._validateParameters('createImg', arguments); + var elt = document.createElement('img'); + elt.crossOrigin = 'Anonymous'; + var args = arguments; + var self; + var setAttrs = function() { + self.width = elt.offsetWidth || elt.width; + self.height = elt.offsetHeight || elt.height; + if (args.length > 1 && typeof args[1] === 'function') { + self.fn = args[1]; + self.fn(); + } else if (args.length > 1 && typeof args[2] === 'function') { + self.fn = args[2]; + self.fn(); + } + }; + elt.src = args[0]; + if (args.length > 1 && typeof args[1] === 'string') { + elt.alt = args[1]; + } + elt.onload = function() { + setAttrs(); + }; + self = addElement(elt, this); + return self; + }; + + /** + * Creates an <a></a> element in the DOM for including a hyperlink. + * Appends to the container node if one is specified, otherwise + * appends to body. + * + * @method createA + * @param {String} href url of page to link to + * @param {String} html inner html of link element to display + * @param {String} [target] target where new link should open, + * could be _blank, _self, _parent, _top. + * @return {p5.Element} pointer to p5.Element holding created node + * @example + *
+ * createA('http://p5js.org/', 'this is a link'); + *
+ */ + p5.prototype.createA = function(href, html, target) { + p5._validateParameters('createA', arguments); + var elt = document.createElement('a'); + elt.href = href; + elt.innerHTML = html; + if (target) elt.target = target; + return addElement(elt, this); + }; + + /** INPUT **/ + + /** + * Creates a slider <input></input> element in the DOM. + * Use .size() to set the display length of the slider. + * Appends to the container node if one is specified, otherwise + * appends to body. + * + * @method createSlider + * @param {Number} min minimum value of the slider + * @param {Number} max maximum value of the slider + * @param {Number} [value] default value of the slider + * @param {Number} [step] step size for each tick of the slider (if step is set to 0, the slider will move continuously from the minimum to the maximum value) + * @return {p5.Element} pointer to p5.Element holding created node + * @example + *
+ * var slider; + * function setup() { + * slider = createSlider(0, 255, 100); + * slider.position(10, 10); + * slider.style('width', '80px'); + * } + * + * function draw() { + * var val = slider.value(); + * background(val); + * } + *
+ * + *
+ * var slider; + * function setup() { + * colorMode(HSB); + * slider = createSlider(0, 360, 60, 40); + * slider.position(10, 10); + * slider.style('width', '80px'); + * } + * + * function draw() { + * var val = slider.value(); + * background(val, 100, 100, 1); + * } + *
+ */ + p5.prototype.createSlider = function(min, max, value, step) { + p5._validateParameters('createSlider', arguments); + var elt = document.createElement('input'); + elt.type = 'range'; + elt.min = min; + elt.max = max; + if (step === 0) { + elt.step = 0.000000000000000001; // smallest valid step + } else if (step) { + elt.step = step; + } + if (typeof value === 'number') elt.value = value; + return addElement(elt, this); + }; + + /** + * Creates a <button></button> element in the DOM. + * Use .size() to set the display size of the button. + * Use .mousePressed() to specify behavior on press. + * Appends to the container node if one is specified, otherwise + * appends to body. + * + * @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 + * @example + *
+ * var button; + * function setup() { + * createCanvas(100, 100); + * background(0); + * button = createButton('click me'); + * button.position(19, 19); + * button.mousePressed(changeBG); + * } + * + * function changeBG() { + * var val = random(255); + * background(val); + * } + *
+ */ + p5.prototype.createButton = function(label, value) { + p5._validateParameters('createButton', arguments); + var elt = document.createElement('button'); + elt.innerHTML = label; + if (value) elt.value = value; + return addElement(elt, this); + }; + + /** + * Creates a checkbox <input></input> element in the DOM. + * Calling .checked() on a checkbox returns if it is checked or not + * + * @method createCheckbox + * @param {String} [label] label displayed after checkbox + * @param {boolean} [value] value of the checkbox; checked is true, unchecked is false + * @return {p5.Element} pointer to p5.Element holding created node + * @example + *
+ * var checkbox; + * + * function setup() { + * checkbox = createCheckbox('label', false); + * checkbox.changed(myCheckedEvent); + * } + * + * function myCheckedEvent() { + * if (this.checked()) { + * console.log('Checking!'); + * } else { + * console.log('Unchecking!'); + * } + * } + *
+ */ + p5.prototype.createCheckbox = function() { + p5._validateParameters('createCheckbox', arguments); + var elt = document.createElement('div'); + var checkbox = document.createElement('input'); + checkbox.type = 'checkbox'; + elt.appendChild(checkbox); + //checkbox must be wrapped in p5.Element before label so that label appears after + var self = addElement(elt, this); + self.checked = function() { + var cb = self.elt.getElementsByTagName('input')[0]; + if (cb) { + if (arguments.length === 0) { + return cb.checked; + } else if (arguments[0]) { + cb.checked = true; + } else { + cb.checked = false; + } + } + return self; + }; + this.value = function(val) { + self.value = val; + return this; + }; + if (arguments[0]) { + var ran = Math.random() + .toString(36) + .slice(2); + var label = document.createElement('label'); + checkbox.setAttribute('id', ran); + label.htmlFor = ran; + self.value(arguments[0]); + label.appendChild(document.createTextNode(arguments[0])); + elt.appendChild(label); + } + if (arguments[1]) { + checkbox.checked = true; + } + return self; + }; + + /** + * Creates a dropdown menu <select></select> element in the DOM. + * It also helps to assign select-box methods to p5.Element when selecting existing select box + * @method createSelect + * @param {boolean} [multiple] true if dropdown should support multiple selections + * @return {p5.Element} + * @example + *
+ * var 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() { + * var item = sel.value(); + * background(200); + * text('It is a ' + item + '!', 50, 50); + * } + *
+ */ + /** + * @method createSelect + * @param {Object} existing DOM select element + * @return {p5.Element} + */ + + p5.prototype.createSelect = function() { + p5._validateParameters('createSelect', arguments); + var elt, self; + var arg = arguments[0]; + if (typeof arg === 'object' && arg.elt.nodeName === 'SELECT') { + self = arg; + elt = this.elt = arg.elt; + } else { + elt = document.createElement('select'); + if (arg && typeof arg === 'boolean') { + elt.setAttribute('multiple', 'true'); + } + self = addElement(elt, this); + } + self.option = function(name, value) { + var index; + //see if there is already an option with this name + for (var i = 0; i < this.elt.length; i++) { + if (this.elt[i].innerHTML === name) { + index = i; + break; + } + } + //if there is an option with this name we will modify it + if (index !== undefined) { + //if the user passed in false then delete that option + if (value === false) { + this.elt.remove(index); + } else { + //otherwise if the name and value are the same then change both + if (this.elt[index].innerHTML === this.elt[index].value) { + this.elt[index].innerHTML = this.elt[index].value = value; + //otherwise just change the value + } else { + this.elt[index].value = value; + } + } + } else { + //if it doesn't exist make it + var opt = document.createElement('option'); + opt.innerHTML = name; + if (arguments.length > 1) opt.value = value; + else opt.value = name; + elt.appendChild(opt); + } + }; + self.selected = function(value) { + var arr = [], + i; + if (arguments.length > 0) { + for (i = 0; i < this.elt.length; i++) { + if (value.toString() === this.elt[i].value) { + this.elt.selectedIndex = i; + } + } + return this; + } else { + if (this.elt.getAttribute('multiple')) { + for (i = 0; i < this.elt.selectedOptions.length; i++) { + arr.push(this.elt.selectedOptions[i].value); + } + return arr; + } else { + return this.elt.value; + } + } + }; + return self; + }; + + /** + * Creates a radio button <input></input> element in the DOM. + * The .option() method can be used to set options for the radio after it is + * created. The .value() method will return the currently selected option. + * + * @method createRadio + * @param {String} [divId] the id and name of the created div and input field respectively + * @return {p5.Element} pointer to p5.Element holding created node + * @example + *
+ * var radio; + * + * function setup() { + * radio = createRadio(); + * radio.option('black'); + * radio.option('white'); + * radio.option('gray'); + * radio.style('width', '60px'); + * textAlign(CENTER); + * fill(255, 0, 0); + * } + * + * function draw() { + * var val = radio.value(); + * background(val); + * text(val, width / 2, height / 2); + * } + *
+ *
+ * var radio; + * + * function setup() { + * radio = createRadio(); + * radio.option('apple', 1); + * radio.option('bread', 2); + * radio.option('juice', 3); + * radio.style('width', '60px'); + * textAlign(CENTER); + * } + * + * function draw() { + * background(200); + * var val = radio.value(); + * if (val) { + * text('item cost is $' + val, width / 2, height / 2); + * } + * } + *
+ */ + p5.prototype.createRadio = function(existing_radios) { + p5._validateParameters('createRadio', arguments); + // do some prep by counting number of radios on page + var radios = document.querySelectorAll('input[type=radio]'); + var count = 0; + if (radios.length > 1) { + var length = radios.length; + var prev = radios[0].name; + var current = radios[1].name; + count = 1; + for (var i = 1; i < length; i++) { + current = radios[i].name; + if (prev !== current) { + count++; + } + prev = current; + } + } else if (radios.length === 1) { + count = 1; + } + // see if we got an existing set of radios from callee + var elt, self; + if (typeof existing_radios === 'object') { + // use existing elements + self = existing_radios; + elt = this.elt = existing_radios.elt; + } else { + // create a set of radio buttons + elt = document.createElement('div'); + self = addElement(elt, this); + } + // setup member functions + self._getInputChildrenArray = function() { + return Array.prototype.slice.call(this.elt.children).filter(function(c) { + return c.tagName === 'INPUT'; + }); + }; + + var times = -1; + self.option = function(name, value) { + var opt = document.createElement('input'); + opt.type = 'radio'; + opt.innerHTML = name; + if (value) opt.value = value; + else opt.value = name; + opt.setAttribute('name', 'defaultradio' + count); + elt.appendChild(opt); + if (name) { + times++; + var label = document.createElement('label'); + opt.setAttribute('id', 'defaultradio' + count + '-' + times); + label.htmlFor = 'defaultradio' + count + '-' + times; + label.appendChild(document.createTextNode(name)); + elt.appendChild(label); + } + return opt; + }; + self.selected = function(value) { + var i; + var inputChildren = self._getInputChildrenArray(); + if (value) { + for (i = 0; i < inputChildren.length; i++) { + if (inputChildren[i].value === value) inputChildren[i].checked = true; + } + return this; + } else { + for (i = 0; i < inputChildren.length; i++) { + if (inputChildren[i].checked === true) return inputChildren[i].value; + } + } + }; + self.value = function(value) { + var i; + var inputChildren = self._getInputChildrenArray(); + if (value) { + for (i = 0; i < inputChildren.length; i++) { + if (inputChildren[i].value === value) inputChildren[i].checked = true; + } + return this; + } else { + for (i = 0; i < inputChildren.length; i++) { + if (inputChildren[i].checked === true) return inputChildren[i].value; + } + return ''; + } + }; + return self; + }; + + /** + * Creates a colorPicker element in the DOM for color input. + * The .value() method will return a hex string (#rrggbb) of the color. + * The .color() method will return a p5.Color object with the current chosen color. + * + * @method createColorPicker + * @param {String|p5.Color} [value] default color of element + * @return {p5.Element} pointer to p5.Element holding created node + * @example + *
+ * + * var inp1, inp2; + * function setup() { + * createCanvas(100, 100); + * background('grey'); + * inp1 = createColorPicker('#ff0000'); + * inp2 = createColorPicker(color('yellow')); + * inp1.input(setShade1); + * inp2.input(setShade2); + * setMidShade(); + * } + * + * function setMidShade() { + * // Finding a shade between the two + * var commonShade = lerpColor(inp1.color(), inp2.color(), 0.5); + * fill(commonShade); + * rect(20, 20, 60, 60); + * } + * + * function setShade1() { + * setMidShade(); + * console.log('You are choosing shade 1 to be : ', this.value()); + * } + * function setShade2() { + * setMidShade(); + * console.log('You are choosing shade 2 to be : ', this.value()); + * } + * + *
+ */ + p5.prototype.createColorPicker = function(value) { + p5._validateParameters('createColorPicker', arguments); + var elt = document.createElement('input'); + var self; + elt.type = 'color'; + if (value) { + if (value instanceof p5.Color) { + elt.value = value.toString('#rrggbb'); + } else { + p5.prototype._colorMode = 'rgb'; + p5.prototype._colorMaxes = { + rgb: [255, 255, 255, 255], + hsb: [360, 100, 100, 1], + hsl: [360, 100, 100, 1] + }; + elt.value = p5.prototype.color(value).toString('#rrggbb'); + } + } else { + elt.value = '#000000'; + } + self = addElement(elt, this); + // Method to return a p5.Color object for the given color. + self.color = function() { + if (value.mode) { + p5.prototype._colorMode = value.mode; + } + if (value.maxes) { + p5.prototype._colorMaxes = value.maxes; + } + return p5.prototype.color(this.elt.value); + }; + return self; + }; + + /** + * Creates an <input></input> element in the DOM for text input. + * Use .size() to set the display length of the box. + * Appends to the container node if one is specified, otherwise + * appends to body. + * + * @method createInput + * @param {String} [value] default value of the input box + * @param {String} [type] type of text, ie text, password etc. Defaults to text + * @return {p5.Element} pointer to p5.Element holding created node + * @example + *
+ * function setup() { + * var inp = createInput(''); + * inp.input(myInputEvent); + * } + * + * function myInputEvent() { + * console.log('you are typing: ', this.value()); + * } + *
+ */ + p5.prototype.createInput = function(value, type) { + p5._validateParameters('createInput', arguments); + var elt = document.createElement('input'); + elt.type = type ? type : 'text'; + if (value) elt.value = value; + return addElement(elt, this); + }; + + /** + * Creates an <input></input> element in the DOM of type 'file'. + * This allows users to select local files for use in a sketch. + * + * @method createFileInput + * @param {Function} [callback] callback function for when a file loaded + * @param {String} [multiple] optional to allow multiple files selected + * @return {p5.Element} pointer to p5.Element holding created DOM element + * @example + *
+ * let input; + * let img; + * + * function setup() { + * input = createFileInput(handleFile); + * input.position(0, 0); + * } + * + * function draw() { + * background(255); + * if (img) { + * image(img, 0, 0, width, height); + * } + * } + * + * function handleFile(file) { + * print(file); + * if (file.type === 'image') { + * img = createImg(file.data); + * img.hide(); + * } else { + * img = null; + * } + * } + *
+ */ + p5.prototype.createFileInput = function(callback, multiple) { + p5._validateParameters('createFileInput', arguments); + // Function to handle when a file is selected + // We're simplifying life and assuming that we always + // want to load every selected file + function handleFileSelect(evt) { + // These are the files + var files = evt.target.files; + // Load each one and trigger a callback + for (var i = 0; i < files.length; i++) { + var f = files[i]; + p5.File._load(f, callback); + } + } + // Is the file stuff supported? + if (window.File && window.FileReader && window.FileList && window.Blob) { + // Yup, we're ok and make an input file selector + var elt = document.createElement('input'); + elt.type = 'file'; + + // If we get a second argument that evaluates to true + // then we are looking for multiple files + if (multiple) { + // Anything gets the job done + elt.multiple = 'multiple'; + } + + // Now let's handle when a file was selected + elt.addEventListener('change', handleFileSelect, false); + return addElement(elt, this); + } else { + console.log( + 'The File APIs are not fully supported in this browser. Cannot create element.' + ); + } + }; + + /** VIDEO STUFF **/ + + function createMedia(pInst, type, src, callback) { + var elt = document.createElement(type); + + // allow src to be empty + src = src || ''; + if (typeof src === 'string') { + src = [src]; + } + for (var i = 0; i < src.length; i++) { + var source = document.createElement('source'); + source.src = src[i]; + elt.appendChild(source); + } + if (typeof callback !== 'undefined') { + var callbackHandler = function() { + callback(); + elt.removeEventListener('canplaythrough', callbackHandler); + }; + elt.addEventListener('canplaythrough', callbackHandler); + } + + var c = addElement(elt, pInst, true); + c.loadedmetadata = false; + // set width and height onload metadata + elt.addEventListener('loadedmetadata', function() { + c.width = elt.videoWidth; + c.height = elt.videoHeight; + //c.elt.playbackRate = s; + // set elt width and height if not set + if (c.elt.width === 0) c.elt.width = elt.videoWidth; + if (c.elt.height === 0) c.elt.height = elt.videoHeight; + if (c.presetPlaybackRate) { + c.elt.playbackRate = c.presetPlaybackRate; + delete c.presetPlaybackRate; + } + c.loadedmetadata = true; + }); + + return c; + } + /** + * 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 video(). Appends to the container + * node if one is specified, otherwise appends to body. The first parameter + * can be either a single string path to a video file, or an array of string + * paths to different formats of the same video. This is useful for ensuring + * that your video can play across different browsers, as each supports + * different formats. See this + * page for further information about supported formats. + * + * @method createVideo + * @param {String|String[]} src path to a video file, or array of paths for + * supporting different browsers + * @param {Function} [callback] callback function to be called upon + * 'canplaythrough' event fire, that is, when the + * browser can play the media, and estimates that + * enough data has been loaded to play the media + * up to its end without having to stop for + * further buffering of content + * @return {p5.MediaElement} pointer to video p5.Element + * @example + *
+ * var vid; + * function setup() { + * noCanvas(); + * + * vid = createVideo( + * ['assets/small.mp4', 'assets/small.ogv', 'assets/small.webm'], + * vidLoad + * ); + * + * vid.size(100, 100); + * } + * + * // This function is called when the video loads + * function vidLoad() { + * vid.loop(); + * vid.volume(0); + * } + *
+ */ + p5.prototype.createVideo = function(src, callback) { + p5._validateParameters('createVideo', arguments); + return createMedia(this, 'video', src, callback); + }; + + /** AUDIO STUFF **/ + + /** + * Creates a hidden HTML5 <audio> element in the DOM for simple audio + * playback. Appends to the container node if one is specified, + * otherwise appends to body. The first parameter + * can be either a single string path to a audio file, or an array of string + * paths to different formats of the same audio. This is useful for ensuring + * that your audio can play across different browsers, as each supports + * different formats. See this + * page for further information about supported formats. + * + * @method createAudio + * @param {String|String[]} [src] path to an audio file, or array of paths + * for supporting different browsers + * @param {Function} [callback] callback function to be called upon + * 'canplaythrough' event fire, that is, when the + * browser can play the media, and estimates that + * enough data has been loaded to play the media + * up to its end without having to stop for + * further buffering of content + * @return {p5.MediaElement} pointer to audio p5.Element + * @example + *
+ * var ele; + * function setup() { + * ele = createAudio('assets/beat.mp3'); + * + * // here we set the element to autoplay + * // The element will play as soon + * // as it is able to do so. + * ele.autoplay(true); + * } + *
+ */ + p5.prototype.createAudio = function(src, callback) { + p5._validateParameters('createAudio', arguments); + return createMedia(this, 'audio', src, callback); + }; + + /** CAMERA STUFF **/ + + /** + * @property {String} VIDEO + * @final + * @category Constants + */ + p5.prototype.VIDEO = 'video'; + /** + * @property {String} AUDIO + * @final + * @category Constants + */ + p5.prototype.AUDIO = 'audio'; + + // from: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia + // Older browsers might not implement mediaDevices at all, so we set an empty object first + if (navigator.mediaDevices === undefined) { + navigator.mediaDevices = {}; + } + + // Some browsers partially implement mediaDevices. We can't just assign an object + // with getUserMedia as it would overwrite existing properties. + // Here, we will just add the getUserMedia property if it's missing. + if (navigator.mediaDevices.getUserMedia === undefined) { + navigator.mediaDevices.getUserMedia = function(constraints) { + // First get ahold of the legacy getUserMedia, if present + var getUserMedia = + navigator.webkitGetUserMedia || navigator.mozGetUserMedia; + + // Some browsers just don't implement it - return a rejected promise with an error + // to keep a consistent interface + if (!getUserMedia) { + return Promise.reject( + new Error('getUserMedia is not implemented in this browser') + ); + } + + // Otherwise, wrap the call to the old navigator.getUserMedia with a Promise + return new Promise(function(resolve, reject) { + getUserMedia.call(navigator, constraints, resolve, reject); + }); + }; + } + + /** + *

Creates a new HTML5 <video> element that contains the audio/video + * feed from a webcam. The element is separate from the canvas and is + * displayed by default. The element can be hidden using .hide(). The feed + * can be drawn onto the canvas using image(). The loadedmetadata property can + * be used to detect when the element has fully loaded (see second example).

+ *

More specific properties of the feed can be passing in a Constraints object. + * See the + * W3C + * spec for possible properties. Note that not all of these are supported + * by all browsers.

+ *

Security note: A new browser security specification requires that getUserMedia, + * which is behind createCapture(), only works when you're running the code locally, + * or on HTTPS. Learn more here + * and here.

+ * + * @method createCapture + * @param {String|Constant|Object} type type of capture, either VIDEO or + * AUDIO if none specified, default both, + * or a Constraints object + * @param {Function} [callback] function to be called once + * stream has loaded + * @return {p5.Element} capture video p5.Element + * @example + *
+ * var capture; + * + * function setup() { + * createCanvas(480, 480); + * capture = createCapture(VIDEO); + * capture.hide(); + * } + * + * function draw() { + * image(capture, 0, 0, width, width * capture.height / capture.width); + * filter(INVERT); + * } + *
+ *
+ * function setup() { + * createCanvas(480, 120); + * var constraints = { + * video: { + * mandatory: { + * minWidth: 1280, + * minHeight: 720 + * }, + * optional: [{ maxFrameRate: 10 }] + * }, + * audio: true + * }; + * createCapture(constraints, function(stream) { + * console.log(stream); + * }); + * } + *
+ *
+ * var capture; + * + * function setup() { + * createCanvas(640, 480); + * capture = createCapture(VIDEO); + * } + * function draw() { + * background(0); + * if (capture.loadedmetadata) { + * var c = capture.get(0, 0, 100, 100); + * image(c, 0, 0); + * } + * } + *
+ */ + p5.prototype.createCapture = function() { + p5._validateParameters('createCapture', arguments); + var useVideo = true; + var useAudio = true; + var constraints; + var cb; + for (var i = 0; i < arguments.length; i++) { + if (arguments[i] === p5.prototype.VIDEO) { + useAudio = false; + } else if (arguments[i] === p5.prototype.AUDIO) { + useVideo = false; + } else if (typeof arguments[i] === 'object') { + constraints = arguments[i]; + } else if (typeof arguments[i] === 'function') { + cb = arguments[i]; + } + } + if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { + var elt = document.createElement('video'); + // required to work in iOS 11 & up: + elt.setAttribute('playsinline', ''); + + if (!constraints) { + constraints = { video: useVideo, audio: useAudio }; + } + + navigator.mediaDevices.getUserMedia(constraints).then( + function(stream) { + try { + if ('srcObject' in elt) { + elt.srcObject = stream; + } else { + elt.src = window.URL.createObjectURL(stream); + } + } catch (err) { + elt.src = stream; + } + if (cb) { + cb(stream); + } + }, + function(e) { + console.log(e); + } + ); + } else { + throw 'getUserMedia not supported in this browser'; + } + var c = addElement(elt, this, true); + c.loadedmetadata = false; + // set width and height onload metadata + elt.addEventListener('loadedmetadata', function() { + elt.play(); + if (elt.width) { + c.width = elt.videoWidth = elt.width; + c.height = elt.videoHeight = elt.height; + } else { + c.width = c.elt.width = elt.videoWidth; + c.height = c.elt.height = elt.videoHeight; + } + c.loadedmetadata = true; + }); + return c; + }; + + /** + * Creates element with given tag in the DOM with given content. + * Appends to the container node if one is specified, otherwise + * appends to body. + * + * @method createElement + * @param {String} tag tag for the new element + * @param {String} [content] html content to be inserted into the element + * @return {p5.Element} pointer to p5.Element holding created node + * @example + *
+ * createElement('h2', 'im an h2 p5.element!'); + *
+ */ + p5.prototype.createElement = function(tag, content) { + p5._validateParameters('createElement', arguments); + var elt = document.createElement(tag); + if (typeof content !== 'undefined') { + elt.innerHTML = content; + } + return addElement(elt, this); + }; + + // ============================================================================= + // p5.Element additions + // ============================================================================= + /** + * + * Adds specified class to the element. + * + * @for p5.Element + * @method addClass + * @param {String} class name of class to add + * @chainable + * @example + *
+ * var div = createDiv('div'); + * div.addClass('myClass'); + *
+ */ + p5.Element.prototype.addClass = function(c) { + if (this.elt.className) { + if (!this.hasClass(c)) { + this.elt.className = this.elt.className + ' ' + c; + } + } else { + this.elt.className = c; + } + return this; + }; + + /** + * + * Removes specified class from the element. + * + * @method removeClass + * @param {String} class name of class to remove + * @chainable + * @example + *
+ * // In this example, a class is set when the div is created + * // and removed when mouse is pressed. This could link up + * // with a CSS style rule to toggle style properties. + * + * var div; + * + * function setup() { + * div = createDiv('div'); + * div.addClass('myClass'); + * } + * + * function mousePressed() { + * div.removeClass('myClass'); + * } + *
+ */ + p5.Element.prototype.removeClass = function(c) { + // Note: Removing a class that does not exist does NOT throw an error in classList.remove method + this.elt.classList.remove(c); + return this; + }; + + /** + * + * Checks if specified class already set to element + * + * @method hasClass + * @returns {boolean} a boolean value if element has specified class + * @param c {String} class name of class to check + * @example + *
+ * var div; + * + * function setup() { + * div = createDiv('div'); + * div.addClass('show'); + * } + * + * function mousePressed() { + * if (div.hasClass('show')) { + * div.addClass('show'); + * } else { + * div.removeClass('show'); + * } + * } + *
+ */ + p5.Element.prototype.hasClass = function(c) { + return this.elt.classList.contains(c); + }; + + /** + * + * Toggles element class + * + * @method toggleClass + * @param c {String} class name to toggle + * @chainable + * @example + *
+ * var div; + * + * function setup() { + * div = createDiv('div'); + * div.addClass('show'); + * } + * + * function mousePressed() { + * div.toggleClass('show'); + * } + *
+ */ + p5.Element.prototype.toggleClass = function(c) { + // classList also has a toggle() method, but we cannot use that yet as support is unclear. + // See https://github.com/processing/p5.js/issues/3631 + // this.elt.classList.toggle(c); + if (this.elt.classList.contains(c)) { + this.elt.classList.remove(c); + } else { + this.elt.classList.add(c); + } + return this; + }; + + /** + * + * Attaches the element as a child to the parent specified. + * Accepts either a string ID, DOM node, or p5.Element. + * If no argument is specified, an array of children DOM nodes is returned. + * + * @method child + * @returns {Node[]} an array of child nodes + * @example + *
+ * var div0 = createDiv('this is the parent'); + * var div1 = createDiv('this is the child'); + * div0.child(div1); // use p5.Element + *
+ *
+ * var div0 = createDiv('this is the parent'); + * var div1 = createDiv('this is the child'); + * div1.id('apples'); + * div0.child('apples'); // use id + *
+ *
+ * // this example assumes there is a div already on the page + * // with id "myChildDiv" + * var div0 = createDiv('this is the parent'); + * var elt = document.getElementById('myChildDiv'); + * div0.child(elt); // use element from page + *
+ */ + /** + * @method child + * @param {String|p5.Element} [child] the ID, DOM node, or p5.Element + * to add to the current element + * @chainable + */ + p5.Element.prototype.child = function(c) { + if (typeof c === 'undefined') { + return this.elt.childNodes; + } + if (typeof c === 'string') { + if (c[0] === '#') { + c = c.substring(1); + } + c = document.getElementById(c); + } else if (c instanceof p5.Element) { + c = c.elt; + } + this.elt.appendChild(c); + return this; + }; + + /** + * Centers a p5 Element either vertically, horizontally, + * or both, relative to its parent or according to + * the body if the Element has no parent. If no argument is passed + * the Element is aligned both vertically and horizontally. + * + * @method center + * @param {String} [align] passing 'vertical', 'horizontal' aligns element accordingly + * @chainable + * + * @example + *
+ * function setup() { + * var div = createDiv('').size(10, 10); + * div.style('background-color', 'orange'); + * div.center(); + * } + *
+ */ + p5.Element.prototype.center = function(align) { + var style = this.elt.style.display; + var hidden = this.elt.style.display === 'none'; + var parentHidden = this.parent().style.display === 'none'; + var pos = { x: this.elt.offsetLeft, y: this.elt.offsetTop }; + + if (hidden) this.show(); + + this.elt.style.display = 'block'; + this.position(0, 0); + + if (parentHidden) this.parent().style.display = 'block'; + + var wOffset = Math.abs(this.parent().offsetWidth - this.elt.offsetWidth); + var hOffset = Math.abs(this.parent().offsetHeight - this.elt.offsetHeight); + var y = pos.y; + var x = pos.x; + + if (align === 'both' || align === undefined) { + this.position(wOffset / 2, hOffset / 2); + } else if (align === 'horizontal') { + this.position(wOffset / 2, y); + } else if (align === 'vertical') { + this.position(x, hOffset / 2); + } + + this.style('display', style); + + if (hidden) this.hide(); + + if (parentHidden) this.parent().style.display = 'none'; + + return this; + }; + + /** + * + * If an argument is given, sets the inner HTML of the element, + * replacing any existing html. If true is included as a second + * argument, html is appended instead of replacing existing html. + * If no arguments are given, returns + * the inner HTML of the element. + * + * @for p5.Element + * @method html + * @returns {String} the inner HTML of the element + * @example + *
+ * var div = createDiv('').size(100, 100); + * div.html('hi'); + *
+ *
+ * var div = createDiv('Hello ').size(100, 100); + * div.html('World', true); + *
+ */ + /** + * @method html + * @param {String} [html] the HTML to be placed inside the element + * @param {boolean} [append] whether to append HTML to existing + * @chainable + */ + p5.Element.prototype.html = function() { + if (arguments.length === 0) { + return this.elt.innerHTML; + } else if (arguments[1]) { + this.elt.innerHTML += arguments[0]; + return this; + } else { + this.elt.innerHTML = arguments[0]; + return this; + } + }; + + /** + * + * Sets the position of the element relative to (0, 0) of the + * window. Essentially, sets position:absolute and left and top + * properties of style. If no arguments given returns the x and y position + * of the element in an object. + * + * @method position + * @returns {Object} the x and y position of the element in an object + * @example + *
+ * function setup() { + * var cnv = createCanvas(100, 100); + * // positions canvas 50px to the right and 100px + * // below upper left corner of the window + * cnv.position(50, 100); + * } + *
+ */ + /** + * @method position + * @param {Number} [x] x-position relative to upper left of window + * @param {Number} [y] y-position relative to upper left of window + * @chainable + */ + p5.Element.prototype.position = function() { + if (arguments.length === 0) { + return { x: this.elt.offsetLeft, y: this.elt.offsetTop }; + } else { + this.elt.style.position = 'absolute'; + this.elt.style.left = arguments[0] + 'px'; + this.elt.style.top = arguments[1] + 'px'; + this.x = arguments[0]; + this.y = arguments[1]; + return this; + } + }; + + /* Helper method called by p5.Element.style() */ + p5.Element.prototype._translate = function() { + this.elt.style.position = 'absolute'; + // save out initial non-translate transform styling + var transform = ''; + if (this.elt.style.transform) { + transform = this.elt.style.transform.replace(/translate3d\(.*\)/g, ''); + transform = transform.replace(/translate[X-Z]?\(.*\)/g, ''); + } + if (arguments.length === 2) { + this.elt.style.transform = + 'translate(' + arguments[0] + 'px, ' + arguments[1] + 'px)'; + } else if (arguments.length > 2) { + this.elt.style.transform = + 'translate3d(' + + arguments[0] + + 'px,' + + arguments[1] + + 'px,' + + arguments[2] + + 'px)'; + if (arguments.length === 3) { + this.elt.parentElement.style.perspective = '1000px'; + } else { + this.elt.parentElement.style.perspective = arguments[3] + 'px'; + } + } + // add any extra transform styling back on end + this.elt.style.transform += transform; + return this; + }; + + /* Helper method called by p5.Element.style() */ + p5.Element.prototype._rotate = function() { + // save out initial non-rotate transform styling + var transform = ''; + if (this.elt.style.transform) { + transform = this.elt.style.transform.replace(/rotate3d\(.*\)/g, ''); + transform = transform.replace(/rotate[X-Z]?\(.*\)/g, ''); + } + + if (arguments.length === 1) { + this.elt.style.transform = 'rotate(' + arguments[0] + 'deg)'; + } else if (arguments.length === 2) { + this.elt.style.transform = + 'rotate(' + arguments[0] + 'deg, ' + arguments[1] + 'deg)'; + } else if (arguments.length === 3) { + this.elt.style.transform = 'rotateX(' + arguments[0] + 'deg)'; + this.elt.style.transform += 'rotateY(' + arguments[1] + 'deg)'; + this.elt.style.transform += 'rotateZ(' + arguments[2] + 'deg)'; + } + // add remaining transform back on + this.elt.style.transform += transform; + return this; + }; + + /** + * Sets the given style (css) property (1st arg) of the element with the + * given value (2nd arg). If a single argument is given, .style() + * returns the value of the given property; however, if the single argument + * is given in css syntax ('text-align:center'), .style() sets the css + * appropriately. + * + * @method style + * @param {String} property property to be set + * @returns {String} value of property + * @example + *
+ * var myDiv = createDiv('I like pandas.'); + * myDiv.style('font-size', '18px'); + * myDiv.style('color', '#ff0000'); + *
+ *
+ * var col = color(25, 23, 200, 50); + * var button = createButton('button'); + * button.style('background-color', col); + * button.position(10, 10); + *
+ *
+ * var myDiv; + * function setup() { + * background(200); + * myDiv = createDiv('I like gray.'); + * myDiv.position(20, 20); + * } + * + * function draw() { + * myDiv.style('font-size', mouseX + 'px'); + * } + *
+ */ + /** + * @method style + * @param {String} property + * @param {String|Number|p5.Color} value value to assign to property + * @return {String} current value of property, if no value is given as second argument + * @chainable + */ + p5.Element.prototype.style = function(prop, val) { + var self = this; + + if (val instanceof p5.Color) { + val = + 'rgba(' + + val.levels[0] + + ',' + + val.levels[1] + + ',' + + val.levels[2] + + ',' + + val.levels[3] / 255 + + ')'; + } + + if (typeof val === 'undefined') { + // input provided as single line string + if (prop.indexOf(':') === -1) { + var styles = window.getComputedStyle(self.elt); + var style = styles.getPropertyValue(prop); + return style; + } else { + var attrs = prop.split(';'); + for (var i = 0; i < attrs.length; i++) { + var parts = attrs[i].split(':'); + if (parts[0] && parts[1]) { + this.elt.style[parts[0].trim()] = parts[1].trim(); + } + } + } + } else { + // input provided as key,val pair + this.elt.style[prop] = val; + if ( + prop === 'width' || + prop === 'height' || + prop === 'left' || + prop === 'top' + ) { + var numVal = val.replace(/\D+/g, ''); + this[prop] = parseInt(numVal, 10); + } + } + return this; + }; + + /** + * + * Adds a new attribute or changes the value of an existing attribute + * on the specified element. If no value is specified, returns the + * value of the given attribute, or null if attribute is not set. + * + * @method attribute + * @return {String} value of attribute + * + * @example + *
+ * var myDiv = createDiv('I like pandas.'); + * myDiv.attribute('align', 'center'); + *
+ */ + /** + * @method attribute + * @param {String} attr attribute to set + * @param {String} value value to assign to attribute + * @chainable + */ + p5.Element.prototype.attribute = function(attr, value) { + //handling for checkboxes and radios to ensure options get + //attributes not divs + if ( + this.elt.firstChild != null && + (this.elt.firstChild.type === 'checkbox' || + this.elt.firstChild.type === 'radio') + ) { + if (typeof value === 'undefined') { + return this.elt.firstChild.getAttribute(attr); + } else { + for (var i = 0; i < this.elt.childNodes.length; i++) { + this.elt.childNodes[i].setAttribute(attr, value); + } + } + } else if (typeof value === 'undefined') { + return this.elt.getAttribute(attr); + } else { + this.elt.setAttribute(attr, value); + return this; + } + }; + + /** + * + * Removes an attribute on the specified element. + * + * @method removeAttribute + * @param {String} attr attribute to remove + * @chainable + * + * @example + *
+ * var button; + * var checkbox; + * + * function setup() { + * checkbox = createCheckbox('enable', true); + * checkbox.changed(enableButton); + * button = createButton('button'); + * button.position(10, 10); + * } + * + * function enableButton() { + * if (this.checked()) { + * // Re-enable the button + * button.removeAttribute('disabled'); + * } else { + * // Disable the button + * button.attribute('disabled', ''); + * } + * } + *
+ */ + p5.Element.prototype.removeAttribute = function(attr) { + if ( + this.elt.firstChild != null && + (this.elt.firstChild.type === 'checkbox' || + this.elt.firstChild.type === 'radio') + ) { + for (var i = 0; i < this.elt.childNodes.length; i++) { + this.elt.childNodes[i].removeAttribute(attr); + } + } + this.elt.removeAttribute(attr); + return this; + }; + + /** + * Either returns the value of the element if no arguments + * given, or sets the value of the element. + * + * @method value + * @return {String|Number} value of the element + * @example + *
+ * // gets the value + * var inp; + * function setup() { + * inp = createInput(''); + * } + * + * function mousePressed() { + * print(inp.value()); + * } + *
+ *
+ * // sets the value + * var inp; + * function setup() { + * inp = createInput('myValue'); + * } + * + * function mousePressed() { + * inp.value('myValue'); + * } + *
+ */ + /** + * @method value + * @param {String|Number} value + * @chainable + */ + p5.Element.prototype.value = function() { + if (arguments.length > 0) { + this.elt.value = arguments[0]; + return this; + } else { + if (this.elt.type === 'range') { + return parseFloat(this.elt.value); + } else return this.elt.value; + } + }; + + /** + * + * Shows the current element. Essentially, setting display:block for the style. + * + * @method show + * @chainable + * @example + *
+ * var div = createDiv('div'); + * div.style('display', 'none'); + * div.show(); // turns display to block + *
+ */ + p5.Element.prototype.show = function() { + this.elt.style.display = 'block'; + return this; + }; + + /** + * Hides the current element. Essentially, setting display:none for the style. + * + * @method hide + * @chainable + * @example + *
+ * var div = createDiv('this is a div'); + * div.hide(); + *
+ */ + p5.Element.prototype.hide = function() { + this.elt.style.display = 'none'; + return this; + }; + + /** + * + * Sets the width and height of the element. AUTO can be used to + * only adjust one dimension at a time. If no arguments are given, it + * returns the width and height of the element in an object. In case of + * elements which need to be loaded, such as images, it is recommended + * to call the function after the element has finished loading. + * + * @method size + * @return {Object} the width and height of the element in an object + * @example + *
+ * let div = createDiv('this is a div'); + * div.size(100, 100); + * let img = createImg('assets/laDefense.jpg', () => { + * img.size(10, AUTO); + * }); + *
+ */ + /** + * @method size + * @param {Number|Constant} w width of the element, either AUTO, or a number + * @param {Number|Constant} [h] height of the element, either AUTO, or a number + * @chainable + */ + p5.Element.prototype.size = function(w, h) { + if (arguments.length === 0) { + return { width: this.elt.offsetWidth, height: this.elt.offsetHeight }; + } else { + var aW = w; + var aH = h; + var AUTO = p5.prototype.AUTO; + if (aW !== AUTO || aH !== AUTO) { + if (aW === AUTO) { + aW = h * this.width / this.height; + } else if (aH === AUTO) { + aH = w * this.height / this.width; + } + // set diff for cnv vs normal div + if (this.elt instanceof HTMLCanvasElement) { + var j = {}; + var k = this.elt.getContext('2d'); + var prop; + for (prop in k) { + j[prop] = k[prop]; + } + this.elt.setAttribute('width', aW * this._pInst._pixelDensity); + this.elt.setAttribute('height', aH * this._pInst._pixelDensity); + this.elt.style.width = aW + 'px'; + this.elt.style.height = aH + 'px'; + this._pInst.scale( + this._pInst._pixelDensity, + this._pInst._pixelDensity + ); + for (prop in j) { + this.elt.getContext('2d')[prop] = j[prop]; + } + } else { + this.elt.style.width = aW + 'px'; + this.elt.style.height = aH + 'px'; + this.elt.width = aW; + this.elt.height = aH; + } + + this.width = this.elt.offsetWidth; + this.height = this.elt.offsetHeight; + + if (this._pInst && this._pInst._curElement) { + // main canvas associated with p5 instance + if (this._pInst._curElement.elt === this.elt) { + this._pInst._setProperty('width', this.elt.offsetWidth); + this._pInst._setProperty('height', this.elt.offsetHeight); + } + } + } + return this; + } + }; + + /** + * Removes the element and deregisters all listeners. + * @method remove + * @example + *
+ * var myDiv = createDiv('this is some text'); + * myDiv.remove(); + *
+ */ + p5.Element.prototype.remove = function() { + // deregister events + for (var ev in this._events) { + this.elt.removeEventListener(ev, this._events[ev]); + } + if (this.elt.parentNode) { + this.elt.parentNode.removeChild(this.elt); + } + delete this; + }; + + /** + * Registers a callback that gets called every time a file that is + * dropped on the element has been loaded. + * p5 will load every dropped file into memory and pass it as a p5.File object to the callback. + * Multiple files dropped at the same time will result in multiple calls to the callback. + * + * You can optionally pass a second callback which will be registered to the raw + * drop event. + * The callback will thus be provided the original + * DragEvent. + * Dropping multiple files at the same time will trigger the second callback once per drop, + * whereas the first callback will trigger for each loaded file. + * + * @method drop + * @param {Function} callback callback to receive loaded file, called for each file dropped. + * @param {Function} [fxn] callback triggered once when files are dropped with the drop event. + * @chainable + * @example + *
+ * function setup() { + * var 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); + * } + *
+ * + *
+ * var img; + * + * function setup() { + * var c = createCanvas(100, 100); + * background(200); + * textAlign(CENTER); + * text('drop image', width / 2, height / 2); + * c.drop(gotFile); + * } + * + * function draw() { + * if (img) { + * image(img, 0, 0, width, height); + * } + * } + * + * function gotFile(file) { + * img = createImg(file.data).hide(); + * } + *
+ * + * @alt + * Canvas turns into whatever image is dragged/dropped onto it. + */ + p5.Element.prototype.drop = function(callback, fxn) { + // Is the file stuff supported? + if (window.File && window.FileReader && window.FileList && window.Blob) { + if (!this._dragDisabled) { + this._dragDisabled = true; + + var preventDefault = function(evt) { + evt.preventDefault(); + }; + + // If you want to be able to drop you've got to turn off + // a lot of default behavior. + // avoid `attachListener` here, since it overrides other handlers. + this.elt.addEventListener('dragover', preventDefault); + + // If this is a drag area we need to turn off the default behavior + this.elt.addEventListener('dragleave', preventDefault); + } + + // Deal with the files + p5.Element._attachListener( + 'drop', + function(evt) { + evt.preventDefault(); + // Call the second argument as a callback that receives the raw drop event + if (typeof fxn === 'function') { + fxn.call(this, evt); + } + // A FileList + var files = evt.dataTransfer.files; + + // Load each one and trigger the callback + for (var i = 0; i < files.length; i++) { + var f = files[i]; + p5.File._load(f, callback); + } + }, + this + ); + } else { + console.log('The File APIs are not fully supported in this browser.'); + } + + return this; + }; + + // ============================================================================= + // p5.MediaElement additions + // ============================================================================= + + /** + * Extends p5.Element to handle audio and video. In addition to the methods + * of p5.Element, it also contains methods for controlling media. It is not + * called directly, but p5.MediaElements are created by calling createVideo, + * createAudio, and createCapture. + * + * @class p5.MediaElement + * @constructor + * @param {String} elt DOM node that is wrapped + */ + p5.MediaElement = function(elt, pInst) { + p5.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; + this._pixelsDirty = true; + this._pixelsTime = -1; // the time at which we last updated 'pixels' + + /** + * Path to the media element source. + * + * @property src + * @return {String} src + * @example + *
+ * var 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() { + 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(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); + }; + }; + p5.MediaElement.prototype = Object.create(p5.Element.prototype); + + /** + * Play an HTML5 media element. + * + * @method play + * @chainable + * @example + *
+ * var 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); + * } + * } + *
+ */ + p5.MediaElement.prototype.play = function() { + if (this.elt.currentTime === this.elt.duration) { + this.elt.currentTime = 0; + } + var promise; + if (this.elt.readyState > 1) { + promise = this.elt.play(); + } else { + // in Chrome, playback cannot resume after being stopped and must reload + this.elt.load(); + promise = this.elt.play(); + } + if (promise && promise.catch) { + promise.catch(function(e) { + console.log( + 'WARN: Element play method raised an error asynchronously', + 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 + * var ele; + * + * //while our audio is playing, + * //this will be set to true + * var sampleIsPlaying = false; + * + * function setup() { + * //Here we create a p5.MediaElement object + * //using the createAudio() function. + * ele = createAudio('assets/beat.mp3'); + * background(200); + * textAlign(CENTER); + * text('Click to play!', width / 2, height / 2); + * } + * + * function mouseClicked() { + * //here we test if the mouse is over the + * //canvas element when it's clicked + * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) { + * background(200); + * + * if (sampleIsPlaying) { + * //if the sample is currently playing + * //calling the stop() function on + * //our p5.MediaElement will stop + * //it and reset its current + * //time to 0 (i.e. it will start + * //at the beginning the next time + * //you play it) + * ele.stop(); + * + * sampleIsPlaying = false; + * text('Click to play!', width / 2, height / 2); + * } else { + * //loop our sound element until we + * //call ele.stop() on it. + * ele.loop(); + * + * sampleIsPlaying = true; + * text('Click to stop!', width / 2, height / 2); + * } + * } + * } + *
+ */ + p5.MediaElement.prototype.stop = function() { + this.elt.pause(); + this.elt.currentTime = 0; + return this; + }; + + /** + * Pauses an HTML5 media element. + * + * @method pause + * @chainable + * @example + *
+ * //This example both starts + * //and pauses a sound sample + * //when the user clicks the canvas + * + * //We will store the p5.MediaElement + * //object in here + * var ele; + * + * //while our audio is playing, + * //this will be set to true + * var 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); + * } + * } + * } + *
+ */ + p5.MediaElement.prototype.pause = function() { + this.elt.pause(); + return this; + }; + + /** + * Set 'loop' to true for an HTML5 media element, and starts playing. + * + * @method loop + * @chainable + * @example + *
+ * //Clicking the canvas will loop + * //the audio sample until the user + * //clicks again to stop it + * + * //We will store the p5.MediaElement + * //object in here + * var ele; + * + * //while our audio is playing, + * //this will be set to true + * var sampleIsLooping = false; + * + * function setup() { + * //Here we create a p5.MediaElement object + * //using the createAudio() function. + * ele = createAudio('assets/lucky_dragons.mp3'); + * background(200); + * textAlign(CENTER); + * text('Click to loop!', width / 2, height / 2); + * } + * + * function mouseClicked() { + * //here we test if the mouse is over the + * //canvas element when it's clicked + * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) { + * background(200); + * + * if (!sampleIsLooping) { + * //loop our sound element until we + * //call ele.stop() on it. + * ele.loop(); + * + * sampleIsLooping = true; + * text('Click to stop!', width / 2, height / 2); + * } else { + * ele.stop(); + * + * sampleIsLooping = false; + * text('Click to loop!', width / 2, height / 2); + * } + * } + * } + *
+ */ + p5.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 + * var ele; + * //while our audio is playing, + * //this will be set to true + * var sampleIsPlaying = false; + * + * function setup() { + * //Here we create a p5.MediaElement object + * //using the createAudio() function. + * ele = createAudio('assets/beat.mp3'); + * background(200); + * textAlign(CENTER); + * text('Click to play!', width / 2, height / 2); + * } + * + * function mouseClicked() { + * //here we test if the mouse is over the + * //canvas element when it's clicked + * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) { + * background(200); + * + * if (sampleIsPlaying) { + * ele.noLoop(); + * text('No more Loops!', width / 2, height / 2); + * } else { + * ele.loop(); + * sampleIsPlaying = true; + * text('Click to stop looping!', width / 2, height / 2); + * } + * } + * } + *
+ * + */ + p5.MediaElement.prototype.noLoop = function() { + this.elt.setAttribute('loop', false); + return this; + }; + + /** + * Set HTML5 media element to autoplay or not. + * + * @method autoplay + * @param {Boolean} autoplay whether the element should autoplay + * @chainable + */ + p5.MediaElement.prototype.autoplay = function(val) { + this.elt.setAttribute('autoplay', val); + return this; + }; + + /** + * Sets volume for this HTML5 media element. If no argument is given, + * returns the current volume. + * + * @method volume + * @return {Number} current volume + * + * @example + *
+ * var ele; + * function setup() { + * // p5.MediaElement objects are usually created + * // by calling the createAudio(), createVideo(), + * // and createCapture() functions. + * // In this example we create + * // a new p5.MediaElement via createAudio(). + * ele = createAudio('assets/lucky_dragons.mp3'); + * background(250); + * textAlign(CENTER); + * text('Click to Play!', width / 2, height / 2); + * } + * function mouseClicked() { + * // Here we call the volume() function + * // on the sound element to set its volume + * // Volume must be between 0.0 and 1.0 + * ele.volume(0.2); + * ele.play(); + * background(200); + * text('You clicked Play!', width / 2, height / 2); + * } + *
+ *
+ * var audio; + * var counter = 0; + * + * function loaded() { + * audio.play(); + * } + * + * function setup() { + * audio = createAudio('assets/lucky_dragons.mp3', loaded); + * textAlign(CENTER); + * } + * + * function draw() { + * if (counter === 0) { + * background(0, 255, 0); + * text('volume(0.9)', width / 2, height / 2); + * } else if (counter === 1) { + * background(255, 255, 0); + * text('volume(0.5)', width / 2, height / 2); + * } else if (counter === 2) { + * background(255, 0, 0); + * text('volume(0.1)', width / 2, height / 2); + * } + * } + * + * function mousePressed() { + * counter++; + * if (counter === 0) { + * audio.volume(0.9); + * } else if (counter === 1) { + * audio.volume(0.5); + * } else if (counter === 2) { + * audio.volume(0.1); + * } else { + * counter = 0; + * audio.volume(0.9); + * } + * } + * + *
+ */ + /** + * @method volume + * @param {Number} val volume between 0.0 and 1.0 + * @chainable + */ + p5.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 + * var ele; + * var button; + * + * function setup() { + * createCanvas(710, 400); + * //Here we create a p5.MediaElement object + * //using the createAudio() function. + * ele = createAudio('assets/beat.mp3'); + * ele.loop(); + * background(200); + * + * button = createButton('2x speed'); + * button.position(100, 68); + * button.mousePressed(twice_speed); + * + * button = createButton('half speed'); + * button.position(200, 68); + * button.mousePressed(half_speed); + * + * button = createButton('reverse play'); + * button.position(300, 68); + * button.mousePressed(reverse_speed); + * + * button = createButton('STOP'); + * button.position(400, 68); + * button.mousePressed(stop_song); + * + * button = createButton('PLAY!'); + * button.position(500, 68); + * button.mousePressed(play_speed); + * } + * + * function twice_speed() { + * ele.speed(2); + * } + * + * function half_speed() { + * ele.speed(0.5); + * } + * + * function reverse_speed() { + * ele.speed(-1); + * } + * + * function stop_song() { + * ele.stop(); + * } + * + * function play_speed() { + * ele.play(); + * } + *
+ */ + /** + * @method speed + * @param {Number} speed speed multiplier for element playback + * @chainable + */ + p5.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 + *
+ * var ele; + * var 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 + */ + p5.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 + *
+ * var 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); + * } + *
+ */ + p5.MediaElement.prototype.duration = function() { + return this.elt.duration; + }; + p5.MediaElement.prototype.pixels = []; + p5.MediaElement.prototype._ensureCanvas = function() { + if (!this.canvas) this.loadPixels(); + }; + p5.MediaElement.prototype.loadPixels = function() { + if (!this.canvas) { + this.canvas = document.createElement('canvas'); + this.drawingContext = this.canvas.getContext('2d'); + } + 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._pixelsDirty = true; + } + + var currentTime = this.elt.currentTime; + if (this._pixelsDirty || this._pixelsTime !== currentTime) { + // only update the pixels array if it's dirty, or + // if the video time has changed. + this._pixelsTime = currentTime; + this._pixelsDirty = true; + + this.drawingContext.drawImage( + this.elt, + 0, + 0, + this.canvas.width, + this.canvas.height + ); + p5.Renderer2D.prototype.loadPixels.call(this); + } + } + this.setModified(true); + return this; + }; + p5.MediaElement.prototype.updatePixels = function(x, y, w, h) { + if (this.loadedmetadata) { + // wait for metadata + this._ensureCanvas(); + p5.Renderer2D.prototype.updatePixels.call(this, x, y, w, h); + } + this.setModified(true); + return this; + }; + p5.MediaElement.prototype.get = function() { + this._ensureCanvas(); + return p5.Renderer2D.prototype.get.apply(this, arguments); + }; + p5.MediaElement.prototype._getPixel = function() { + if (this.loadedmetadata) { + // wait for metadata + var currentTime = this.elt.currentTime; + if (this._pixelsTime !== currentTime) { + this.loadPixels(); + } else { + this._ensureCanvas(); + } + } + return p5.Renderer2D.prototype._getPixel.apply(this, arguments); + }; + + p5.MediaElement.prototype.set = function(x, y, imgOrCol) { + if (this.loadedmetadata) { + // wait for metadata + this._ensureCanvas(); + p5.Renderer2D.prototype.set.call(this, x, y, imgOrCol); + this.setModified(true); + } + }; + p5.MediaElement.prototype.copy = function() { + this._ensureCanvas(); + p5.Renderer2D.prototype.copy.apply(this, arguments); + }; + p5.MediaElement.prototype.mask = function() { + this.loadPixels(); + this.setModified(true); + p5.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. + */ + p5.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 + */ + p5.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() { + * var audioEl = createAudio('assets/beat.mp3'); + * audioEl.showControls(); + * audioEl.onended(sayDone); + * } + * + * function sayDone(elt) { + * alert('done playing ' + elt.src); + * } + *
+ */ + p5.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 master + * 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 + */ + p5.MediaElement.prototype.connect = function(obj) { + var audioContext, masterOutput; + + // if p5.sound exists, same audio context + if (typeof p5.prototype.getAudioContext === 'function') { + audioContext = p5.prototype.getAudioContext(); + masterOutput = p5.soundOut.input; + } else { + try { + audioContext = obj.context; + masterOutput = 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 master output when this method is first called + this.audioSourceNode.connect(masterOutput); + } + + // connect to object if provided + if (obj) { + if (obj.input) { + this.audioSourceNode.connect(obj.input); + } else { + this.audioSourceNode.connect(obj); + } + } else { + // otherwise connect to master output of p5.sound / AudioContext + this.audioSourceNode.connect(masterOutput); + } + }; + + /** + * Disconnect all Web Audio routing, including to master output. + * This is useful if you want to re-route the output through + * audio effects, for example. + * + * @method disconnect + */ + p5.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 + *
+ * var 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); + * } + *
+ */ + p5.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 + *
+ * var 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); + * } + *
+ */ + p5.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(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() { + * noCanvas(); + * + * var 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); + * } + *
+ */ + p5.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 + *
+ * var 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); + * } + *
+ */ + p5.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 + *
+ * var 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); + * } + *
+ */ + p5.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). + p5.MediaElement.prototype._onTimeUpdate = function() { + var playbackTime = this.time(); + + for (var i = 0; i < this._cues.length; i++) { + var callbackTime = this._cues[i].time; + var val = this._cues[i].val; + + if (this._prevTime < callbackTime && callbackTime <= playbackTime) { + // pass the scheduled callbackTime as parameter to the callback + this._cues[i].callback(val); + } + } + + this._prevTime = playbackTime; + }; + + /** + * Base class for a file. + * Used for Element.drop and createFileInput. + * + * @class p5.File + * @constructor + * @param {File} file File that is wrapped + */ + p5.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 image data. + * + * @property data + */ + this.data = undefined; + }; + + p5.File._createLoader = function(theFile, callback) { + var reader = new FileReader(); + reader.onload = function(e) { + var p5file = new p5.File(theFile); + p5file.data = e.target.result; + callback(p5file); + }; + return reader; + }; + + p5.File._load = function(f, callback) { + // Text or data? + // This should likely be improved + if (/^text\//.test(f.type)) { + p5.File._createLoader(f, callback).readAsText(f); + } else if (!/^(video|audio)\//.test(f.type)) { + p5.File._createLoader(f, callback).readAsDataURL(f); + } else { + var file = new p5.File(f); + file.data = URL.createObjectURL(f); + callback(file); + } + }; +}); diff --git a/pyp5js/static/p5/addons/p5.dom.min.js b/pyp5js/static/p5/addons/p5.dom.min.js new file mode 100644 index 00000000..385b2ea4 --- /dev/null +++ b/pyp5js/static/p5/addons/p5.dom.min.js @@ -0,0 +1,3 @@ +/*! p5.js v0.8.0 April 08, 2019 */ + +!function(t,e){"function"==typeof define&&define.amd?define("p5.dom",["p5"],function(t){e(t)}):"object"==typeof exports?e(require("../p5")):e(t.p5)}(this,function(d){function l(t){var e=document;return"string"==typeof t&&"#"===t[0]?(t=t.slice(1),e=document.getElementById(t)||document):t instanceof d.Element?e=t.elt:t instanceof HTMLElement&&(e=t),e}function c(t,e,i){(e._userNode?e._userNode:document.body).appendChild(t);var n=i?new d.MediaElement(t,e):new d.Element(t,e);return e._elements.push(n),n}d.prototype.select=function(t,e){d._validateParameters("select",arguments);var i=null,n=l(e);return(i="."===t[0]?(t=t.slice(1),(i=n.getElementsByClassName(t)).length?i[0]:null):"#"===t[0]?(t=t.slice(1),n.getElementById(t)):(i=n.getElementsByTagName(t)).length?i[0]:null)?this._wrapElement(i):null},d.prototype.selectAll=function(t,e){d._validateParameters("selectAll",arguments);var i,n=[],r=l(e);if(i="."===t[0]?(t=t.slice(1),r.getElementsByClassName(t)):r.getElementsByTagName(t))for(var o=0;oWeb Audio functionality including audio input, + * playback, analysis and synthesis. + *

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

+ * p5.sound is on GitHub. + * Download the latest version + * here. + * + * @module p5.sound + * @submodule p5.sound + * @for p5.sound + * @main + */ + +/** + * p5.sound + * https://p5js.org/reference/#/libraries/p5.sound + * + * From the Processing Foundation and contributors + * https://github.com/processing/p5.js-sound/graphs/contributors + * + * MIT License (MIT) + * https://github.com/processing/p5.js-sound/blob/master/LICENSE + * + * Some of the many audio libraries & resources that inspire p5.sound: + * - TONE.js (c) Yotam Mann. Licensed under The MIT License (MIT). https://github.com/TONEnoTONE/Tone.js + * - buzz.js (c) Jay Salvat. Licensed under The MIT License (MIT). http://buzz.jaysalvat.com/ + * - Boris Smus Web Audio API book, 2013. Licensed under the Apache License http://www.apache.org/licenses/LICENSE-2.0 + * - wavesurfer.js https://github.com/katspaugh/wavesurfer.js + * - Web Audio Components by Jordan Santell https://github.com/web-audio-components + * - Wilm Thoben's Sound library for Processing https://github.com/processing/processing/tree/master/java/libraries/sound + * + * Web Audio API: http://w3.org/TR/webaudio/ + */ + +(function (root, factory) { + if (typeof define === 'function' && define.amd) + define('p5.sound', ['p5'], function (p5) { (factory(p5));}); + else if (typeof exports === 'object') + factory(require('../p5')); + else + factory(root['p5']); +}(this, function (p5) { + +var shims; +'use strict'; /** + * This module has shims + */ +shims = function () { + /* AudioContext Monkeypatch + Copyright 2013 Chris Wilson + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + (function () { + function fixSetTarget(param) { + if (!param) + // if NYI, just return + return; + if (!param.setTargetAtTime) + param.setTargetAtTime = param.setTargetValueAtTime; + } + if (window.hasOwnProperty('webkitAudioContext') && !window.hasOwnProperty('AudioContext')) { + window.AudioContext = window.webkitAudioContext; + if (typeof AudioContext.prototype.createGain !== 'function') + AudioContext.prototype.createGain = AudioContext.prototype.createGainNode; + if (typeof AudioContext.prototype.createDelay !== 'function') + AudioContext.prototype.createDelay = AudioContext.prototype.createDelayNode; + if (typeof AudioContext.prototype.createScriptProcessor !== 'function') + AudioContext.prototype.createScriptProcessor = AudioContext.prototype.createJavaScriptNode; + if (typeof AudioContext.prototype.createPeriodicWave !== 'function') + AudioContext.prototype.createPeriodicWave = AudioContext.prototype.createWaveTable; + AudioContext.prototype.internal_createGain = AudioContext.prototype.createGain; + AudioContext.prototype.createGain = function () { + var node = this.internal_createGain(); + fixSetTarget(node.gain); + return node; + }; + AudioContext.prototype.internal_createDelay = AudioContext.prototype.createDelay; + AudioContext.prototype.createDelay = function (maxDelayTime) { + var node = maxDelayTime ? this.internal_createDelay(maxDelayTime) : this.internal_createDelay(); + fixSetTarget(node.delayTime); + return node; + }; + AudioContext.prototype.internal_createBufferSource = AudioContext.prototype.createBufferSource; + AudioContext.prototype.createBufferSource = function () { + var node = this.internal_createBufferSource(); + if (!node.start) { + node.start = function (when, offset, duration) { + if (offset || duration) + this.noteGrainOn(when || 0, offset, duration); + else + this.noteOn(when || 0); + }; + } else { + node.internal_start = node.start; + node.start = function (when, offset, duration) { + if (typeof duration !== 'undefined') + node.internal_start(when || 0, offset, duration); + else + node.internal_start(when || 0, offset || 0); + }; + } + if (!node.stop) { + node.stop = function (when) { + this.noteOff(when || 0); + }; + } else { + node.internal_stop = node.stop; + node.stop = function (when) { + node.internal_stop(when || 0); + }; + } + fixSetTarget(node.playbackRate); + return node; + }; + AudioContext.prototype.internal_createDynamicsCompressor = AudioContext.prototype.createDynamicsCompressor; + AudioContext.prototype.createDynamicsCompressor = function () { + var node = this.internal_createDynamicsCompressor(); + fixSetTarget(node.threshold); + fixSetTarget(node.knee); + fixSetTarget(node.ratio); + fixSetTarget(node.reduction); + fixSetTarget(node.attack); + fixSetTarget(node.release); + return node; + }; + AudioContext.prototype.internal_createBiquadFilter = AudioContext.prototype.createBiquadFilter; + AudioContext.prototype.createBiquadFilter = function () { + var node = this.internal_createBiquadFilter(); + fixSetTarget(node.frequency); + fixSetTarget(node.detune); + fixSetTarget(node.Q); + fixSetTarget(node.gain); + return node; + }; + if (typeof AudioContext.prototype.createOscillator !== 'function') { + AudioContext.prototype.internal_createOscillator = AudioContext.prototype.createOscillator; + AudioContext.prototype.createOscillator = function () { + var node = this.internal_createOscillator(); + if (!node.start) { + node.start = function (when) { + this.noteOn(when || 0); + }; + } else { + node.internal_start = node.start; + node.start = function (when) { + node.internal_start(when || 0); + }; + } + if (!node.stop) { + node.stop = function (when) { + this.noteOff(when || 0); + }; + } else { + node.internal_stop = node.stop; + node.stop = function (when) { + node.internal_stop(when || 0); + }; + } + if (!node.setPeriodicWave) + node.setPeriodicWave = node.setWaveTable; + fixSetTarget(node.frequency); + fixSetTarget(node.detune); + return node; + }; + } + } + if (window.hasOwnProperty('webkitOfflineAudioContext') && !window.hasOwnProperty('OfflineAudioContext')) { + window.OfflineAudioContext = window.webkitOfflineAudioContext; + } + }(window)); + // <-- end MonkeyPatch. + // Polyfill for AudioIn, also handled by p5.dom createCapture + navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; + /** + * Determine which filetypes are supported (inspired by buzz.js) + * The audio element (el) will only be used to test browser support for various audio formats + */ + var el = document.createElement('audio'); + p5.prototype.isSupported = function () { + return !!el.canPlayType; + }; + var isOGGSupported = function () { + return !!el.canPlayType && el.canPlayType('audio/ogg; codecs="vorbis"'); + }; + var isMP3Supported = function () { + return !!el.canPlayType && el.canPlayType('audio/mpeg;'); + }; + var isWAVSupported = function () { + return !!el.canPlayType && el.canPlayType('audio/wav; codecs="1"'); + }; + var isAACSupported = function () { + return !!el.canPlayType && (el.canPlayType('audio/x-m4a;') || el.canPlayType('audio/aac;')); + }; + var isAIFSupported = function () { + return !!el.canPlayType && el.canPlayType('audio/x-aiff;'); + }; + p5.prototype.isFileSupported = function (extension) { + switch (extension.toLowerCase()) { + case 'mp3': + return isMP3Supported(); + case 'wav': + return isWAVSupported(); + case 'ogg': + return isOGGSupported(); + case 'aac': + case 'm4a': + case 'mp4': + return isAACSupported(); + case 'aif': + case 'aiff': + return isAIFSupported(); + default: + return false; + } + }; +}(); +var StartAudioContext; +(function (root, factory) { + if (true) { + StartAudioContext = function () { + return factory(); + }(); + } else if (typeof module === 'object' && module.exports) { + module.exports = factory(); + } else { + root.StartAudioContext = factory(); + } +}(this, function () { + var TapListener = function (element, context) { + this._dragged = false; + this._element = element; + this._bindedMove = this._moved.bind(this); + this._bindedEnd = this._ended.bind(this, context); + element.addEventListener('touchstart', this._bindedEnd); + element.addEventListener('touchmove', this._bindedMove); + element.addEventListener('touchend', this._bindedEnd); + element.addEventListener('mouseup', this._bindedEnd); + }; + TapListener.prototype._moved = function (e) { + this._dragged = true; + }; + TapListener.prototype._ended = function (context) { + if (!this._dragged) { + startContext(context); + } + this._dragged = false; + }; + TapListener.prototype.dispose = function () { + this._element.removeEventListener('touchstart', this._bindedEnd); + this._element.removeEventListener('touchmove', this._bindedMove); + this._element.removeEventListener('touchend', this._bindedEnd); + this._element.removeEventListener('mouseup', this._bindedEnd); + this._bindedMove = null; + this._bindedEnd = null; + this._element = null; + }; + function startContext(context) { + var buffer = context.createBuffer(1, 1, context.sampleRate); + var source = context.createBufferSource(); + source.buffer = buffer; + source.connect(context.destination); + source.start(0); + if (context.resume) { + context.resume(); + } + } + function isStarted(context) { + return context.state === 'running'; + } + function onStarted(context, callback) { + function checkLoop() { + if (isStarted(context)) { + callback(); + } else { + requestAnimationFrame(checkLoop); + if (context.resume) { + context.resume(); + } + } + } + if (isStarted(context)) { + callback(); + } else { + checkLoop(); + } + } + function bindTapListener(element, tapListeners, context) { + if (Array.isArray(element) || NodeList && element instanceof NodeList) { + for (var i = 0; i < element.length; i++) { + bindTapListener(element[i], tapListeners, context); + } + } else if (typeof element === 'string') { + bindTapListener(document.querySelectorAll(element), tapListeners, context); + } else if (element.jquery && typeof element.toArray === 'function') { + bindTapListener(element.toArray(), tapListeners, context); + } else if (Element && element instanceof Element) { + var tap = new TapListener(element, context); + tapListeners.push(tap); + } + } + function StartAudioContext(context, elements, callback) { + var promise = new Promise(function (success) { + onStarted(context, success); + }); + var tapListeners = []; + if (!elements) { + elements = document.body; + } + bindTapListener(elements, tapListeners, context); + promise.then(function () { + for (var i = 0; i < tapListeners.length; i++) { + tapListeners[i].dispose(); + } + tapListeners = null; + if (callback) { + callback(); + } + }); + return promise; + } + return StartAudioContext; +})); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_core_Tone; +Tone_core_Tone = function () { + 'use strict'; + var Tone = function (inputs, outputs) { + if (this.isUndef(inputs) || inputs === 1) { + this.input = this.context.createGain(); + } else if (inputs > 1) { + this.input = new Array(inputs); + } + if (this.isUndef(outputs) || outputs === 1) { + this.output = this.context.createGain(); + } else if (outputs > 1) { + this.output = new Array(inputs); + } + }; + Tone.prototype.set = function (params, value, rampTime) { + if (this.isObject(params)) { + rampTime = value; + } else if (this.isString(params)) { + var tmpObj = {}; + tmpObj[params] = value; + params = tmpObj; + } + paramLoop: + for (var attr in params) { + value = params[attr]; + var parent = this; + if (attr.indexOf('.') !== -1) { + var attrSplit = attr.split('.'); + for (var i = 0; i < attrSplit.length - 1; i++) { + parent = parent[attrSplit[i]]; + if (parent instanceof Tone) { + attrSplit.splice(0, i + 1); + var innerParam = attrSplit.join('.'); + parent.set(innerParam, value); + continue paramLoop; + } + } + attr = attrSplit[attrSplit.length - 1]; + } + var param = parent[attr]; + if (this.isUndef(param)) { + continue; + } + if (Tone.Signal && param instanceof Tone.Signal || Tone.Param && param instanceof Tone.Param) { + if (param.value !== value) { + if (this.isUndef(rampTime)) { + param.value = value; + } else { + param.rampTo(value, rampTime); + } + } + } else if (param instanceof AudioParam) { + if (param.value !== value) { + param.value = value; + } + } else if (param instanceof Tone) { + param.set(value); + } else if (param !== value) { + parent[attr] = value; + } + } + return this; + }; + Tone.prototype.get = function (params) { + if (this.isUndef(params)) { + params = this._collectDefaults(this.constructor); + } else if (this.isString(params)) { + params = [params]; + } + var ret = {}; + for (var i = 0; i < params.length; i++) { + var attr = params[i]; + var parent = this; + var subRet = ret; + if (attr.indexOf('.') !== -1) { + var attrSplit = attr.split('.'); + for (var j = 0; j < attrSplit.length - 1; j++) { + var subAttr = attrSplit[j]; + subRet[subAttr] = subRet[subAttr] || {}; + subRet = subRet[subAttr]; + parent = parent[subAttr]; + } + attr = attrSplit[attrSplit.length - 1]; + } + var param = parent[attr]; + if (this.isObject(params[attr])) { + subRet[attr] = param.get(); + } else if (Tone.Signal && param instanceof Tone.Signal) { + subRet[attr] = param.value; + } else if (Tone.Param && param instanceof Tone.Param) { + subRet[attr] = param.value; + } else if (param instanceof AudioParam) { + subRet[attr] = param.value; + } else if (param instanceof Tone) { + subRet[attr] = param.get(); + } else if (!this.isFunction(param) && !this.isUndef(param)) { + subRet[attr] = param; + } + } + return ret; + }; + Tone.prototype._collectDefaults = function (constr) { + var ret = []; + if (!this.isUndef(constr.defaults)) { + ret = Object.keys(constr.defaults); + } + if (!this.isUndef(constr._super)) { + var superDefs = this._collectDefaults(constr._super); + for (var i = 0; i < superDefs.length; i++) { + if (ret.indexOf(superDefs[i]) === -1) { + ret.push(superDefs[i]); + } + } + } + return ret; + }; + Tone.prototype.toString = function () { + for (var className in Tone) { + var isLetter = className[0].match(/^[A-Z]$/); + var sameConstructor = Tone[className] === this.constructor; + if (this.isFunction(Tone[className]) && isLetter && sameConstructor) { + return className; + } + } + return 'Tone'; + }; + Object.defineProperty(Tone.prototype, 'numberOfInputs', { + get: function () { + if (this.input) { + if (this.isArray(this.input)) { + return this.input.length; + } else { + return 1; + } + } else { + return 0; + } + } + }); + Object.defineProperty(Tone.prototype, 'numberOfOutputs', { + get: function () { + if (this.output) { + if (this.isArray(this.output)) { + return this.output.length; + } else { + return 1; + } + } else { + return 0; + } + } + }); + Tone.prototype.dispose = function () { + if (!this.isUndef(this.input)) { + if (this.input instanceof AudioNode) { + this.input.disconnect(); + } + this.input = null; + } + if (!this.isUndef(this.output)) { + if (this.output instanceof AudioNode) { + this.output.disconnect(); + } + this.output = null; + } + return this; + }; + Tone.prototype.connect = function (unit, outputNum, inputNum) { + if (Array.isArray(this.output)) { + outputNum = this.defaultArg(outputNum, 0); + this.output[outputNum].connect(unit, 0, inputNum); + } else { + this.output.connect(unit, outputNum, inputNum); + } + return this; + }; + Tone.prototype.disconnect = function (destination, outputNum, inputNum) { + if (this.isArray(this.output)) { + if (this.isNumber(destination)) { + this.output[destination].disconnect(); + } else { + outputNum = this.defaultArg(outputNum, 0); + this.output[outputNum].disconnect(destination, 0, inputNum); + } + } else { + this.output.disconnect.apply(this.output, arguments); + } + }; + Tone.prototype.connectSeries = function () { + if (arguments.length > 1) { + var currentUnit = arguments[0]; + for (var i = 1; i < arguments.length; i++) { + var toUnit = arguments[i]; + currentUnit.connect(toUnit); + currentUnit = toUnit; + } + } + return this; + }; + Tone.prototype.chain = function () { + if (arguments.length > 0) { + var currentUnit = this; + for (var i = 0; i < arguments.length; i++) { + var toUnit = arguments[i]; + currentUnit.connect(toUnit); + currentUnit = toUnit; + } + } + return this; + }; + Tone.prototype.fan = function () { + if (arguments.length > 0) { + for (var i = 0; i < arguments.length; i++) { + this.connect(arguments[i]); + } + } + return this; + }; + AudioNode.prototype.chain = Tone.prototype.chain; + AudioNode.prototype.fan = Tone.prototype.fan; + Tone.prototype.defaultArg = function (given, fallback) { + if (this.isObject(given) && this.isObject(fallback)) { + var ret = {}; + for (var givenProp in given) { + ret[givenProp] = this.defaultArg(fallback[givenProp], given[givenProp]); + } + for (var fallbackProp in fallback) { + ret[fallbackProp] = this.defaultArg(given[fallbackProp], fallback[fallbackProp]); + } + return ret; + } else { + return this.isUndef(given) ? fallback : given; + } + }; + Tone.prototype.optionsObject = function (values, keys, defaults) { + var options = {}; + if (values.length === 1 && this.isObject(values[0])) { + options = values[0]; + } else { + for (var i = 0; i < keys.length; i++) { + options[keys[i]] = values[i]; + } + } + if (!this.isUndef(defaults)) { + return this.defaultArg(options, defaults); + } else { + return options; + } + }; + Tone.prototype.isUndef = function (val) { + return typeof val === 'undefined'; + }; + Tone.prototype.isFunction = function (val) { + return typeof val === 'function'; + }; + Tone.prototype.isNumber = function (arg) { + return typeof arg === 'number'; + }; + Tone.prototype.isObject = function (arg) { + return Object.prototype.toString.call(arg) === '[object Object]' && arg.constructor === Object; + }; + Tone.prototype.isBoolean = function (arg) { + return typeof arg === 'boolean'; + }; + Tone.prototype.isArray = function (arg) { + return Array.isArray(arg); + }; + Tone.prototype.isString = function (arg) { + return typeof arg === 'string'; + }; + Tone.noOp = function () { + }; + Tone.prototype._readOnly = function (property) { + if (Array.isArray(property)) { + for (var i = 0; i < property.length; i++) { + this._readOnly(property[i]); + } + } else { + Object.defineProperty(this, property, { + writable: false, + enumerable: true + }); + } + }; + Tone.prototype._writable = function (property) { + if (Array.isArray(property)) { + for (var i = 0; i < property.length; i++) { + this._writable(property[i]); + } + } else { + Object.defineProperty(this, property, { writable: true }); + } + }; + Tone.State = { + Started: 'started', + Stopped: 'stopped', + Paused: 'paused' + }; + Tone.prototype.equalPowerScale = function (percent) { + var piFactor = 0.5 * Math.PI; + return Math.sin(percent * piFactor); + }; + Tone.prototype.dbToGain = function (db) { + return Math.pow(2, db / 6); + }; + Tone.prototype.gainToDb = function (gain) { + return 20 * (Math.log(gain) / Math.LN10); + }; + Tone.prototype.intervalToFrequencyRatio = function (interval) { + return Math.pow(2, interval / 12); + }; + Tone.prototype.now = function () { + return Tone.context.now(); + }; + Tone.now = function () { + return Tone.context.now(); + }; + Tone.extend = function (child, parent) { + if (Tone.prototype.isUndef(parent)) { + parent = Tone; + } + function TempConstructor() { + } + TempConstructor.prototype = parent.prototype; + child.prototype = new TempConstructor(); + child.prototype.constructor = child; + child._super = parent; + }; + var audioContext; + Object.defineProperty(Tone, 'context', { + get: function () { + return audioContext; + }, + set: function (context) { + if (Tone.Context && context instanceof Tone.Context) { + audioContext = context; + } else { + audioContext = new Tone.Context(context); + } + if (Tone.Context) { + Tone.Context.emit('init', audioContext); + } + } + }); + Object.defineProperty(Tone.prototype, 'context', { + get: function () { + return Tone.context; + } + }); + Tone.setContext = function (ctx) { + Tone.context = ctx; + }; + Object.defineProperty(Tone.prototype, 'blockTime', { + get: function () { + return 128 / this.context.sampleRate; + } + }); + Object.defineProperty(Tone.prototype, 'sampleTime', { + get: function () { + return 1 / this.context.sampleRate; + } + }); + Object.defineProperty(Tone, 'supported', { + get: function () { + var hasAudioContext = window.hasOwnProperty('AudioContext') || window.hasOwnProperty('webkitAudioContext'); + var hasPromises = window.hasOwnProperty('Promise'); + var hasWorkers = window.hasOwnProperty('Worker'); + return hasAudioContext && hasPromises && hasWorkers; + } + }); + Tone.version = 'r10'; + if (!window.TONE_SILENCE_VERSION_LOGGING) { + } + return Tone; +}(); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_core_Emitter; +Tone_core_Emitter = function (Tone) { + 'use strict'; + Tone.Emitter = function () { + this._events = {}; + }; + Tone.extend(Tone.Emitter); + Tone.Emitter.prototype.on = function (event, callback) { + var events = event.split(/\W+/); + for (var i = 0; i < events.length; i++) { + var eventName = events[i]; + if (!this._events.hasOwnProperty(eventName)) { + this._events[eventName] = []; + } + this._events[eventName].push(callback); + } + return this; + }; + Tone.Emitter.prototype.off = function (event, callback) { + var events = event.split(/\W+/); + for (var ev = 0; ev < events.length; ev++) { + event = events[ev]; + if (this._events.hasOwnProperty(event)) { + if (Tone.prototype.isUndef(callback)) { + this._events[event] = []; + } else { + var eventList = this._events[event]; + for (var i = 0; i < eventList.length; i++) { + if (eventList[i] === callback) { + eventList.splice(i, 1); + } + } + } + } + } + return this; + }; + Tone.Emitter.prototype.emit = function (event) { + if (this._events) { + var args = Array.apply(null, arguments).slice(1); + if (this._events.hasOwnProperty(event)) { + var eventList = this._events[event]; + for (var i = 0, len = eventList.length; i < len; i++) { + eventList[i].apply(this, args); + } + } + } + return this; + }; + Tone.Emitter.mixin = function (object) { + var functions = [ + 'on', + 'off', + 'emit' + ]; + object._events = {}; + for (var i = 0; i < functions.length; i++) { + var func = functions[i]; + var emitterFunc = Tone.Emitter.prototype[func]; + object[func] = emitterFunc; + } + }; + Tone.Emitter.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._events = null; + return this; + }; + return Tone.Emitter; +}(Tone_core_Tone); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_core_Context; +Tone_core_Context = function (Tone) { + if (!window.hasOwnProperty('AudioContext') && window.hasOwnProperty('webkitAudioContext')) { + window.AudioContext = window.webkitAudioContext; + } + Tone.Context = function (context) { + Tone.Emitter.call(this); + if (!context) { + context = new window.AudioContext(); + } + this._context = context; + for (var prop in this._context) { + this._defineProperty(this._context, prop); + } + this._latencyHint = 'interactive'; + this._lookAhead = 0.1; + this._updateInterval = this._lookAhead / 3; + this._computedUpdateInterval = 0; + this._worker = this._createWorker(); + this._constants = {}; + }; + Tone.extend(Tone.Context, Tone.Emitter); + Tone.Emitter.mixin(Tone.Context); + Tone.Context.prototype._defineProperty = function (context, prop) { + if (this.isUndef(this[prop])) { + Object.defineProperty(this, prop, { + get: function () { + if (typeof context[prop] === 'function') { + return context[prop].bind(context); + } else { + return context[prop]; + } + }, + set: function (val) { + context[prop] = val; + } + }); + } + }; + Tone.Context.prototype.now = function () { + return this._context.currentTime; + }; + Tone.Context.prototype._createWorker = function () { + window.URL = window.URL || window.webkitURL; + var blob = new Blob(['var timeoutTime = ' + (this._updateInterval * 1000).toFixed(1) + ';' + 'self.onmessage = function(msg){' + '\ttimeoutTime = parseInt(msg.data);' + '};' + 'function tick(){' + '\tsetTimeout(tick, timeoutTime);' + '\tself.postMessage(\'tick\');' + '}' + 'tick();']); + var blobUrl = URL.createObjectURL(blob); + var worker = new Worker(blobUrl); + worker.addEventListener('message', function () { + this.emit('tick'); + }.bind(this)); + worker.addEventListener('message', function () { + var now = this.now(); + if (this.isNumber(this._lastUpdate)) { + var diff = now - this._lastUpdate; + this._computedUpdateInterval = Math.max(diff, this._computedUpdateInterval * 0.97); + } + this._lastUpdate = now; + }.bind(this)); + return worker; + }; + Tone.Context.prototype.getConstant = function (val) { + if (this._constants[val]) { + return this._constants[val]; + } else { + var buffer = this._context.createBuffer(1, 128, this._context.sampleRate); + var arr = buffer.getChannelData(0); + for (var i = 0; i < arr.length; i++) { + arr[i] = val; + } + var constant = this._context.createBufferSource(); + constant.channelCount = 1; + constant.channelCountMode = 'explicit'; + constant.buffer = buffer; + constant.loop = true; + constant.start(0); + this._constants[val] = constant; + return constant; + } + }; + Object.defineProperty(Tone.Context.prototype, 'lag', { + get: function () { + var diff = this._computedUpdateInterval - this._updateInterval; + diff = Math.max(diff, 0); + return diff; + } + }); + Object.defineProperty(Tone.Context.prototype, 'lookAhead', { + get: function () { + return this._lookAhead; + }, + set: function (lA) { + this._lookAhead = lA; + } + }); + Object.defineProperty(Tone.Context.prototype, 'updateInterval', { + get: function () { + return this._updateInterval; + }, + set: function (interval) { + this._updateInterval = Math.max(interval, Tone.prototype.blockTime); + this._worker.postMessage(Math.max(interval * 1000, 1)); + } + }); + Object.defineProperty(Tone.Context.prototype, 'latencyHint', { + get: function () { + return this._latencyHint; + }, + set: function (hint) { + var lookAhead = hint; + this._latencyHint = hint; + if (this.isString(hint)) { + switch (hint) { + case 'interactive': + lookAhead = 0.1; + this._context.latencyHint = hint; + break; + case 'playback': + lookAhead = 0.8; + this._context.latencyHint = hint; + break; + case 'balanced': + lookAhead = 0.25; + this._context.latencyHint = hint; + break; + case 'fastest': + lookAhead = 0.01; + break; + } + } + this.lookAhead = lookAhead; + this.updateInterval = lookAhead / 3; + } + }); + function shimConnect() { + var nativeConnect = AudioNode.prototype.connect; + var nativeDisconnect = AudioNode.prototype.disconnect; + function toneConnect(B, outNum, inNum) { + if (B.input) { + if (Array.isArray(B.input)) { + if (Tone.prototype.isUndef(inNum)) { + inNum = 0; + } + this.connect(B.input[inNum]); + } else { + this.connect(B.input, outNum, inNum); + } + } else { + try { + if (B instanceof AudioNode) { + nativeConnect.call(this, B, outNum, inNum); + } else { + nativeConnect.call(this, B, outNum); + } + } catch (e) { + throw new Error('error connecting to node: ' + B + '\n' + e); + } + } + } + function toneDisconnect(B, outNum, inNum) { + if (B && B.input && Array.isArray(B.input)) { + if (Tone.prototype.isUndef(inNum)) { + inNum = 0; + } + this.disconnect(B.input[inNum], outNum, inNum); + } else if (B && B.input) { + this.disconnect(B.input, outNum, inNum); + } else { + try { + nativeDisconnect.apply(this, arguments); + } catch (e) { + throw new Error('error disconnecting node: ' + B + '\n' + e); + } + } + } + if (AudioNode.prototype.connect !== toneConnect) { + AudioNode.prototype.connect = toneConnect; + AudioNode.prototype.disconnect = toneDisconnect; + } + } + if (Tone.supported) { + shimConnect(); + Tone.context = new Tone.Context(); + } else { + console.warn('This browser does not support Tone.js'); + } + return Tone.Context; +}(Tone_core_Tone); +var audiocontext; +'use strict'; +audiocontext = function (StartAudioContext, Context, Tone) { + // Create the Audio Context + const audiocontext = new window.AudioContext(); + Tone.context.dispose(); + Tone.setContext(audiocontext); + /** + *

Returns the Audio Context for this sketch. Useful for users + * who would like to dig deeper into the Web Audio API + * .

+ * + *

Some browsers require users to startAudioContext + * with a user gesture, such as touchStarted in the example below.

+ * + * @method getAudioContext + * @return {Object} AudioContext for this sketch + * @example + *
+ * function draw() { + * background(255); + * textAlign(CENTER); + * + * if (getAudioContext().state !== 'running') { + * text('click to start audio', width/2, height/2); + * } else { + * text('audio is enabled', width/2, height/2); + * } + * } + * + * function touchStarted() { + * if (getAudioContext().state !== 'running') { + * getAudioContext().resume(); + * } + * var synth = new p5.MonoSynth(); + * synth.play('A4', 0.5, 0, 0.2); + * } + * + *
+ */ + p5.prototype.getAudioContext = function () { + return audiocontext; + }; + /** + *

It is a good practice to give users control over starting audio playback. + * This practice is enforced by Google Chrome's autoplay policy as of r70 + * (info), iOS Safari, and other browsers. + *

+ * + *

+ * userStartAudio() starts the Audio Context on a user gesture. It utilizes + * the StartAudioContext library by + * Yotam Mann (MIT Licence, 2016). Read more at https://github.com/tambien/StartAudioContext. + *

+ * + *

Starting the audio context on a user gesture can be as simple as userStartAudio(). + * Optional parameters let you decide on a specific element that will start the audio context, + * and/or call a function once the audio context is started.

+ * @param {Element|Array} [element(s)] This argument can be an Element, + * Selector String, NodeList, p5.Element, + * jQuery Element, or an Array of any of those. + * @param {Function} [callback] Callback to invoke when the AudioContext has started + * @return {Promise} Returns a Promise which is resolved when + * the AudioContext state is 'running' + * @method userStartAudio + * @example + *
+ * function setup() { + * var myDiv = createDiv('click to start audio'); + * myDiv.position(0, 0); + * + * var mySynth = new p5.MonoSynth(); + * + * // This won't play until the context has started + * mySynth.play('A6'); + * + * // Start the audio context on a click/touch event + * userStartAudio().then(function() { + * myDiv.remove(); + * }); + * } + *
+ */ + p5.prototype.userStartAudio = function (elements, callback) { + var elt = elements; + if (elements instanceof p5.Element) { + elt = elements.elt; + } else if (elements instanceof Array && elements[0] instanceof p5.Element) { + elt = elements.map(function (e) { + return e.elt; + }); + } + return StartAudioContext(audiocontext, elt, callback); + }; + return audiocontext; +}(StartAudioContext, Tone_core_Context, Tone_core_Tone); +var master; +'use strict'; +master = function (audiocontext) { + /** + * Master contains AudioContext and the master sound output. + */ + var Master = function () { + this.input = audiocontext.createGain(); + this.output = audiocontext.createGain(); + //put a hard limiter on the output + this.limiter = audiocontext.createDynamicsCompressor(); + this.limiter.threshold.value = -3; + this.limiter.ratio.value = 20; + this.limiter.knee.value = 1; + this.audiocontext = audiocontext; + this.output.disconnect(); + // connect input to limiter + this.input.connect(this.limiter); + // connect limiter to output + this.limiter.connect(this.output); + // meter is just for global Amplitude / FFT analysis + this.meter = audiocontext.createGain(); + this.fftMeter = audiocontext.createGain(); + this.output.connect(this.meter); + this.output.connect(this.fftMeter); + // connect output to destination + this.output.connect(this.audiocontext.destination); + // an array of all sounds in the sketch + this.soundArray = []; + // an array of all musical parts in the sketch + this.parts = []; + // file extensions to search for + this.extensions = []; + }; + // create a single instance of the p5Sound / master output for use within this sketch + var p5sound = new Master(); + /** + * Returns a number representing the master amplitude (volume) for sound + * in this sketch. + * + * @method getMasterVolume + * @return {Number} Master amplitude (volume) for sound in this sketch. + * Should be between 0.0 (silence) and 1.0. + */ + p5.prototype.getMasterVolume = function () { + return p5sound.output.gain.value; + }; + /** + *

Scale the output of all sound in this sketch

+ * Scaled between 0.0 (silence) and 1.0 (full volume). + * 1.0 is the maximum amplitude of a digital sound, so multiplying + * by greater than 1.0 may cause digital distortion. To + * fade, provide a rampTime parameter. For more + * complex fades, see the Envelope class. + * + * Alternately, you can pass in a signal source such as an + * oscillator to modulate the amplitude with an audio signal. + * + *

How This Works: When you load the p5.sound module, it + * creates a single instance of p5sound. All sound objects in this + * module output to p5sound before reaching your computer's output. + * So if you change the amplitude of p5sound, it impacts all of the + * sound in this module.

+ * + *

If no value is provided, returns a Web Audio API Gain Node

+ * + * @method masterVolume + * @param {Number|Object} volume Volume (amplitude) between 0.0 + * and 1.0 or modulating signal/oscillator + * @param {Number} [rampTime] Fade for t seconds + * @param {Number} [timeFromNow] Schedule this event to happen at + * t seconds in the future + */ + p5.prototype.masterVolume = function (vol, rampTime, tFromNow) { + if (typeof vol === 'number') { + var rampTime = rampTime || 0; + var tFromNow = tFromNow || 0; + var now = p5sound.audiocontext.currentTime; + var currentVol = p5sound.output.gain.value; + p5sound.output.gain.cancelScheduledValues(now + tFromNow); + p5sound.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow); + p5sound.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime); + } else if (vol) { + vol.connect(p5sound.output.gain); + } else { + // return the Gain Node + return p5sound.output.gain; + } + }; + /** + * `p5.soundOut` is the p5.sound master output. It sends output to + * the destination of this window's web audio context. It contains + * Web Audio API nodes including a dyanmicsCompressor (.limiter), + * and Gain Nodes for .input and .output. + * + * @property {Object} soundOut + */ + p5.prototype.soundOut = p5.soundOut = p5sound; + /** + * a silent connection to the DesinationNode + * which will ensure that anything connected to it + * will not be garbage collected + * + * @private + */ + p5.soundOut._silentNode = p5sound.audiocontext.createGain(); + p5.soundOut._silentNode.gain.value = 0; + p5.soundOut._silentNode.connect(p5sound.audiocontext.destination); + return p5sound; +}(audiocontext); +var helpers; +'use strict'; +helpers = function () { + var p5sound = master; + /** + * @for p5 + */ + /** + * Returns a number representing the sample rate, in samples per second, + * of all sound objects in this audio context. It is determined by the + * sampling rate of your operating system's sound card, and it is not + * currently possile to change. + * It is often 44100, or twice the range of human hearing. + * + * @method sampleRate + * @return {Number} samplerate samples per second + */ + p5.prototype.sampleRate = function () { + return p5sound.audiocontext.sampleRate; + }; + /** + * Returns the closest MIDI note value for + * a given frequency. + * + * @method freqToMidi + * @param {Number} frequency A freqeuncy, for example, the "A" + * above Middle C is 440Hz + * @return {Number} MIDI note value + */ + p5.prototype.freqToMidi = function (f) { + var mathlog2 = Math.log(f / 440) / Math.log(2); + var m = Math.round(12 * mathlog2) + 69; + return m; + }; + /** + * Returns the frequency value of a MIDI note value. + * General MIDI treats notes as integers where middle C + * is 60, C# is 61, D is 62 etc. Useful for generating + * musical frequencies with oscillators. + * + * @method midiToFreq + * @param {Number} midiNote The number of a MIDI note + * @return {Number} Frequency value of the given MIDI note + * @example + *
+ * var notes = [60, 64, 67, 72]; + * var i = 0; + * + * function setup() { + * osc = new p5.Oscillator('Triangle'); + * osc.start(); + * frameRate(1); + * } + * + * function draw() { + * var freq = midiToFreq(notes[i]); + * osc.freq(freq); + * i++; + * if (i >= notes.length){ + * i = 0; + * } + * } + *
+ */ + var midiToFreq = p5.prototype.midiToFreq = function (m) { + return 440 * Math.pow(2, (m - 69) / 12); + }; + // This method converts ANSI notes specified as a string "C4", "Eb3" to a frequency + var noteToFreq = function (note) { + if (typeof note !== 'string') { + return note; + } + var wholeNotes = { + A: 21, + B: 23, + C: 24, + D: 26, + E: 28, + F: 29, + G: 31 + }; + var value = wholeNotes[note[0].toUpperCase()]; + var octave = ~~note.slice(-1); + value += 12 * (octave - 1); + switch (note[1]) { + case '#': + value += 1; + break; + case 'b': + value -= 1; + break; + default: + break; + } + return midiToFreq(value); + }; + /** + * List the SoundFile formats that you will include. LoadSound + * will search your directory for these extensions, and will pick + * a format that is compatable with the client's web browser. + * Here is a free online file + * converter. + * + * @method soundFormats + * @param {String} [...formats] i.e. 'mp3', 'wav', 'ogg' + * @example + *
+ * function preload() { + * // set the global sound formats + * soundFormats('mp3', 'ogg'); + * + * // load either beatbox.mp3, or .ogg, depending on browser + * mySound = loadSound('assets/beatbox.mp3'); + * } + * + * function setup() { + * mySound.play(); + * } + *
+ */ + p5.prototype.soundFormats = function () { + // reset extensions array + p5sound.extensions = []; + // add extensions + for (var i = 0; i < arguments.length; i++) { + arguments[i] = arguments[i].toLowerCase(); + if ([ + 'mp3', + 'wav', + 'ogg', + 'm4a', + 'aac' + ].indexOf(arguments[i]) > -1) { + p5sound.extensions.push(arguments[i]); + } else { + throw arguments[i] + ' is not a valid sound format!'; + } + } + }; + p5.prototype.disposeSound = function () { + for (var i = 0; i < p5sound.soundArray.length; i++) { + p5sound.soundArray[i].dispose(); + } + }; + // register removeSound to dispose of p5sound SoundFiles, Convolvers, + // Oscillators etc when sketch ends + p5.prototype.registerMethod('remove', p5.prototype.disposeSound); + p5.prototype._checkFileFormats = function (paths) { + var path; + // if path is a single string, check to see if extension is provided + if (typeof paths === 'string') { + path = paths; + // see if extension is provided + var extTest = path.split('.').pop(); + // if an extension is provided... + if ([ + 'mp3', + 'wav', + 'ogg', + 'm4a', + 'aac' + ].indexOf(extTest) > -1) { + if (p5.prototype.isFileSupported(extTest)) { + path = path; + } else { + var pathSplit = path.split('.'); + var pathCore = pathSplit[pathSplit.length - 1]; + for (var i = 0; i < p5sound.extensions.length; i++) { + var extension = p5sound.extensions[i]; + var supported = p5.prototype.isFileSupported(extension); + if (supported) { + pathCore = ''; + if (pathSplit.length === 2) { + pathCore += pathSplit[0]; + } + for (var i = 1; i <= pathSplit.length - 2; i++) { + var p = pathSplit[i]; + pathCore += '.' + p; + } + path = pathCore += '.'; + path = path += extension; + break; + } + } + } + } else { + for (var i = 0; i < p5sound.extensions.length; i++) { + var extension = p5sound.extensions[i]; + var supported = p5.prototype.isFileSupported(extension); + if (supported) { + path = path + '.' + extension; + break; + } + } + } + } else if (typeof paths === 'object') { + for (var i = 0; i < paths.length; i++) { + var extension = paths[i].split('.').pop(); + var supported = p5.prototype.isFileSupported(extension); + if (supported) { + // console.log('.'+extension + ' is ' + supported + + // ' supported by your browser.'); + path = paths[i]; + break; + } + } + } + return path; + }; + /** + * Used by Osc and Envelope to chain signal math + */ + p5.prototype._mathChain = function (o, math, thisChain, nextChain, type) { + // if this type of math already exists in the chain, replace it + for (var i in o.mathOps) { + if (o.mathOps[i] instanceof type) { + o.mathOps[i].dispose(); + thisChain = i; + if (thisChain < o.mathOps.length - 1) { + nextChain = o.mathOps[i + 1]; + } + } + } + o.mathOps[thisChain - 1].disconnect(); + o.mathOps[thisChain - 1].connect(math); + math.connect(nextChain); + o.mathOps[thisChain] = math; + return o; + }; + // helper methods to convert audio file as .wav format, + // will use as saving .wav file and saving blob object + // Thank you to Matt Diamond's RecorderJS (MIT License) + // https://github.com/mattdiamond/Recorderjs + function convertToWav(audioBuffer) { + var leftChannel, rightChannel; + leftChannel = audioBuffer.getChannelData(0); + // handle mono files + if (audioBuffer.numberOfChannels > 1) { + rightChannel = audioBuffer.getChannelData(1); + } else { + rightChannel = leftChannel; + } + var interleaved = interleave(leftChannel, rightChannel); + // create the buffer and view to create the .WAV file + var buffer = new window.ArrayBuffer(44 + interleaved.length * 2); + var view = new window.DataView(buffer); + // write the WAV container, + // check spec at: https://web.archive.org/web/20171215131933/http://tiny.systems/software/soundProgrammer/WavFormatDocs.pdf + // RIFF chunk descriptor + writeUTFBytes(view, 0, 'RIFF'); + view.setUint32(4, 36 + interleaved.length * 2, true); + writeUTFBytes(view, 8, 'WAVE'); + // FMT sub-chunk + writeUTFBytes(view, 12, 'fmt '); + view.setUint32(16, 16, true); + view.setUint16(20, 1, true); + // stereo (2 channels) + view.setUint16(22, 2, true); + view.setUint32(24, p5sound.audiocontext.sampleRate, true); + view.setUint32(28, p5sound.audiocontext.sampleRate * 4, true); + view.setUint16(32, 4, true); + view.setUint16(34, 16, true); + // data sub-chunk + writeUTFBytes(view, 36, 'data'); + view.setUint32(40, interleaved.length * 2, true); + // write the PCM samples + var lng = interleaved.length; + var index = 44; + var volume = 1; + for (var i = 0; i < lng; i++) { + view.setInt16(index, interleaved[i] * (32767 * volume), true); + index += 2; + } + return view; + } + // helper methods to save waves + function interleave(leftChannel, rightChannel) { + var length = leftChannel.length + rightChannel.length; + var result = new Float32Array(length); + var inputIndex = 0; + for (var index = 0; index < length;) { + result[index++] = leftChannel[inputIndex]; + result[index++] = rightChannel[inputIndex]; + inputIndex++; + } + return result; + } + function writeUTFBytes(view, offset, string) { + var lng = string.length; + for (var i = 0; i < lng; i++) { + view.setUint8(offset + i, string.charCodeAt(i)); + } + } + return { + convertToWav: convertToWav, + midiToFreq: midiToFreq, + noteToFreq: noteToFreq + }; +}(master); +var errorHandler; +'use strict'; +errorHandler = function () { + /* + Helper function to generate an error + with a custom stack trace that points to the sketch + and removes other parts of the stack trace. + + @private + @class customError + @constructor + @param {String} name custom error name + @param {String} errorTrace custom error trace + @param {String} failedPath path to the file that failed to load + @property {String} name custom error name + @property {String} message custom error message + @property {String} stack trace the error back to a line in the user's sketch. + Note: this edits out stack trace within p5.js and p5.sound. + @property {String} originalStack unedited, original stack trace + @property {String} failedPath path to the file that failed to load + @return {Error} returns a custom Error object + */ + var CustomError = function (name, errorTrace, failedPath) { + var err = new Error(); + var tempStack, splitStack; + err.name = name; + err.originalStack = err.stack + errorTrace; + tempStack = err.stack + errorTrace; + err.failedPath = failedPath; + // only print the part of the stack trace that refers to the user code: + var splitStack = tempStack.split('\n'); + splitStack = splitStack.filter(function (ln) { + return !ln.match(/(p5.|native code|globalInit)/g); + }); + err.stack = splitStack.join('\n'); + return err; + }; + return CustomError; +}(); +var panner; +'use strict'; +panner = function () { + var p5sound = master; + var ac = p5sound.audiocontext; + // Stereo panner + // if there is a stereo panner node use it + if (typeof ac.createStereoPanner !== 'undefined') { + p5.Panner = function (input, output) { + this.stereoPanner = this.input = ac.createStereoPanner(); + input.connect(this.stereoPanner); + this.stereoPanner.connect(output); + }; + p5.Panner.prototype.pan = function (val, tFromNow) { + var time = tFromNow || 0; + var t = ac.currentTime + time; + this.stereoPanner.pan.linearRampToValueAtTime(val, t); + }; + //not implemented because stereopanner + //node does not require this and will automatically + //convert single channel or multichannel to stereo. + //tested with single and stereo, not with (>2) multichannel + p5.Panner.prototype.inputChannels = function () { + }; + p5.Panner.prototype.connect = function (obj) { + this.stereoPanner.connect(obj); + }; + p5.Panner.prototype.disconnect = function () { + if (this.stereoPanner) { + this.stereoPanner.disconnect(); + } + }; + } else { + // if there is no createStereoPanner object + // such as in safari 7.1.7 at the time of writing this + // use this method to create the effect + p5.Panner = function (input, output, numInputChannels) { + this.input = ac.createGain(); + input.connect(this.input); + this.left = ac.createGain(); + this.right = ac.createGain(); + this.left.channelInterpretation = 'discrete'; + this.right.channelInterpretation = 'discrete'; + // if input is stereo + if (numInputChannels > 1) { + this.splitter = ac.createChannelSplitter(2); + this.input.connect(this.splitter); + this.splitter.connect(this.left, 1); + this.splitter.connect(this.right, 0); + } else { + this.input.connect(this.left); + this.input.connect(this.right); + } + this.output = ac.createChannelMerger(2); + this.left.connect(this.output, 0, 1); + this.right.connect(this.output, 0, 0); + this.output.connect(output); + }; + // -1 is left, +1 is right + p5.Panner.prototype.pan = function (val, tFromNow) { + var time = tFromNow || 0; + var t = ac.currentTime + time; + var v = (val + 1) / 2; + var rightVal = Math.cos(v * Math.PI / 2); + var leftVal = Math.sin(v * Math.PI / 2); + this.left.gain.linearRampToValueAtTime(leftVal, t); + this.right.gain.linearRampToValueAtTime(rightVal, t); + }; + p5.Panner.prototype.inputChannels = function (numChannels) { + if (numChannels === 1) { + this.input.disconnect(); + this.input.connect(this.left); + this.input.connect(this.right); + } else if (numChannels === 2) { + if (typeof (this.splitter === 'undefined')) { + this.splitter = ac.createChannelSplitter(2); + } + this.input.disconnect(); + this.input.connect(this.splitter); + this.splitter.connect(this.left, 1); + this.splitter.connect(this.right, 0); + } + }; + p5.Panner.prototype.connect = function (obj) { + this.output.connect(obj); + }; + p5.Panner.prototype.disconnect = function () { + if (this.output) { + this.output.disconnect(); + } + }; + } +}(master); +var soundfile; +'use strict'; +soundfile = function () { + var CustomError = errorHandler; + var p5sound = master; + var ac = p5sound.audiocontext; + var midiToFreq = helpers.midiToFreq; + var convertToWav = helpers.convertToWav; + /** + *

SoundFile object with a path to a file.

+ * + *

The p5.SoundFile may not be available immediately because + * it loads the file information asynchronously.

+ * + *

To do something with the sound as soon as it loads + * pass the name of a function as the second parameter.

+ * + *

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

+ * + * @class p5.SoundFile + * @constructor + * @param {String|Array} path path to a sound file (String). Optionally, + * you may include multiple file formats in + * an array. Alternately, accepts an object + * from the HTML5 File API, or a p5.File. + * @param {Function} [successCallback] Name of a function to call once file loads + * @param {Function} [errorCallback] Name of a function to call if file fails to + * load. This function will receive an error or + * XMLHttpRequest object with information + * about what went wrong. + * @param {Function} [whileLoadingCallback] Name of a function to call while file + * is loading. That function will + * receive progress of the request to + * load the sound file + * (between 0 and 1) as its first + * parameter. This progress + * does not account for the additional + * time needed to decode the audio data. + * + * @example + *
+ * + * function preload() { + * soundFormats('mp3', 'ogg'); + * mySound = loadSound('assets/doorbell.mp3'); + * } + * + * function setup() { + * mySound.setVolume(0.1); + * mySound.play(); + * } + * + *
+ */ + p5.SoundFile = function (paths, onload, onerror, whileLoading) { + if (typeof paths !== 'undefined') { + if (typeof paths === 'string' || typeof paths[0] === 'string') { + var path = p5.prototype._checkFileFormats(paths); + this.url = path; + } else if (typeof paths === 'object') { + if (!(window.File && window.FileReader && window.FileList && window.Blob)) { + // The File API isn't supported in this browser + throw 'Unable to load file because the File API is not supported'; + } + } + // if type is a p5.File...get the actual file + if (paths.file) { + paths = paths.file; + } + this.file = paths; + } + // private _onended callback, set by the method: onended(callback) + this._onended = function () { + }; + this._looping = false; + this._playing = false; + this._paused = false; + this._pauseTime = 0; + // cues for scheduling events with addCue() removeCue() + this._cues = []; + this._cueIDCounter = 0; + // position of the most recently played sample + this._lastPos = 0; + this._counterNode = null; + this._scopeNode = null; + // array of sources so that they can all be stopped! + this.bufferSourceNodes = []; + // current source + this.bufferSourceNode = null; + this.buffer = null; + this.playbackRate = 1; + this.input = p5sound.audiocontext.createGain(); + this.output = p5sound.audiocontext.createGain(); + this.reversed = false; + // start and end of playback / loop + this.startTime = 0; + this.endTime = null; + this.pauseTime = 0; + // "restart" would stop playback before retriggering + this.mode = 'sustain'; + // time that playback was started, in millis + this.startMillis = null; + // stereo panning + this.panPosition = 0; + this.panner = new p5.Panner(this.output, p5sound.input, 2); + // it is possible to instantiate a soundfile with no path + if (this.url || this.file) { + this.load(onload, onerror); + } + // add this p5.SoundFile to the soundArray + p5sound.soundArray.push(this); + if (typeof whileLoading === 'function') { + this._whileLoading = whileLoading; + } else { + this._whileLoading = function () { + }; + } + this._onAudioProcess = _onAudioProcess.bind(this); + this._clearOnEnd = _clearOnEnd.bind(this); + }; + // register preload handling of loadSound + p5.prototype.registerPreloadMethod('loadSound', p5.prototype); + /** + * loadSound() returns a new p5.SoundFile from a specified + * path. If called during preload(), the p5.SoundFile will be ready + * to play in time for setup() and draw(). If called outside of + * preload, the p5.SoundFile will not be ready immediately, so + * loadSound accepts a callback as the second parameter. Using a + * + * local server is recommended when loading external files. + * + * @method loadSound + * @param {String|Array} path Path to the sound file, or an array with + * paths to soundfiles in multiple formats + * i.e. ['sound.ogg', 'sound.mp3']. + * Alternately, accepts an object: either + * from the HTML5 File API, or a p5.File. + * @param {Function} [successCallback] Name of a function to call once file loads + * @param {Function} [errorCallback] Name of a function to call if there is + * an error loading the file. + * @param {Function} [whileLoading] Name of a function to call while file is loading. + * This function will receive the percentage loaded + * so far, from 0.0 to 1.0. + * @return {SoundFile} Returns a p5.SoundFile + * @example + *
+ * function preload() { + * mySound = loadSound('assets/doorbell.mp3'); + * } + * + * function setup() { + * mySound.setVolume(0.1); + * mySound.play(); + * } + *
+ */ + p5.prototype.loadSound = function (path, callback, onerror, whileLoading) { + // if loading locally without a server + if (window.location.origin.indexOf('file://') > -1 && window.cordova === 'undefined') { + window.alert('This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS'); + } + var self = this; + var s = new p5.SoundFile(path, function () { + if (typeof callback === 'function') { + callback.apply(self, arguments); + } + if (typeof self._decrementPreload === 'function') { + self._decrementPreload(); + } + }, onerror, whileLoading); + return s; + }; + /** + * This is a helper function that the p5.SoundFile calls to load + * itself. Accepts a callback (the name of another function) + * as an optional parameter. + * + * @private + * @param {Function} [successCallback] Name of a function to call once file loads + * @param {Function} [errorCallback] Name of a function to call if there is an error + */ + p5.SoundFile.prototype.load = function (callback, errorCallback) { + var self = this; + var errorTrace = new Error().stack; + if (this.url !== undefined && this.url !== '') { + var request = new XMLHttpRequest(); + request.addEventListener('progress', function (evt) { + self._updateProgress(evt); + }, false); + request.open('GET', this.url, true); + request.responseType = 'arraybuffer'; + request.onload = function () { + if (request.status === 200) { + // on sucess loading file: + if (!self.panner) + return; + ac.decodeAudioData(request.response, // success decoding buffer: + function (buff) { + if (!self.panner) + return; + self.buffer = buff; + self.panner.inputChannels(buff.numberOfChannels); + if (callback) { + callback(self); + } + }, // error decoding buffer. "e" is undefined in Chrome 11/22/2015 + function () { + if (!self.panner) + return; + var err = new CustomError('decodeAudioData', errorTrace, self.url); + var msg = 'AudioContext error at decodeAudioData for ' + self.url; + if (errorCallback) { + err.msg = msg; + errorCallback(err); + } else { + console.error(msg + '\n The error stack trace includes: \n' + err.stack); + } + }); + } else { + if (!self.panner) + return; + var err = new CustomError('loadSound', errorTrace, self.url); + var msg = 'Unable to load ' + self.url + '. The request status was: ' + request.status + ' (' + request.statusText + ')'; + if (errorCallback) { + err.message = msg; + errorCallback(err); + } else { + console.error(msg + '\n The error stack trace includes: \n' + err.stack); + } + } + }; + // if there is another error, aside from 404... + request.onerror = function () { + var err = new CustomError('loadSound', errorTrace, self.url); + var msg = 'There was no response from the server at ' + self.url + '. Check the url and internet connectivity.'; + if (errorCallback) { + err.message = msg; + errorCallback(err); + } else { + console.error(msg + '\n The error stack trace includes: \n' + err.stack); + } + }; + request.send(); + } else if (this.file !== undefined) { + var reader = new FileReader(); + reader.onload = function () { + if (!self.panner) + return; + ac.decodeAudioData(reader.result, function (buff) { + if (!self.panner) + return; + self.buffer = buff; + self.panner.inputChannels(buff.numberOfChannels); + if (callback) { + callback(self); + } + }); + }; + reader.onerror = function (e) { + if (!self.panner) + return; + if (onerror) { + onerror(e); + } + }; + reader.readAsArrayBuffer(this.file); + } + }; + // TO DO: use this method to create a loading bar that shows progress during file upload/decode. + p5.SoundFile.prototype._updateProgress = function (evt) { + if (evt.lengthComputable) { + var percentComplete = evt.loaded / evt.total * 0.99; + this._whileLoading(percentComplete, evt); + } else { + // Unable to compute progress information since the total size is unknown + this._whileLoading('size unknown'); + } + }; + /** + * Returns true if the sound file finished loading successfully. + * + * @method isLoaded + * @return {Boolean} + */ + p5.SoundFile.prototype.isLoaded = function () { + if (this.buffer) { + return true; + } else { + return false; + } + }; + /** + * Play the p5.SoundFile + * + * @method play + * @param {Number} [startTime] (optional) schedule playback to start (in seconds from now). + * @param {Number} [rate] (optional) playback rate + * @param {Number} [amp] (optional) amplitude (volume) + * of playback + * @param {Number} [cueStart] (optional) cue start time in seconds + * @param {Number} [duration] (optional) duration of playback in seconds + */ + p5.SoundFile.prototype.play = function (startTime, rate, amp, _cueStart, duration) { + if (!this.output) { + console.warn('SoundFile.play() called after dispose'); + return; + } + var self = this; + var now = p5sound.audiocontext.currentTime; + var cueStart, cueEnd; + var time = startTime || 0; + if (time < 0) { + time = 0; + } + time = time + now; + if (typeof rate !== 'undefined') { + this.rate(rate); + } + if (typeof amp !== 'undefined') { + this.setVolume(amp); + } + // TO DO: if already playing, create array of buffers for easy stop() + if (this.buffer) { + // reset the pause time (if it was paused) + this._pauseTime = 0; + // handle restart playmode + if (this.mode === 'restart' && this.buffer && this.bufferSourceNode) { + this.bufferSourceNode.stop(time); + this._counterNode.stop(time); + } + //dont create another instance if already playing + if (this.mode === 'untildone' && this.isPlaying()) { + return; + } + // make a new source and counter. They are automatically assigned playbackRate and buffer + this.bufferSourceNode = this._initSourceNode(); + // garbage collect counterNode and create a new one + delete this._counterNode; + this._counterNode = this._initCounterNode(); + if (_cueStart) { + if (_cueStart >= 0 && _cueStart < this.buffer.duration) { + // this.startTime = cueStart; + cueStart = _cueStart; + } else { + throw 'start time out of range'; + } + } else { + cueStart = 0; + } + if (duration) { + // if duration is greater than buffer.duration, just play entire file anyway rather than throw an error + duration = duration <= this.buffer.duration - cueStart ? duration : this.buffer.duration; + } + // if it was paused, play at the pause position + if (this._paused) { + this.bufferSourceNode.start(time, this.pauseTime, duration); + this._counterNode.start(time, this.pauseTime, duration); + } else { + this.bufferSourceNode.start(time, cueStart, duration); + this._counterNode.start(time, cueStart, duration); + } + this._playing = true; + this._paused = false; + // add source to sources array, which is used in stopAll() + this.bufferSourceNodes.push(this.bufferSourceNode); + this.bufferSourceNode._arrayIndex = this.bufferSourceNodes.length - 1; + this.bufferSourceNode.addEventListener('ended', this._clearOnEnd); + } else { + throw 'not ready to play file, buffer has yet to load. Try preload()'; + } + // if looping, will restart at original time + this.bufferSourceNode.loop = this._looping; + this._counterNode.loop = this._looping; + if (this._looping === true) { + cueEnd = duration ? duration : cueStart - 1e-15; + this.bufferSourceNode.loopStart = cueStart; + this.bufferSourceNode.loopEnd = cueEnd; + this._counterNode.loopStart = cueStart; + this._counterNode.loopEnd = cueEnd; + } + }; + /** + * p5.SoundFile has two play modes: restart and + * sustain. Play Mode determines what happens to a + * p5.SoundFile if it is triggered while in the middle of playback. + * In sustain mode, playback will continue simultaneous to the + * new playback. In restart mode, play() will stop playback + * and start over. With untilDone, a sound will play only if it's + * not already playing. Sustain is the default mode. + * + * @method playMode + * @param {String} str 'restart' or 'sustain' or 'untilDone' + * @example + *
+ * var mySound; + * function preload(){ + * mySound = loadSound('assets/Damscray_DancingTiger.mp3'); + * } + * function mouseClicked() { + * mySound.playMode('sustain'); + * mySound.play(); + * } + * function keyPressed() { + * mySound.playMode('restart'); + * mySound.play(); + * } + * + *
+ */ + p5.SoundFile.prototype.playMode = function (str) { + var s = str.toLowerCase(); + // if restart, stop all other sounds from playing + if (s === 'restart' && this.buffer && this.bufferSourceNode) { + for (var i = 0; i < this.bufferSourceNodes.length - 1; i++) { + var now = p5sound.audiocontext.currentTime; + this.bufferSourceNodes[i].stop(now); + } + } + // set play mode to effect future playback + if (s === 'restart' || s === 'sustain' || s === 'untildone') { + this.mode = s; + } else { + throw 'Invalid play mode. Must be either "restart" or "sustain"'; + } + }; + /** + * Pauses a file that is currently playing. If the file is not + * playing, then nothing will happen. + * + * After pausing, .play() will resume from the paused + * position. + * If p5.SoundFile had been set to loop before it was paused, + * it will continue to loop after it is unpaused with .play(). + * + * @method pause + * @param {Number} [startTime] (optional) schedule event to occur + * seconds from now + * @example + *
+ * var soundFile; + * + * function preload() { + * soundFormats('ogg', 'mp3'); + * soundFile = loadSound('assets/Damscray_-_Dancing_Tiger_02.mp3'); + * } + * function setup() { + * background(0, 255, 0); + * soundFile.setVolume(0.1); + * soundFile.loop(); + * } + * function keyTyped() { + * if (key == 'p') { + * soundFile.pause(); + * background(255, 0, 0); + * } + * } + * + * function keyReleased() { + * if (key == 'p') { + * soundFile.play(); + * background(0, 255, 0); + * } + * } + * + *
+ */ + p5.SoundFile.prototype.pause = function (startTime) { + var now = p5sound.audiocontext.currentTime; + var time = startTime || 0; + var pTime = time + now; + if (this.isPlaying() && this.buffer && this.bufferSourceNode) { + this.pauseTime = this.currentTime(); + this.bufferSourceNode.stop(pTime); + this._counterNode.stop(pTime); + this._paused = true; + this._playing = false; + this._pauseTime = this.currentTime(); + } else { + this._pauseTime = 0; + } + }; + /** + * Loop the p5.SoundFile. Accepts optional parameters to set the + * playback rate, playback volume, loopStart, loopEnd. + * + * @method loop + * @param {Number} [startTime] (optional) schedule event to occur + * seconds from now + * @param {Number} [rate] (optional) playback rate + * @param {Number} [amp] (optional) playback volume + * @param {Number} [cueLoopStart] (optional) startTime in seconds + * @param {Number} [duration] (optional) loop duration in seconds + */ + p5.SoundFile.prototype.loop = function (startTime, rate, amp, loopStart, duration) { + this._looping = true; + this.play(startTime, rate, amp, loopStart, duration); + }; + /** + * Set a p5.SoundFile's looping flag to true or false. If the sound + * is currently playing, this change will take effect when it + * reaches the end of the current playback. + * + * @method setLoop + * @param {Boolean} Boolean set looping to true or false + */ + p5.SoundFile.prototype.setLoop = function (bool) { + if (bool === true) { + this._looping = true; + } else if (bool === false) { + this._looping = false; + } else { + throw 'Error: setLoop accepts either true or false'; + } + if (this.bufferSourceNode) { + this.bufferSourceNode.loop = this._looping; + this._counterNode.loop = this._looping; + } + }; + /** + * Returns 'true' if a p5.SoundFile is currently looping and playing, 'false' if not. + * + * @method isLooping + * @return {Boolean} + */ + p5.SoundFile.prototype.isLooping = function () { + if (!this.bufferSourceNode) { + return false; + } + if (this._looping === true && this.isPlaying() === true) { + return true; + } + return false; + }; + /** + * Returns true if a p5.SoundFile is playing, false if not (i.e. + * paused or stopped). + * + * @method isPlaying + * @return {Boolean} + */ + p5.SoundFile.prototype.isPlaying = function () { + return this._playing; + }; + /** + * Returns true if a p5.SoundFile is paused, false if not (i.e. + * playing or stopped). + * + * @method isPaused + * @return {Boolean} + */ + p5.SoundFile.prototype.isPaused = function () { + return this._paused; + }; + /** + * Stop soundfile playback. + * + * @method stop + * @param {Number} [startTime] (optional) schedule event to occur + * in seconds from now + */ + p5.SoundFile.prototype.stop = function (timeFromNow) { + var time = timeFromNow || 0; + if (this.mode === 'sustain' || this.mode === 'untildone') { + this.stopAll(time); + this._playing = false; + this.pauseTime = 0; + this._paused = false; + } else if (this.buffer && this.bufferSourceNode) { + var now = p5sound.audiocontext.currentTime; + var t = time || 0; + this.pauseTime = 0; + this.bufferSourceNode.stop(now + t); + this._counterNode.stop(now + t); + this._playing = false; + this._paused = false; + } + }; + /** + * Stop playback on all of this soundfile's sources. + * @private + */ + p5.SoundFile.prototype.stopAll = function (_time) { + var now = p5sound.audiocontext.currentTime; + var time = _time || 0; + if (this.buffer && this.bufferSourceNode) { + for (var i in this.bufferSourceNodes) { + const bufferSourceNode = this.bufferSourceNodes[i]; + if (!!bufferSourceNode) { + try { + bufferSourceNode.stop(now + time); + } catch (e) { + } + } + } + this._counterNode.stop(now + time); + this._onended(this); + } + }; + /** + * Multiply the output volume (amplitude) of a sound file + * between 0.0 (silence) and 1.0 (full volume). + * 1.0 is the maximum amplitude of a digital sound, so multiplying + * by greater than 1.0 may cause digital distortion. To + * fade, provide a rampTime parameter. For more + * complex fades, see the Envelope class. + * + * Alternately, you can pass in a signal source such as an + * oscillator to modulate the amplitude with an audio signal. + * + * @method setVolume + * @param {Number|Object} volume Volume (amplitude) between 0.0 + * and 1.0 or modulating signal/oscillator + * @param {Number} [rampTime] Fade for t seconds + * @param {Number} [timeFromNow] Schedule this event to happen at + * t seconds in the future + */ + p5.SoundFile.prototype.setVolume = function (vol, _rampTime, _tFromNow) { + if (typeof vol === 'number') { + var rampTime = _rampTime || 0; + var tFromNow = _tFromNow || 0; + var now = p5sound.audiocontext.currentTime; + var currentVol = this.output.gain.value; + this.output.gain.cancelScheduledValues(now + tFromNow); + this.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow); + this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime); + } else if (vol) { + vol.connect(this.output.gain); + } else { + // return the Gain Node + return this.output.gain; + } + }; + // same as setVolume, to match Processing Sound + p5.SoundFile.prototype.amp = p5.SoundFile.prototype.setVolume; + // these are the same thing + p5.SoundFile.prototype.fade = p5.SoundFile.prototype.setVolume; + p5.SoundFile.prototype.getVolume = function () { + return this.output.gain.value; + }; + /** + * Set the stereo panning of a p5.sound object to + * a floating point number between -1.0 (left) and 1.0 (right). + * Default is 0.0 (center). + * + * @method pan + * @param {Number} [panValue] Set the stereo panner + * @param {Number} [timeFromNow] schedule this event to happen + * seconds from now + * @example + *
+ * + * var ball = {}; + * var soundFile; + * + * function preload() { + * soundFormats('ogg', 'mp3'); + * soundFile = loadSound('assets/beatbox.mp3'); + * } + * + * function draw() { + * background(0); + * ball.x = constrain(mouseX, 0, width); + * ellipse(ball.x, height/2, 20, 20) + * } + * + * function mousePressed(){ + * // map the ball's x location to a panning degree + * // between -1.0 (left) and 1.0 (right) + * var panning = map(ball.x, 0., width,-1.0, 1.0); + * soundFile.pan(panning); + * soundFile.play(); + * } + *
+ */ + p5.SoundFile.prototype.pan = function (pval, tFromNow) { + this.panPosition = pval; + this.panner.pan(pval, tFromNow); + }; + /** + * Returns the current stereo pan position (-1.0 to 1.0) + * + * @method getPan + * @return {Number} Returns the stereo pan setting of the Oscillator + * as a number between -1.0 (left) and 1.0 (right). + * 0.0 is center and default. + */ + p5.SoundFile.prototype.getPan = function () { + return this.panPosition; + }; + /** + * Set the playback rate of a sound file. Will change the speed and the pitch. + * Values less than zero will reverse the audio buffer. + * + * @method rate + * @param {Number} [playbackRate] Set the playback rate. 1.0 is normal, + * .5 is half-speed, 2.0 is twice as fast. + * Values less than zero play backwards. + * @example + *
+ * var song; + * + * function preload() { + * song = loadSound('assets/Damscray_DancingTiger.mp3'); + * } + * + * function setup() { + * song.loop(); + * } + * + * function draw() { + * background(200); + * + * // Set the rate to a range between 0.1 and 4 + * // Changing the rate also alters the pitch + * var speed = map(mouseY, 0.1, height, 0, 2); + * speed = constrain(speed, 0.01, 4); + * song.rate(speed); + * + * // Draw a circle to show what is going on + * stroke(0); + * fill(51, 100); + * ellipse(mouseX, 100, 48, 48); + * } + * + * + *
+ * + */ + p5.SoundFile.prototype.rate = function (playbackRate) { + var reverse = false; + if (typeof playbackRate === 'undefined') { + return this.playbackRate; + } + this.playbackRate = playbackRate; + if (playbackRate === 0) { + playbackRate = 1e-13; + } else if (playbackRate < 0 && !this.reversed) { + playbackRate = Math.abs(playbackRate); + reverse = true; + } else if (playbackRate > 0 && this.reversed) { + reverse = true; + } + if (this.bufferSourceNode) { + var now = p5sound.audiocontext.currentTime; + this.bufferSourceNode.playbackRate.cancelScheduledValues(now); + this.bufferSourceNode.playbackRate.linearRampToValueAtTime(Math.abs(playbackRate), now); + this._counterNode.playbackRate.cancelScheduledValues(now); + this._counterNode.playbackRate.linearRampToValueAtTime(Math.abs(playbackRate), now); + } + if (reverse) { + this.reverseBuffer(); + } + return this.playbackRate; + }; + // TO DO: document this + p5.SoundFile.prototype.setPitch = function (num) { + var newPlaybackRate = midiToFreq(num) / midiToFreq(60); + this.rate(newPlaybackRate); + }; + p5.SoundFile.prototype.getPlaybackRate = function () { + return this.playbackRate; + }; + /** + * Returns the duration of a sound file in seconds. + * + * @method duration + * @return {Number} The duration of the soundFile in seconds. + */ + p5.SoundFile.prototype.duration = function () { + // Return Duration + if (this.buffer) { + return this.buffer.duration; + } else { + return 0; + } + }; + /** + * Return the current position of the p5.SoundFile playhead, in seconds. + * Time is relative to the normal buffer direction, so if `reverseBuffer` + * has been called, currentTime will count backwards. + * + * @method currentTime + * @return {Number} currentTime of the soundFile in seconds. + */ + p5.SoundFile.prototype.currentTime = function () { + return this.reversed ? Math.abs(this._lastPos - this.buffer.length) / ac.sampleRate : this._lastPos / ac.sampleRate; + }; + /** + * Move the playhead of the song to a position, in seconds. Start timing + * and playback duration. If none are given, will reset the file to play + * entire duration from start to finish. + * + * @method jump + * @param {Number} cueTime cueTime of the soundFile in seconds. + * @param {Number} duration duration in seconds. + */ + p5.SoundFile.prototype.jump = function (cueTime, duration) { + if (cueTime < 0 || cueTime > this.buffer.duration) { + throw 'jump time out of range'; + } + if (duration > this.buffer.duration - cueTime) { + throw 'end time out of range'; + } + var cTime = cueTime || 0; + var dur = duration || undefined; + if (this.isPlaying()) { + this.stop(0); + } + this.play(0, this.playbackRate, this.output.gain.value, cTime, dur); + }; + /** + * Return the number of channels in a sound file. + * For example, Mono = 1, Stereo = 2. + * + * @method channels + * @return {Number} [channels] + */ + p5.SoundFile.prototype.channels = function () { + return this.buffer.numberOfChannels; + }; + /** + * Return the sample rate of the sound file. + * + * @method sampleRate + * @return {Number} [sampleRate] + */ + p5.SoundFile.prototype.sampleRate = function () { + return this.buffer.sampleRate; + }; + /** + * Return the number of samples in a sound file. + * Equal to sampleRate * duration. + * + * @method frames + * @return {Number} [sampleCount] + */ + p5.SoundFile.prototype.frames = function () { + return this.buffer.length; + }; + /** + * Returns an array of amplitude peaks in a p5.SoundFile that can be + * used to draw a static waveform. Scans through the p5.SoundFile's + * audio buffer to find the greatest amplitudes. Accepts one + * parameter, 'length', which determines size of the array. + * Larger arrays result in more precise waveform visualizations. + * + * Inspired by Wavesurfer.js. + * + * @method getPeaks + * @params {Number} [length] length is the size of the returned array. + * Larger length results in more precision. + * Defaults to 5*width of the browser window. + * @returns {Float32Array} Array of peaks. + */ + p5.SoundFile.prototype.getPeaks = function (length) { + if (this.buffer) { + // set length to window's width if no length is provided + if (!length) { + length = window.width * 5; + } + if (this.buffer) { + var buffer = this.buffer; + var sampleSize = buffer.length / length; + var sampleStep = ~~(sampleSize / 10) || 1; + var channels = buffer.numberOfChannels; + var peaks = new Float32Array(Math.round(length)); + for (var c = 0; c < channels; c++) { + var chan = buffer.getChannelData(c); + for (var i = 0; i < length; i++) { + var start = ~~(i * sampleSize); + var end = ~~(start + sampleSize); + var max = 0; + for (var j = start; j < end; j += sampleStep) { + var value = chan[j]; + if (value > max) { + max = value; + } else if (-value > max) { + max = value; + } + } + if (c === 0 || Math.abs(max) > peaks[i]) { + peaks[i] = max; + } + } + } + return peaks; + } + } else { + throw 'Cannot load peaks yet, buffer is not loaded'; + } + }; + /** + * Reverses the p5.SoundFile's buffer source. + * Playback must be handled separately (see example). + * + * @method reverseBuffer + * @example + *
+ * var drum; + * + * function preload() { + * drum = loadSound('assets/drum.mp3'); + * } + * + * function setup() { + * drum.reverseBuffer(); + * drum.play(); + * } + * + * + *
+ */ + p5.SoundFile.prototype.reverseBuffer = function () { + if (this.buffer) { + var currentPos = this._lastPos / ac.sampleRate; + var curVol = this.getVolume(); + this.setVolume(0, 0.001); + const numChannels = this.buffer.numberOfChannels; + for (var i = 0; i < numChannels; i++) { + this.buffer.getChannelData(i).reverse(); + } + // set reversed flag + this.reversed = !this.reversed; + if (currentPos) { + this.jump(this.duration() - currentPos); + } + this.setVolume(curVol, 0.001); + } else { + throw 'SoundFile is not done loading'; + } + }; + /** + * Schedule an event to be called when the soundfile + * reaches the end of a buffer. If the soundfile is + * playing through once, this will be called when it + * ends. If it is looping, it will be called when + * stop is called. + * + * @method onended + * @param {Function} callback function to call when the + * soundfile has ended. + */ + p5.SoundFile.prototype.onended = function (callback) { + this._onended = callback; + return this; + }; + p5.SoundFile.prototype.add = function () { + }; + p5.SoundFile.prototype.dispose = function () { + var now = p5sound.audiocontext.currentTime; + // remove reference to soundfile + var index = p5sound.soundArray.indexOf(this); + p5sound.soundArray.splice(index, 1); + this.stop(now); + if (this.buffer && this.bufferSourceNode) { + for (var i = 0; i < this.bufferSourceNodes.length - 1; i++) { + if (this.bufferSourceNodes[i] !== null) { + this.bufferSourceNodes[i].disconnect(); + try { + this.bufferSourceNodes[i].stop(now); + } catch (e) { + console.warning('no buffer source node to dispose'); + } + this.bufferSourceNodes[i] = null; + } + } + if (this.isPlaying()) { + try { + this._counterNode.stop(now); + } catch (e) { + console.log(e); + } + this._counterNode = null; + } + } + if (this.output) { + this.output.disconnect(); + this.output = null; + } + if (this.panner) { + this.panner.disconnect(); + this.panner = null; + } + }; + /** + * Connects the output of a p5sound object to input of another + * p5.sound object. For example, you may connect a p5.SoundFile to an + * FFT or an Effect. If no parameter is given, it will connect to + * the master output. Most p5sound objects connect to the master + * output when they are created. + * + * @method connect + * @param {Object} [object] Audio object that accepts an input + */ + p5.SoundFile.prototype.connect = function (unit) { + if (!unit) { + this.panner.connect(p5sound.input); + } else { + if (unit.hasOwnProperty('input')) { + this.panner.connect(unit.input); + } else { + this.panner.connect(unit); + } + } + }; + /** + * Disconnects the output of this p5sound object. + * + * @method disconnect + */ + p5.SoundFile.prototype.disconnect = function () { + if (this.panner) { + this.panner.disconnect(); + } + }; + /** + */ + p5.SoundFile.prototype.getLevel = function () { + console.warn('p5.SoundFile.getLevel has been removed from the library. Use p5.Amplitude instead'); + }; + /** + * Reset the source for this SoundFile to a + * new path (URL). + * + * @method setPath + * @param {String} path path to audio file + * @param {Function} callback Callback + */ + p5.SoundFile.prototype.setPath = function (p, callback) { + var path = p5.prototype._checkFileFormats(p); + this.url = path; + this.load(callback); + }; + /** + * Replace the current Audio Buffer with a new Buffer. + * + * @method setBuffer + * @param {Array} buf Array of Float32 Array(s). 2 Float32 Arrays + * will create a stereo source. 1 will create + * a mono source. + */ + p5.SoundFile.prototype.setBuffer = function (buf) { + var numChannels = buf.length; + var size = buf[0].length; + var newBuffer = ac.createBuffer(numChannels, size, ac.sampleRate); + if (!(buf[0] instanceof Float32Array)) { + buf[0] = new Float32Array(buf[0]); + } + for (var channelNum = 0; channelNum < numChannels; channelNum++) { + var channel = newBuffer.getChannelData(channelNum); + channel.set(buf[channelNum]); + } + this.buffer = newBuffer; + // set numbers of channels on input to the panner + this.panner.inputChannels(numChannels); + }; + ////////////////////////////////////////////////// + // script processor node with an empty buffer to help + // keep a sample-accurate position in playback buffer. + // Inspired by Chinmay Pendharkar's technique for Sonoport --> http://bit.ly/1HwdCsV + // Copyright [2015] [Sonoport (Asia) Pte. Ltd.], + // Licensed under the Apache License http://apache.org/licenses/LICENSE-2.0 + //////////////////////////////////////////////////////////////////////////////////// + var _createCounterBuffer = function (buffer) { + const len = buffer.length; + const audioBuf = ac.createBuffer(1, buffer.length, ac.sampleRate); + const arrayBuffer = audioBuf.getChannelData(0); + for (var index = 0; index < len; index++) { + arrayBuffer[index] = index; + } + return audioBuf; + }; + // initialize counterNode, set its initial buffer and playbackRate + p5.SoundFile.prototype._initCounterNode = function () { + var self = this; + var now = ac.currentTime; + var cNode = ac.createBufferSource(); + // dispose of scope node if it already exists + if (self._scopeNode) { + self._scopeNode.disconnect(); + self._scopeNode.removeEventListener('audioprocess', self._onAudioProcess); + delete self._scopeNode; + } + self._scopeNode = ac.createScriptProcessor(256, 1, 1); + // create counter buffer of the same length as self.buffer + cNode.buffer = _createCounterBuffer(self.buffer); + cNode.playbackRate.setValueAtTime(self.playbackRate, now); + cNode.connect(self._scopeNode); + self._scopeNode.connect(p5.soundOut._silentNode); + self._scopeNode.addEventListener('audioprocess', self._onAudioProcess); + return cNode; + }; + // initialize sourceNode, set its initial buffer and playbackRate + p5.SoundFile.prototype._initSourceNode = function () { + var bufferSourceNode = ac.createBufferSource(); + bufferSourceNode.buffer = this.buffer; + bufferSourceNode.playbackRate.value = this.playbackRate; + bufferSourceNode.connect(this.output); + return bufferSourceNode; + }; + /** + * processPeaks returns an array of timestamps where it thinks there is a beat. + * + * This is an asynchronous function that processes the soundfile in an offline audio context, + * and sends the results to your callback function. + * + * The process involves running the soundfile through a lowpass filter, and finding all of the + * peaks above the initial threshold. If the total number of peaks are below the minimum number of peaks, + * it decreases the threshold and re-runs the analysis until either minPeaks or minThreshold are reached. + * + * @method processPeaks + * @param {Function} callback a function to call once this data is returned + * @param {Number} [initThreshold] initial threshold defaults to 0.9 + * @param {Number} [minThreshold] minimum threshold defaults to 0.22 + * @param {Number} [minPeaks] minimum number of peaks defaults to 200 + * @return {Array} Array of timestamped peaks + */ + p5.SoundFile.prototype.processPeaks = function (callback, _initThreshold, _minThreshold, _minPeaks) { + var bufLen = this.buffer.length; + var sampleRate = this.buffer.sampleRate; + var buffer = this.buffer; + var allPeaks = []; + var initialThreshold = _initThreshold || 0.9, threshold = initialThreshold, minThreshold = _minThreshold || 0.22, minPeaks = _minPeaks || 200; + // Create offline context + var offlineContext = new window.OfflineAudioContext(1, bufLen, sampleRate); + // create buffer source + var source = offlineContext.createBufferSource(); + source.buffer = buffer; + // Create filter. TO DO: allow custom setting of filter + var filter = offlineContext.createBiquadFilter(); + filter.type = 'lowpass'; + source.connect(filter); + filter.connect(offlineContext.destination); + // start playing at time:0 + source.start(0); + offlineContext.startRendering(); + // Render the song + // act on the result + offlineContext.oncomplete = function (e) { + if (!self.panner) + return; + var filteredBuffer = e.renderedBuffer; + var bufferData = filteredBuffer.getChannelData(0); + // step 1: + // create Peak instances, add them to array, with strength and sampleIndex + do { + allPeaks = getPeaksAtThreshold(bufferData, threshold); + threshold -= 0.005; + } while (Object.keys(allPeaks).length < minPeaks && threshold >= minThreshold); + // step 2: + // find intervals for each peak in the sampleIndex, add tempos array + var intervalCounts = countIntervalsBetweenNearbyPeaks(allPeaks); + // step 3: find top tempos + var groups = groupNeighborsByTempo(intervalCounts, filteredBuffer.sampleRate); + // sort top intervals + var topTempos = groups.sort(function (intA, intB) { + return intB.count - intA.count; + }).splice(0, 5); + // set this SoundFile's tempo to the top tempo ?? + this.tempo = topTempos[0].tempo; + // step 4: + // new array of peaks at top tempo within a bpmVariance + var bpmVariance = 5; + var tempoPeaks = getPeaksAtTopTempo(allPeaks, topTempos[0].tempo, filteredBuffer.sampleRate, bpmVariance); + callback(tempoPeaks); + }; + }; + // process peaks + var Peak = function (amp, i) { + this.sampleIndex = i; + this.amplitude = amp; + this.tempos = []; + this.intervals = []; + }; + // 1. for processPeaks() Function to identify peaks above a threshold + // returns an array of peak indexes as frames (samples) of the original soundfile + function getPeaksAtThreshold(data, threshold) { + var peaksObj = {}; + var length = data.length; + for (var i = 0; i < length; i++) { + if (data[i] > threshold) { + var amp = data[i]; + var peak = new Peak(amp, i); + peaksObj[i] = peak; + // Skip forward ~ 1/8s to get past this peak. + i += 6000; + } + i++; + } + return peaksObj; + } + // 2. for processPeaks() + function countIntervalsBetweenNearbyPeaks(peaksObj) { + var intervalCounts = []; + var peaksArray = Object.keys(peaksObj).sort(); + for (var index = 0; index < peaksArray.length; index++) { + // find intervals in comparison to nearby peaks + for (var i = 0; i < 10; i++) { + var startPeak = peaksObj[peaksArray[index]]; + var endPeak = peaksObj[peaksArray[index + i]]; + if (startPeak && endPeak) { + var startPos = startPeak.sampleIndex; + var endPos = endPeak.sampleIndex; + var interval = endPos - startPos; + // add a sample interval to the startPeak in the allPeaks array + if (interval > 0) { + startPeak.intervals.push(interval); + } + // tally the intervals and return interval counts + var foundInterval = intervalCounts.some(function (intervalCount) { + if (intervalCount.interval === interval) { + intervalCount.count++; + return intervalCount; + } + }); + // store with JSON like formatting + if (!foundInterval) { + intervalCounts.push({ + interval: interval, + count: 1 + }); + } + } + } + } + return intervalCounts; + } + // 3. for processPeaks --> find tempo + function groupNeighborsByTempo(intervalCounts, sampleRate) { + var tempoCounts = []; + intervalCounts.forEach(function (intervalCount) { + try { + // Convert an interval to tempo + var theoreticalTempo = Math.abs(60 / (intervalCount.interval / sampleRate)); + theoreticalTempo = mapTempo(theoreticalTempo); + var foundTempo = tempoCounts.some(function (tempoCount) { + if (tempoCount.tempo === theoreticalTempo) + return tempoCount.count += intervalCount.count; + }); + if (!foundTempo) { + if (isNaN(theoreticalTempo)) { + return; + } + tempoCounts.push({ + tempo: Math.round(theoreticalTempo), + count: intervalCount.count + }); + } + } catch (e) { + throw e; + } + }); + return tempoCounts; + } + // 4. for processPeaks - get peaks at top tempo + function getPeaksAtTopTempo(peaksObj, tempo, sampleRate, bpmVariance) { + var peaksAtTopTempo = []; + var peaksArray = Object.keys(peaksObj).sort(); + // TO DO: filter out peaks that have the tempo and return + for (var i = 0; i < peaksArray.length; i++) { + var key = peaksArray[i]; + var peak = peaksObj[key]; + for (var j = 0; j < peak.intervals.length; j++) { + var intervalBPM = Math.round(Math.abs(60 / (peak.intervals[j] / sampleRate))); + intervalBPM = mapTempo(intervalBPM); + if (Math.abs(intervalBPM - tempo) < bpmVariance) { + // convert sampleIndex to seconds + peaksAtTopTempo.push(peak.sampleIndex / sampleRate); + } + } + } + // filter out peaks that are very close to each other + peaksAtTopTempo = peaksAtTopTempo.filter(function (peakTime, index, arr) { + var dif = arr[index + 1] - peakTime; + if (dif > 0.01) { + return true; + } + }); + return peaksAtTopTempo; + } + // helper function for processPeaks + function mapTempo(theoreticalTempo) { + // these scenarios create infinite while loop + if (!isFinite(theoreticalTempo) || theoreticalTempo === 0) { + return; + } + // Adjust the tempo to fit within the 90-180 BPM range + while (theoreticalTempo < 90) + theoreticalTempo *= 2; + while (theoreticalTempo > 180 && theoreticalTempo > 90) + theoreticalTempo /= 2; + return theoreticalTempo; + } + /*** SCHEDULE EVENTS ***/ + // Cue inspired by JavaScript setTimeout, and the + // Tone.js Transport Timeline Event, MIT License Yotam Mann 2015 tonejs.org + var Cue = function (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 + *
+ * var mySound; + * function preload() { + * mySound = loadSound('assets/beat.mp3'); + * } + * + * function setup() { + * background(0); + * noStroke(); + * fill(255); + * textAlign(CENTER); + * text('click to play', width/2, height/2); + * + * // schedule calls to changeText + * mySound.addCue(0.50, changeText, "hello" ); + * mySound.addCue(1.00, changeText, "p5" ); + * mySound.addCue(1.50, changeText, "what" ); + * mySound.addCue(2.00, changeText, "do" ); + * mySound.addCue(2.50, changeText, "you" ); + * mySound.addCue(3.00, changeText, "want" ); + * mySound.addCue(4.00, changeText, "to" ); + * mySound.addCue(5.00, changeText, "make" ); + * mySound.addCue(6.00, changeText, "?" ); + * } + * + * function changeText(val) { + * background(0); + * text(val, width/2, height/2); + * } + * + * function mouseClicked() { + * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { + * if (mySound.isPlaying() ) { + * mySound.stop(); + * } else { + * mySound.play(); + * } + * } + * } + *
+ */ + p5.SoundFile.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 + */ + p5.SoundFile.prototype.removeCue = function (id) { + var cueLength = this._cues.length; + for (var i = 0; i < cueLength; i++) { + var cue = this._cues[i]; + if (cue.id === id) { + this._cues.splice(i, 1); + break; + } + } + if (this._cues.length === 0) { + } + }; + /** + * Remove all of the callbacks that had originally been scheduled + * via the addCue method. + * + * @method clearCues + */ + p5.SoundFile.prototype.clearCues = function () { + this._cues = []; + }; + // private method that checks for cues to be fired if events + // have been scheduled using addCue(callback, time). + p5.SoundFile.prototype._onTimeUpdate = function (position) { + var playbackTime = position / this.buffer.sampleRate; + var cueLength = this._cues.length; + for (var i = 0; i < cueLength; i++) { + var cue = this._cues[i]; + var callbackTime = cue.time; + var val = cue.val; + if (this._prevTime < callbackTime && callbackTime <= playbackTime) { + // pass the scheduled callbackTime as parameter to the callback + cue.callback(val); + } + } + this._prevTime = playbackTime; + }; + /** + * Save a p5.SoundFile as a .wav file. The browser will prompt the user + * to download the file to their device. To upload a file to a server, see + * getBlob + * + * @method save + * @param {String} [fileName] name of the resulting .wav file. + * @example + *
+ * var inp, button, mySound; + * var fileName = 'cool'; + * function preload() { + * mySound = loadSound('assets/doorbell.mp3'); + * } + * function setup() { + * btn = createButton('click to save file'); + * btn.position(0, 0); + * btn.mouseClicked(handleMouseClick); + * } + * + * function handleMouseClick() { + * mySound.save(fileName); + * } + *
+ */ + p5.SoundFile.prototype.save = function (fileName) { + const dataView = convertToWav(this.buffer); + p5.prototype.saveSound([dataView], fileName, 'wav'); + }; + /** + * This method is useful for sending a SoundFile to a server. It returns the + * .wav-encoded audio data as a "Blob". + * A Blob is a file-like data object that can be uploaded to a server + * with an http request. We'll + * use the `httpDo` options object to send a POST request with some + * specific options: we encode the request as `multipart/form-data`, + * and attach the blob as one of the form values using `FormData`. + * + * + * @method getBlob + * @returns {Blob} A file-like data object + * @example + *
+ * + * function preload() { + * mySound = loadSound('assets/doorbell.mp3'); + * } + * + * function setup() { + * noCanvas(); + * var soundBlob = mySound.getBlob(); + * + * // Now we can send the blob to a server... + * var serverUrl = 'https://jsonplaceholder.typicode.com/posts'; + * var httpRequestOptions = { + * method: 'POST', + * body: new FormData().append('soundBlob', soundBlob), + * headers: new Headers({ + * 'Content-Type': 'multipart/form-data' + * }) + * }; + * httpDo(serverUrl, httpRequestOptions); + * + * // We can also create an `ObjectURL` pointing to the Blob + * var blobUrl = URL.createObjectURL(soundBlob); + * + * // The `
+ */ + p5.SoundFile.prototype.getBlob = function () { + const dataView = convertToWav(this.buffer); + return new Blob([dataView], { type: 'audio/wav' }); + }; + // event handler to keep track of current position + function _onAudioProcess(processEvent) { + var inputBuffer = processEvent.inputBuffer.getChannelData(0); + this._lastPos = inputBuffer[inputBuffer.length - 1] || 0; + // do any callbacks that have been scheduled + this._onTimeUpdate(self._lastPos); + } + // event handler to remove references to the bufferSourceNode when it is done playing + function _clearOnEnd(e) { + const thisBufferSourceNode = e.target; + const soundFile = this; + // delete this.bufferSourceNode from the sources array when it is done playing: + thisBufferSourceNode._playing = false; + thisBufferSourceNode.removeEventListener('ended', soundFile._clearOnEnd); + // call the onended callback + soundFile._onended(soundFile); + soundFile.bufferSourceNodes.forEach(function (n, i) { + if (n._playing === false) { + soundFile.bufferSourceNodes.splice(i); + } + }); + if (soundFile.bufferSourceNodes.length === 0) { + soundFile._playing = false; + } + } +}(errorHandler, master, helpers, helpers); +var amplitude; +'use strict'; +amplitude = function () { + var p5sound = master; + /** + * Amplitude measures volume between 0.0 and 1.0. + * Listens to all p5sound by default, or use setInput() + * to listen to a specific sound source. Accepts an optional + * smoothing value, which defaults to 0. + * + * @class p5.Amplitude + * @constructor + * @param {Number} [smoothing] between 0.0 and .999 to smooth + * amplitude readings (defaults to 0) + * @example + *
+ * var sound, amplitude, cnv; + * + * function preload(){ + * sound = loadSound('assets/beat.mp3'); + * } + * function setup() { + * cnv = createCanvas(100,100); + * amplitude = new p5.Amplitude(); + * + * // start / stop the sound when canvas is clicked + * cnv.mouseClicked(function() { + * if (sound.isPlaying() ){ + * sound.stop(); + * } else { + * sound.play(); + * } + * }); + * } + * function draw() { + * background(0); + * fill(255); + * var level = amplitude.getLevel(); + * var size = map(level, 0, 1, 0, 200); + * ellipse(width/2, height/2, size, size); + * } + * + *
+ */ + p5.Amplitude = function (smoothing) { + // Set to 2048 for now. In future iterations, this should be inherited or parsed from p5sound's default + this.bufferSize = 2048; + // set audio context + this.audiocontext = p5sound.audiocontext; + this.processor = this.audiocontext.createScriptProcessor(this.bufferSize, 2, 1); + // for connections + this.input = this.processor; + this.output = this.audiocontext.createGain(); + // smoothing defaults to 0 + this.smoothing = smoothing || 0; + // the variables to return + this.volume = 0; + this.average = 0; + this.stereoVol = [ + 0, + 0 + ]; + this.stereoAvg = [ + 0, + 0 + ]; + this.stereoVolNorm = [ + 0, + 0 + ]; + this.volMax = 0.001; + this.normalize = false; + this.processor.onaudioprocess = this._audioProcess.bind(this); + this.processor.connect(this.output); + this.output.gain.value = 0; + // this may only be necessary because of a Chrome bug + this.output.connect(this.audiocontext.destination); + // connect to p5sound master output by default, unless set by input() + p5sound.meter.connect(this.processor); + // add this p5.SoundFile to the soundArray + p5sound.soundArray.push(this); + }; + /** + * Connects to the p5sound instance (master output) by default. + * Optionally, you can pass in a specific source (i.e. a soundfile). + * + * @method setInput + * @param {soundObject|undefined} [snd] set the sound source + * (optional, defaults to + * master output) + * @param {Number|undefined} [smoothing] a range between 0.0 and 1.0 + * to smooth amplitude readings + * @example + *
+ * function preload(){ + * sound1 = loadSound('assets/beat.mp3'); + * sound2 = loadSound('assets/drum.mp3'); + * } + * function setup(){ + * amplitude = new p5.Amplitude(); + * sound1.play(); + * sound2.play(); + * amplitude.setInput(sound2); + * } + * function draw() { + * background(0); + * fill(255); + * var level = amplitude.getLevel(); + * var size = map(level, 0, 1, 0, 200); + * ellipse(width/2, height/2, size, size); + * } + * function mouseClicked(){ + * sound1.stop(); + * sound2.stop(); + * } + *
+ */ + p5.Amplitude.prototype.setInput = function (source, smoothing) { + p5sound.meter.disconnect(); + if (smoothing) { + this.smoothing = smoothing; + } + // connect to the master out of p5s instance if no snd is provided + if (source == null) { + console.log('Amplitude input source is not ready! Connecting to master output instead'); + p5sound.meter.connect(this.processor); + } else if (source instanceof p5.Signal) { + source.output.connect(this.processor); + } else if (source) { + source.connect(this.processor); + this.processor.disconnect(); + this.processor.connect(this.output); + } else { + p5sound.meter.connect(this.processor); + } + }; + p5.Amplitude.prototype.connect = function (unit) { + if (unit) { + if (unit.hasOwnProperty('input')) { + this.output.connect(unit.input); + } else { + this.output.connect(unit); + } + } else { + this.output.connect(this.panner.connect(p5sound.input)); + } + }; + p5.Amplitude.prototype.disconnect = function () { + if (this.output) { + this.output.disconnect(); + } + }; + // TO DO make this stereo / dependent on # of audio channels + p5.Amplitude.prototype._audioProcess = function (event) { + for (var channel = 0; channel < event.inputBuffer.numberOfChannels; channel++) { + var inputBuffer = event.inputBuffer.getChannelData(channel); + var bufLength = inputBuffer.length; + var total = 0; + var sum = 0; + var x; + for (var i = 0; i < bufLength; i++) { + x = inputBuffer[i]; + if (this.normalize) { + total += Math.max(Math.min(x / this.volMax, 1), -1); + sum += Math.max(Math.min(x / this.volMax, 1), -1) * Math.max(Math.min(x / this.volMax, 1), -1); + } else { + total += x; + sum += x * x; + } + } + var average = total / bufLength; + // ... then take the square root of the sum. + var rms = Math.sqrt(sum / bufLength); + this.stereoVol[channel] = Math.max(rms, this.stereoVol[channel] * this.smoothing); + this.stereoAvg[channel] = Math.max(average, this.stereoVol[channel] * this.smoothing); + this.volMax = Math.max(this.stereoVol[channel], this.volMax); + } + // add volume from all channels together + var self = this; + var volSum = this.stereoVol.reduce(function (previousValue, currentValue, index) { + self.stereoVolNorm[index - 1] = Math.max(Math.min(self.stereoVol[index - 1] / self.volMax, 1), 0); + self.stereoVolNorm[index] = Math.max(Math.min(self.stereoVol[index] / self.volMax, 1), 0); + return previousValue + currentValue; + }); + // volume is average of channels + this.volume = volSum / this.stereoVol.length; + // normalized value + this.volNorm = Math.max(Math.min(this.volume / this.volMax, 1), 0); + }; + /** + * Returns a single Amplitude reading at the moment it is called. + * For continuous readings, run in the draw loop. + * + * @method getLevel + * @param {Number} [channel] Optionally return only channel 0 (left) or 1 (right) + * @return {Number} Amplitude as a number between 0.0 and 1.0 + * @example + *
+ * function preload(){ + * sound = loadSound('assets/beat.mp3'); + * } + * function setup() { + * amplitude = new p5.Amplitude(); + * sound.play(); + * } + * function draw() { + * background(0); + * fill(255); + * var level = amplitude.getLevel(); + * var size = map(level, 0, 1, 0, 200); + * ellipse(width/2, height/2, size, size); + * } + * function mouseClicked(){ + * sound.stop(); + * } + *
+ */ + p5.Amplitude.prototype.getLevel = function (channel) { + if (typeof channel !== 'undefined') { + if (this.normalize) { + return this.stereoVolNorm[channel]; + } else { + return this.stereoVol[channel]; + } + } else if (this.normalize) { + return this.volNorm; + } else { + return this.volume; + } + }; + /** + * Determines whether the results of Amplitude.process() will be + * Normalized. To normalize, Amplitude finds the difference the + * loudest reading it has processed and the maximum amplitude of + * 1.0. Amplitude adds this difference to all values to produce + * results that will reliably map between 0.0 and 1.0. However, + * if a louder moment occurs, the amount that Normalize adds to + * all the values will change. Accepts an optional boolean parameter + * (true or false). Normalizing is off by default. + * + * @method toggleNormalize + * @param {boolean} [boolean] set normalize to true (1) or false (0) + */ + p5.Amplitude.prototype.toggleNormalize = function (bool) { + if (typeof bool === 'boolean') { + this.normalize = bool; + } else { + this.normalize = !this.normalize; + } + }; + /** + * Smooth Amplitude analysis by averaging with the last analysis + * frame. Off by default. + * + * @method smooth + * @param {Number} set smoothing from 0.0 <= 1 + */ + p5.Amplitude.prototype.smooth = function (s) { + if (s >= 0 && s < 1) { + this.smoothing = s; + } else { + console.log('Error: smoothing must be between 0 and 1'); + } + }; + p5.Amplitude.prototype.dispose = function () { + // remove reference from soundArray + var index = p5sound.soundArray.indexOf(this); + p5sound.soundArray.splice(index, 1); + if (this.input) { + this.input.disconnect(); + delete this.input; + } + if (this.output) { + this.output.disconnect(); + delete this.output; + } + delete this.processor; + }; +}(master); +var fft; +'use strict'; +fft = function () { + var p5sound = master; + /** + *

FFT (Fast Fourier Transform) is an analysis algorithm that + * isolates individual + * + * audio frequencies within a waveform.

+ * + *

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

+ * + *

FFT analyzes a very short snapshot of sound called a sample + * buffer. It returns an array of amplitude measurements, referred + * to as bins. The array is 1024 bins long by default. + * You can change the bin array length, but it must be a power of 2 + * between 16 and 1024 in order for the FFT algorithm to function + * correctly. The actual size of the FFT buffer is twice the + * number of bins, so given a standard sample rate, the buffer is + * 2048/44100 seconds long.

+ * + * + * @class p5.FFT + * @constructor + * @param {Number} [smoothing] Smooth results of Freq Spectrum. + * 0.0 < smoothing < 1.0. + * Defaults to 0.8. + * @param {Number} [bins] Length of resulting array. + * Must be a power of two between + * 16 and 1024. Defaults to 1024. + * @example + *
+ * function preload(){ + * sound = loadSound('assets/Damscray_DancingTiger.mp3'); + * } + * + * function setup(){ + * var cnv = createCanvas(100,100); + * cnv.mouseClicked(togglePlay); + * fft = new p5.FFT(); + * sound.amp(0.2); + * } + * + * function draw(){ + * background(0); + * + * var spectrum = fft.analyze(); + * noStroke(); + * fill(0,255,0); // spectrum is green + * for (var i = 0; i< spectrum.length; i++){ + * var x = map(i, 0, spectrum.length, 0, width); + * var h = -height + map(spectrum[i], 0, 255, height, 0); + * rect(x, height, width / spectrum.length, h ) + * } + * + * var waveform = fft.waveform(); + * noFill(); + * beginShape(); + * stroke(255,0,0); // waveform is red + * strokeWeight(1); + * for (var i = 0; i< waveform.length; i++){ + * var x = map(i, 0, waveform.length, 0, width); + * var y = map( waveform[i], -1, 1, 0, height); + * vertex(x,y); + * } + * endShape(); + * + * text('click to play/pause', 4, 10); + * } + * + * // fade sound if mouse is over canvas + * function togglePlay() { + * if (sound.isPlaying()) { + * sound.pause(); + * } else { + * sound.loop(); + * } + * } + *
+ */ + p5.FFT = function (smoothing, bins) { + this.input = this.analyser = p5sound.audiocontext.createAnalyser(); + Object.defineProperties(this, { + bins: { + get: function () { + return this.analyser.fftSize / 2; + }, + set: function (b) { + this.analyser.fftSize = b * 2; + }, + configurable: true, + enumerable: true + }, + smoothing: { + get: function () { + return this.analyser.smoothingTimeConstant; + }, + set: function (s) { + this.analyser.smoothingTimeConstant = s; + }, + configurable: true, + enumerable: true + } + }); + // set default smoothing and bins + this.smooth(smoothing); + this.bins = bins || 1024; + // default connections to p5sound fftMeter + p5sound.fftMeter.connect(this.analyser); + this.freqDomain = new Uint8Array(this.analyser.frequencyBinCount); + this.timeDomain = new Uint8Array(this.analyser.frequencyBinCount); + // predefined frequency ranges, these will be tweakable + this.bass = [ + 20, + 140 + ]; + this.lowMid = [ + 140, + 400 + ]; + this.mid = [ + 400, + 2600 + ]; + this.highMid = [ + 2600, + 5200 + ]; + this.treble = [ + 5200, + 14000 + ]; + // add this p5.SoundFile to the soundArray + p5sound.soundArray.push(this); + }; + /** + * Set the input source for the FFT analysis. If no source is + * provided, FFT will analyze all sound in the sketch. + * + * @method setInput + * @param {Object} [source] p5.sound object (or web audio API source node) + */ + p5.FFT.prototype.setInput = function (source) { + if (!source) { + p5sound.fftMeter.connect(this.analyser); + } else { + if (source.output) { + source.output.connect(this.analyser); + } else if (source.connect) { + source.connect(this.analyser); + } + p5sound.fftMeter.disconnect(); + } + }; + /** + * Returns an array of amplitude values (between -1.0 and +1.0) that represent + * a snapshot of amplitude readings in a single buffer. Length will be + * equal to bins (defaults to 1024). Can be used to draw the waveform + * of a sound. + * + * @method waveform + * @param {Number} [bins] Must be a power of two between + * 16 and 1024. Defaults to 1024. + * @param {String} [precision] If any value is provided, will return results + * in a Float32 Array which is more precise + * than a regular array. + * @return {Array} Array Array of amplitude values (-1 to 1) + * over time. Array length = bins. + * + */ + p5.FFT.prototype.waveform = function () { + var bins, mode, normalArray; + for (var i = 0; i < arguments.length; i++) { + if (typeof arguments[i] === 'number') { + bins = arguments[i]; + this.analyser.fftSize = bins * 2; + } + if (typeof arguments[i] === 'string') { + mode = arguments[i]; + } + } + // getFloatFrequencyData doesnt work in Safari as of 5/2015 + if (mode && !p5.prototype._isSafari()) { + timeToFloat(this, this.timeDomain); + this.analyser.getFloatTimeDomainData(this.timeDomain); + return this.timeDomain; + } else { + timeToInt(this, this.timeDomain); + this.analyser.getByteTimeDomainData(this.timeDomain); + var normalArray = new Array(); + for (var j = 0; j < this.timeDomain.length; j++) { + var scaled = p5.prototype.map(this.timeDomain[j], 0, 255, -1, 1); + normalArray.push(scaled); + } + return normalArray; + } + }; + /** + * Returns an array of amplitude values (between 0 and 255) + * across the frequency spectrum. Length is equal to FFT bins + * (1024 by default). The array indices correspond to frequencies + * (i.e. pitches), from the lowest to the highest that humans can + * hear. Each value represents amplitude at that slice of the + * frequency spectrum. Must be called prior to using + * getEnergy(). + * + * @method analyze + * @param {Number} [bins] Must be a power of two between + * 16 and 1024. Defaults to 1024. + * @param {Number} [scale] If "dB," returns decibel + * float measurements between + * -140 and 0 (max). + * Otherwise returns integers from 0-255. + * @return {Array} spectrum Array of energy (amplitude/volume) + * values across the frequency spectrum. + * Lowest energy (silence) = 0, highest + * possible is 255. + * @example + *
+ * var osc; + * var fft; + * + * function setup(){ + * createCanvas(100,100); + * osc = new p5.Oscillator(); + * osc.amp(0); + * osc.start(); + * fft = new p5.FFT(); + * } + * + * function draw(){ + * background(0); + * + * var freq = map(mouseX, 0, 800, 20, 15000); + * freq = constrain(freq, 1, 20000); + * osc.freq(freq); + * + * var spectrum = fft.analyze(); + * noStroke(); + * fill(0,255,0); // spectrum is green + * for (var i = 0; i< spectrum.length; i++){ + * var x = map(i, 0, spectrum.length, 0, width); + * var h = -height + map(spectrum[i], 0, 255, height, 0); + * rect(x, height, width / spectrum.length, h ); + * } + * + * stroke(255); + * text('Freq: ' + round(freq)+'Hz', 10, 10); + * + * isMouseOverCanvas(); + * } + * + * // only play sound when mouse is over canvas + * function isMouseOverCanvas() { + * var mX = mouseX, mY = mouseY; + * if (mX > 0 && mX < width && mY < height && mY > 0) { + * osc.amp(0.5, 0.2); + * } else { + * osc.amp(0, 0.2); + * } + * } + *
+ * + * + */ + p5.FFT.prototype.analyze = function () { + var mode; + for (var i = 0; i < arguments.length; i++) { + if (typeof arguments[i] === 'number') { + this.bins = arguments[i]; + this.analyser.fftSize = this.bins * 2; + } + if (typeof arguments[i] === 'string') { + mode = arguments[i]; + } + } + if (mode && mode.toLowerCase() === 'db') { + freqToFloat(this); + this.analyser.getFloatFrequencyData(this.freqDomain); + return this.freqDomain; + } else { + freqToInt(this, this.freqDomain); + this.analyser.getByteFrequencyData(this.freqDomain); + var normalArray = Array.apply([], this.freqDomain); + normalArray.length === this.analyser.fftSize; + normalArray.constructor === Array; + return normalArray; + } + }; + /** + * Returns the amount of energy (volume) at a specific + * + * frequency, or the average amount of energy between two + * frequencies. Accepts Number(s) corresponding + * to frequency (in Hz), or a String corresponding to predefined + * frequency ranges ("bass", "lowMid", "mid", "highMid", "treble"). + * Returns a range between 0 (no energy/volume at that frequency) and + * 255 (maximum energy). + * NOTE: analyze() must be called prior to getEnergy(). Analyze() + * tells the FFT to analyze frequency data, and getEnergy() uses + * the results determine the value at a specific frequency or + * range of frequencies.

+ * + * @method getEnergy + * @param {Number|String} frequency1 Will return a value representing + * energy at this frequency. Alternately, + * the strings "bass", "lowMid" "mid", + * "highMid", and "treble" will return + * predefined frequency ranges. + * @param {Number} [frequency2] If a second frequency is given, + * will return average amount of + * energy that exists between the + * two frequencies. + * @return {Number} Energy Energy (volume/amplitude) from + * 0 and 255. + * + */ + p5.FFT.prototype.getEnergy = function (frequency1, frequency2) { + var nyquist = p5sound.audiocontext.sampleRate / 2; + if (frequency1 === 'bass') { + frequency1 = this.bass[0]; + frequency2 = this.bass[1]; + } else if (frequency1 === 'lowMid') { + frequency1 = this.lowMid[0]; + frequency2 = this.lowMid[1]; + } else if (frequency1 === 'mid') { + frequency1 = this.mid[0]; + frequency2 = this.mid[1]; + } else if (frequency1 === 'highMid') { + frequency1 = this.highMid[0]; + frequency2 = this.highMid[1]; + } else if (frequency1 === 'treble') { + frequency1 = this.treble[0]; + frequency2 = this.treble[1]; + } + if (typeof frequency1 !== 'number') { + throw 'invalid input for getEnergy()'; + } else if (!frequency2) { + // if only one parameter: + var index = Math.round(frequency1 / nyquist * this.freqDomain.length); + return this.freqDomain[index]; + } else if (frequency1 && frequency2) { + // if two parameters: + // if second is higher than first + if (frequency1 > frequency2) { + var swap = frequency2; + frequency2 = frequency1; + frequency1 = swap; + } + var lowIndex = Math.round(frequency1 / nyquist * this.freqDomain.length); + var highIndex = Math.round(frequency2 / nyquist * this.freqDomain.length); + var total = 0; + var numFrequencies = 0; + // add up all of the values for the frequencies + for (var i = lowIndex; i <= highIndex; i++) { + total += this.freqDomain[i]; + numFrequencies += 1; + } + // divide by total number of frequencies + var toReturn = total / numFrequencies; + return toReturn; + } else { + throw 'invalid input for getEnergy()'; + } + }; + // compatability with v.012, changed to getEnergy in v.0121. Will be deprecated... + p5.FFT.prototype.getFreq = function (freq1, freq2) { + console.log('getFreq() is deprecated. Please use getEnergy() instead.'); + var x = this.getEnergy(freq1, freq2); + return x; + }; + /** + * Returns the + * + * spectral centroid of the input signal. + * NOTE: analyze() must be called prior to getCentroid(). Analyze() + * tells the FFT to analyze frequency data, and getCentroid() uses + * the results determine the spectral centroid.

+ * + * @method getCentroid + * @return {Number} Spectral Centroid Frequency Frequency of the spectral centroid in Hz. + * + * + * @example + *
+ * + * + *function setup(){ + * cnv = createCanvas(100,100); + * sound = new p5.AudioIn(); + * sound.start(); + * fft = new p5.FFT(); + * sound.connect(fft); + *} + * + * + *function draw(){ + * + * var centroidplot = 0.0; + * var spectralCentroid = 0; + * + * + * background(0); + * stroke(0,255,0); + * var spectrum = fft.analyze(); + * fill(0,255,0); // spectrum is green + * + * //draw the spectrum + * for (var i = 0; i< spectrum.length; i++){ + * var x = map(log(i), 0, log(spectrum.length), 0, width); + * var h = map(spectrum[i], 0, 255, 0, height); + * var rectangle_width = (log(i+1)-log(i))*(width/log(spectrum.length)); + * rect(x, height, rectangle_width, -h ) + * } + + * var nyquist = 22050; + * + * // get the centroid + * spectralCentroid = fft.getCentroid(); + * + * // the mean_freq_index calculation is for the display. + * var mean_freq_index = spectralCentroid/(nyquist/spectrum.length); + * + * centroidplot = map(log(mean_freq_index), 0, log(spectrum.length), 0, width); + * + * + * stroke(255,0,0); // the line showing where the centroid is will be red + * + * rect(centroidplot, 0, width / spectrum.length, height) + * noStroke(); + * fill(255,255,255); // text is white + * text("centroid: ", 10, 20); + * text(round(spectralCentroid)+" Hz", 10, 40); + *} + *
+ */ + p5.FFT.prototype.getCentroid = function () { + var nyquist = p5sound.audiocontext.sampleRate / 2; + var cumulative_sum = 0; + var centroid_normalization = 0; + for (var i = 0; i < this.freqDomain.length; i++) { + cumulative_sum += i * this.freqDomain[i]; + centroid_normalization += this.freqDomain[i]; + } + var mean_freq_index = 0; + if (centroid_normalization !== 0) { + mean_freq_index = cumulative_sum / centroid_normalization; + } + var spec_centroid_freq = mean_freq_index * (nyquist / this.freqDomain.length); + return spec_centroid_freq; + }; + /** + * Smooth FFT analysis by averaging with the last analysis frame. + * + * @method smooth + * @param {Number} smoothing 0.0 < smoothing < 1.0. + * Defaults to 0.8. + */ + p5.FFT.prototype.smooth = function (s) { + if (typeof s !== 'undefined') { + this.smoothing = s; + } + return this.smoothing; + }; + p5.FFT.prototype.dispose = function () { + // remove reference from soundArray + var index = p5sound.soundArray.indexOf(this); + p5sound.soundArray.splice(index, 1); + if (this.analyser) { + this.analyser.disconnect(); + delete this.analyser; + } + }; + /** + * Returns an array of average amplitude values for a given number + * of frequency bands split equally. N defaults to 16. + * NOTE: analyze() must be called prior to linAverages(). Analyze() + * tells the FFT to analyze frequency data, and linAverages() uses + * the results to group them into a smaller set of averages.

+ * + * @method linAverages + * @param {Number} N Number of returned frequency groups + * @return {Array} linearAverages Array of average amplitude values for each group + */ + p5.FFT.prototype.linAverages = function (N) { + var N = N || 16; + // This prevents undefined, null or 0 values of N + var spectrum = this.freqDomain; + var spectrumLength = spectrum.length; + var spectrumStep = Math.floor(spectrumLength / N); + var linearAverages = new Array(N); + // Keep a second index for the current average group and place the values accordingly + // with only one loop in the spectrum data + var groupIndex = 0; + for (var specIndex = 0; specIndex < spectrumLength; specIndex++) { + linearAverages[groupIndex] = linearAverages[groupIndex] !== undefined ? (linearAverages[groupIndex] + spectrum[specIndex]) / 2 : spectrum[specIndex]; + // Increase the group index when the last element of the group is processed + if (specIndex % spectrumStep === spectrumStep - 1) { + groupIndex++; + } + } + return linearAverages; + }; + /** + * Returns an array of average amplitude values of the spectrum, for a given + * set of + * Octave Bands + * NOTE: analyze() must be called prior to logAverages(). Analyze() + * tells the FFT to analyze frequency data, and logAverages() uses + * the results to group them into a smaller set of averages.

+ * + * @method logAverages + * @param {Array} octaveBands Array of Octave Bands objects for grouping + * @return {Array} logAverages Array of average amplitude values for each group + */ + p5.FFT.prototype.logAverages = function (octaveBands) { + var nyquist = p5sound.audiocontext.sampleRate / 2; + var spectrum = this.freqDomain; + var spectrumLength = spectrum.length; + var logAverages = new Array(octaveBands.length); + // Keep a second index for the current average group and place the values accordingly + // With only one loop in the spectrum data + var octaveIndex = 0; + for (var specIndex = 0; specIndex < spectrumLength; specIndex++) { + var specIndexFrequency = Math.round(specIndex * nyquist / this.freqDomain.length); + // Increase the group index if the current frequency exceeds the limits of the band + if (specIndexFrequency > octaveBands[octaveIndex].hi) { + octaveIndex++; + } + logAverages[octaveIndex] = logAverages[octaveIndex] !== undefined ? (logAverages[octaveIndex] + spectrum[specIndex]) / 2 : spectrum[specIndex]; + } + return logAverages; + }; + /** + * Calculates and Returns the 1/N + * Octave Bands + * N defaults to 3 and minimum central frequency to 15.625Hz. + * (1/3 Octave Bands ~= 31 Frequency Bands) + * Setting fCtr0 to a central value of a higher octave will ignore the lower bands + * and produce less frequency groups. + * + * @method getOctaveBands + * @param {Number} N Specifies the 1/N type of generated octave bands + * @param {Number} fCtr0 Minimum central frequency for the lowest band + * @return {Array} octaveBands Array of octave band objects with their bounds + */ + p5.FFT.prototype.getOctaveBands = function (N, fCtr0) { + var N = N || 3; + // Default to 1/3 Octave Bands + var fCtr0 = fCtr0 || 15.625; + // Minimum central frequency, defaults to 15.625Hz + var octaveBands = []; + var lastFrequencyBand = { + lo: fCtr0 / Math.pow(2, 1 / (2 * N)), + ctr: fCtr0, + hi: fCtr0 * Math.pow(2, 1 / (2 * N)) + }; + octaveBands.push(lastFrequencyBand); + var nyquist = p5sound.audiocontext.sampleRate / 2; + while (lastFrequencyBand.hi < nyquist) { + var newFrequencyBand = {}; + newFrequencyBand.lo = lastFrequencyBand.hi; + newFrequencyBand.ctr = lastFrequencyBand.ctr * Math.pow(2, 1 / N); + newFrequencyBand.hi = newFrequencyBand.ctr * Math.pow(2, 1 / (2 * N)); + octaveBands.push(newFrequencyBand); + lastFrequencyBand = newFrequencyBand; + } + return octaveBands; + }; + // helper methods to convert type from float (dB) to int (0-255) + var freqToFloat = function (fft) { + if (fft.freqDomain instanceof Float32Array === false) { + fft.freqDomain = new Float32Array(fft.analyser.frequencyBinCount); + } + }; + var freqToInt = function (fft) { + if (fft.freqDomain instanceof Uint8Array === false) { + fft.freqDomain = new Uint8Array(fft.analyser.frequencyBinCount); + } + }; + var timeToFloat = function (fft) { + if (fft.timeDomain instanceof Float32Array === false) { + fft.timeDomain = new Float32Array(fft.analyser.frequencyBinCount); + } + }; + var timeToInt = function (fft) { + if (fft.timeDomain instanceof Uint8Array === false) { + fft.timeDomain = new Uint8Array(fft.analyser.frequencyBinCount); + } + }; +}(master); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_signal_SignalBase; +Tone_signal_SignalBase = function (Tone) { + 'use strict'; + Tone.SignalBase = function () { + }; + Tone.extend(Tone.SignalBase); + Tone.SignalBase.prototype.connect = function (node, outputNumber, inputNumber) { + if (Tone.Signal && Tone.Signal === node.constructor || Tone.Param && Tone.Param === node.constructor || Tone.TimelineSignal && Tone.TimelineSignal === node.constructor) { + node._param.cancelScheduledValues(0); + node._param.value = 0; + node.overridden = true; + } else if (node instanceof AudioParam) { + node.cancelScheduledValues(0); + node.value = 0; + } + Tone.prototype.connect.call(this, node, outputNumber, inputNumber); + return this; + }; + return Tone.SignalBase; +}(Tone_core_Tone); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_signal_WaveShaper; +Tone_signal_WaveShaper = function (Tone) { + 'use strict'; + Tone.WaveShaper = function (mapping, bufferLen) { + this._shaper = this.input = this.output = this.context.createWaveShaper(); + this._curve = null; + if (Array.isArray(mapping)) { + this.curve = mapping; + } else if (isFinite(mapping) || this.isUndef(mapping)) { + this._curve = new Float32Array(this.defaultArg(mapping, 1024)); + } else if (this.isFunction(mapping)) { + this._curve = new Float32Array(this.defaultArg(bufferLen, 1024)); + this.setMap(mapping); + } + }; + Tone.extend(Tone.WaveShaper, Tone.SignalBase); + Tone.WaveShaper.prototype.setMap = function (mapping) { + for (var i = 0, len = this._curve.length; i < len; i++) { + var normalized = i / (len - 1) * 2 - 1; + this._curve[i] = mapping(normalized, i); + } + this._shaper.curve = this._curve; + return this; + }; + Object.defineProperty(Tone.WaveShaper.prototype, 'curve', { + get: function () { + return this._shaper.curve; + }, + set: function (mapping) { + this._curve = new Float32Array(mapping); + this._shaper.curve = this._curve; + } + }); + Object.defineProperty(Tone.WaveShaper.prototype, 'oversample', { + get: function () { + return this._shaper.oversample; + }, + set: function (oversampling) { + if ([ + 'none', + '2x', + '4x' + ].indexOf(oversampling) !== -1) { + this._shaper.oversample = oversampling; + } else { + throw new RangeError('Tone.WaveShaper: oversampling must be either \'none\', \'2x\', or \'4x\''); + } + } + }); + Tone.WaveShaper.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._shaper.disconnect(); + this._shaper = null; + this._curve = null; + return this; + }; + return Tone.WaveShaper; +}(Tone_core_Tone); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_type_TimeBase; +Tone_type_TimeBase = function (Tone) { + Tone.TimeBase = function (val, units) { + if (this instanceof Tone.TimeBase) { + this._expr = this._noOp; + if (val instanceof Tone.TimeBase) { + this.copy(val); + } else if (!this.isUndef(units) || this.isNumber(val)) { + units = this.defaultArg(units, this._defaultUnits); + var method = this._primaryExpressions[units].method; + this._expr = method.bind(this, val); + } else if (this.isString(val)) { + this.set(val); + } else if (this.isUndef(val)) { + this._expr = this._defaultExpr(); + } + } else { + return new Tone.TimeBase(val, units); + } + }; + Tone.extend(Tone.TimeBase); + Tone.TimeBase.prototype.set = function (exprString) { + this._expr = this._parseExprString(exprString); + return this; + }; + Tone.TimeBase.prototype.clone = function () { + var instance = new this.constructor(); + instance.copy(this); + return instance; + }; + Tone.TimeBase.prototype.copy = function (time) { + var val = time._expr(); + return this.set(val); + }; + Tone.TimeBase.prototype._primaryExpressions = { + 'n': { + regexp: /^(\d+)n/i, + method: function (value) { + value = parseInt(value); + if (value === 1) { + return this._beatsToUnits(this._timeSignature()); + } else { + return this._beatsToUnits(4 / value); + } + } + }, + 't': { + regexp: /^(\d+)t/i, + method: function (value) { + value = parseInt(value); + return this._beatsToUnits(8 / (parseInt(value) * 3)); + } + }, + 'm': { + regexp: /^(\d+)m/i, + method: function (value) { + return this._beatsToUnits(parseInt(value) * this._timeSignature()); + } + }, + 'i': { + regexp: /^(\d+)i/i, + method: function (value) { + return this._ticksToUnits(parseInt(value)); + } + }, + 'hz': { + regexp: /^(\d+(?:\.\d+)?)hz/i, + method: function (value) { + return this._frequencyToUnits(parseFloat(value)); + } + }, + 'tr': { + regexp: /^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/, + method: function (m, q, s) { + var total = 0; + if (m && m !== '0') { + total += this._beatsToUnits(this._timeSignature() * parseFloat(m)); + } + if (q && q !== '0') { + total += this._beatsToUnits(parseFloat(q)); + } + if (s && s !== '0') { + total += this._beatsToUnits(parseFloat(s) / 4); + } + return total; + } + }, + 's': { + regexp: /^(\d+(?:\.\d+)?s)/, + method: function (value) { + return this._secondsToUnits(parseFloat(value)); + } + }, + 'samples': { + regexp: /^(\d+)samples/, + method: function (value) { + return parseInt(value) / this.context.sampleRate; + } + }, + 'default': { + regexp: /^(\d+(?:\.\d+)?)/, + method: function (value) { + return this._primaryExpressions[this._defaultUnits].method.call(this, value); + } + } + }; + Tone.TimeBase.prototype._binaryExpressions = { + '+': { + regexp: /^\+/, + precedence: 2, + method: function (lh, rh) { + return lh() + rh(); + } + }, + '-': { + regexp: /^\-/, + precedence: 2, + method: function (lh, rh) { + return lh() - rh(); + } + }, + '*': { + regexp: /^\*/, + precedence: 1, + method: function (lh, rh) { + return lh() * rh(); + } + }, + '/': { + regexp: /^\//, + precedence: 1, + method: function (lh, rh) { + return lh() / rh(); + } + } + }; + Tone.TimeBase.prototype._unaryExpressions = { + 'neg': { + regexp: /^\-/, + method: function (lh) { + return -lh(); + } + } + }; + Tone.TimeBase.prototype._syntaxGlue = { + '(': { regexp: /^\(/ }, + ')': { regexp: /^\)/ } + }; + Tone.TimeBase.prototype._tokenize = function (expr) { + var position = -1; + var tokens = []; + while (expr.length > 0) { + expr = expr.trim(); + var token = getNextToken(expr, this); + tokens.push(token); + expr = expr.substr(token.value.length); + } + function getNextToken(expr, context) { + var expressions = [ + '_binaryExpressions', + '_unaryExpressions', + '_primaryExpressions', + '_syntaxGlue' + ]; + for (var i = 0; i < expressions.length; i++) { + var group = context[expressions[i]]; + for (var opName in group) { + var op = group[opName]; + var reg = op.regexp; + var match = expr.match(reg); + if (match !== null) { + return { + method: op.method, + precedence: op.precedence, + regexp: op.regexp, + value: match[0] + }; + } + } + } + throw new SyntaxError('Tone.TimeBase: Unexpected token ' + expr); + } + return { + next: function () { + return tokens[++position]; + }, + peek: function () { + return tokens[position + 1]; + } + }; + }; + Tone.TimeBase.prototype._matchGroup = function (token, group, prec) { + var ret = false; + if (!this.isUndef(token)) { + for (var opName in group) { + var op = group[opName]; + if (op.regexp.test(token.value)) { + if (!this.isUndef(prec)) { + if (op.precedence === prec) { + return op; + } + } else { + return op; + } + } + } + } + return ret; + }; + Tone.TimeBase.prototype._parseBinary = function (lexer, precedence) { + if (this.isUndef(precedence)) { + precedence = 2; + } + var expr; + if (precedence < 0) { + expr = this._parseUnary(lexer); + } else { + expr = this._parseBinary(lexer, precedence - 1); + } + var token = lexer.peek(); + while (token && this._matchGroup(token, this._binaryExpressions, precedence)) { + token = lexer.next(); + expr = token.method.bind(this, expr, this._parseBinary(lexer, precedence - 1)); + token = lexer.peek(); + } + return expr; + }; + Tone.TimeBase.prototype._parseUnary = function (lexer) { + var token, expr; + token = lexer.peek(); + var op = this._matchGroup(token, this._unaryExpressions); + if (op) { + token = lexer.next(); + expr = this._parseUnary(lexer); + return op.method.bind(this, expr); + } + return this._parsePrimary(lexer); + }; + Tone.TimeBase.prototype._parsePrimary = function (lexer) { + var token, expr; + token = lexer.peek(); + if (this.isUndef(token)) { + throw new SyntaxError('Tone.TimeBase: Unexpected end of expression'); + } + if (this._matchGroup(token, this._primaryExpressions)) { + token = lexer.next(); + var matching = token.value.match(token.regexp); + return token.method.bind(this, matching[1], matching[2], matching[3]); + } + if (token && token.value === '(') { + lexer.next(); + expr = this._parseBinary(lexer); + token = lexer.next(); + if (!(token && token.value === ')')) { + throw new SyntaxError('Expected )'); + } + return expr; + } + throw new SyntaxError('Tone.TimeBase: Cannot process token ' + token.value); + }; + Tone.TimeBase.prototype._parseExprString = function (exprString) { + if (!this.isString(exprString)) { + exprString = exprString.toString(); + } + var lexer = this._tokenize(exprString); + var tree = this._parseBinary(lexer); + return tree; + }; + Tone.TimeBase.prototype._noOp = function () { + return 0; + }; + Tone.TimeBase.prototype._defaultExpr = function () { + return this._noOp; + }; + Tone.TimeBase.prototype._defaultUnits = 's'; + Tone.TimeBase.prototype._frequencyToUnits = function (freq) { + return 1 / freq; + }; + Tone.TimeBase.prototype._beatsToUnits = function (beats) { + return 60 / Tone.Transport.bpm.value * beats; + }; + Tone.TimeBase.prototype._secondsToUnits = function (seconds) { + return seconds; + }; + Tone.TimeBase.prototype._ticksToUnits = function (ticks) { + return ticks * (this._beatsToUnits(1) / Tone.Transport.PPQ); + }; + Tone.TimeBase.prototype._timeSignature = function () { + return Tone.Transport.timeSignature; + }; + Tone.TimeBase.prototype._pushExpr = function (val, name, units) { + if (!(val instanceof Tone.TimeBase)) { + val = new this.constructor(val, units); + } + this._expr = this._binaryExpressions[name].method.bind(this, this._expr, val._expr); + return this; + }; + Tone.TimeBase.prototype.add = function (val, units) { + return this._pushExpr(val, '+', units); + }; + Tone.TimeBase.prototype.sub = function (val, units) { + return this._pushExpr(val, '-', units); + }; + Tone.TimeBase.prototype.mult = function (val, units) { + return this._pushExpr(val, '*', units); + }; + Tone.TimeBase.prototype.div = function (val, units) { + return this._pushExpr(val, '/', units); + }; + Tone.TimeBase.prototype.valueOf = function () { + return this._expr(); + }; + Tone.TimeBase.prototype.dispose = function () { + this._expr = null; + }; + return Tone.TimeBase; +}(Tone_core_Tone); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_type_Time; +Tone_type_Time = function (Tone) { + Tone.Time = function (val, units) { + if (this instanceof Tone.Time) { + this._plusNow = false; + Tone.TimeBase.call(this, val, units); + } else { + return new Tone.Time(val, units); + } + }; + Tone.extend(Tone.Time, Tone.TimeBase); + Tone.Time.prototype._unaryExpressions = Object.create(Tone.TimeBase.prototype._unaryExpressions); + Tone.Time.prototype._unaryExpressions.quantize = { + regexp: /^@/, + method: function (rh) { + return Tone.Transport.nextSubdivision(rh()); + } + }; + Tone.Time.prototype._unaryExpressions.now = { + regexp: /^\+/, + method: function (lh) { + this._plusNow = true; + return lh(); + } + }; + Tone.Time.prototype.quantize = function (subdiv, percent) { + percent = this.defaultArg(percent, 1); + this._expr = function (expr, subdivision, percent) { + expr = expr(); + subdivision = subdivision.toSeconds(); + var multiple = Math.round(expr / subdivision); + var ideal = multiple * subdivision; + var diff = ideal - expr; + return expr + diff * percent; + }.bind(this, this._expr, new this.constructor(subdiv), percent); + return this; + }; + Tone.Time.prototype.addNow = function () { + this._plusNow = true; + return this; + }; + Tone.Time.prototype._defaultExpr = function () { + this._plusNow = true; + return this._noOp; + }; + Tone.Time.prototype.copy = function (time) { + Tone.TimeBase.prototype.copy.call(this, time); + this._plusNow = time._plusNow; + return this; + }; + Tone.Time.prototype.toNotation = function () { + var time = this.toSeconds(); + var testNotations = [ + '1m', + '2n', + '4n', + '8n', + '16n', + '32n', + '64n', + '128n' + ]; + var retNotation = this._toNotationHelper(time, testNotations); + var testTripletNotations = [ + '1m', + '2n', + '2t', + '4n', + '4t', + '8n', + '8t', + '16n', + '16t', + '32n', + '32t', + '64n', + '64t', + '128n' + ]; + var retTripletNotation = this._toNotationHelper(time, testTripletNotations); + if (retTripletNotation.split('+').length < retNotation.split('+').length) { + return retTripletNotation; + } else { + return retNotation; + } + }; + Tone.Time.prototype._toNotationHelper = function (units, testNotations) { + var threshold = this._notationToUnits(testNotations[testNotations.length - 1]); + var retNotation = ''; + for (var i = 0; i < testNotations.length; i++) { + var notationTime = this._notationToUnits(testNotations[i]); + var multiple = units / notationTime; + var floatingPointError = 0.000001; + if (1 - multiple % 1 < floatingPointError) { + multiple += floatingPointError; + } + multiple = Math.floor(multiple); + if (multiple > 0) { + if (multiple === 1) { + retNotation += testNotations[i]; + } else { + retNotation += multiple.toString() + '*' + testNotations[i]; + } + units -= multiple * notationTime; + if (units < threshold) { + break; + } else { + retNotation += ' + '; + } + } + } + if (retNotation === '') { + retNotation = '0'; + } + return retNotation; + }; + Tone.Time.prototype._notationToUnits = function (notation) { + var primaryExprs = this._primaryExpressions; + var notationExprs = [ + primaryExprs.n, + primaryExprs.t, + primaryExprs.m + ]; + for (var i = 0; i < notationExprs.length; i++) { + var expr = notationExprs[i]; + var match = notation.match(expr.regexp); + if (match) { + return expr.method.call(this, match[1]); + } + } + }; + Tone.Time.prototype.toBarsBeatsSixteenths = function () { + var quarterTime = this._beatsToUnits(1); + var quarters = this.toSeconds() / quarterTime; + var measures = Math.floor(quarters / this._timeSignature()); + var sixteenths = quarters % 1 * 4; + quarters = Math.floor(quarters) % this._timeSignature(); + sixteenths = sixteenths.toString(); + if (sixteenths.length > 3) { + sixteenths = parseFloat(sixteenths).toFixed(3); + } + var progress = [ + measures, + quarters, + sixteenths + ]; + return progress.join(':'); + }; + Tone.Time.prototype.toTicks = function () { + var quarterTime = this._beatsToUnits(1); + var quarters = this.valueOf() / quarterTime; + return Math.floor(quarters * Tone.Transport.PPQ); + }; + Tone.Time.prototype.toSamples = function () { + return this.toSeconds() * this.context.sampleRate; + }; + Tone.Time.prototype.toFrequency = function () { + return 1 / this.toSeconds(); + }; + Tone.Time.prototype.toSeconds = function () { + return this.valueOf(); + }; + Tone.Time.prototype.toMilliseconds = function () { + return this.toSeconds() * 1000; + }; + Tone.Time.prototype.valueOf = function () { + var val = this._expr(); + return val + (this._plusNow ? this.now() : 0); + }; + return Tone.Time; +}(Tone_core_Tone); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_type_Frequency; +Tone_type_Frequency = function (Tone) { + Tone.Frequency = function (val, units) { + if (this instanceof Tone.Frequency) { + Tone.TimeBase.call(this, val, units); + } else { + return new Tone.Frequency(val, units); + } + }; + Tone.extend(Tone.Frequency, Tone.TimeBase); + Tone.Frequency.prototype._primaryExpressions = Object.create(Tone.TimeBase.prototype._primaryExpressions); + Tone.Frequency.prototype._primaryExpressions.midi = { + regexp: /^(\d+(?:\.\d+)?midi)/, + method: function (value) { + return this.midiToFrequency(value); + } + }; + Tone.Frequency.prototype._primaryExpressions.note = { + regexp: /^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i, + method: function (pitch, octave) { + var index = noteToScaleIndex[pitch.toLowerCase()]; + var noteNumber = index + (parseInt(octave) + 1) * 12; + return this.midiToFrequency(noteNumber); + } + }; + Tone.Frequency.prototype._primaryExpressions.tr = { + regexp: /^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/, + method: function (m, q, s) { + var total = 1; + if (m && m !== '0') { + total *= this._beatsToUnits(this._timeSignature() * parseFloat(m)); + } + if (q && q !== '0') { + total *= this._beatsToUnits(parseFloat(q)); + } + if (s && s !== '0') { + total *= this._beatsToUnits(parseFloat(s) / 4); + } + return total; + } + }; + Tone.Frequency.prototype.transpose = function (interval) { + this._expr = function (expr, interval) { + var val = expr(); + return val * this.intervalToFrequencyRatio(interval); + }.bind(this, this._expr, interval); + return this; + }; + Tone.Frequency.prototype.harmonize = function (intervals) { + this._expr = function (expr, intervals) { + var val = expr(); + var ret = []; + for (var i = 0; i < intervals.length; i++) { + ret[i] = val * this.intervalToFrequencyRatio(intervals[i]); + } + return ret; + }.bind(this, this._expr, intervals); + return this; + }; + Tone.Frequency.prototype.toMidi = function () { + return this.frequencyToMidi(this.valueOf()); + }; + Tone.Frequency.prototype.toNote = function () { + var freq = this.valueOf(); + var log = Math.log(freq / Tone.Frequency.A4) / Math.LN2; + var noteNumber = Math.round(12 * log) + 57; + var octave = Math.floor(noteNumber / 12); + if (octave < 0) { + noteNumber += -12 * octave; + } + var noteName = scaleIndexToNote[noteNumber % 12]; + return noteName + octave.toString(); + }; + Tone.Frequency.prototype.toSeconds = function () { + return 1 / this.valueOf(); + }; + Tone.Frequency.prototype.toFrequency = function () { + return this.valueOf(); + }; + Tone.Frequency.prototype.toTicks = function () { + var quarterTime = this._beatsToUnits(1); + var quarters = this.valueOf() / quarterTime; + return Math.floor(quarters * Tone.Transport.PPQ); + }; + Tone.Frequency.prototype._frequencyToUnits = function (freq) { + return freq; + }; + Tone.Frequency.prototype._ticksToUnits = function (ticks) { + return 1 / (ticks * 60 / (Tone.Transport.bpm.value * Tone.Transport.PPQ)); + }; + Tone.Frequency.prototype._beatsToUnits = function (beats) { + return 1 / Tone.TimeBase.prototype._beatsToUnits.call(this, beats); + }; + Tone.Frequency.prototype._secondsToUnits = function (seconds) { + return 1 / seconds; + }; + Tone.Frequency.prototype._defaultUnits = 'hz'; + var noteToScaleIndex = { + 'cbb': -2, + 'cb': -1, + 'c': 0, + 'c#': 1, + 'cx': 2, + 'dbb': 0, + 'db': 1, + 'd': 2, + 'd#': 3, + 'dx': 4, + 'ebb': 2, + 'eb': 3, + 'e': 4, + 'e#': 5, + 'ex': 6, + 'fbb': 3, + 'fb': 4, + 'f': 5, + 'f#': 6, + 'fx': 7, + 'gbb': 5, + 'gb': 6, + 'g': 7, + 'g#': 8, + 'gx': 9, + 'abb': 7, + 'ab': 8, + 'a': 9, + 'a#': 10, + 'ax': 11, + 'bbb': 9, + 'bb': 10, + 'b': 11, + 'b#': 12, + 'bx': 13 + }; + var scaleIndexToNote = [ + 'C', + 'C#', + 'D', + 'D#', + 'E', + 'F', + 'F#', + 'G', + 'G#', + 'A', + 'A#', + 'B' + ]; + Tone.Frequency.A4 = 440; + Tone.Frequency.prototype.midiToFrequency = function (midi) { + return Tone.Frequency.A4 * Math.pow(2, (midi - 69) / 12); + }; + Tone.Frequency.prototype.frequencyToMidi = function (frequency) { + return 69 + 12 * Math.log(frequency / Tone.Frequency.A4) / Math.LN2; + }; + return Tone.Frequency; +}(Tone_core_Tone); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_type_TransportTime; +Tone_type_TransportTime = function (Tone) { + Tone.TransportTime = function (val, units) { + if (this instanceof Tone.TransportTime) { + Tone.Time.call(this, val, units); + } else { + return new Tone.TransportTime(val, units); + } + }; + Tone.extend(Tone.TransportTime, Tone.Time); + Tone.TransportTime.prototype._unaryExpressions = Object.create(Tone.Time.prototype._unaryExpressions); + Tone.TransportTime.prototype._unaryExpressions.quantize = { + regexp: /^@/, + method: function (rh) { + var subdivision = this._secondsToTicks(rh()); + var multiple = Math.ceil(Tone.Transport.ticks / subdivision); + return this._ticksToUnits(multiple * subdivision); + } + }; + Tone.TransportTime.prototype._secondsToTicks = function (seconds) { + var quarterTime = this._beatsToUnits(1); + var quarters = seconds / quarterTime; + return Math.round(quarters * Tone.Transport.PPQ); + }; + Tone.TransportTime.prototype.valueOf = function () { + var val = this._secondsToTicks(this._expr()); + return val + (this._plusNow ? Tone.Transport.ticks : 0); + }; + Tone.TransportTime.prototype.toTicks = function () { + return this.valueOf(); + }; + Tone.TransportTime.prototype.toSeconds = function () { + var val = this._expr(); + return val + (this._plusNow ? Tone.Transport.seconds : 0); + }; + Tone.TransportTime.prototype.toFrequency = function () { + return 1 / this.toSeconds(); + }; + return Tone.TransportTime; +}(Tone_core_Tone); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_type_Type; +Tone_type_Type = function (Tone) { + Tone.Type = { + Default: 'number', + Time: 'time', + Frequency: 'frequency', + TransportTime: 'transportTime', + Ticks: 'ticks', + NormalRange: 'normalRange', + AudioRange: 'audioRange', + Decibels: 'db', + Interval: 'interval', + BPM: 'bpm', + Positive: 'positive', + Cents: 'cents', + Degrees: 'degrees', + MIDI: 'midi', + BarsBeatsSixteenths: 'barsBeatsSixteenths', + Samples: 'samples', + Hertz: 'hertz', + Note: 'note', + Milliseconds: 'milliseconds', + Seconds: 'seconds', + Notation: 'notation' + }; + Tone.prototype.toSeconds = function (time) { + if (this.isNumber(time)) { + return time; + } else if (this.isUndef(time)) { + return this.now(); + } else if (this.isString(time)) { + return new Tone.Time(time).toSeconds(); + } else if (time instanceof Tone.TimeBase) { + return time.toSeconds(); + } + }; + Tone.prototype.toFrequency = function (freq) { + if (this.isNumber(freq)) { + return freq; + } else if (this.isString(freq) || this.isUndef(freq)) { + return new Tone.Frequency(freq).valueOf(); + } else if (freq instanceof Tone.TimeBase) { + return freq.toFrequency(); + } + }; + Tone.prototype.toTicks = function (time) { + if (this.isNumber(time) || this.isString(time)) { + return new Tone.TransportTime(time).toTicks(); + } else if (this.isUndef(time)) { + return Tone.Transport.ticks; + } else if (time instanceof Tone.TimeBase) { + return time.toTicks(); + } + }; + return Tone; +}(Tone_core_Tone, Tone_type_Time, Tone_type_Frequency, Tone_type_TransportTime); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_core_Param; +Tone_core_Param = function (Tone) { + 'use strict'; + Tone.Param = function () { + var options = this.optionsObject(arguments, [ + 'param', + 'units', + 'convert' + ], Tone.Param.defaults); + this._param = this.input = options.param; + this.units = options.units; + this.convert = options.convert; + this.overridden = false; + this._lfo = null; + if (this.isObject(options.lfo)) { + this.value = options.lfo; + } else if (!this.isUndef(options.value)) { + this.value = options.value; + } + }; + Tone.extend(Tone.Param); + Tone.Param.defaults = { + 'units': Tone.Type.Default, + 'convert': true, + 'param': undefined + }; + Object.defineProperty(Tone.Param.prototype, 'value', { + get: function () { + return this._toUnits(this._param.value); + }, + set: function (value) { + if (this.isObject(value)) { + if (this.isUndef(Tone.LFO)) { + throw new Error('Include \'Tone.LFO\' to use an LFO as a Param value.'); + } + if (this._lfo) { + this._lfo.dispose(); + } + this._lfo = new Tone.LFO(value).start(); + this._lfo.connect(this.input); + } else { + var convertedVal = this._fromUnits(value); + this._param.cancelScheduledValues(0); + this._param.value = convertedVal; + } + } + }); + Tone.Param.prototype._fromUnits = function (val) { + if (this.convert || this.isUndef(this.convert)) { + switch (this.units) { + case Tone.Type.Time: + return this.toSeconds(val); + case Tone.Type.Frequency: + return this.toFrequency(val); + case Tone.Type.Decibels: + return this.dbToGain(val); + case Tone.Type.NormalRange: + return Math.min(Math.max(val, 0), 1); + case Tone.Type.AudioRange: + return Math.min(Math.max(val, -1), 1); + case Tone.Type.Positive: + return Math.max(val, 0); + default: + return val; + } + } else { + return val; + } + }; + Tone.Param.prototype._toUnits = function (val) { + if (this.convert || this.isUndef(this.convert)) { + switch (this.units) { + case Tone.Type.Decibels: + return this.gainToDb(val); + default: + return val; + } + } else { + return val; + } + }; + Tone.Param.prototype._minOutput = 0.00001; + Tone.Param.prototype.setValueAtTime = function (value, time) { + value = this._fromUnits(value); + time = this.toSeconds(time); + if (time <= this.now() + this.blockTime) { + this._param.value = value; + } else { + this._param.setValueAtTime(value, time); + } + return this; + }; + Tone.Param.prototype.setRampPoint = function (now) { + now = this.defaultArg(now, this.now()); + var currentVal = this._param.value; + if (currentVal === 0) { + currentVal = this._minOutput; + } + this._param.setValueAtTime(currentVal, now); + return this; + }; + Tone.Param.prototype.linearRampToValueAtTime = function (value, endTime) { + value = this._fromUnits(value); + this._param.linearRampToValueAtTime(value, this.toSeconds(endTime)); + return this; + }; + Tone.Param.prototype.exponentialRampToValueAtTime = function (value, endTime) { + value = this._fromUnits(value); + value = Math.max(this._minOutput, value); + this._param.exponentialRampToValueAtTime(value, this.toSeconds(endTime)); + return this; + }; + Tone.Param.prototype.exponentialRampToValue = function (value, rampTime, startTime) { + startTime = this.toSeconds(startTime); + this.setRampPoint(startTime); + this.exponentialRampToValueAtTime(value, startTime + this.toSeconds(rampTime)); + return this; + }; + Tone.Param.prototype.linearRampToValue = function (value, rampTime, startTime) { + startTime = this.toSeconds(startTime); + this.setRampPoint(startTime); + this.linearRampToValueAtTime(value, startTime + this.toSeconds(rampTime)); + return this; + }; + Tone.Param.prototype.setTargetAtTime = function (value, startTime, timeConstant) { + value = this._fromUnits(value); + value = Math.max(this._minOutput, value); + timeConstant = Math.max(this._minOutput, timeConstant); + this._param.setTargetAtTime(value, this.toSeconds(startTime), timeConstant); + return this; + }; + Tone.Param.prototype.setValueCurveAtTime = function (values, startTime, duration) { + for (var i = 0; i < values.length; i++) { + values[i] = this._fromUnits(values[i]); + } + this._param.setValueCurveAtTime(values, this.toSeconds(startTime), this.toSeconds(duration)); + return this; + }; + Tone.Param.prototype.cancelScheduledValues = function (startTime) { + this._param.cancelScheduledValues(this.toSeconds(startTime)); + return this; + }; + Tone.Param.prototype.rampTo = function (value, rampTime, startTime) { + rampTime = this.defaultArg(rampTime, 0); + if (this.units === Tone.Type.Frequency || this.units === Tone.Type.BPM || this.units === Tone.Type.Decibels) { + this.exponentialRampToValue(value, rampTime, startTime); + } else { + this.linearRampToValue(value, rampTime, startTime); + } + return this; + }; + Object.defineProperty(Tone.Param.prototype, 'lfo', { + get: function () { + return this._lfo; + } + }); + Tone.Param.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._param = null; + if (this._lfo) { + this._lfo.dispose(); + this._lfo = null; + } + return this; + }; + return Tone.Param; +}(Tone_core_Tone); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_core_Gain; +Tone_core_Gain = function (Tone) { + 'use strict'; + if (window.GainNode && !AudioContext.prototype.createGain) { + AudioContext.prototype.createGain = AudioContext.prototype.createGainNode; + } + Tone.Gain = function () { + var options = this.optionsObject(arguments, [ + 'gain', + 'units' + ], Tone.Gain.defaults); + this.input = this.output = this._gainNode = this.context.createGain(); + this.gain = new Tone.Param({ + 'param': this._gainNode.gain, + 'units': options.units, + 'value': options.gain, + 'convert': options.convert + }); + this._readOnly('gain'); + }; + Tone.extend(Tone.Gain); + Tone.Gain.defaults = { + 'gain': 1, + 'convert': true + }; + Tone.Gain.prototype.dispose = function () { + Tone.Param.prototype.dispose.call(this); + this._gainNode.disconnect(); + this._gainNode = null; + this._writable('gain'); + this.gain.dispose(); + this.gain = null; + }; + Tone.prototype.createInsOuts = function (inputs, outputs) { + if (inputs === 1) { + this.input = new Tone.Gain(); + } else if (inputs > 1) { + this.input = new Array(inputs); + } + if (outputs === 1) { + this.output = new Tone.Gain(); + } else if (outputs > 1) { + this.output = new Array(inputs); + } + }; + return Tone.Gain; +}(Tone_core_Tone, Tone_core_Param); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_signal_Signal; +Tone_signal_Signal = function (Tone) { + 'use strict'; + Tone.Signal = function () { + var options = this.optionsObject(arguments, [ + 'value', + 'units' + ], Tone.Signal.defaults); + this.output = this._gain = this.context.createGain(); + options.param = this._gain.gain; + Tone.Param.call(this, options); + this.input = this._param = this._gain.gain; + this.context.getConstant(1).chain(this._gain); + }; + Tone.extend(Tone.Signal, Tone.Param); + Tone.Signal.defaults = { + 'value': 0, + 'units': Tone.Type.Default, + 'convert': true + }; + Tone.Signal.prototype.connect = Tone.SignalBase.prototype.connect; + Tone.Signal.prototype.dispose = function () { + Tone.Param.prototype.dispose.call(this); + this._param = null; + this._gain.disconnect(); + this._gain = null; + return this; + }; + return Tone.Signal; +}(Tone_core_Tone, Tone_signal_WaveShaper, Tone_type_Type, Tone_core_Param); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_signal_Add; +Tone_signal_Add = function (Tone) { + 'use strict'; + Tone.Add = function (value) { + this.createInsOuts(2, 0); + this._sum = this.input[0] = this.input[1] = this.output = new Tone.Gain(); + this._param = this.input[1] = new Tone.Signal(value); + this._param.connect(this._sum); + }; + Tone.extend(Tone.Add, Tone.Signal); + Tone.Add.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._sum.dispose(); + this._sum = null; + this._param.dispose(); + this._param = null; + return this; + }; + return Tone.Add; +}(Tone_core_Tone, Tone_signal_Signal); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_signal_Multiply; +Tone_signal_Multiply = function (Tone) { + 'use strict'; + Tone.Multiply = function (value) { + this.createInsOuts(2, 0); + this._mult = this.input[0] = this.output = new Tone.Gain(); + this._param = this.input[1] = this.output.gain; + this._param.value = this.defaultArg(value, 0); + }; + Tone.extend(Tone.Multiply, Tone.Signal); + Tone.Multiply.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._mult.dispose(); + this._mult = null; + this._param = null; + return this; + }; + return Tone.Multiply; +}(Tone_core_Tone, Tone_signal_Signal); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_signal_Scale; +Tone_signal_Scale = function (Tone) { + 'use strict'; + Tone.Scale = function (outputMin, outputMax) { + this._outputMin = this.defaultArg(outputMin, 0); + this._outputMax = this.defaultArg(outputMax, 1); + this._scale = this.input = new Tone.Multiply(1); + this._add = this.output = new Tone.Add(0); + this._scale.connect(this._add); + this._setRange(); + }; + Tone.extend(Tone.Scale, Tone.SignalBase); + Object.defineProperty(Tone.Scale.prototype, 'min', { + get: function () { + return this._outputMin; + }, + set: function (min) { + this._outputMin = min; + this._setRange(); + } + }); + Object.defineProperty(Tone.Scale.prototype, 'max', { + get: function () { + return this._outputMax; + }, + set: function (max) { + this._outputMax = max; + this._setRange(); + } + }); + Tone.Scale.prototype._setRange = function () { + this._add.value = this._outputMin; + this._scale.value = this._outputMax - this._outputMin; + }; + Tone.Scale.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._add.dispose(); + this._add = null; + this._scale.dispose(); + this._scale = null; + return this; + }; + return Tone.Scale; +}(Tone_core_Tone, Tone_signal_Add, Tone_signal_Multiply); +var signal; +'use strict'; +signal = function () { + // Signal is built with the Tone.js signal by Yotam Mann + // https://github.com/TONEnoTONE/Tone.js/ + var Signal = Tone_signal_Signal; + var Add = Tone_signal_Add; + var Mult = Tone_signal_Multiply; + var Scale = Tone_signal_Scale; + /** + *

p5.Signal is a constant audio-rate signal used by p5.Oscillator + * and p5.Envelope for modulation math.

+ * + *

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

+ * + * @class p5.Signal + * @constructor + * @return {Tone.Signal} A Signal object from the Tone.js library + * @example + *
+ * function setup() { + * carrier = new p5.Oscillator('sine'); + * carrier.amp(1); // set amplitude + * carrier.freq(220); // set frequency + * carrier.start(); // start oscillating + * + * modulator = new p5.Oscillator('sawtooth'); + * modulator.disconnect(); + * modulator.amp(1); + * modulator.freq(4); + * modulator.start(); + * + * // Modulator's default amplitude range is -1 to 1. + * // Multiply it by -200, so the range is -200 to 200 + * // then add 220 so the range is 20 to 420 + * carrier.freq( modulator.mult(-200).add(220) ); + * } + *
+ */ + p5.Signal = function (value) { + var s = new Signal(value); + // p5sound.soundArray.push(s); + return s; + }; + /** + * Fade to value, for smooth transitions + * + * @method fade + * @param {Number} value Value to set this signal + * @param {Number} [secondsFromNow] Length of fade, in seconds from now + */ + Signal.prototype.fade = Signal.prototype.linearRampToValueAtTime; + Mult.prototype.fade = Signal.prototype.fade; + Add.prototype.fade = Signal.prototype.fade; + Scale.prototype.fade = Signal.prototype.fade; + /** + * Connect a p5.sound object or Web Audio node to this + * p5.Signal so that its amplitude values can be scaled. + * + * @method setInput + * @param {Object} input + */ + Signal.prototype.setInput = function (_input) { + _input.connect(this); + }; + Mult.prototype.setInput = Signal.prototype.setInput; + Add.prototype.setInput = Signal.prototype.setInput; + Scale.prototype.setInput = Signal.prototype.setInput; + // signals can add / mult / scale themselves + /** + * Add a constant value to this audio signal, + * and return the resulting audio signal. Does + * not change the value of the original signal, + * instead it returns a new p5.SignalAdd. + * + * @method add + * @param {Number} number + * @return {p5.Signal} object + */ + Signal.prototype.add = function (num) { + var add = new Add(num); + // add.setInput(this); + this.connect(add); + return add; + }; + Mult.prototype.add = Signal.prototype.add; + Add.prototype.add = Signal.prototype.add; + Scale.prototype.add = Signal.prototype.add; + /** + * Multiply this signal by a constant value, + * and return the resulting audio signal. Does + * not change the value of the original signal, + * instead it returns a new p5.SignalMult. + * + * @method mult + * @param {Number} number to multiply + * @return {p5.Signal} object + */ + Signal.prototype.mult = function (num) { + var mult = new Mult(num); + // mult.setInput(this); + this.connect(mult); + return mult; + }; + Mult.prototype.mult = Signal.prototype.mult; + Add.prototype.mult = Signal.prototype.mult; + Scale.prototype.mult = Signal.prototype.mult; + /** + * Scale this signal value to a given range, + * and return the result as an audio signal. Does + * not change the value of the original signal, + * instead it returns a new p5.SignalScale. + * + * @method scale + * @param {Number} number to multiply + * @param {Number} inMin input range minumum + * @param {Number} inMax input range maximum + * @param {Number} outMin input range minumum + * @param {Number} outMax input range maximum + * @return {p5.Signal} object + */ + Signal.prototype.scale = function (inMin, inMax, outMin, outMax) { + var mapOutMin, mapOutMax; + if (arguments.length === 4) { + mapOutMin = p5.prototype.map(outMin, inMin, inMax, 0, 1) - 0.5; + mapOutMax = p5.prototype.map(outMax, inMin, inMax, 0, 1) - 0.5; + } else { + mapOutMin = arguments[0]; + mapOutMax = arguments[1]; + } + var scale = new Scale(mapOutMin, mapOutMax); + this.connect(scale); + return scale; + }; + Mult.prototype.scale = Signal.prototype.scale; + Add.prototype.scale = Signal.prototype.scale; + Scale.prototype.scale = Signal.prototype.scale; +}(Tone_signal_Signal, Tone_signal_Add, Tone_signal_Multiply, Tone_signal_Scale); +var oscillator; +'use strict'; +oscillator = function () { + var p5sound = master; + var Add = Tone_signal_Add; + var Mult = Tone_signal_Multiply; + var Scale = Tone_signal_Scale; + /** + *

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

+ * + *

Set the type of oscillation with setType(), or by instantiating a + * specific oscillator: p5.SinOsc, p5.TriOsc, p5.SqrOsc, or p5.SawOsc. + *

+ * + * @class p5.Oscillator + * @constructor + * @param {Number} [freq] frequency defaults to 440Hz + * @param {String} [type] type of oscillator. Options: + * 'sine' (default), 'triangle', + * 'sawtooth', 'square' + * @example + *
+ * var osc; + * var playing = false; + * + * function setup() { + * backgroundColor = color(255,0,255); + * textAlign(CENTER); + * + * osc = new p5.Oscillator(); + * osc.setType('sine'); + * osc.freq(240); + * osc.amp(0); + * osc.start(); + * } + * + * function draw() { + * background(backgroundColor) + * text('click to play', width/2, height/2); + * } + * + * function mouseClicked() { + * if (mouseX > 0 && mouseX < width && mouseY < height && mouseY > 0) { + * if (!playing) { + * // ramp amplitude to 0.5 over 0.05 seconds + * osc.amp(0.5, 0.05); + * playing = true; + * backgroundColor = color(0,255,255); + * } else { + * // ramp amplitude to 0 over 0.5 seconds + * osc.amp(0, 0.5); + * playing = false; + * backgroundColor = color(255,0,255); + * } + * } + * } + *
+ */ + p5.Oscillator = function (freq, type) { + if (typeof freq === 'string') { + var f = type; + type = freq; + freq = f; + } + if (typeof type === 'number') { + var f = type; + type = freq; + freq = f; + } + this.started = false; + // components + this.phaseAmount = undefined; + this.oscillator = p5sound.audiocontext.createOscillator(); + this.f = freq || 440; + // frequency + this.oscillator.type = type || 'sine'; + this.oscillator.frequency.setValueAtTime(this.f, p5sound.audiocontext.currentTime); + // connections + this.output = p5sound.audiocontext.createGain(); + this._freqMods = []; + // modulators connected to this oscillator's frequency + // set default output gain to 0.5 + this.output.gain.value = 0.5; + this.output.gain.setValueAtTime(0.5, p5sound.audiocontext.currentTime); + this.oscillator.connect(this.output); + // stereo panning + this.panPosition = 0; + this.connection = p5sound.input; + // connect to p5sound by default + this.panner = new p5.Panner(this.output, this.connection, 1); + //array of math operation signal chaining + this.mathOps = [this.output]; + // add to the soundArray so we can dispose of the osc later + p5sound.soundArray.push(this); + }; + /** + * Start an oscillator. Accepts an optional parameter to + * determine how long (in seconds from now) until the + * oscillator starts. + * + * @method start + * @param {Number} [time] startTime in seconds from now. + * @param {Number} [frequency] frequency in Hz. + */ + p5.Oscillator.prototype.start = function (time, f) { + if (this.started) { + var now = p5sound.audiocontext.currentTime; + this.stop(now); + } + if (!this.started) { + var freq = f || this.f; + var type = this.oscillator.type; + // set old osc free to be garbage collected (memory) + if (this.oscillator) { + this.oscillator.disconnect(); + delete this.oscillator; + } + // var detune = this.oscillator.frequency.value; + this.oscillator = p5sound.audiocontext.createOscillator(); + this.oscillator.frequency.value = Math.abs(freq); + this.oscillator.type = type; + // this.oscillator.detune.value = detune; + this.oscillator.connect(this.output); + time = time || 0; + this.oscillator.start(time + p5sound.audiocontext.currentTime); + this.freqNode = this.oscillator.frequency; + // if other oscillators are already connected to this osc's freq + for (var i in this._freqMods) { + if (typeof this._freqMods[i].connect !== 'undefined') { + this._freqMods[i].connect(this.oscillator.frequency); + } + } + this.started = true; + } + }; + /** + * Stop an oscillator. Accepts an optional parameter + * to determine how long (in seconds from now) until the + * oscillator stops. + * + * @method stop + * @param {Number} secondsFromNow Time, in seconds from now. + */ + p5.Oscillator.prototype.stop = function (time) { + if (this.started) { + var t = time || 0; + var now = p5sound.audiocontext.currentTime; + this.oscillator.stop(t + now); + this.started = false; + } + }; + /** + * Set the amplitude between 0 and 1.0. Or, pass in an object + * such as an oscillator to modulate amplitude with an audio signal. + * + * @method amp + * @param {Number|Object} vol between 0 and 1.0 + * or a modulating signal/oscillator + * @param {Number} [rampTime] create a fade that lasts rampTime + * @param {Number} [timeFromNow] schedule this event to happen + * seconds from now + * @return {AudioParam} gain If no value is provided, + * returns the Web Audio API + * AudioParam that controls + * this oscillator's + * gain/amplitude/volume) + */ + p5.Oscillator.prototype.amp = function (vol, rampTime, tFromNow) { + var self = this; + if (typeof vol === 'number') { + var rampTime = rampTime || 0; + var tFromNow = tFromNow || 0; + var now = p5sound.audiocontext.currentTime; + this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime); + } else if (vol) { + vol.connect(self.output.gain); + } else { + // return the Gain Node + return this.output.gain; + } + }; + // these are now the same thing + p5.Oscillator.prototype.fade = p5.Oscillator.prototype.amp; + p5.Oscillator.prototype.getAmp = function () { + return this.output.gain.value; + }; + /** + * Set frequency of an oscillator to a value. Or, pass in an object + * such as an oscillator to modulate the frequency with an audio signal. + * + * @method freq + * @param {Number|Object} Frequency Frequency in Hz + * or modulating signal/oscillator + * @param {Number} [rampTime] Ramp time (in seconds) + * @param {Number} [timeFromNow] Schedule this event to happen + * at x seconds from now + * @return {AudioParam} Frequency If no value is provided, + * returns the Web Audio API + * AudioParam that controls + * this oscillator's frequency + * @example + *
+ * var osc = new p5.Oscillator(300); + * osc.start(); + * osc.freq(40, 10); + *
+ */ + p5.Oscillator.prototype.freq = function (val, rampTime, tFromNow) { + if (typeof val === 'number' && !isNaN(val)) { + this.f = val; + var now = p5sound.audiocontext.currentTime; + var rampTime = rampTime || 0; + var tFromNow = tFromNow || 0; + var t = now + tFromNow + rampTime; + // var currentFreq = this.oscillator.frequency.value; + // this.oscillator.frequency.cancelScheduledValues(now); + if (rampTime === 0) { + this.oscillator.frequency.setValueAtTime(val, tFromNow + now); + } else { + if (val > 0) { + this.oscillator.frequency.exponentialRampToValueAtTime(val, tFromNow + rampTime + now); + } else { + this.oscillator.frequency.linearRampToValueAtTime(val, tFromNow + rampTime + now); + } + } + // reset phase if oscillator has a phase + if (this.phaseAmount) { + this.phase(this.phaseAmount); + } + } else if (val) { + if (val.output) { + val = val.output; + } + val.connect(this.oscillator.frequency); + // keep track of what is modulating this param + // so it can be re-connected if + this._freqMods.push(val); + } else { + // return the Frequency Node + return this.oscillator.frequency; + } + }; + p5.Oscillator.prototype.getFreq = function () { + return this.oscillator.frequency.value; + }; + /** + * Set type to 'sine', 'triangle', 'sawtooth' or 'square'. + * + * @method setType + * @param {String} type 'sine', 'triangle', 'sawtooth' or 'square'. + */ + p5.Oscillator.prototype.setType = function (type) { + this.oscillator.type = type; + }; + p5.Oscillator.prototype.getType = function () { + return this.oscillator.type; + }; + /** + * Connect to a p5.sound / Web Audio object. + * + * @method connect + * @param {Object} unit A p5.sound or Web Audio object + */ + p5.Oscillator.prototype.connect = function (unit) { + if (!unit) { + this.panner.connect(p5sound.input); + } else if (unit.hasOwnProperty('input')) { + this.panner.connect(unit.input); + this.connection = unit.input; + } else { + this.panner.connect(unit); + this.connection = unit; + } + }; + /** + * Disconnect all outputs + * + * @method disconnect + */ + p5.Oscillator.prototype.disconnect = function () { + if (this.output) { + this.output.disconnect(); + } + if (this.panner) { + this.panner.disconnect(); + if (this.output) { + this.output.connect(this.panner); + } + } + this.oscMods = []; + }; + /** + * Pan between Left (-1) and Right (1) + * + * @method pan + * @param {Number} panning Number between -1 and 1 + * @param {Number} timeFromNow schedule this event to happen + * seconds from now + */ + p5.Oscillator.prototype.pan = function (pval, tFromNow) { + this.panPosition = pval; + this.panner.pan(pval, tFromNow); + }; + p5.Oscillator.prototype.getPan = function () { + return this.panPosition; + }; + // get rid of the oscillator + p5.Oscillator.prototype.dispose = function () { + // remove reference from soundArray + var index = p5sound.soundArray.indexOf(this); + p5sound.soundArray.splice(index, 1); + if (this.oscillator) { + var now = p5sound.audiocontext.currentTime; + this.stop(now); + this.disconnect(); + this.panner = null; + this.oscillator = null; + } + // if it is a Pulse + if (this.osc2) { + this.osc2.dispose(); + } + }; + /** + * Set the phase of an oscillator between 0.0 and 1.0. + * In this implementation, phase is a delay time + * based on the oscillator's current frequency. + * + * @method phase + * @param {Number} phase float between 0.0 and 1.0 + */ + p5.Oscillator.prototype.phase = function (p) { + var delayAmt = p5.prototype.map(p, 0, 1, 0, 1 / this.f); + var now = p5sound.audiocontext.currentTime; + this.phaseAmount = p; + if (!this.dNode) { + // create a delay node + this.dNode = p5sound.audiocontext.createDelay(); + // put the delay node in between output and panner + this.oscillator.disconnect(); + this.oscillator.connect(this.dNode); + this.dNode.connect(this.output); + } + // set delay time to match phase: + this.dNode.delayTime.setValueAtTime(delayAmt, now); + }; + // ========================== // + // SIGNAL MATH FOR MODULATION // + // ========================== // + // return sigChain(this, scale, thisChain, nextChain, Scale); + var sigChain = function (o, mathObj, thisChain, nextChain, type) { + var chainSource = o.oscillator; + // if this type of math already exists in the chain, replace it + for (var i in o.mathOps) { + if (o.mathOps[i] instanceof type) { + chainSource.disconnect(); + o.mathOps[i].dispose(); + thisChain = i; + // assume nextChain is output gain node unless... + if (thisChain < o.mathOps.length - 2) { + nextChain = o.mathOps[i + 1]; + } + } + } + if (thisChain === o.mathOps.length - 1) { + o.mathOps.push(nextChain); + } + // assume source is the oscillator unless i > 0 + if (i > 0) { + chainSource = o.mathOps[i - 1]; + } + chainSource.disconnect(); + chainSource.connect(mathObj); + mathObj.connect(nextChain); + o.mathOps[thisChain] = mathObj; + return o; + }; + /** + * Add a value to the p5.Oscillator's output amplitude, + * and return the oscillator. Calling this method again + * will override the initial add() with a new value. + * + * @method add + * @param {Number} number Constant number to add + * @return {p5.Oscillator} Oscillator Returns this oscillator + * with scaled output + * + */ + p5.Oscillator.prototype.add = function (num) { + var add = new Add(num); + var thisChain = this.mathOps.length - 1; + var nextChain = this.output; + return sigChain(this, add, thisChain, nextChain, Add); + }; + /** + * Multiply the p5.Oscillator's output amplitude + * by a fixed value (i.e. turn it up!). Calling this method + * again will override the initial mult() with a new value. + * + * @method mult + * @param {Number} number Constant number to multiply + * @return {p5.Oscillator} Oscillator Returns this oscillator + * with multiplied output + */ + p5.Oscillator.prototype.mult = function (num) { + var mult = new Mult(num); + var thisChain = this.mathOps.length - 1; + var nextChain = this.output; + return sigChain(this, mult, thisChain, nextChain, Mult); + }; + /** + * Scale this oscillator's amplitude values to a given + * range, and return the oscillator. Calling this method + * again will override the initial scale() with new values. + * + * @method scale + * @param {Number} inMin input range minumum + * @param {Number} inMax input range maximum + * @param {Number} outMin input range minumum + * @param {Number} outMax input range maximum + * @return {p5.Oscillator} Oscillator Returns this oscillator + * with scaled output + */ + p5.Oscillator.prototype.scale = function (inMin, inMax, outMin, outMax) { + var mapOutMin, mapOutMax; + if (arguments.length === 4) { + mapOutMin = p5.prototype.map(outMin, inMin, inMax, 0, 1) - 0.5; + mapOutMax = p5.prototype.map(outMax, inMin, inMax, 0, 1) - 0.5; + } else { + mapOutMin = arguments[0]; + mapOutMax = arguments[1]; + } + var scale = new Scale(mapOutMin, mapOutMax); + var thisChain = this.mathOps.length - 1; + var nextChain = this.output; + return sigChain(this, scale, thisChain, nextChain, Scale); + }; + // ============================== // + // SinOsc, TriOsc, SqrOsc, SawOsc // + // ============================== // + /** + * Constructor: new p5.SinOsc(). + * This creates a Sine Wave Oscillator and is + * equivalent to new p5.Oscillator('sine') + * or creating a p5.Oscillator and then calling + * its method setType('sine'). + * See p5.Oscillator for methods. + * + * @class p5.SinOsc + * @constructor + * @extends p5.Oscillator + * @param {Number} [freq] Set the frequency + */ + p5.SinOsc = function (freq) { + p5.Oscillator.call(this, freq, 'sine'); + }; + p5.SinOsc.prototype = Object.create(p5.Oscillator.prototype); + /** + * Constructor: new p5.TriOsc(). + * This creates a Triangle Wave Oscillator and is + * equivalent to new p5.Oscillator('triangle') + * or creating a p5.Oscillator and then calling + * its method setType('triangle'). + * See p5.Oscillator for methods. + * + * @class p5.TriOsc + * @constructor + * @extends p5.Oscillator + * @param {Number} [freq] Set the frequency + */ + p5.TriOsc = function (freq) { + p5.Oscillator.call(this, freq, 'triangle'); + }; + p5.TriOsc.prototype = Object.create(p5.Oscillator.prototype); + /** + * Constructor: new p5.SawOsc(). + * This creates a SawTooth Wave Oscillator and is + * equivalent to new p5.Oscillator('sawtooth') + * or creating a p5.Oscillator and then calling + * its method setType('sawtooth'). + * See p5.Oscillator for methods. + * + * @class p5.SawOsc + * @constructor + * @extends p5.Oscillator + * @param {Number} [freq] Set the frequency + */ + p5.SawOsc = function (freq) { + p5.Oscillator.call(this, freq, 'sawtooth'); + }; + p5.SawOsc.prototype = Object.create(p5.Oscillator.prototype); + /** + * Constructor: new p5.SqrOsc(). + * This creates a Square Wave Oscillator and is + * equivalent to new p5.Oscillator('square') + * or creating a p5.Oscillator and then calling + * its method setType('square'). + * See p5.Oscillator for methods. + * + * @class p5.SqrOsc + * @constructor + * @extends p5.Oscillator + * @param {Number} [freq] Set the frequency + */ + p5.SqrOsc = function (freq) { + p5.Oscillator.call(this, freq, 'square'); + }; + p5.SqrOsc.prototype = Object.create(p5.Oscillator.prototype); +}(master, Tone_signal_Add, Tone_signal_Multiply, Tone_signal_Scale); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_core_Timeline; +Tone_core_Timeline = function (Tone) { + 'use strict'; + Tone.Timeline = function () { + var options = this.optionsObject(arguments, ['memory'], Tone.Timeline.defaults); + this._timeline = []; + this._toRemove = []; + this._iterating = false; + this.memory = options.memory; + }; + Tone.extend(Tone.Timeline); + Tone.Timeline.defaults = { 'memory': Infinity }; + Object.defineProperty(Tone.Timeline.prototype, 'length', { + get: function () { + return this._timeline.length; + } + }); + Tone.Timeline.prototype.add = function (event) { + if (this.isUndef(event.time)) { + throw new Error('Tone.Timeline: events must have a time attribute'); + } + if (this._timeline.length) { + var index = this._search(event.time); + this._timeline.splice(index + 1, 0, event); + } else { + this._timeline.push(event); + } + if (this.length > this.memory) { + var diff = this.length - this.memory; + this._timeline.splice(0, diff); + } + return this; + }; + Tone.Timeline.prototype.remove = function (event) { + if (this._iterating) { + this._toRemove.push(event); + } else { + var index = this._timeline.indexOf(event); + if (index !== -1) { + this._timeline.splice(index, 1); + } + } + return this; + }; + Tone.Timeline.prototype.get = function (time) { + var index = this._search(time); + if (index !== -1) { + return this._timeline[index]; + } else { + return null; + } + }; + Tone.Timeline.prototype.peek = function () { + return this._timeline[0]; + }; + Tone.Timeline.prototype.shift = function () { + return this._timeline.shift(); + }; + Tone.Timeline.prototype.getAfter = function (time) { + var index = this._search(time); + if (index + 1 < this._timeline.length) { + return this._timeline[index + 1]; + } else { + return null; + } + }; + Tone.Timeline.prototype.getBefore = function (time) { + var len = this._timeline.length; + if (len > 0 && this._timeline[len - 1].time < time) { + return this._timeline[len - 1]; + } + var index = this._search(time); + if (index - 1 >= 0) { + return this._timeline[index - 1]; + } else { + return null; + } + }; + Tone.Timeline.prototype.cancel = function (after) { + if (this._timeline.length > 1) { + var index = this._search(after); + if (index >= 0) { + if (this._timeline[index].time === after) { + for (var i = index; i >= 0; i--) { + if (this._timeline[i].time === after) { + index = i; + } else { + break; + } + } + this._timeline = this._timeline.slice(0, index); + } else { + this._timeline = this._timeline.slice(0, index + 1); + } + } else { + this._timeline = []; + } + } else if (this._timeline.length === 1) { + if (this._timeline[0].time >= after) { + this._timeline = []; + } + } + return this; + }; + Tone.Timeline.prototype.cancelBefore = function (time) { + if (this._timeline.length) { + var index = this._search(time); + if (index >= 0) { + this._timeline = this._timeline.slice(index + 1); + } + } + return this; + }; + Tone.Timeline.prototype._search = function (time) { + var beginning = 0; + var len = this._timeline.length; + var end = len; + if (len > 0 && this._timeline[len - 1].time <= time) { + return len - 1; + } + while (beginning < end) { + var midPoint = Math.floor(beginning + (end - beginning) / 2); + var event = this._timeline[midPoint]; + var nextEvent = this._timeline[midPoint + 1]; + if (event.time === time) { + for (var i = midPoint; i < this._timeline.length; i++) { + var testEvent = this._timeline[i]; + if (testEvent.time === time) { + midPoint = i; + } + } + return midPoint; + } else if (event.time < time && nextEvent.time > time) { + return midPoint; + } else if (event.time > time) { + end = midPoint; + } else if (event.time < time) { + beginning = midPoint + 1; + } + } + return -1; + }; + Tone.Timeline.prototype._iterate = function (callback, lowerBound, upperBound) { + this._iterating = true; + lowerBound = this.defaultArg(lowerBound, 0); + upperBound = this.defaultArg(upperBound, this._timeline.length - 1); + for (var i = lowerBound; i <= upperBound; i++) { + callback(this._timeline[i]); + } + this._iterating = false; + if (this._toRemove.length > 0) { + for (var j = 0; j < this._toRemove.length; j++) { + var index = this._timeline.indexOf(this._toRemove[j]); + if (index !== -1) { + this._timeline.splice(index, 1); + } + } + this._toRemove = []; + } + }; + Tone.Timeline.prototype.forEach = function (callback) { + this._iterate(callback); + return this; + }; + Tone.Timeline.prototype.forEachBefore = function (time, callback) { + var upperBound = this._search(time); + if (upperBound !== -1) { + this._iterate(callback, 0, upperBound); + } + return this; + }; + Tone.Timeline.prototype.forEachAfter = function (time, callback) { + var lowerBound = this._search(time); + this._iterate(callback, lowerBound + 1); + return this; + }; + Tone.Timeline.prototype.forEachFrom = function (time, callback) { + var lowerBound = this._search(time); + while (lowerBound >= 0 && this._timeline[lowerBound].time >= time) { + lowerBound--; + } + this._iterate(callback, lowerBound + 1); + return this; + }; + Tone.Timeline.prototype.forEachAtTime = function (time, callback) { + var upperBound = this._search(time); + if (upperBound !== -1) { + this._iterate(function (event) { + if (event.time === time) { + callback(event); + } + }, 0, upperBound); + } + return this; + }; + Tone.Timeline.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._timeline = null; + this._toRemove = null; + }; + return Tone.Timeline; +}(Tone_core_Tone); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_signal_TimelineSignal; +Tone_signal_TimelineSignal = function (Tone) { + 'use strict'; + Tone.TimelineSignal = function () { + var options = this.optionsObject(arguments, [ + 'value', + 'units' + ], Tone.Signal.defaults); + this._events = new Tone.Timeline(10); + Tone.Signal.apply(this, options); + options.param = this._param; + Tone.Param.call(this, options); + this._initial = this._fromUnits(this._param.value); + }; + Tone.extend(Tone.TimelineSignal, Tone.Param); + Tone.TimelineSignal.Type = { + Linear: 'linear', + Exponential: 'exponential', + Target: 'target', + Curve: 'curve', + Set: 'set' + }; + Object.defineProperty(Tone.TimelineSignal.prototype, 'value', { + get: function () { + var now = this.now(); + var val = this.getValueAtTime(now); + return this._toUnits(val); + }, + set: function (value) { + var convertedVal = this._fromUnits(value); + this._initial = convertedVal; + this.cancelScheduledValues(); + this._param.value = convertedVal; + } + }); + Tone.TimelineSignal.prototype.setValueAtTime = function (value, startTime) { + value = this._fromUnits(value); + startTime = this.toSeconds(startTime); + this._events.add({ + 'type': Tone.TimelineSignal.Type.Set, + 'value': value, + 'time': startTime + }); + this._param.setValueAtTime(value, startTime); + return this; + }; + Tone.TimelineSignal.prototype.linearRampToValueAtTime = function (value, endTime) { + value = this._fromUnits(value); + endTime = this.toSeconds(endTime); + this._events.add({ + 'type': Tone.TimelineSignal.Type.Linear, + 'value': value, + 'time': endTime + }); + this._param.linearRampToValueAtTime(value, endTime); + return this; + }; + Tone.TimelineSignal.prototype.exponentialRampToValueAtTime = function (value, endTime) { + endTime = this.toSeconds(endTime); + var beforeEvent = this._searchBefore(endTime); + if (beforeEvent && beforeEvent.value === 0) { + this.setValueAtTime(this._minOutput, beforeEvent.time); + } + value = this._fromUnits(value); + var setValue = Math.max(value, this._minOutput); + this._events.add({ + 'type': Tone.TimelineSignal.Type.Exponential, + 'value': setValue, + 'time': endTime + }); + if (value < this._minOutput) { + this._param.exponentialRampToValueAtTime(this._minOutput, endTime - this.sampleTime); + this.setValueAtTime(0, endTime); + } else { + this._param.exponentialRampToValueAtTime(value, endTime); + } + return this; + }; + Tone.TimelineSignal.prototype.setTargetAtTime = function (value, startTime, timeConstant) { + value = this._fromUnits(value); + value = Math.max(this._minOutput, value); + timeConstant = Math.max(this._minOutput, timeConstant); + startTime = this.toSeconds(startTime); + this._events.add({ + 'type': Tone.TimelineSignal.Type.Target, + 'value': value, + 'time': startTime, + 'constant': timeConstant + }); + this._param.setTargetAtTime(value, startTime, timeConstant); + return this; + }; + Tone.TimelineSignal.prototype.setValueCurveAtTime = function (values, startTime, duration, scaling) { + scaling = this.defaultArg(scaling, 1); + var floats = new Array(values.length); + for (var i = 0; i < floats.length; i++) { + floats[i] = this._fromUnits(values[i]) * scaling; + } + startTime = this.toSeconds(startTime); + duration = this.toSeconds(duration); + this._events.add({ + 'type': Tone.TimelineSignal.Type.Curve, + 'value': floats, + 'time': startTime, + 'duration': duration + }); + this._param.setValueAtTime(floats[0], startTime); + for (var j = 1; j < floats.length; j++) { + var segmentTime = startTime + j / (floats.length - 1) * duration; + this._param.linearRampToValueAtTime(floats[j], segmentTime); + } + return this; + }; + Tone.TimelineSignal.prototype.cancelScheduledValues = function (after) { + after = this.toSeconds(after); + this._events.cancel(after); + this._param.cancelScheduledValues(after); + return this; + }; + Tone.TimelineSignal.prototype.setRampPoint = function (time) { + time = this.toSeconds(time); + var val = this._toUnits(this.getValueAtTime(time)); + var before = this._searchBefore(time); + if (before && before.time === time) { + this.cancelScheduledValues(time + this.sampleTime); + } else if (before && before.type === Tone.TimelineSignal.Type.Curve && before.time + before.duration > time) { + this.cancelScheduledValues(time); + this.linearRampToValueAtTime(val, time); + } else { + var after = this._searchAfter(time); + if (after) { + this.cancelScheduledValues(time); + if (after.type === Tone.TimelineSignal.Type.Linear) { + this.linearRampToValueAtTime(val, time); + } else if (after.type === Tone.TimelineSignal.Type.Exponential) { + this.exponentialRampToValueAtTime(val, time); + } + } + this.setValueAtTime(val, time); + } + return this; + }; + Tone.TimelineSignal.prototype.linearRampToValueBetween = function (value, start, finish) { + this.setRampPoint(start); + this.linearRampToValueAtTime(value, finish); + return this; + }; + Tone.TimelineSignal.prototype.exponentialRampToValueBetween = function (value, start, finish) { + this.setRampPoint(start); + this.exponentialRampToValueAtTime(value, finish); + return this; + }; + Tone.TimelineSignal.prototype._searchBefore = function (time) { + return this._events.get(time); + }; + Tone.TimelineSignal.prototype._searchAfter = function (time) { + return this._events.getAfter(time); + }; + Tone.TimelineSignal.prototype.getValueAtTime = function (time) { + time = this.toSeconds(time); + var after = this._searchAfter(time); + var before = this._searchBefore(time); + var value = this._initial; + if (before === null) { + value = this._initial; + } else if (before.type === Tone.TimelineSignal.Type.Target) { + var previous = this._events.getBefore(before.time); + var previouVal; + if (previous === null) { + previouVal = this._initial; + } else { + previouVal = previous.value; + } + value = this._exponentialApproach(before.time, previouVal, before.value, before.constant, time); + } else if (before.type === Tone.TimelineSignal.Type.Curve) { + value = this._curveInterpolate(before.time, before.value, before.duration, time); + } else if (after === null) { + value = before.value; + } else if (after.type === Tone.TimelineSignal.Type.Linear) { + value = this._linearInterpolate(before.time, before.value, after.time, after.value, time); + } else if (after.type === Tone.TimelineSignal.Type.Exponential) { + value = this._exponentialInterpolate(before.time, before.value, after.time, after.value, time); + } else { + value = before.value; + } + return value; + }; + Tone.TimelineSignal.prototype.connect = Tone.SignalBase.prototype.connect; + Tone.TimelineSignal.prototype._exponentialApproach = function (t0, v0, v1, timeConstant, t) { + return v1 + (v0 - v1) * Math.exp(-(t - t0) / timeConstant); + }; + Tone.TimelineSignal.prototype._linearInterpolate = function (t0, v0, t1, v1, t) { + return v0 + (v1 - v0) * ((t - t0) / (t1 - t0)); + }; + Tone.TimelineSignal.prototype._exponentialInterpolate = function (t0, v0, t1, v1, t) { + v0 = Math.max(this._minOutput, v0); + return v0 * Math.pow(v1 / v0, (t - t0) / (t1 - t0)); + }; + Tone.TimelineSignal.prototype._curveInterpolate = function (start, curve, duration, time) { + var len = curve.length; + if (time >= start + duration) { + return curve[len - 1]; + } else if (time <= start) { + return curve[0]; + } else { + var progress = (time - start) / duration; + var lowerIndex = Math.floor((len - 1) * progress); + var upperIndex = Math.ceil((len - 1) * progress); + var lowerVal = curve[lowerIndex]; + var upperVal = curve[upperIndex]; + if (upperIndex === lowerIndex) { + return lowerVal; + } else { + return this._linearInterpolate(lowerIndex, lowerVal, upperIndex, upperVal, progress * (len - 1)); + } + } + }; + Tone.TimelineSignal.prototype.dispose = function () { + Tone.Signal.prototype.dispose.call(this); + Tone.Param.prototype.dispose.call(this); + this._events.dispose(); + this._events = null; + }; + return Tone.TimelineSignal; +}(Tone_core_Tone, Tone_signal_Signal); +var envelope; +'use strict'; +envelope = function () { + var p5sound = master; + var Add = Tone_signal_Add; + var Mult = Tone_signal_Multiply; + var Scale = Tone_signal_Scale; + var TimelineSignal = Tone_signal_TimelineSignal; + /** + *

Envelopes are pre-defined amplitude distribution over time. + * Typically, envelopes are used to control the output volume + * of an object, a series of fades referred to as Attack, Decay, + * Sustain and Release ( + * ADSR + * ). Envelopes can also control other Web Audio Parameters—for example, a p5.Envelope can + * control an Oscillator's frequency like this: osc.freq(env).

+ *

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

+ *

Use the play method to play the entire envelope, + * the ramp method for a pingable trigger, + * or triggerAttack/ + * triggerRelease to trigger noteOn/noteOff.

+ * + * @class p5.Envelope + * @constructor + * @example + *
+ * var attackLevel = 1.0; + * var releaseLevel = 0; + * + * var attackTime = 0.001; + * var decayTime = 0.2; + * var susPercent = 0.2; + * var releaseTime = 0.5; + * + * var env, triOsc; + * + * function setup() { + * var cnv = createCanvas(100, 100); + * + * textAlign(CENTER); + * text('click to play', width/2, height/2); + * + * env = new p5.Envelope(); + * env.setADSR(attackTime, decayTime, susPercent, releaseTime); + * env.setRange(attackLevel, releaseLevel); + * + * triOsc = new p5.Oscillator('triangle'); + * triOsc.amp(env); + * triOsc.start(); + * triOsc.freq(220); + * + * cnv.mousePressed(playEnv); + * } + * + * function playEnv() { + * env.play(); + * } + *
+ */ + p5.Envelope = function (t1, l1, t2, l2, t3, l3) { + /** + * Time until envelope reaches attackLevel + * @property attackTime + */ + this.aTime = t1 || 0.1; + /** + * Level once attack is complete. + * @property attackLevel + */ + this.aLevel = l1 || 1; + /** + * Time until envelope reaches decayLevel. + * @property decayTime + */ + this.dTime = t2 || 0.5; + /** + * Level after decay. The envelope will sustain here until it is released. + * @property decayLevel + */ + this.dLevel = l2 || 0; + /** + * Duration of the release portion of the envelope. + * @property releaseTime + */ + this.rTime = t3 || 0; + /** + * Level at the end of the release. + * @property releaseLevel + */ + this.rLevel = l3 || 0; + this._rampHighPercentage = 0.98; + this._rampLowPercentage = 0.02; + this.output = p5sound.audiocontext.createGain(); + this.control = new TimelineSignal(); + this._init(); + // this makes sure the envelope starts at zero + this.control.connect(this.output); + // connect to the output + this.connection = null; + // store connection + //array of math operation signal chaining + this.mathOps = [this.control]; + //whether envelope should be linear or exponential curve + this.isExponential = false; + // oscillator or buffer source to clear on env complete + // to save resources if/when it is retriggered + this.sourceToClear = null; + // set to true if attack is set, then false on release + this.wasTriggered = false; + // add to the soundArray so we can dispose of the env later + p5sound.soundArray.push(this); + }; + // this init function just smooths the starting value to zero and gives a start point for the timeline + // - it was necessary to remove glitches at the beginning. + p5.Envelope.prototype._init = function () { + var now = p5sound.audiocontext.currentTime; + var t = now; + this.control.setTargetAtTime(0.00001, t, 0.001); + //also, compute the correct time constants + this._setRampAD(this.aTime, this.dTime); + }; + /** + * Reset the envelope with a series of time/value pairs. + * + * @method set + * @param {Number} attackTime Time (in seconds) before level + * reaches attackLevel + * @param {Number} attackLevel Typically an amplitude between + * 0.0 and 1.0 + * @param {Number} decayTime Time + * @param {Number} decayLevel Amplitude (In a standard ADSR envelope, + * decayLevel = sustainLevel) + * @param {Number} releaseTime Release Time (in seconds) + * @param {Number} releaseLevel Amplitude + * @example + *
+ * var t1 = 0.1; // attack time in seconds + * var l1 = 0.7; // attack level 0.0 to 1.0 + * var t2 = 0.3; // decay time in seconds + * var l2 = 0.1; // decay level 0.0 to 1.0 + * var t3 = 0.2; // sustain time in seconds + * var l3 = 0.5; // sustain level 0.0 to 1.0 + * // release level defaults to zero + * + * var env; + * var triOsc; + * + * function setup() { + * background(0); + * noStroke(); + * fill(255); + * textAlign(CENTER); + * text('click to play', width/2, height/2); + * + * env = new p5.Envelope(t1, l1, t2, l2, t3, l3); + * triOsc = new p5.Oscillator('triangle'); + * triOsc.amp(env); // give the env control of the triOsc's amp + * triOsc.start(); + * } + * + * // mouseClick triggers envelope if over canvas + * function mouseClicked() { + * // is mouse over canvas? + * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { + * env.play(triOsc); + * } + * } + *
+ * + */ + p5.Envelope.prototype.set = function (t1, l1, t2, l2, t3, l3) { + this.aTime = t1; + this.aLevel = l1; + this.dTime = t2 || 0; + this.dLevel = l2 || 0; + this.rTime = t3 || 0; + this.rLevel = l3 || 0; + // set time constants for ramp + this._setRampAD(t1, t2); + }; + /** + * Set values like a traditional + * + * ADSR envelope + * . + * + * @method setADSR + * @param {Number} attackTime Time (in seconds before envelope + * reaches Attack Level + * @param {Number} [decayTime] Time (in seconds) before envelope + * reaches Decay/Sustain Level + * @param {Number} [susRatio] Ratio between attackLevel and releaseLevel, on a scale from 0 to 1, + * where 1.0 = attackLevel, 0.0 = releaseLevel. + * The susRatio determines the decayLevel and the level at which the + * sustain portion of the envelope will sustain. + * For example, if attackLevel is 0.4, releaseLevel is 0, + * and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is + * increased to 1.0 (using setRange), + * then decayLevel would increase proportionally, to become 0.5. + * @param {Number} [releaseTime] Time in seconds from now (defaults to 0) + * @example + *
+ * var attackLevel = 1.0; + * var releaseLevel = 0; + * + * var attackTime = 0.001; + * var decayTime = 0.2; + * var susPercent = 0.2; + * var releaseTime = 0.5; + * + * var env, triOsc; + * + * function setup() { + * var cnv = createCanvas(100, 100); + * + * textAlign(CENTER); + * text('click to play', width/2, height/2); + * + * env = new p5.Envelope(); + * env.setADSR(attackTime, decayTime, susPercent, releaseTime); + * env.setRange(attackLevel, releaseLevel); + * + * triOsc = new p5.Oscillator('triangle'); + * triOsc.amp(env); + * triOsc.start(); + * triOsc.freq(220); + * + * cnv.mousePressed(playEnv); + * } + * + * function playEnv() { + * env.play(); + * } + *
+ */ + p5.Envelope.prototype.setADSR = function (aTime, dTime, sPercent, rTime) { + this.aTime = aTime; + this.dTime = dTime || 0; + // lerp + this.sPercent = sPercent || 0; + this.dLevel = typeof sPercent !== 'undefined' ? sPercent * (this.aLevel - this.rLevel) + this.rLevel : 0; + this.rTime = rTime || 0; + // also set time constants for ramp + this._setRampAD(aTime, dTime); + }; + /** + * Set max (attackLevel) and min (releaseLevel) of envelope. + * + * @method setRange + * @param {Number} aLevel attack level (defaults to 1) + * @param {Number} rLevel release level (defaults to 0) + * @example + *
+ * var attackLevel = 1.0; + * var releaseLevel = 0; + * + * var attackTime = 0.001; + * var decayTime = 0.2; + * var susPercent = 0.2; + * var releaseTime = 0.5; + * + * var env, triOsc; + * + * function setup() { + * var cnv = createCanvas(100, 100); + * + * textAlign(CENTER); + * text('click to play', width/2, height/2); + * + * env = new p5.Envelope(); + * env.setADSR(attackTime, decayTime, susPercent, releaseTime); + * env.setRange(attackLevel, releaseLevel); + * + * triOsc = new p5.Oscillator('triangle'); + * triOsc.amp(env); + * triOsc.start(); + * triOsc.freq(220); + * + * cnv.mousePressed(playEnv); + * } + * + * function playEnv() { + * env.play(); + * } + *
+ */ + p5.Envelope.prototype.setRange = function (aLevel, rLevel) { + this.aLevel = aLevel || 1; + this.rLevel = rLevel || 0; + }; + // private (undocumented) method called when ADSR is set to set time constants for ramp + // + // Set the + // time constants for simple exponential ramps. + // The larger the time constant value, the slower the + // transition will be. + // + // method _setRampAD + // param {Number} attackTimeConstant attack time constant + // param {Number} decayTimeConstant decay time constant + // + p5.Envelope.prototype._setRampAD = function (t1, t2) { + this._rampAttackTime = this.checkExpInput(t1); + this._rampDecayTime = this.checkExpInput(t2); + var TCDenominator = 1; + /// Aatish Bhatia's calculation for time constant for rise(to adjust 1/1-e calculation to any percentage) + TCDenominator = Math.log(1 / this.checkExpInput(1 - this._rampHighPercentage)); + this._rampAttackTC = t1 / this.checkExpInput(TCDenominator); + TCDenominator = Math.log(1 / this._rampLowPercentage); + this._rampDecayTC = t2 / this.checkExpInput(TCDenominator); + }; + // private method + p5.Envelope.prototype.setRampPercentages = function (p1, p2) { + //set the percentages that the simple exponential ramps go to + this._rampHighPercentage = this.checkExpInput(p1); + this._rampLowPercentage = this.checkExpInput(p2); + var TCDenominator = 1; + //now re-compute the time constants based on those percentages + /// Aatish Bhatia's calculation for time constant for rise(to adjust 1/1-e calculation to any percentage) + TCDenominator = Math.log(1 / this.checkExpInput(1 - this._rampHighPercentage)); + this._rampAttackTC = this._rampAttackTime / this.checkExpInput(TCDenominator); + TCDenominator = Math.log(1 / this._rampLowPercentage); + this._rampDecayTC = this._rampDecayTime / this.checkExpInput(TCDenominator); + }; + /** + * Assign a parameter to be controlled by this envelope. + * If a p5.Sound object is given, then the p5.Envelope will control its + * output gain. If multiple inputs are provided, the env will + * control all of them. + * + * @method setInput + * @param {Object} [...inputs] A p5.sound object or + * Web Audio Param. + */ + p5.Envelope.prototype.setInput = function () { + for (var i = 0; i < arguments.length; i++) { + this.connect(arguments[i]); + } + }; + /** + * Set whether the envelope ramp is linear (default) or exponential. + * Exponential ramps can be useful because we perceive amplitude + * and frequency logarithmically. + * + * @method setExp + * @param {Boolean} isExp true is exponential, false is linear + */ + p5.Envelope.prototype.setExp = function (isExp) { + this.isExponential = isExp; + }; + //helper method to protect against zero values being sent to exponential functions + p5.Envelope.prototype.checkExpInput = function (value) { + if (value <= 0) { + value = 1e-8; + } + return value; + }; + /** + * Play tells the envelope to start acting on a given input. + * If the input is a p5.sound object (i.e. AudioIn, Oscillator, + * SoundFile), then Envelope will control its output volume. + * Envelopes can also be used to control any + * Web Audio Audio Param. + * + * @method play + * @param {Object} unit A p5.sound object or + * Web Audio Param. + * @param {Number} [startTime] time from now (in seconds) at which to play + * @param {Number} [sustainTime] time to sustain before releasing the envelope + * @example + *
+ * var attackLevel = 1.0; + * var releaseLevel = 0; + * + * var attackTime = 0.001; + * var decayTime = 0.2; + * var susPercent = 0.2; + * var releaseTime = 0.5; + * + * var env, triOsc; + * + * function setup() { + * var cnv = createCanvas(100, 100); + * + * textAlign(CENTER); + * text('click to play', width/2, height/2); + * + * env = new p5.Envelope(); + * env.setADSR(attackTime, decayTime, susPercent, releaseTime); + * env.setRange(attackLevel, releaseLevel); + * + * triOsc = new p5.Oscillator('triangle'); + * triOsc.amp(env); + * triOsc.start(); + * triOsc.freq(220); + * + * cnv.mousePressed(playEnv); + * } + * + * function playEnv() { + * // trigger env on triOsc, 0 seconds from now + * // After decay, sustain for 0.2 seconds before release + * env.play(triOsc, 0, 0.2); + * } + *
+ */ + p5.Envelope.prototype.play = function (unit, secondsFromNow, susTime) { + var tFromNow = secondsFromNow || 0; + var susTime = susTime || 0; + if (unit) { + if (this.connection !== unit) { + this.connect(unit); + } + } + this.triggerAttack(unit, tFromNow); + this.triggerRelease(unit, tFromNow + this.aTime + this.dTime + susTime); + }; + /** + * Trigger the Attack, and Decay portion of the Envelope. + * Similar to holding down a key on a piano, but it will + * hold the sustain level until you let go. Input can be + * any p5.sound object, or a + * Web Audio Param. + * + * @method triggerAttack + * @param {Object} unit p5.sound Object or Web Audio Param + * @param {Number} secondsFromNow time from now (in seconds) + * @example + *
+ * + * var attackLevel = 1.0; + * var releaseLevel = 0; + * + * var attackTime = 0.001; + * var decayTime = 0.3; + * var susPercent = 0.4; + * var releaseTime = 0.5; + * + * var env, triOsc; + * + * function setup() { + * var cnv = createCanvas(100, 100); + * background(200); + * textAlign(CENTER); + * text('click to play', width/2, height/2); + * + * env = new p5.Envelope(); + * env.setADSR(attackTime, decayTime, susPercent, releaseTime); + * env.setRange(attackLevel, releaseLevel); + * + * triOsc = new p5.Oscillator('triangle'); + * triOsc.amp(env); + * triOsc.start(); + * triOsc.freq(220); + * + * cnv.mousePressed(envAttack); + * } + * + * function envAttack() { + * console.log('trigger attack'); + * env.triggerAttack(); + * + * background(0,255,0); + * text('attack!', width/2, height/2); + * } + * + * function mouseReleased() { + * env.triggerRelease(); + * + * background(200); + * text('click to play', width/2, height/2); + * } + *
+ */ + p5.Envelope.prototype.triggerAttack = function (unit, secondsFromNow) { + var now = p5sound.audiocontext.currentTime; + var tFromNow = secondsFromNow || 0; + var t = now + tFromNow; + this.lastAttack = t; + this.wasTriggered = true; + if (unit) { + if (this.connection !== unit) { + this.connect(unit); + } + } + // get and set value (with linear ramp) to anchor automation + var valToSet = this.control.getValueAtTime(t); + if (this.isExponential === true) { + this.control.exponentialRampToValueAtTime(this.checkExpInput(valToSet), t); + } else { + this.control.linearRampToValueAtTime(valToSet, t); + } + // after each ramp completes, cancel scheduled values + // (so they can be overridden in case env has been re-triggered) + // then, set current value (with linearRamp to avoid click) + // then, schedule the next automation... + // attack + t += this.aTime; + if (this.isExponential === true) { + this.control.exponentialRampToValueAtTime(this.checkExpInput(this.aLevel), t); + valToSet = this.checkExpInput(this.control.getValueAtTime(t)); + this.control.cancelScheduledValues(t); + this.control.exponentialRampToValueAtTime(valToSet, t); + } else { + this.control.linearRampToValueAtTime(this.aLevel, t); + valToSet = this.control.getValueAtTime(t); + this.control.cancelScheduledValues(t); + this.control.linearRampToValueAtTime(valToSet, t); + } + // decay to decay level (if using ADSR, then decay level == sustain level) + t += this.dTime; + if (this.isExponential === true) { + this.control.exponentialRampToValueAtTime(this.checkExpInput(this.dLevel), t); + valToSet = this.checkExpInput(this.control.getValueAtTime(t)); + this.control.cancelScheduledValues(t); + this.control.exponentialRampToValueAtTime(valToSet, t); + } else { + this.control.linearRampToValueAtTime(this.dLevel, t); + valToSet = this.control.getValueAtTime(t); + this.control.cancelScheduledValues(t); + this.control.linearRampToValueAtTime(valToSet, t); + } + }; + /** + * Trigger the Release of the Envelope. This is similar to releasing + * the key on a piano and letting the sound fade according to the + * release level and release time. + * + * @method triggerRelease + * @param {Object} unit p5.sound Object or Web Audio Param + * @param {Number} secondsFromNow time to trigger the release + * @example + *
+ * + * var attackLevel = 1.0; + * var releaseLevel = 0; + * + * var attackTime = 0.001; + * var decayTime = 0.3; + * var susPercent = 0.4; + * var releaseTime = 0.5; + * + * var env, triOsc; + * + * function setup() { + * var cnv = createCanvas(100, 100); + * background(200); + * textAlign(CENTER); + * text('click to play', width/2, height/2); + * + * env = new p5.Envelope(); + * env.setADSR(attackTime, decayTime, susPercent, releaseTime); + * env.setRange(attackLevel, releaseLevel); + * + * triOsc = new p5.Oscillator('triangle'); + * triOsc.amp(env); + * triOsc.start(); + * triOsc.freq(220); + * + * cnv.mousePressed(envAttack); + * } + * + * function envAttack() { + * console.log('trigger attack'); + * env.triggerAttack(); + * + * background(0,255,0); + * text('attack!', width/2, height/2); + * } + * + * function mouseReleased() { + * env.triggerRelease(); + * + * background(200); + * text('click to play', width/2, height/2); + * } + *
+ */ + p5.Envelope.prototype.triggerRelease = function (unit, secondsFromNow) { + // only trigger a release if an attack was triggered + if (!this.wasTriggered) { + // this currently causes a bit of trouble: + // if a later release has been scheduled (via the play function) + // a new earlier release won't interrupt it, because + // this.wasTriggered has already been set to false. + // If we want new earlier releases to override, then we need to + // keep track of the last release time, and if the new release time is + // earlier, then use it. + return; + } + var now = p5sound.audiocontext.currentTime; + var tFromNow = secondsFromNow || 0; + var t = now + tFromNow; + if (unit) { + if (this.connection !== unit) { + this.connect(unit); + } + } + // get and set value (with linear or exponential ramp) to anchor automation + var valToSet = this.control.getValueAtTime(t); + if (this.isExponential === true) { + this.control.exponentialRampToValueAtTime(this.checkExpInput(valToSet), t); + } else { + this.control.linearRampToValueAtTime(valToSet, t); + } + // release + t += this.rTime; + if (this.isExponential === true) { + this.control.exponentialRampToValueAtTime(this.checkExpInput(this.rLevel), t); + valToSet = this.checkExpInput(this.control.getValueAtTime(t)); + this.control.cancelScheduledValues(t); + this.control.exponentialRampToValueAtTime(valToSet, t); + } else { + this.control.linearRampToValueAtTime(this.rLevel, t); + valToSet = this.control.getValueAtTime(t); + this.control.cancelScheduledValues(t); + this.control.linearRampToValueAtTime(valToSet, t); + } + this.wasTriggered = false; + }; + /** + * Exponentially ramp to a value using the first two + * values from setADSR(attackTime, decayTime) + * as + * time constants for simple exponential ramps. + * If the value is higher than current value, it uses attackTime, + * while a decrease uses decayTime. + * + * @method ramp + * @param {Object} unit p5.sound Object or Web Audio Param + * @param {Number} secondsFromNow When to trigger the ramp + * @param {Number} v Target value + * @param {Number} [v2] Second target value (optional) + * @example + *
+ * var env, osc, amp, cnv; + * + * var attackTime = 0.001; + * var decayTime = 0.2; + * var attackLevel = 1; + * var decayLevel = 0; + * + * function setup() { + * cnv = createCanvas(100, 100); + * fill(0,255,0); + * noStroke(); + * + * env = new p5.Envelope(); + * env.setADSR(attackTime, decayTime); + * + * osc = new p5.Oscillator(); + * osc.amp(env); + * osc.start(); + * + * amp = new p5.Amplitude(); + * + * cnv.mousePressed(triggerRamp); + * } + * + * function triggerRamp() { + * env.ramp(osc, 0, attackLevel, decayLevel); + * } + * + * function draw() { + * background(20,20,20); + * text('click me', 10, 20); + * var h = map(amp.getLevel(), 0, 0.4, 0, height);; + * + * rect(0, height, width, -h); + * } + *
+ */ + p5.Envelope.prototype.ramp = function (unit, secondsFromNow, v1, v2) { + var now = p5sound.audiocontext.currentTime; + var tFromNow = secondsFromNow || 0; + var t = now + tFromNow; + var destination1 = this.checkExpInput(v1); + var destination2 = typeof v2 !== 'undefined' ? this.checkExpInput(v2) : undefined; + // connect env to unit if not already connected + if (unit) { + if (this.connection !== unit) { + this.connect(unit); + } + } + //get current value + var currentVal = this.checkExpInput(this.control.getValueAtTime(t)); + // this.control.cancelScheduledValues(t); + //if it's going up + if (destination1 > currentVal) { + this.control.setTargetAtTime(destination1, t, this._rampAttackTC); + t += this._rampAttackTime; + } else if (destination1 < currentVal) { + this.control.setTargetAtTime(destination1, t, this._rampDecayTC); + t += this._rampDecayTime; + } + // Now the second part of envelope begins + if (destination2 === undefined) + return; + //if it's going up + if (destination2 > destination1) { + this.control.setTargetAtTime(destination2, t, this._rampAttackTC); + } else if (destination2 < destination1) { + this.control.setTargetAtTime(destination2, t, this._rampDecayTC); + } + }; + p5.Envelope.prototype.connect = function (unit) { + this.connection = unit; + // assume we're talking about output gain + // unless given a different audio param + if (unit instanceof p5.Oscillator || unit instanceof p5.SoundFile || unit instanceof p5.AudioIn || unit instanceof p5.Reverb || unit instanceof p5.Noise || unit instanceof p5.Filter || unit instanceof p5.Delay) { + unit = unit.output.gain; + } + if (unit instanceof AudioParam) { + //set the initial value + unit.setValueAtTime(0, p5sound.audiocontext.currentTime); + } + if (unit instanceof p5.Signal) { + unit.setValue(0); + } + this.output.connect(unit); + }; + p5.Envelope.prototype.disconnect = function () { + if (this.output) { + this.output.disconnect(); + } + }; + // Signal Math + /** + * Add a value to the p5.Oscillator's output amplitude, + * and return the oscillator. Calling this method + * again will override the initial add() with new values. + * + * @method add + * @param {Number} number Constant number to add + * @return {p5.Envelope} Envelope Returns this envelope + * with scaled output + */ + p5.Envelope.prototype.add = function (num) { + var add = new Add(num); + var thisChain = this.mathOps.length; + var nextChain = this.output; + return p5.prototype._mathChain(this, add, thisChain, nextChain, Add); + }; + /** + * Multiply the p5.Envelope's output amplitude + * by a fixed value. Calling this method + * again will override the initial mult() with new values. + * + * @method mult + * @param {Number} number Constant number to multiply + * @return {p5.Envelope} Envelope Returns this envelope + * with scaled output + */ + p5.Envelope.prototype.mult = function (num) { + var mult = new Mult(num); + var thisChain = this.mathOps.length; + var nextChain = this.output; + return p5.prototype._mathChain(this, mult, thisChain, nextChain, Mult); + }; + /** + * Scale this envelope's amplitude values to a given + * range, and return the envelope. Calling this method + * again will override the initial scale() with new values. + * + * @method scale + * @param {Number} inMin input range minumum + * @param {Number} inMax input range maximum + * @param {Number} outMin input range minumum + * @param {Number} outMax input range maximum + * @return {p5.Envelope} Envelope Returns this envelope + * with scaled output + */ + p5.Envelope.prototype.scale = function (inMin, inMax, outMin, outMax) { + var scale = new Scale(inMin, inMax, outMin, outMax); + var thisChain = this.mathOps.length; + var nextChain = this.output; + return p5.prototype._mathChain(this, scale, thisChain, nextChain, Scale); + }; + // get rid of the oscillator + p5.Envelope.prototype.dispose = function () { + // remove reference from soundArray + var index = p5sound.soundArray.indexOf(this); + p5sound.soundArray.splice(index, 1); + this.disconnect(); + if (this.control) { + this.control.dispose(); + this.control = null; + } + for (var i = 1; i < this.mathOps.length; i++) { + this.mathOps[i].dispose(); + } + }; + // Different name for backwards compatibility, replicates p5.Envelope class + p5.Env = function (t1, l1, t2, l2, t3, l3) { + console.warn('WARNING: p5.Env is now deprecated and may be removed in future versions. ' + 'Please use the new p5.Envelope instead.'); + p5.Envelope.call(this, t1, l1, t2, l2, t3, l3); + }; + p5.Env.prototype = Object.create(p5.Envelope.prototype); +}(master, Tone_signal_Add, Tone_signal_Multiply, Tone_signal_Scale, Tone_signal_TimelineSignal); +var pulse; +'use strict'; +pulse = function () { + var p5sound = master; + /** + * Creates a Pulse object, an oscillator that implements + * Pulse Width Modulation. + * The pulse is created with two oscillators. + * Accepts a parameter for frequency, and to set the + * width between the pulses. See + * p5.Oscillator for a full list of methods. + * + * @class p5.Pulse + * @extends p5.Oscillator + * @constructor + * @param {Number} [freq] Frequency in oscillations per second (Hz) + * @param {Number} [w] Width between the pulses (0 to 1.0, + * defaults to 0) + * @example + *
+ * var pulse; + * function setup() { + * background(0); + * + * // Create and start the pulse wave oscillator + * pulse = new p5.Pulse(); + * pulse.amp(0.5); + * pulse.freq(220); + * pulse.start(); + * } + * + * function draw() { + * var w = map(mouseX, 0, width, 0, 1); + * w = constrain(w, 0, 1); + * pulse.width(w) + * } + *
+ */ + p5.Pulse = function (freq, w) { + p5.Oscillator.call(this, freq, 'sawtooth'); + // width of PWM, should be betw 0 to 1.0 + this.w = w || 0; + // create a second oscillator with inverse frequency + this.osc2 = new p5.SawOsc(freq); + // create a delay node + this.dNode = p5sound.audiocontext.createDelay(); + // dc offset + this.dcOffset = createDCOffset(); + this.dcGain = p5sound.audiocontext.createGain(); + this.dcOffset.connect(this.dcGain); + this.dcGain.connect(this.output); + // set delay time based on PWM width + this.f = freq || 440; + var mW = this.w / this.oscillator.frequency.value; + this.dNode.delayTime.value = mW; + this.dcGain.gain.value = 1.7 * (0.5 - this.w); + // disconnect osc2 and connect it to delay, which is connected to output + this.osc2.disconnect(); + this.osc2.panner.disconnect(); + this.osc2.amp(-1); + // inverted amplitude + this.osc2.output.connect(this.dNode); + this.dNode.connect(this.output); + this.output.gain.value = 1; + this.output.connect(this.panner); + }; + p5.Pulse.prototype = Object.create(p5.Oscillator.prototype); + /** + * Set the width of a Pulse object (an oscillator that implements + * Pulse Width Modulation). + * + * @method width + * @param {Number} [width] Width between the pulses (0 to 1.0, + * defaults to 0) + */ + p5.Pulse.prototype.width = function (w) { + if (typeof w === 'number') { + if (w <= 1 && w >= 0) { + this.w = w; + // set delay time based on PWM width + // var mW = map(this.w, 0, 1.0, 0, 1/this.f); + var mW = this.w / this.oscillator.frequency.value; + this.dNode.delayTime.value = mW; + } + this.dcGain.gain.value = 1.7 * (0.5 - this.w); + } else { + w.connect(this.dNode.delayTime); + var sig = new p5.SignalAdd(-0.5); + sig.setInput(w); + sig = sig.mult(-1); + sig = sig.mult(1.7); + sig.connect(this.dcGain.gain); + } + }; + p5.Pulse.prototype.start = function (f, time) { + var now = p5sound.audiocontext.currentTime; + var t = time || 0; + if (!this.started) { + var freq = f || this.f; + var type = this.oscillator.type; + this.oscillator = p5sound.audiocontext.createOscillator(); + this.oscillator.frequency.setValueAtTime(freq, now); + this.oscillator.type = type; + this.oscillator.connect(this.output); + this.oscillator.start(t + now); + // set up osc2 + this.osc2.oscillator = p5sound.audiocontext.createOscillator(); + this.osc2.oscillator.frequency.setValueAtTime(freq, t + now); + this.osc2.oscillator.type = type; + this.osc2.oscillator.connect(this.osc2.output); + this.osc2.start(t + now); + this.freqNode = [ + this.oscillator.frequency, + this.osc2.oscillator.frequency + ]; + // start dcOffset, too + this.dcOffset = createDCOffset(); + this.dcOffset.connect(this.dcGain); + this.dcOffset.start(t + now); + // if LFO connections depend on these oscillators + if (this.mods !== undefined && this.mods.frequency !== undefined) { + this.mods.frequency.connect(this.freqNode[0]); + this.mods.frequency.connect(this.freqNode[1]); + } + this.started = true; + this.osc2.started = true; + } + }; + p5.Pulse.prototype.stop = function (time) { + if (this.started) { + var t = time || 0; + var now = p5sound.audiocontext.currentTime; + this.oscillator.stop(t + now); + if (this.osc2.oscillator) { + this.osc2.oscillator.stop(t + now); + } + this.dcOffset.stop(t + now); + this.started = false; + this.osc2.started = false; + } + }; + p5.Pulse.prototype.freq = function (val, rampTime, tFromNow) { + if (typeof val === 'number') { + this.f = val; + var now = p5sound.audiocontext.currentTime; + var rampTime = rampTime || 0; + var tFromNow = tFromNow || 0; + var currentFreq = this.oscillator.frequency.value; + this.oscillator.frequency.cancelScheduledValues(now); + this.oscillator.frequency.setValueAtTime(currentFreq, now + tFromNow); + this.oscillator.frequency.exponentialRampToValueAtTime(val, tFromNow + rampTime + now); + this.osc2.oscillator.frequency.cancelScheduledValues(now); + this.osc2.oscillator.frequency.setValueAtTime(currentFreq, now + tFromNow); + this.osc2.oscillator.frequency.exponentialRampToValueAtTime(val, tFromNow + rampTime + now); + if (this.freqMod) { + this.freqMod.output.disconnect(); + this.freqMod = null; + } + } else if (val.output) { + val.output.disconnect(); + val.output.connect(this.oscillator.frequency); + val.output.connect(this.osc2.oscillator.frequency); + this.freqMod = val; + } + }; + // inspiration: http://webaudiodemos.appspot.com/oscilloscope/ + function createDCOffset() { + var ac = p5sound.audiocontext; + var buffer = ac.createBuffer(1, 2048, ac.sampleRate); + var data = buffer.getChannelData(0); + for (var i = 0; i < 2048; i++) + data[i] = 1; + var bufferSource = ac.createBufferSource(); + bufferSource.buffer = buffer; + bufferSource.loop = true; + return bufferSource; + } +}(master, oscillator); +var noise; +'use strict'; +noise = function () { + var p5sound = master; + /** + * Noise is a type of oscillator that generates a buffer with random values. + * + * @class p5.Noise + * @extends p5.Oscillator + * @constructor + * @param {String} type Type of noise can be 'white' (default), + * 'brown' or 'pink'. + */ + p5.Noise = function (type) { + var assignType; + p5.Oscillator.call(this); + delete this.f; + delete this.freq; + delete this.oscillator; + if (type === 'brown') { + assignType = _brownNoise; + } else if (type === 'pink') { + assignType = _pinkNoise; + } else { + assignType = _whiteNoise; + } + this.buffer = assignType; + }; + p5.Noise.prototype = Object.create(p5.Oscillator.prototype); + // generate noise buffers + var _whiteNoise = function () { + var bufferSize = 2 * p5sound.audiocontext.sampleRate; + var whiteBuffer = p5sound.audiocontext.createBuffer(1, bufferSize, p5sound.audiocontext.sampleRate); + var noiseData = whiteBuffer.getChannelData(0); + for (var i = 0; i < bufferSize; i++) { + noiseData[i] = Math.random() * 2 - 1; + } + whiteBuffer.type = 'white'; + return whiteBuffer; + }(); + var _pinkNoise = function () { + var bufferSize = 2 * p5sound.audiocontext.sampleRate; + var pinkBuffer = p5sound.audiocontext.createBuffer(1, bufferSize, p5sound.audiocontext.sampleRate); + var noiseData = pinkBuffer.getChannelData(0); + var b0, b1, b2, b3, b4, b5, b6; + b0 = b1 = b2 = b3 = b4 = b5 = b6 = 0; + for (var i = 0; i < bufferSize; i++) { + var white = Math.random() * 2 - 1; + b0 = 0.99886 * b0 + white * 0.0555179; + b1 = 0.99332 * b1 + white * 0.0750759; + b2 = 0.969 * b2 + white * 0.153852; + b3 = 0.8665 * b3 + white * 0.3104856; + b4 = 0.55 * b4 + white * 0.5329522; + b5 = -0.7616 * b5 - white * 0.016898; + noiseData[i] = b0 + b1 + b2 + b3 + b4 + b5 + b6 + white * 0.5362; + noiseData[i] *= 0.11; + // (roughly) compensate for gain + b6 = white * 0.115926; + } + pinkBuffer.type = 'pink'; + return pinkBuffer; + }(); + var _brownNoise = function () { + var bufferSize = 2 * p5sound.audiocontext.sampleRate; + var brownBuffer = p5sound.audiocontext.createBuffer(1, bufferSize, p5sound.audiocontext.sampleRate); + var noiseData = brownBuffer.getChannelData(0); + var lastOut = 0; + for (var i = 0; i < bufferSize; i++) { + var white = Math.random() * 2 - 1; + noiseData[i] = (lastOut + 0.02 * white) / 1.02; + lastOut = noiseData[i]; + noiseData[i] *= 3.5; + } + brownBuffer.type = 'brown'; + return brownBuffer; + }(); + /** + * Set type of noise to 'white', 'pink' or 'brown'. + * White is the default. + * + * @method setType + * @param {String} [type] 'white', 'pink' or 'brown' + */ + p5.Noise.prototype.setType = function (type) { + switch (type) { + case 'white': + this.buffer = _whiteNoise; + break; + case 'pink': + this.buffer = _pinkNoise; + break; + case 'brown': + this.buffer = _brownNoise; + break; + default: + this.buffer = _whiteNoise; + } + if (this.started) { + var now = p5sound.audiocontext.currentTime; + this.stop(now); + this.start(now + 0.01); + } + }; + p5.Noise.prototype.getType = function () { + return this.buffer.type; + }; + p5.Noise.prototype.start = function () { + if (this.started) { + this.stop(); + } + this.noise = p5sound.audiocontext.createBufferSource(); + this.noise.buffer = this.buffer; + this.noise.loop = true; + this.noise.connect(this.output); + var now = p5sound.audiocontext.currentTime; + this.noise.start(now); + this.started = true; + }; + p5.Noise.prototype.stop = function () { + var now = p5sound.audiocontext.currentTime; + if (this.noise) { + this.noise.stop(now); + this.started = false; + } + }; + p5.Noise.prototype.dispose = function () { + var now = p5sound.audiocontext.currentTime; + // remove reference from soundArray + var index = p5sound.soundArray.indexOf(this); + p5sound.soundArray.splice(index, 1); + if (this.noise) { + this.noise.disconnect(); + this.stop(now); + } + if (this.output) { + this.output.disconnect(); + } + if (this.panner) { + this.panner.disconnect(); + } + this.output = null; + this.panner = null; + this.buffer = null; + this.noise = null; + }; +}(master); +var audioin; +'use strict'; +audioin = function () { + var p5sound = master; + // an array of input sources + p5sound.inputSources = []; + /** + *

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

+ * + *

Turn the mic on/off with the start() and stop() methods. When the mic + * is on, its volume can be measured with getLevel or by connecting an + * FFT object.

+ * + *

If you want to hear the AudioIn, use the .connect() method. + * AudioIn does not connect to p5.sound output by default to prevent + * feedback.

+ * + *

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

+ * + * @class p5.AudioIn + * @constructor + * @param {Function} [errorCallback] A function to call if there is an error + * accessing the AudioIn. For example, + * Safari and iOS devices do not + * currently allow microphone access. + * @example + *
+ * var mic; + * function setup(){ + * mic = new p5.AudioIn() + * mic.start(); + * } + * function draw(){ + * background(0); + * micLevel = mic.getLevel(); + * ellipse(width/2, constrain(height-micLevel*height*5, 0, height), 10, 10); + * } + *
+ */ + p5.AudioIn = function (errorCallback) { + // set up audio input + /** + * @property {GainNode} input + */ + this.input = p5sound.audiocontext.createGain(); + /** + * @property {GainNode} output + */ + this.output = p5sound.audiocontext.createGain(); + /** + * @property {MediaStream|null} stream + */ + this.stream = null; + /** + * @property {MediaStreamAudioSourceNode|null} mediaStream + */ + this.mediaStream = null; + /** + * @property {Number|null} currentSource + */ + this.currentSource = null; + /** + * Client must allow browser to access their microphone / audioin source. + * Default: false. Will become true when the client enables acces. + * + * @property {Boolean} enabled + */ + this.enabled = false; + /** + * Input amplitude, connect to it by default but not to master out + * + * @property {p5.Amplitude} amplitude + */ + this.amplitude = new p5.Amplitude(); + this.output.connect(this.amplitude.input); + if (!window.MediaStreamTrack || !window.navigator.mediaDevices || !window.navigator.mediaDevices.getUserMedia) { + errorCallback ? errorCallback() : window.alert('This browser does not support MediaStreamTrack and mediaDevices'); + } + // add to soundArray so we can dispose on close + p5sound.soundArray.push(this); + }; + /** + * Start processing audio input. This enables the use of other + * AudioIn methods like getLevel(). Note that by default, AudioIn + * is not connected to p5.sound's output. So you won't hear + * anything unless you use the connect() method.
+ * + * Certain browsers limit access to the user's microphone. For example, + * Chrome only allows access from localhost and over https. For this reason, + * you may want to include an errorCallback—a function that is called in case + * the browser won't provide mic access. + * + * @method start + * @param {Function} [successCallback] Name of a function to call on + * success. + * @param {Function} [errorCallback] Name of a function to call if + * there was an error. For example, + * some browsers do not support + * getUserMedia. + */ + p5.AudioIn.prototype.start = function (successCallback, errorCallback) { + var self = this; + if (this.stream) { + this.stop(); + } + // set the audio source + var audioSource = p5sound.inputSources[self.currentSource]; + var constraints = { + audio: { + sampleRate: p5sound.audiocontext.sampleRate, + echoCancellation: false + } + }; + // if developers determine which source to use + if (p5sound.inputSources[this.currentSource]) { + constraints.audio.deviceId = audioSource.deviceId; + } + window.navigator.mediaDevices.getUserMedia(constraints).then(function (stream) { + self.stream = stream; + self.enabled = true; + // Wrap a MediaStreamSourceNode around the live input + self.mediaStream = p5sound.audiocontext.createMediaStreamSource(stream); + self.mediaStream.connect(self.output); + // only send to the Amplitude reader, so we can see it but not hear it. + self.amplitude.setInput(self.output); + if (successCallback) + successCallback(); + }).catch(function (err) { + if (errorCallback) + errorCallback(err); + else + console.error(err); + }); + }; + /** + * Turn the AudioIn off. If the AudioIn is stopped, it cannot getLevel(). + * If re-starting, the user may be prompted for permission access. + * + * @method stop + */ + p5.AudioIn.prototype.stop = function () { + if (this.stream) { + this.stream.getTracks().forEach(function (track) { + track.stop(); + }); + this.mediaStream.disconnect(); + delete this.mediaStream; + delete this.stream; + } + }; + /** + * Connect to an audio unit. If no parameter is provided, will + * connect to the master output (i.e. your speakers).
+ * + * @method connect + * @param {Object} [unit] An object that accepts audio input, + * such as an FFT + */ + p5.AudioIn.prototype.connect = function (unit) { + if (unit) { + if (unit.hasOwnProperty('input')) { + this.output.connect(unit.input); + } else if (unit.hasOwnProperty('analyser')) { + this.output.connect(unit.analyser); + } else { + this.output.connect(unit); + } + } else { + this.output.connect(p5sound.input); + } + }; + /** + * Disconnect the AudioIn from all audio units. For example, if + * connect() had been called, disconnect() will stop sending + * signal to your speakers.
+ * + * @method disconnect + */ + p5.AudioIn.prototype.disconnect = function () { + if (this.output) { + this.output.disconnect(); + // stay connected to amplitude even if not outputting to p5 + this.output.connect(this.amplitude.input); + } + }; + /** + * Read the Amplitude (volume level) of an AudioIn. The AudioIn + * class contains its own instance of the Amplitude class to help + * make it easy to get a microphone's volume level. Accepts an + * optional smoothing value (0.0 < 1.0). NOTE: AudioIn must + * .start() before using .getLevel().
+ * + * @method getLevel + * @param {Number} [smoothing] Smoothing is 0.0 by default. + * Smooths values based on previous values. + * @return {Number} Volume level (between 0.0 and 1.0) + */ + p5.AudioIn.prototype.getLevel = function (smoothing) { + if (smoothing) { + this.amplitude.smoothing = smoothing; + } + return this.amplitude.getLevel(); + }; + /** + * Set amplitude (volume) of a mic input between 0 and 1.0.
+ * + * @method amp + * @param {Number} vol between 0 and 1.0 + * @param {Number} [time] ramp time (optional) + */ + p5.AudioIn.prototype.amp = function (vol, t) { + if (t) { + var rampTime = t || 0; + var currentVol = this.output.gain.value; + this.output.gain.cancelScheduledValues(p5sound.audiocontext.currentTime); + this.output.gain.setValueAtTime(currentVol, p5sound.audiocontext.currentTime); + this.output.gain.linearRampToValueAtTime(vol, rampTime + p5sound.audiocontext.currentTime); + } else { + this.output.gain.cancelScheduledValues(p5sound.audiocontext.currentTime); + this.output.gain.setValueAtTime(vol, p5sound.audiocontext.currentTime); + } + }; + /** + * Returns a list of available input sources. This is a wrapper + * for and it returns a Promise. + * + * @method getSources + * @param {Function} [successCallback] This callback function handles the sources when they + * have been enumerated. The callback function + * receives the deviceList array as its only argument + * @param {Function} [errorCallback] This optional callback receives the error + * message as its argument. + * @returns {Promise} Returns a Promise that can be used in place of the callbacks, similar + * to the enumerateDevices() method + * @example + *
+ * var audiograb; + * + * function setup(){ + * //new audioIn + * audioGrab = new p5.AudioIn(); + * + * audioGrab.getSources(function(deviceList) { + * //print out the array of available sources + * console.log(deviceList); + * //set the source to the first item in the deviceList array + * audioGrab.setSource(0); + * }); + * } + *
+ */ + p5.AudioIn.prototype.getSources = function (onSuccess, onError) { + return new Promise(function (resolve, reject) { + window.navigator.mediaDevices.enumerateDevices().then(function (devices) { + p5sound.inputSources = devices.filter(function (device) { + return device.kind === 'audioinput'; + }); + resolve(p5sound.inputSources); + if (onSuccess) { + onSuccess(p5sound.inputSources); + } + }).catch(function (error) { + reject(error); + if (onError) { + onError(error); + } else { + console.error('This browser does not support MediaStreamTrack.getSources()'); + } + }); + }); + }; + /** + * Set the input source. Accepts a number representing a + * position in the array returned by getSources(). + * This is only available in browsers that support + *
navigator.mediaDevices.enumerateDevices().
+ * + * @method setSource + * @param {number} num position of input source in the array + */ + p5.AudioIn.prototype.setSource = function (num) { + if (p5sound.inputSources.length > 0 && num < p5sound.inputSources.length) { + // set the current source + this.currentSource = num; + console.log('set source to ', p5sound.inputSources[this.currentSource]); + } else { + console.log('unable to set input source'); + } + // restart stream if currently active + if (this.stream && this.stream.active) { + this.start(); + } + }; + // private method + p5.AudioIn.prototype.dispose = function () { + // remove reference from soundArray + var index = p5sound.soundArray.indexOf(this); + p5sound.soundArray.splice(index, 1); + this.stop(); + if (this.output) { + this.output.disconnect(); + } + if (this.amplitude) { + this.amplitude.disconnect(); + } + delete this.amplitude; + delete this.output; + }; +}(master); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_signal_Negate; +Tone_signal_Negate = function (Tone) { + 'use strict'; + Tone.Negate = function () { + this._multiply = this.input = this.output = new Tone.Multiply(-1); + }; + Tone.extend(Tone.Negate, Tone.SignalBase); + Tone.Negate.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._multiply.dispose(); + this._multiply = null; + return this; + }; + return Tone.Negate; +}(Tone_core_Tone, Tone_signal_Multiply); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_signal_Subtract; +Tone_signal_Subtract = function (Tone) { + 'use strict'; + Tone.Subtract = function (value) { + this.createInsOuts(2, 0); + this._sum = this.input[0] = this.output = new Tone.Gain(); + this._neg = new Tone.Negate(); + this._param = this.input[1] = new Tone.Signal(value); + this._param.chain(this._neg, this._sum); + }; + Tone.extend(Tone.Subtract, Tone.Signal); + Tone.Subtract.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._neg.dispose(); + this._neg = null; + this._sum.disconnect(); + this._sum = null; + this._param.dispose(); + this._param = null; + return this; + }; + return Tone.Subtract; +}(Tone_core_Tone, Tone_signal_Add, Tone_signal_Negate, Tone_signal_Signal); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_signal_GreaterThanZero; +Tone_signal_GreaterThanZero = function (Tone) { + 'use strict'; + Tone.GreaterThanZero = function () { + this._thresh = this.output = new Tone.WaveShaper(function (val) { + if (val <= 0) { + return 0; + } else { + return 1; + } + }, 127); + this._scale = this.input = new Tone.Multiply(10000); + this._scale.connect(this._thresh); + }; + Tone.extend(Tone.GreaterThanZero, Tone.SignalBase); + Tone.GreaterThanZero.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._scale.dispose(); + this._scale = null; + this._thresh.dispose(); + this._thresh = null; + return this; + }; + return Tone.GreaterThanZero; +}(Tone_core_Tone, Tone_signal_Signal, Tone_signal_Multiply); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_signal_GreaterThan; +Tone_signal_GreaterThan = function (Tone) { + 'use strict'; + Tone.GreaterThan = function (value) { + this.createInsOuts(2, 0); + this._param = this.input[0] = new Tone.Subtract(value); + this.input[1] = this._param.input[1]; + this._gtz = this.output = new Tone.GreaterThanZero(); + this._param.connect(this._gtz); + }; + Tone.extend(Tone.GreaterThan, Tone.Signal); + Tone.GreaterThan.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._param.dispose(); + this._param = null; + this._gtz.dispose(); + this._gtz = null; + return this; + }; + return Tone.GreaterThan; +}(Tone_core_Tone, Tone_signal_GreaterThanZero, Tone_signal_Subtract); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_signal_Abs; +Tone_signal_Abs = function (Tone) { + 'use strict'; + Tone.Abs = function () { + this._abs = this.input = this.output = new Tone.WaveShaper(function (val) { + if (val === 0) { + return 0; + } else { + return Math.abs(val); + } + }, 127); + }; + Tone.extend(Tone.Abs, Tone.SignalBase); + Tone.Abs.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._abs.dispose(); + this._abs = null; + return this; + }; + return Tone.Abs; +}(Tone_core_Tone, Tone_signal_WaveShaper); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_signal_Modulo; +Tone_signal_Modulo = function (Tone) { + 'use strict'; + Tone.Modulo = function (modulus) { + this.createInsOuts(1, 0); + this._shaper = new Tone.WaveShaper(Math.pow(2, 16)); + this._multiply = new Tone.Multiply(); + this._subtract = this.output = new Tone.Subtract(); + this._modSignal = new Tone.Signal(modulus); + this.input.fan(this._shaper, this._subtract); + this._modSignal.connect(this._multiply, 0, 0); + this._shaper.connect(this._multiply, 0, 1); + this._multiply.connect(this._subtract, 0, 1); + this._setWaveShaper(modulus); + }; + Tone.extend(Tone.Modulo, Tone.SignalBase); + Tone.Modulo.prototype._setWaveShaper = function (mod) { + this._shaper.setMap(function (val) { + var multiple = Math.floor((val + 0.0001) / mod); + return multiple; + }); + }; + Object.defineProperty(Tone.Modulo.prototype, 'value', { + get: function () { + return this._modSignal.value; + }, + set: function (mod) { + this._modSignal.value = mod; + this._setWaveShaper(mod); + } + }); + Tone.Modulo.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._shaper.dispose(); + this._shaper = null; + this._multiply.dispose(); + this._multiply = null; + this._subtract.dispose(); + this._subtract = null; + this._modSignal.dispose(); + this._modSignal = null; + return this; + }; + return Tone.Modulo; +}(Tone_core_Tone, Tone_signal_WaveShaper, Tone_signal_Multiply); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_signal_Pow; +Tone_signal_Pow = function (Tone) { + 'use strict'; + Tone.Pow = function (exp) { + this._exp = this.defaultArg(exp, 1); + this._expScaler = this.input = this.output = new Tone.WaveShaper(this._expFunc(this._exp), 8192); + }; + Tone.extend(Tone.Pow, Tone.SignalBase); + Object.defineProperty(Tone.Pow.prototype, 'value', { + get: function () { + return this._exp; + }, + set: function (exp) { + this._exp = exp; + this._expScaler.setMap(this._expFunc(this._exp)); + } + }); + Tone.Pow.prototype._expFunc = function (exp) { + return function (val) { + return Math.pow(Math.abs(val), exp); + }; + }; + Tone.Pow.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._expScaler.dispose(); + this._expScaler = null; + return this; + }; + return Tone.Pow; +}(Tone_core_Tone); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_signal_AudioToGain; +Tone_signal_AudioToGain = function (Tone) { + 'use strict'; + Tone.AudioToGain = function () { + this._norm = this.input = this.output = new Tone.WaveShaper(function (x) { + return (x + 1) / 2; + }); + }; + Tone.extend(Tone.AudioToGain, Tone.SignalBase); + Tone.AudioToGain.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._norm.dispose(); + this._norm = null; + return this; + }; + return Tone.AudioToGain; +}(Tone_core_Tone, Tone_signal_WaveShaper); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_signal_Expr; +Tone_signal_Expr = function (Tone) { + 'use strict'; + Tone.Expr = function () { + var expr = this._replacements(Array.prototype.slice.call(arguments)); + var inputCount = this._parseInputs(expr); + this._nodes = []; + this.input = new Array(inputCount); + for (var i = 0; i < inputCount; i++) { + this.input[i] = this.context.createGain(); + } + var tree = this._parseTree(expr); + var result; + try { + result = this._eval(tree); + } catch (e) { + this._disposeNodes(); + throw new Error('Tone.Expr: Could evaluate expression: ' + expr); + } + this.output = result; + }; + Tone.extend(Tone.Expr, Tone.SignalBase); + function applyBinary(Constructor, args, self) { + var op = new Constructor(); + self._eval(args[0]).connect(op, 0, 0); + self._eval(args[1]).connect(op, 0, 1); + return op; + } + function applyUnary(Constructor, args, self) { + var op = new Constructor(); + self._eval(args[0]).connect(op, 0, 0); + return op; + } + function getNumber(arg) { + return arg ? parseFloat(arg) : undefined; + } + function literalNumber(arg) { + return arg && arg.args ? parseFloat(arg.args) : undefined; + } + Tone.Expr._Expressions = { + 'value': { + 'signal': { + regexp: /^\d+\.\d+|^\d+/, + method: function (arg) { + var sig = new Tone.Signal(getNumber(arg)); + return sig; + } + }, + 'input': { + regexp: /^\$\d/, + method: function (arg, self) { + return self.input[getNumber(arg.substr(1))]; + } + } + }, + 'glue': { + '(': { regexp: /^\(/ }, + ')': { regexp: /^\)/ }, + ',': { regexp: /^,/ } + }, + 'func': { + 'abs': { + regexp: /^abs/, + method: applyUnary.bind(this, Tone.Abs) + }, + 'mod': { + regexp: /^mod/, + method: function (args, self) { + var modulus = literalNumber(args[1]); + var op = new Tone.Modulo(modulus); + self._eval(args[0]).connect(op); + return op; + } + }, + 'pow': { + regexp: /^pow/, + method: function (args, self) { + var exp = literalNumber(args[1]); + var op = new Tone.Pow(exp); + self._eval(args[0]).connect(op); + return op; + } + }, + 'a2g': { + regexp: /^a2g/, + method: function (args, self) { + var op = new Tone.AudioToGain(); + self._eval(args[0]).connect(op); + return op; + } + } + }, + 'binary': { + '+': { + regexp: /^\+/, + precedence: 1, + method: applyBinary.bind(this, Tone.Add) + }, + '-': { + regexp: /^\-/, + precedence: 1, + method: function (args, self) { + if (args.length === 1) { + return applyUnary(Tone.Negate, args, self); + } else { + return applyBinary(Tone.Subtract, args, self); + } + } + }, + '*': { + regexp: /^\*/, + precedence: 0, + method: applyBinary.bind(this, Tone.Multiply) + } + }, + 'unary': { + '-': { + regexp: /^\-/, + method: applyUnary.bind(this, Tone.Negate) + }, + '!': { + regexp: /^\!/, + method: applyUnary.bind(this, Tone.NOT) + } + } + }; + Tone.Expr.prototype._parseInputs = function (expr) { + var inputArray = expr.match(/\$\d/g); + var inputMax = 0; + if (inputArray !== null) { + for (var i = 0; i < inputArray.length; i++) { + var inputNum = parseInt(inputArray[i].substr(1)) + 1; + inputMax = Math.max(inputMax, inputNum); + } + } + return inputMax; + }; + Tone.Expr.prototype._replacements = function (args) { + var expr = args.shift(); + for (var i = 0; i < args.length; i++) { + expr = expr.replace(/\%/i, args[i]); + } + return expr; + }; + Tone.Expr.prototype._tokenize = function (expr) { + var position = -1; + var tokens = []; + while (expr.length > 0) { + expr = expr.trim(); + var token = getNextToken(expr); + tokens.push(token); + expr = expr.substr(token.value.length); + } + function getNextToken(expr) { + for (var type in Tone.Expr._Expressions) { + var group = Tone.Expr._Expressions[type]; + for (var opName in group) { + var op = group[opName]; + var reg = op.regexp; + var match = expr.match(reg); + if (match !== null) { + return { + type: type, + value: match[0], + method: op.method + }; + } + } + } + throw new SyntaxError('Tone.Expr: Unexpected token ' + expr); + } + return { + next: function () { + return tokens[++position]; + }, + peek: function () { + return tokens[position + 1]; + } + }; + }; + Tone.Expr.prototype._parseTree = function (expr) { + var lexer = this._tokenize(expr); + var isUndef = this.isUndef.bind(this); + function matchSyntax(token, syn) { + return !isUndef(token) && token.type === 'glue' && token.value === syn; + } + function matchGroup(token, groupName, prec) { + var ret = false; + var group = Tone.Expr._Expressions[groupName]; + if (!isUndef(token)) { + for (var opName in group) { + var op = group[opName]; + if (op.regexp.test(token.value)) { + if (!isUndef(prec)) { + if (op.precedence === prec) { + return true; + } + } else { + return true; + } + } + } + } + return ret; + } + function parseExpression(precedence) { + if (isUndef(precedence)) { + precedence = 5; + } + var expr; + if (precedence < 0) { + expr = parseUnary(); + } else { + expr = parseExpression(precedence - 1); + } + var token = lexer.peek(); + while (matchGroup(token, 'binary', precedence)) { + token = lexer.next(); + expr = { + operator: token.value, + method: token.method, + args: [ + expr, + parseExpression(precedence - 1) + ] + }; + token = lexer.peek(); + } + return expr; + } + function parseUnary() { + var token, expr; + token = lexer.peek(); + if (matchGroup(token, 'unary')) { + token = lexer.next(); + expr = parseUnary(); + return { + operator: token.value, + method: token.method, + args: [expr] + }; + } + return parsePrimary(); + } + function parsePrimary() { + var token, expr; + token = lexer.peek(); + if (isUndef(token)) { + throw new SyntaxError('Tone.Expr: Unexpected termination of expression'); + } + if (token.type === 'func') { + token = lexer.next(); + return parseFunctionCall(token); + } + if (token.type === 'value') { + token = lexer.next(); + return { + method: token.method, + args: token.value + }; + } + if (matchSyntax(token, '(')) { + lexer.next(); + expr = parseExpression(); + token = lexer.next(); + if (!matchSyntax(token, ')')) { + throw new SyntaxError('Expected )'); + } + return expr; + } + throw new SyntaxError('Tone.Expr: Parse error, cannot process token ' + token.value); + } + function parseFunctionCall(func) { + var token, args = []; + token = lexer.next(); + if (!matchSyntax(token, '(')) { + throw new SyntaxError('Tone.Expr: Expected ( in a function call "' + func.value + '"'); + } + token = lexer.peek(); + if (!matchSyntax(token, ')')) { + args = parseArgumentList(); + } + token = lexer.next(); + if (!matchSyntax(token, ')')) { + throw new SyntaxError('Tone.Expr: Expected ) in a function call "' + func.value + '"'); + } + return { + method: func.method, + args: args, + name: name + }; + } + function parseArgumentList() { + var token, expr, args = []; + while (true) { + expr = parseExpression(); + if (isUndef(expr)) { + break; + } + args.push(expr); + token = lexer.peek(); + if (!matchSyntax(token, ',')) { + break; + } + lexer.next(); + } + return args; + } + return parseExpression(); + }; + Tone.Expr.prototype._eval = function (tree) { + if (!this.isUndef(tree)) { + var node = tree.method(tree.args, this); + this._nodes.push(node); + return node; + } + }; + Tone.Expr.prototype._disposeNodes = function () { + for (var i = 0; i < this._nodes.length; i++) { + var node = this._nodes[i]; + if (this.isFunction(node.dispose)) { + node.dispose(); + } else if (this.isFunction(node.disconnect)) { + node.disconnect(); + } + node = null; + this._nodes[i] = null; + } + this._nodes = null; + }; + Tone.Expr.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._disposeNodes(); + }; + return Tone.Expr; +}(Tone_core_Tone, Tone_signal_Add, Tone_signal_Subtract, Tone_signal_Multiply, Tone_signal_GreaterThan, Tone_signal_GreaterThanZero, Tone_signal_Abs, Tone_signal_Negate, Tone_signal_Modulo, Tone_signal_Pow); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_signal_EqualPowerGain; +Tone_signal_EqualPowerGain = function (Tone) { + 'use strict'; + Tone.EqualPowerGain = function () { + this._eqPower = this.input = this.output = new Tone.WaveShaper(function (val) { + if (Math.abs(val) < 0.001) { + return 0; + } else { + return this.equalPowerScale(val); + } + }.bind(this), 4096); + }; + Tone.extend(Tone.EqualPowerGain, Tone.SignalBase); + Tone.EqualPowerGain.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._eqPower.dispose(); + this._eqPower = null; + return this; + }; + return Tone.EqualPowerGain; +}(Tone_core_Tone); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_component_CrossFade; +Tone_component_CrossFade = function (Tone) { + 'use strict'; + Tone.CrossFade = function (initialFade) { + this.createInsOuts(2, 1); + this.a = this.input[0] = new Tone.Gain(); + this.b = this.input[1] = new Tone.Gain(); + this.fade = new Tone.Signal(this.defaultArg(initialFade, 0.5), Tone.Type.NormalRange); + this._equalPowerA = new Tone.EqualPowerGain(); + this._equalPowerB = new Tone.EqualPowerGain(); + this._invert = new Tone.Expr('1 - $0'); + this.a.connect(this.output); + this.b.connect(this.output); + this.fade.chain(this._equalPowerB, this.b.gain); + this.fade.chain(this._invert, this._equalPowerA, this.a.gain); + this._readOnly('fade'); + }; + Tone.extend(Tone.CrossFade); + Tone.CrossFade.prototype.dispose = function () { + Tone.prototype.dispose.call(this); + this._writable('fade'); + this._equalPowerA.dispose(); + this._equalPowerA = null; + this._equalPowerB.dispose(); + this._equalPowerB = null; + this.fade.dispose(); + this.fade = null; + this._invert.dispose(); + this._invert = null; + this.a.dispose(); + this.a = null; + this.b.dispose(); + this.b = null; + return this; + }; + return Tone.CrossFade; +}(Tone_core_Tone, Tone_signal_Signal, Tone_signal_Expr, Tone_signal_EqualPowerGain); +var effect; +'use strict'; +effect = function () { + var p5sound = master; + var CrossFade = Tone_component_CrossFade; + /** + * Effect is a base class for audio effects in p5.
+ * This module handles the nodes and methods that are + * common and useful for current and future effects. + * + * + * This class is extended by p5.Distortion, + * p5.Compressor, + * p5.Delay, + * p5.Filter, + * p5.Reverb. + * + * @class p5.Effect + * @constructor + * + * @param {Object} [ac] Reference to the audio context of the p5 object + * @param {AudioNode} [input] Gain Node effect wrapper + * @param {AudioNode} [output] Gain Node effect wrapper + * @param {Object} [_drywet] Tone.JS CrossFade node (defaults to value: 1) + * @param {AudioNode} [wet] Effects that extend this class should connect + * to the wet signal to this gain node, so that dry and wet + * signals are mixed properly. + */ + p5.Effect = function () { + this.ac = p5sound.audiocontext; + this.input = this.ac.createGain(); + this.output = this.ac.createGain(); + /** + * The p5.Effect class is built + * using Tone.js CrossFade + * @private + */ + this._drywet = new CrossFade(1); + /** + * In classes that extend + * p5.Effect, connect effect nodes + * to the wet parameter + */ + this.wet = this.ac.createGain(); + this.input.connect(this._drywet.a); + this.wet.connect(this._drywet.b); + this._drywet.connect(this.output); + this.connect(); + //Add to the soundArray + p5sound.soundArray.push(this); + }; + /** + * Set the output volume of the filter. + * + * @method amp + * @param {Number} [vol] amplitude between 0 and 1.0 + * @param {Number} [rampTime] create a fade that lasts until rampTime + * @param {Number} [tFromNow] schedule this event to happen in tFromNow seconds + */ + p5.Effect.prototype.amp = function (vol, rampTime, tFromNow) { + var rampTime = rampTime || 0; + var tFromNow = tFromNow || 0; + var now = p5sound.audiocontext.currentTime; + var currentVol = this.output.gain.value; + this.output.gain.cancelScheduledValues(now); + this.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow + 0.001); + this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime + 0.001); + }; + /** + * Link effects together in a chain + * Example usage: filter.chain(reverb, delay, panner); + * May be used with an open-ended number of arguments + * + * @method chain + * @param {Object} [arguments] Chain together multiple sound objects + */ + p5.Effect.prototype.chain = function () { + if (arguments.length > 0) { + this.connect(arguments[0]); + for (var i = 1; i < arguments.length; i += 1) { + arguments[i - 1].connect(arguments[i]); + } + } + return this; + }; + /** + * Adjust the dry/wet value. + * + * @method drywet + * @param {Number} [fade] The desired drywet value (0 - 1.0) + */ + p5.Effect.prototype.drywet = function (fade) { + if (typeof fade !== 'undefined') { + this._drywet.fade.value = fade; + } + return this._drywet.fade.value; + }; + /** + * Send output to a p5.js-sound, Web Audio Node, or use signal to + * control an AudioParam + * + * @method connect + * @param {Object} unit + */ + p5.Effect.prototype.connect = function (unit) { + var u = unit || p5.soundOut.input; + this.output.connect(u.input ? u.input : u); + }; + /** + * Disconnect all output. + * + * @method disconnect + */ + p5.Effect.prototype.disconnect = function () { + if (this.output) { + this.output.disconnect(); + } + }; + p5.Effect.prototype.dispose = function () { + // remove refernce form soundArray + var index = p5sound.soundArray.indexOf(this); + p5sound.soundArray.splice(index, 1); + if (this.input) { + this.input.disconnect(); + delete this.input; + } + if (this.output) { + this.output.disconnect(); + delete this.output; + } + if (this._drywet) { + this._drywet.disconnect(); + delete this._drywet; + } + if (this.wet) { + this.wet.disconnect(); + delete this.wet; + } + this.ac = undefined; + }; + return p5.Effect; +}(master, Tone_component_CrossFade); +var filter; +'use strict'; +filter = function () { + var p5sound = master; + var Effect = effect; + /** + *

A p5.Filter uses a Web Audio Biquad Filter to filter + * the frequency response of an input source. Subclasses + * include:

+ * * p5.LowPass: + * Allows frequencies below the cutoff frequency to pass through, + * and attenuates frequencies above the cutoff.
+ * * p5.HighPass: + * The opposite of a lowpass filter.
+ * * p5.BandPass: + * Allows a range of frequencies to pass through and attenuates + * the frequencies below and above this frequency range.
+ * + * The .res() method controls either width of the + * bandpass, or resonance of the low/highpass cutoff frequency. + * + * This class extends p5.Effect. + * Methods amp(), chain(), + * drywet(), connect(), and + * disconnect() are available. + * + * @class p5.Filter + * @extends p5.Effect + * @constructor + * @param {String} [type] 'lowpass' (default), 'highpass', 'bandpass' + * @example + *
+ * var fft, noise, filter; + * + * function setup() { + * fill(255, 40, 255); + * + * filter = new p5.BandPass(); + * + * noise = new p5.Noise(); + * // disconnect unfiltered noise, + * // and connect to filter + * noise.disconnect(); + * noise.connect(filter); + * noise.start(); + * + * fft = new p5.FFT(); + * } + * + * function draw() { + * background(30); + * + * // set the BandPass frequency based on mouseX + * var freq = map(mouseX, 0, width, 20, 10000); + * filter.freq(freq); + * // give the filter a narrow band (lower res = wider bandpass) + * filter.res(50); + * + * // draw filtered spectrum + * var spectrum = fft.analyze(); + * noStroke(); + * for (var i = 0; i < spectrum.length; i++) { + * var x = map(i, 0, spectrum.length, 0, width); + * var h = -height + map(spectrum[i], 0, 255, height, 0); + * rect(x, height, width/spectrum.length, h); + * } + * + * isMouseOverCanvas(); + * } + * + * function isMouseOverCanvas() { + * var mX = mouseX, mY = mouseY; + * if (mX > 0 && mX < width && mY < height && mY > 0) { + * noise.amp(0.5, 0.2); + * } else { + * noise.amp(0, 0.2); + * } + * } + *
+ */ + //constructor with inheritance + p5.Filter = function (type) { + Effect.call(this); + //add extend Effect by adding a Biquad Filter + /** + * The p5.Filter is built with a + * + * Web Audio BiquadFilter Node. + * + * @property {DelayNode} biquadFilter + */ + this.biquad = this.ac.createBiquadFilter(); + this.input.connect(this.biquad); + this.biquad.connect(this.wet); + if (type) { + this.setType(type); + } + //Properties useful for the toggle method. + this._on = true; + this._untoggledType = this.biquad.type; + }; + p5.Filter.prototype = Object.create(Effect.prototype); + /** + * Filter an audio signal according to a set + * of filter parameters. + * + * @method process + * @param {Object} Signal An object that outputs audio + * @param {Number} [freq] Frequency in Hz, from 10 to 22050 + * @param {Number} [res] Resonance/Width of the filter frequency + * from 0.001 to 1000 + */ + p5.Filter.prototype.process = function (src, freq, res, time) { + src.connect(this.input); + this.set(freq, res, time); + }; + /** + * Set the frequency and the resonance of the filter. + * + * @method set + * @param {Number} [freq] Frequency in Hz, from 10 to 22050 + * @param {Number} [res] Resonance (Q) from 0.001 to 1000 + * @param {Number} [timeFromNow] schedule this event to happen + * seconds from now + */ + p5.Filter.prototype.set = function (freq, res, time) { + if (freq) { + this.freq(freq, time); + } + if (res) { + this.res(res, time); + } + }; + /** + * Set the filter frequency, in Hz, from 10 to 22050 (the range of + * human hearing, although in reality most people hear in a narrower + * range). + * + * @method freq + * @param {Number} freq Filter Frequency + * @param {Number} [timeFromNow] schedule this event to happen + * seconds from now + * @return {Number} value Returns the current frequency value + */ + p5.Filter.prototype.freq = function (freq, time) { + var t = time || 0; + if (freq <= 0) { + freq = 1; + } + if (typeof freq === 'number') { + this.biquad.frequency.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.biquad.frequency.exponentialRampToValueAtTime(freq, this.ac.currentTime + 0.02 + t); + } else if (freq) { + freq.connect(this.biquad.frequency); + } + return this.biquad.frequency.value; + }; + /** + * Controls either width of a bandpass frequency, + * or the resonance of a low/highpass cutoff frequency. + * + * @method res + * @param {Number} res Resonance/Width of filter freq + * from 0.001 to 1000 + * @param {Number} [timeFromNow] schedule this event to happen + * seconds from now + * @return {Number} value Returns the current res value + */ + p5.Filter.prototype.res = function (res, time) { + var t = time || 0; + if (typeof res === 'number') { + this.biquad.Q.value = res; + this.biquad.Q.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.biquad.Q.linearRampToValueAtTime(res, this.ac.currentTime + 0.02 + t); + } else if (res) { + res.connect(this.biquad.Q); + } + return this.biquad.Q.value; + }; + /** + * Controls the gain attribute of a Biquad Filter. + * This is distinctly different from .amp() which is inherited from p5.Effect + * .amp() controls the volume via the output gain node + * p5.Filter.gain() controls the gain parameter of a Biquad Filter node. + * + * @method gain + * @param {Number} gain + * @return {Number} Returns the current or updated gain value + */ + p5.Filter.prototype.gain = function (gain, time) { + var t = time || 0; + if (typeof gain === 'number') { + this.biquad.gain.value = gain; + this.biquad.gain.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.biquad.gain.linearRampToValueAtTime(gain, this.ac.currentTime + 0.02 + t); + } else if (gain) { + gain.connect(this.biquad.gain); + } + return this.biquad.gain.value; + }; + /** + * Toggle function. Switches between the specified type and allpass + * + * @method toggle + * @return {boolean} [Toggle value] + */ + p5.Filter.prototype.toggle = function () { + this._on = !this._on; + if (this._on === true) { + this.biquad.type = this._untoggledType; + } else if (this._on === false) { + this.biquad.type = 'allpass'; + } + return this._on; + }; + /** + * Set the type of a p5.Filter. Possible types include: + * "lowpass" (default), "highpass", "bandpass", + * "lowshelf", "highshelf", "peaking", "notch", + * "allpass". + * + * @method setType + * @param {String} t + */ + p5.Filter.prototype.setType = function (t) { + this.biquad.type = t; + this._untoggledType = this.biquad.type; + }; + p5.Filter.prototype.dispose = function () { + // remove reference from soundArray + Effect.prototype.dispose.apply(this); + if (this.biquad) { + this.biquad.disconnect(); + delete this.biquad; + } + }; + /** + * Constructor: new p5.LowPass() Filter. + * This is the same as creating a p5.Filter and then calling + * its method setType('lowpass'). + * See p5.Filter for methods. + * + * @class p5.LowPass + * @constructor + * @extends p5.Filter + */ + p5.LowPass = function () { + p5.Filter.call(this, 'lowpass'); + }; + p5.LowPass.prototype = Object.create(p5.Filter.prototype); + /** + * Constructor: new p5.HighPass() Filter. + * This is the same as creating a p5.Filter and then calling + * its method setType('highpass'). + * See p5.Filter for methods. + * + * @class p5.HighPass + * @constructor + * @extends p5.Filter + */ + p5.HighPass = function () { + p5.Filter.call(this, 'highpass'); + }; + p5.HighPass.prototype = Object.create(p5.Filter.prototype); + /** + * Constructor: new p5.BandPass() Filter. + * This is the same as creating a p5.Filter and then calling + * its method setType('bandpass'). + * See p5.Filter for methods. + * + * @class p5.BandPass + * @constructor + * @extends p5.Filter + */ + p5.BandPass = function () { + p5.Filter.call(this, 'bandpass'); + }; + p5.BandPass.prototype = Object.create(p5.Filter.prototype); + return p5.Filter; +}(master, effect); +var src_eqFilter; +'use strict'; +src_eqFilter = function () { + var Filter = filter; + var p5sound = master; + /** + * EQFilter extends p5.Filter with constraints + * necessary for the p5.EQ + * + * @private + */ + var EQFilter = function (freq, res) { + Filter.call(this, 'peaking'); + this.disconnect(); + this.set(freq, res); + this.biquad.gain.value = 0; + delete this.input; + delete this.output; + delete this._drywet; + delete this.wet; + }; + EQFilter.prototype = Object.create(Filter.prototype); + EQFilter.prototype.amp = function () { + console.warn('`amp()` is not available for p5.EQ bands. Use `.gain()`'); + }; + EQFilter.prototype.drywet = function () { + console.warn('`drywet()` is not available for p5.EQ bands.'); + }; + EQFilter.prototype.connect = function (unit) { + var u = unit || p5.soundOut.input; + if (this.biquad) { + this.biquad.connect(u.input ? u.input : u); + } else { + this.output.connect(u.input ? u.input : u); + } + }; + EQFilter.prototype.disconnect = function () { + if (this.biquad) { + this.biquad.disconnect(); + } + }; + EQFilter.prototype.dispose = function () { + // remove reference form soundArray + var index = p5sound.soundArray.indexOf(this); + p5sound.soundArray.splice(index, 1); + this.disconnect(); + delete this.biquad; + }; + return EQFilter; +}(filter, master); +var eq; +'use strict'; +eq = function () { + var Effect = effect; + var EQFilter = src_eqFilter; + /** + * p5.EQ is an audio effect that performs the function of a multiband + * audio equalizer. Equalization is used to adjust the balance of + * frequency compoenents of an audio signal. This process is commonly used + * in sound production and recording to change the waveform before it reaches + * a sound output device. EQ can also be used as an audio effect to create + * interesting distortions by filtering out parts of the spectrum. p5.EQ is + * built using a chain of Web Audio Biquad Filter Nodes and can be + * instantiated with 3 or 8 bands. Bands can be added or removed from + * the EQ by directly modifying p5.EQ.bands (the array that stores filters). + * + * This class extends p5.Effect. + * Methods amp(), chain(), + * drywet(), connect(), and + * disconnect() are available. + * + * @class p5.EQ + * @constructor + * @extends p5.Effect + * @param {Number} [_eqsize] Constructor will accept 3 or 8, defaults to 3 + * @return {Object} p5.EQ object + * + * @example + *
+ * var eq; + * var band_names; + * var band_index; + * + * var soundFile, play; + * + * function preload() { + * soundFormats('mp3', 'ogg'); + * soundFile = loadSound('assets/beat'); + * } + * + * function setup() { + * eq = new p5.EQ(3); + * soundFile.disconnect(); + * eq.process(soundFile); + * + * band_names = ['lows','mids','highs']; + * band_index = 0; + * play = false; + * textAlign(CENTER); + * } + * + * function draw() { + * background(30); + * noStroke(); + * fill(255); + * text('click to kill',50,25); + * + * fill(255, 40, 255); + * textSize(26); + * text(band_names[band_index],50,55); + * + * fill(255); + * textSize(9); + * text('space = play/pause',50,80); + * } + * + * //If mouse is over canvas, cycle to the next band and kill the frequency + * function mouseClicked() { + * for (var i = 0; i < eq.bands.length; i++) { + * eq.bands[i].gain(0); + * } + * eq.bands[band_index].gain(-40); + * if (mouseX > 0 && mouseX < width && mouseY < height && mouseY > 0) { + * band_index === 2 ? band_index = 0 : band_index++; + * } + * } + * + * //use space bar to trigger play / pause + * function keyPressed() { + * if (key===' ') { + * play = !play + * play ? soundFile.loop() : soundFile.pause(); + * } + * } + *
+ */ + p5.EQ = function (_eqsize) { + Effect.call(this); + //p5.EQ can be of size (3) or (8), defaults to 3 + _eqsize = _eqsize === 3 || _eqsize === 8 ? _eqsize : 3; + var factor; + _eqsize === 3 ? factor = Math.pow(2, 3) : factor = 2; + /** + * The p5.EQ is built with abstracted p5.Filter objects. + * To modify any bands, use methods of the + * p5.Filter API, especially `gain` and `freq`. + * Bands are stored in an array, with indices 0 - 3, or 0 - 7 + * @property {Array} bands + * + */ + this.bands = []; + var freq, res; + for (var i = 0; i < _eqsize; i++) { + if (i === _eqsize - 1) { + freq = 21000; + res = 0.01; + } else if (i === 0) { + freq = 100; + res = 0.1; + } else if (i === 1) { + freq = _eqsize === 3 ? 360 * factor : 360; + res = 1; + } else { + freq = this.bands[i - 1].freq() * factor; + res = 1; + } + this.bands[i] = this._newBand(freq, res); + if (i > 0) { + this.bands[i - 1].connect(this.bands[i].biquad); + } else { + this.input.connect(this.bands[i].biquad); + } + } + this.bands[_eqsize - 1].connect(this.output); + }; + p5.EQ.prototype = Object.create(Effect.prototype); + /** + * Process an input by connecting it to the EQ + * @method process + * @param {Object} src Audio source + */ + p5.EQ.prototype.process = function (src) { + src.connect(this.input); + }; + // /** + // * Set the frequency and gain of each band in the EQ. This method should be + // * called with 3 or 8 frequency and gain pairs, depending on the size of the EQ. + // * ex. eq.set(freq0, gain0, freq1, gain1, freq2, gain2); + // * + // * @method set + // * @param {Number} [freq0] Frequency value for band with index 0 + // * @param {Number} [gain0] Gain value for band with index 0 + // * @param {Number} [freq1] Frequency value for band with index 1 + // * @param {Number} [gain1] Gain value for band with index 1 + // * @param {Number} [freq2] Frequency value for band with index 2 + // * @param {Number} [gain2] Gain value for band with index 2 + // * @param {Number} [freq3] Frequency value for band with index 3 + // * @param {Number} [gain3] Gain value for band with index 3 + // * @param {Number} [freq4] Frequency value for band with index 4 + // * @param {Number} [gain4] Gain value for band with index 4 + // * @param {Number} [freq5] Frequency value for band with index 5 + // * @param {Number} [gain5] Gain value for band with index 5 + // * @param {Number} [freq6] Frequency value for band with index 6 + // * @param {Number} [gain6] Gain value for band with index 6 + // * @param {Number} [freq7] Frequency value for band with index 7 + // * @param {Number} [gain7] Gain value for band with index 7 + // */ + p5.EQ.prototype.set = function () { + if (arguments.length === this.bands.length * 2) { + for (var i = 0; i < arguments.length; i += 2) { + this.bands[i / 2].freq(arguments[i]); + this.bands[i / 2].gain(arguments[i + 1]); + } + } else { + console.error('Argument mismatch. .set() should be called with ' + this.bands.length * 2 + ' arguments. (one frequency and gain value pair for each band of the eq)'); + } + }; + /** + * Add a new band. Creates a p5.Filter and strips away everything but + * the raw biquad filter. This method returns an abstracted p5.Filter, + * which can be added to p5.EQ.bands, in order to create new EQ bands. + * @private + * @method _newBand + * @param {Number} freq + * @param {Number} res + * @return {Object} Abstracted Filter + */ + p5.EQ.prototype._newBand = function (freq, res) { + return new EQFilter(freq, res); + }; + p5.EQ.prototype.dispose = function () { + Effect.prototype.dispose.apply(this); + if (this.bands) { + while (this.bands.length > 0) { + delete this.bands.pop().dispose(); + } + delete this.bands; + } + }; + return p5.EQ; +}(effect, src_eqFilter); +var panner3d; +'use strict'; +panner3d = function () { + var p5sound = master; + var Effect = effect; + /** + * Panner3D is based on the + * Web Audio Spatial Panner Node. + * This panner is a spatial processing node that allows audio to be positioned + * and oriented in 3D space. + * + * The position is relative to an + * Audio Context Listener, which can be accessed + * by p5.soundOut.audiocontext.listener + * + * + * @class p5.Panner3D + * @constructor + */ + p5.Panner3D = function () { + Effect.call(this); + /** + * + * Web Audio Spatial Panner Node + * + * Properties include + * - panningModel: "equal power" or "HRTF" + * - distanceModel: "linear", "inverse", or "exponential" + * + * @property {AudioNode} panner + * + */ + this.panner = this.ac.createPanner(); + this.panner.panningModel = 'HRTF'; + this.panner.distanceModel = 'linear'; + this.panner.connect(this.output); + this.input.connect(this.panner); + }; + p5.Panner3D.prototype = Object.create(Effect.prototype); + /** + * Connect an audio sorce + * + * @method process + * @param {Object} src Input source + */ + p5.Panner3D.prototype.process = function (src) { + src.connect(this.input); + }; + /** + * Set the X,Y,Z position of the Panner + * @method set + * @param {Number} xVal + * @param {Number} yVal + * @param {Number} zVal + * @param {Number} time + * @return {Array} Updated x, y, z values as an array + */ + p5.Panner3D.prototype.set = function (xVal, yVal, zVal, time) { + this.positionX(xVal, time); + this.positionY(yVal, time); + this.positionZ(zVal, time); + return [ + this.panner.positionX.value, + this.panner.positionY.value, + this.panner.positionZ.value + ]; + }; + /** + * Getter and setter methods for position coordinates + * @method positionX + * @return {Number} updated coordinate value + */ + /** + * Getter and setter methods for position coordinates + * @method positionY + * @return {Number} updated coordinate value + */ + /** + * Getter and setter methods for position coordinates + * @method positionZ + * @return {Number} updated coordinate value + */ + p5.Panner3D.prototype.positionX = function (xVal, time) { + var t = time || 0; + if (typeof xVal === 'number') { + this.panner.positionX.value = xVal; + this.panner.positionX.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.panner.positionX.linearRampToValueAtTime(xVal, this.ac.currentTime + 0.02 + t); + } else if (xVal) { + xVal.connect(this.panner.positionX); + } + return this.panner.positionX.value; + }; + p5.Panner3D.prototype.positionY = function (yVal, time) { + var t = time || 0; + if (typeof yVal === 'number') { + this.panner.positionY.value = yVal; + this.panner.positionY.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.panner.positionY.linearRampToValueAtTime(yVal, this.ac.currentTime + 0.02 + t); + } else if (yVal) { + yVal.connect(this.panner.positionY); + } + return this.panner.positionY.value; + }; + p5.Panner3D.prototype.positionZ = function (zVal, time) { + var t = time || 0; + if (typeof zVal === 'number') { + this.panner.positionZ.value = zVal; + this.panner.positionZ.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.panner.positionZ.linearRampToValueAtTime(zVal, this.ac.currentTime + 0.02 + t); + } else if (zVal) { + zVal.connect(this.panner.positionZ); + } + return this.panner.positionZ.value; + }; + /** + * Set the X,Y,Z position of the Panner + * @method orient + * @param {Number} xVal + * @param {Number} yVal + * @param {Number} zVal + * @param {Number} time + * @return {Array} Updated x, y, z values as an array + */ + p5.Panner3D.prototype.orient = function (xVal, yVal, zVal, time) { + this.orientX(xVal, time); + this.orientY(yVal, time); + this.orientZ(zVal, time); + return [ + this.panner.orientationX.value, + this.panner.orientationY.value, + this.panner.orientationZ.value + ]; + }; + /** + * Getter and setter methods for orient coordinates + * @method orientX + * @return {Number} updated coordinate value + */ + /** + * Getter and setter methods for orient coordinates + * @method orientY + * @return {Number} updated coordinate value + */ + /** + * Getter and setter methods for orient coordinates + * @method orientZ + * @return {Number} updated coordinate value + */ + p5.Panner3D.prototype.orientX = function (xVal, time) { + var t = time || 0; + if (typeof xVal === 'number') { + this.panner.orientationX.value = xVal; + this.panner.orientationX.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.panner.orientationX.linearRampToValueAtTime(xVal, this.ac.currentTime + 0.02 + t); + } else if (xVal) { + xVal.connect(this.panner.orientationX); + } + return this.panner.orientationX.value; + }; + p5.Panner3D.prototype.orientY = function (yVal, time) { + var t = time || 0; + if (typeof yVal === 'number') { + this.panner.orientationY.value = yVal; + this.panner.orientationY.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.panner.orientationY.linearRampToValueAtTime(yVal, this.ac.currentTime + 0.02 + t); + } else if (yVal) { + yVal.connect(this.panner.orientationY); + } + return this.panner.orientationY.value; + }; + p5.Panner3D.prototype.orientZ = function (zVal, time) { + var t = time || 0; + if (typeof zVal === 'number') { + this.panner.orientationZ.value = zVal; + this.panner.orientationZ.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.panner.orientationZ.linearRampToValueAtTime(zVal, this.ac.currentTime + 0.02 + t); + } else if (zVal) { + zVal.connect(this.panner.orientationZ); + } + return this.panner.orientationZ.value; + }; + /** + * Set the rolloff factor and max distance + * @method setFalloff + * @param {Number} [maxDistance] + * @param {Number} [rolloffFactor] + */ + p5.Panner3D.prototype.setFalloff = function (maxDistance, rolloffFactor) { + this.maxDist(maxDistance); + this.rolloff(rolloffFactor); + }; + /** + * Maxium distance between the source and the listener + * @method maxDist + * @param {Number} maxDistance + * @return {Number} updated value + */ + p5.Panner3D.prototype.maxDist = function (maxDistance) { + if (typeof maxDistance === 'number') { + this.panner.maxDistance = maxDistance; + } + return this.panner.maxDistance; + }; + /** + * How quickly the volume is reduced as the source moves away from the listener + * @method rollof + * @param {Number} rolloffFactor + * @return {Number} updated value + */ + p5.Panner3D.prototype.rolloff = function (rolloffFactor) { + if (typeof rolloffFactor === 'number') { + this.panner.rolloffFactor = rolloffFactor; + } + return this.panner.rolloffFactor; + }; + p5.Panner3D.dispose = function () { + Effect.prototype.dispose.apply(this); + if (this.panner) { + this.panner.disconnect(); + delete this.panner; + } + }; + return p5.Panner3D; +}(master, effect); +var listener3d; +'use strict'; +listener3d = function () { + var p5sound = master; + var Effect = effect; + // /** + // * listener is a class that can construct both a Spatial Panner + // * and a Spatial Listener. The panner is based on the + // * Web Audio Spatial Panner Node + // * https://www.w3.org/TR/webaudio/#the-listenernode-interface + // * This panner is a spatial processing node that allows audio to be positioned + // * and oriented in 3D space. + // * + // * The Listener modifies the properties of the Audio Context Listener. + // * Both objects types use the same methods. The default is a spatial panner. + // * + // * p5.Panner3D - Constructs a Spatial Panner
+ // * p5.Listener3D - Constructs a Spatial Listener
+ // * + // * @class listener + // * @constructor + // * @return {Object} p5.Listener3D Object + // * + // * @param {Web Audio Node} listener Web Audio Spatial Panning Node + // * @param {AudioParam} listener.panningModel "equal power" or "HRTF" + // * @param {AudioParam} listener.distanceModel "linear", "inverse", or "exponential" + // * @param {String} [type] [Specify construction of a spatial panner or listener] + // */ + p5.Listener3D = function (type) { + this.ac = p5sound.audiocontext; + this.listener = this.ac.listener; + }; + // /** + // * Connect an audio sorce + // * @param {Object} src Input source + // */ + p5.Listener3D.prototype.process = function (src) { + src.connect(this.input); + }; + // /** + // * Set the X,Y,Z position of the Panner + // * @param {[Number]} xVal + // * @param {[Number]} yVal + // * @param {[Number]} zVal + // * @param {[Number]} time + // * @return {[Array]} [Updated x, y, z values as an array] + // */ + p5.Listener3D.prototype.position = function (xVal, yVal, zVal, time) { + this.positionX(xVal, time); + this.positionY(yVal, time); + this.positionZ(zVal, time); + return [ + this.listener.positionX.value, + this.listener.positionY.value, + this.listener.positionZ.value + ]; + }; + // /** + // * Getter and setter methods for position coordinates + // * @return {Number} [updated coordinate value] + // */ + p5.Listener3D.prototype.positionX = function (xVal, time) { + var t = time || 0; + if (typeof xVal === 'number') { + this.listener.positionX.value = xVal; + this.listener.positionX.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.listener.positionX.linearRampToValueAtTime(xVal, this.ac.currentTime + 0.02 + t); + } else if (xVal) { + xVal.connect(this.listener.positionX); + } + return this.listener.positionX.value; + }; + p5.Listener3D.prototype.positionY = function (yVal, time) { + var t = time || 0; + if (typeof yVal === 'number') { + this.listener.positionY.value = yVal; + this.listener.positionY.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.listener.positionY.linearRampToValueAtTime(yVal, this.ac.currentTime + 0.02 + t); + } else if (yVal) { + yVal.connect(this.listener.positionY); + } + return this.listener.positionY.value; + }; + p5.Listener3D.prototype.positionZ = function (zVal, time) { + var t = time || 0; + if (typeof zVal === 'number') { + this.listener.positionZ.value = zVal; + this.listener.positionZ.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.listener.positionZ.linearRampToValueAtTime(zVal, this.ac.currentTime + 0.02 + t); + } else if (zVal) { + zVal.connect(this.listener.positionZ); + } + return this.listener.positionZ.value; + }; + // cannot define method when class definition is commented + // /** + // * Overrides the listener orient() method because Listener has slightly + // * different params. In human terms, Forward vectors are the direction the + // * nose is pointing. Up vectors are the direction of the top of the head. + // * + // * @method orient + // * @param {Number} xValF Forward vector X direction + // * @param {Number} yValF Forward vector Y direction + // * @param {Number} zValF Forward vector Z direction + // * @param {Number} xValU Up vector X direction + // * @param {Number} yValU Up vector Y direction + // * @param {Number} zValU Up vector Z direction + // * @param {Number} time + // * @return {Array} All orienation params + // */ + p5.Listener3D.prototype.orient = function (xValF, yValF, zValF, xValU, yValU, zValU, time) { + if (arguments.length === 3 || arguments.length === 4) { + time = arguments[3]; + this.orientForward(xValF, yValF, zValF, time); + } else if (arguments.length === 6 || arguments === 7) { + this.orientForward(xValF, yValF, zValF); + this.orientUp(xValU, yValU, zValU, time); + } + return [ + this.listener.forwardX.value, + this.listener.forwardY.value, + this.listener.forwardZ.value, + this.listener.upX.value, + this.listener.upY.value, + this.listener.upZ.value + ]; + }; + p5.Listener3D.prototype.orientForward = function (xValF, yValF, zValF, time) { + this.forwardX(xValF, time); + this.forwardY(yValF, time); + this.forwardZ(zValF, time); + return [ + this.listener.forwardX, + this.listener.forwardY, + this.listener.forwardZ + ]; + }; + p5.Listener3D.prototype.orientUp = function (xValU, yValU, zValU, time) { + this.upX(xValU, time); + this.upY(yValU, time); + this.upZ(zValU, time); + return [ + this.listener.upX, + this.listener.upY, + this.listener.upZ + ]; + }; + // /** + // * Getter and setter methods for orient coordinates + // * @return {Number} [updated coordinate value] + // */ + p5.Listener3D.prototype.forwardX = function (xVal, time) { + var t = time || 0; + if (typeof xVal === 'number') { + this.listener.forwardX.value = xVal; + this.listener.forwardX.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.listener.forwardX.linearRampToValueAtTime(xVal, this.ac.currentTime + 0.02 + t); + } else if (xVal) { + xVal.connect(this.listener.forwardX); + } + return this.listener.forwardX.value; + }; + p5.Listener3D.prototype.forwardY = function (yVal, time) { + var t = time || 0; + if (typeof yVal === 'number') { + this.listener.forwardY.value = yVal; + this.listener.forwardY.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.listener.forwardY.linearRampToValueAtTime(yVal, this.ac.currentTime + 0.02 + t); + } else if (yVal) { + yVal.connect(this.listener.forwardY); + } + return this.listener.forwardY.value; + }; + p5.Listener3D.prototype.forwardZ = function (zVal, time) { + var t = time || 0; + if (typeof zVal === 'number') { + this.listener.forwardZ.value = zVal; + this.listener.forwardZ.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.listener.forwardZ.linearRampToValueAtTime(zVal, this.ac.currentTime + 0.02 + t); + } else if (zVal) { + zVal.connect(this.listener.forwardZ); + } + return this.listener.forwardZ.value; + }; + p5.Listener3D.prototype.upX = function (xVal, time) { + var t = time || 0; + if (typeof xVal === 'number') { + this.listener.upX.value = xVal; + this.listener.upX.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.listener.upX.linearRampToValueAtTime(xVal, this.ac.currentTime + 0.02 + t); + } else if (xVal) { + xVal.connect(this.listener.upX); + } + return this.listener.upX.value; + }; + p5.Listener3D.prototype.upY = function (yVal, time) { + var t = time || 0; + if (typeof yVal === 'number') { + this.listener.upY.value = yVal; + this.listener.upY.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.listener.upY.linearRampToValueAtTime(yVal, this.ac.currentTime + 0.02 + t); + } else if (yVal) { + yVal.connect(this.listener.upY); + } + return this.listener.upY.value; + }; + p5.Listener3D.prototype.upZ = function (zVal, time) { + var t = time || 0; + if (typeof zVal === 'number') { + this.listener.upZ.value = zVal; + this.listener.upZ.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.listener.upZ.linearRampToValueAtTime(zVal, this.ac.currentTime + 0.02 + t); + } else if (zVal) { + zVal.connect(this.listener.upZ); + } + return this.listener.upZ.value; + }; + return p5.Listener3D; +}(master, effect); +var delay; +'use strict'; +delay = function () { + var Filter = filter; + var Effect = effect; + /** + * Delay is an echo effect. It processes an existing sound source, + * and outputs a delayed version of that sound. The p5.Delay can + * produce different effects depending on the delayTime, feedback, + * filter, and type. In the example below, a feedback of 0.5 (the + * defaul value) will produce a looping delay that decreases in + * volume by 50% each repeat. A filter will cut out the high + * frequencies so that the delay does not sound as piercing as the + * original source. + * + * + * This class extends p5.Effect. + * Methods amp(), chain(), + * drywet(), connect(), and + * disconnect() are available. + * @class p5.Delay + * @extends p5.Effect + * @constructor + * @example + *
+ * var noise, env, delay; + * + * function setup() { + * background(0); + * noStroke(); + * fill(255); + * textAlign(CENTER); + * text('click to play', width/2, height/2); + * + * noise = new p5.Noise('brown'); + * noise.amp(0); + * noise.start(); + * + * delay = new p5.Delay(); + * + * // delay.process() accepts 4 parameters: + * // source, delayTime, feedback, filter frequency + * // play with these numbers!! + * delay.process(noise, .12, .7, 2300); + * + * // play the noise with an envelope, + * // a series of fades ( time / value pairs ) + * env = new p5.Envelope(.01, 0.2, .2, .1); + * } + * + * // mouseClick triggers envelope + * function mouseClicked() { + * // is mouse over canvas? + * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { + * env.play(noise); + * } + * } + *
+ */ + p5.Delay = function () { + Effect.call(this); + this._split = this.ac.createChannelSplitter(2); + this._merge = this.ac.createChannelMerger(2); + this._leftGain = this.ac.createGain(); + this._rightGain = this.ac.createGain(); + /** + * The p5.Delay is built with two + * + * Web Audio Delay Nodes, one for each stereo channel. + * + * @property {DelayNode} leftDelay + */ + this.leftDelay = this.ac.createDelay(); + /** + * The p5.Delay is built with two + * + * Web Audio Delay Nodes, one for each stereo channel. + * + * @property {DelayNode} rightDelay + */ + this.rightDelay = this.ac.createDelay(); + this._leftFilter = new Filter(); + this._rightFilter = new Filter(); + this._leftFilter.disconnect(); + this._rightFilter.disconnect(); + this._leftFilter.biquad.frequency.setValueAtTime(1200, this.ac.currentTime); + this._rightFilter.biquad.frequency.setValueAtTime(1200, this.ac.currentTime); + this._leftFilter.biquad.Q.setValueAtTime(0.3, this.ac.currentTime); + this._rightFilter.biquad.Q.setValueAtTime(0.3, this.ac.currentTime); + // graph routing + this.input.connect(this._split); + this.leftDelay.connect(this._leftGain); + this.rightDelay.connect(this._rightGain); + this._leftGain.connect(this._leftFilter.input); + this._rightGain.connect(this._rightFilter.input); + this._merge.connect(this.wet); + this._leftFilter.biquad.gain.setValueAtTime(1, this.ac.currentTime); + this._rightFilter.biquad.gain.setValueAtTime(1, this.ac.currentTime); + // default routing + this.setType(0); + this._maxDelay = this.leftDelay.delayTime.maxValue; + // set initial feedback to 0.5 + this.feedback(0.5); + }; + p5.Delay.prototype = Object.create(Effect.prototype); + /** + * Add delay to an audio signal according to a set + * of delay parameters. + * + * @method process + * @param {Object} Signal An object that outputs audio + * @param {Number} [delayTime] Time (in seconds) of the delay/echo. + * Some browsers limit delayTime to + * 1 second. + * @param {Number} [feedback] sends the delay back through itself + * in a loop that decreases in volume + * each time. + * @param {Number} [lowPass] Cutoff frequency. Only frequencies + * below the lowPass will be part of the + * delay. + */ + p5.Delay.prototype.process = function (src, _delayTime, _feedback, _filter) { + var feedback = _feedback || 0; + var delayTime = _delayTime || 0; + if (feedback >= 1) { + throw new Error('Feedback value will force a positive feedback loop.'); + } + if (delayTime >= this._maxDelay) { + throw new Error('Delay Time exceeds maximum delay time of ' + this._maxDelay + ' second.'); + } + src.connect(this.input); + this.leftDelay.delayTime.setValueAtTime(delayTime, this.ac.currentTime); + this.rightDelay.delayTime.setValueAtTime(delayTime, this.ac.currentTime); + this._leftGain.gain.value = feedback; + this._rightGain.gain.value = feedback; + if (_filter) { + this._leftFilter.freq(_filter); + this._rightFilter.freq(_filter); + } + }; + /** + * Set the delay (echo) time, in seconds. Usually this value will be + * a floating point number between 0.0 and 1.0. + * + * @method delayTime + * @param {Number} delayTime Time (in seconds) of the delay + */ + p5.Delay.prototype.delayTime = function (t) { + // if t is an audio node... + if (typeof t !== 'number') { + t.connect(this.leftDelay.delayTime); + t.connect(this.rightDelay.delayTime); + } else { + this.leftDelay.delayTime.cancelScheduledValues(this.ac.currentTime); + this.rightDelay.delayTime.cancelScheduledValues(this.ac.currentTime); + this.leftDelay.delayTime.linearRampToValueAtTime(t, this.ac.currentTime); + this.rightDelay.delayTime.linearRampToValueAtTime(t, this.ac.currentTime); + } + }; + /** + * Feedback occurs when Delay sends its signal back through its input + * in a loop. The feedback amount determines how much signal to send each + * time through the loop. A feedback greater than 1.0 is not desirable because + * it will increase the overall output each time through the loop, + * creating an infinite feedback loop. The default value is 0.5 + * + * @method feedback + * @param {Number|Object} feedback 0.0 to 1.0, or an object such as an + * Oscillator that can be used to + * modulate this param + * @returns {Number} Feedback value + * + */ + p5.Delay.prototype.feedback = function (f) { + // if f is an audio node... + if (f && typeof f !== 'number') { + f.connect(this._leftGain.gain); + f.connect(this._rightGain.gain); + } else if (f >= 1) { + throw new Error('Feedback value will force a positive feedback loop.'); + } else if (typeof f === 'number') { + this._leftGain.gain.value = f; + this._rightGain.gain.value = f; + } + // return value of feedback + return this._leftGain.gain.value; + }; + /** + * Set a lowpass filter frequency for the delay. A lowpass filter + * will cut off any frequencies higher than the filter frequency. + * + * @method filter + * @param {Number|Object} cutoffFreq A lowpass filter will cut off any + * frequencies higher than the filter frequency. + * @param {Number|Object} res Resonance of the filter frequency + * cutoff, or an object (i.e. a p5.Oscillator) + * that can be used to modulate this parameter. + * High numbers (i.e. 15) will produce a resonance, + * low numbers (i.e. .2) will produce a slope. + */ + p5.Delay.prototype.filter = function (freq, q) { + this._leftFilter.set(freq, q); + this._rightFilter.set(freq, q); + }; + /** + * Choose a preset type of delay. 'pingPong' bounces the signal + * from the left to the right channel to produce a stereo effect. + * Any other parameter will revert to the default delay setting. + * + * @method setType + * @param {String|Number} type 'pingPong' (1) or 'default' (0) + */ + p5.Delay.prototype.setType = function (t) { + if (t === 1) { + t = 'pingPong'; + } + this._split.disconnect(); + this._leftFilter.disconnect(); + this._rightFilter.disconnect(); + this._split.connect(this.leftDelay, 0); + this._split.connect(this.rightDelay, 1); + switch (t) { + case 'pingPong': + this._rightFilter.setType(this._leftFilter.biquad.type); + this._leftFilter.output.connect(this._merge, 0, 0); + this._rightFilter.output.connect(this._merge, 0, 1); + this._leftFilter.output.connect(this.rightDelay); + this._rightFilter.output.connect(this.leftDelay); + break; + default: + this._leftFilter.output.connect(this._merge, 0, 0); + this._rightFilter.output.connect(this._merge, 0, 1); + this._leftFilter.output.connect(this.leftDelay); + this._rightFilter.output.connect(this.rightDelay); + } + }; + // DocBlocks for methods inherited from p5.Effect + /** + * Set the output level of the delay effect. + * + * @method amp + * @param {Number} volume amplitude between 0 and 1.0 + * @param {Number} [rampTime] create a fade that lasts rampTime + * @param {Number} [timeFromNow] schedule this event to happen + * seconds from now + */ + /** + * Send output to a p5.sound or web audio object + * + * @method connect + * @param {Object} unit + */ + /** + * Disconnect all output. + * + * @method disconnect + */ + p5.Delay.prototype.dispose = function () { + Effect.prototype.dispose.apply(this); + this._split.disconnect(); + this._leftFilter.dispose(); + this._rightFilter.dispose(); + this._merge.disconnect(); + this._leftGain.disconnect(); + this._rightGain.disconnect(); + this.leftDelay.disconnect(); + this.rightDelay.disconnect(); + this._split = undefined; + this._leftFilter = undefined; + this._rightFilter = undefined; + this._merge = undefined; + this._leftGain = undefined; + this._rightGain = undefined; + this.leftDelay = undefined; + this.rightDelay = undefined; + }; +}(filter, effect); +var reverb; +'use strict'; +reverb = function () { + var CustomError = errorHandler; + var Effect = effect; + /** + * Reverb adds depth to a sound through a large number of decaying + * echoes. It creates the perception that sound is occurring in a + * physical space. The p5.Reverb has paramters for Time (how long does the + * reverb last) and decayRate (how much the sound decays with each echo) + * that can be set with the .set() or .process() methods. The p5.Convolver + * extends p5.Reverb allowing you to recreate the sound of actual physical + * spaces through convolution. + * + * This class extends p5.Effect. + * Methods amp(), chain(), + * drywet(), connect(), and + * disconnect() are available. + * + * @class p5.Reverb + * @extends p5.Effect + * @constructor + * @example + *
+ * var soundFile, reverb; + * function preload() { + * soundFile = loadSound('assets/Damscray_DancingTiger.mp3'); + * } + * + * function setup() { + * reverb = new p5.Reverb(); + * soundFile.disconnect(); // so we'll only hear reverb... + * + * // connect soundFile to reverb, process w/ + * // 3 second reverbTime, decayRate of 2% + * reverb.process(soundFile, 3, 2); + * soundFile.play(); + * } + *
+ */ + p5.Reverb = function () { + Effect.call(this); + this._initConvolverNode(); + // otherwise, Safari distorts + this.input.gain.value = 0.5; + // default params + this._seconds = 3; + this._decay = 2; + this._reverse = false; + this._buildImpulse(); + }; + p5.Reverb.prototype = Object.create(Effect.prototype); + p5.Reverb.prototype._initConvolverNode = function () { + this.convolverNode = this.ac.createConvolver(); + this.input.connect(this.convolverNode); + this.convolverNode.connect(this.wet); + }; + p5.Reverb.prototype._teardownConvolverNode = function () { + if (this.convolverNode) { + this.convolverNode.disconnect(); + delete this.convolverNode; + } + }; + p5.Reverb.prototype._setBuffer = function (audioBuffer) { + this._teardownConvolverNode(); + this._initConvolverNode(); + this.convolverNode.buffer = audioBuffer; + }; + /** + * Connect a source to the reverb, and assign reverb parameters. + * + * @method process + * @param {Object} src p5.sound / Web Audio object with a sound + * output. + * @param {Number} [seconds] Duration of the reverb, in seconds. + * Min: 0, Max: 10. Defaults to 3. + * @param {Number} [decayRate] Percentage of decay with each echo. + * Min: 0, Max: 100. Defaults to 2. + * @param {Boolean} [reverse] Play the reverb backwards or forwards. + */ + p5.Reverb.prototype.process = function (src, seconds, decayRate, reverse) { + src.connect(this.input); + var rebuild = false; + if (seconds) { + this._seconds = seconds; + rebuild = true; + } + if (decayRate) { + this._decay = decayRate; + } + if (reverse) { + this._reverse = reverse; + } + if (rebuild) { + this._buildImpulse(); + } + }; + /** + * Set the reverb settings. Similar to .process(), but without + * assigning a new input. + * + * @method set + * @param {Number} [seconds] Duration of the reverb, in seconds. + * Min: 0, Max: 10. Defaults to 3. + * @param {Number} [decayRate] Percentage of decay with each echo. + * Min: 0, Max: 100. Defaults to 2. + * @param {Boolean} [reverse] Play the reverb backwards or forwards. + */ + p5.Reverb.prototype.set = function (seconds, decayRate, reverse) { + var rebuild = false; + if (seconds) { + this._seconds = seconds; + rebuild = true; + } + if (decayRate) { + this._decay = decayRate; + } + if (reverse) { + this._reverse = reverse; + } + if (rebuild) { + this._buildImpulse(); + } + }; + // DocBlocks for methods inherited from p5.Effect + /** + * Set the output level of the reverb effect. + * + * @method amp + * @param {Number} volume amplitude between 0 and 1.0 + * @param {Number} [rampTime] create a fade that lasts rampTime + * @param {Number} [timeFromNow] schedule this event to happen + * seconds from now + */ + /** + * Send output to a p5.sound or web audio object + * + * @method connect + * @param {Object} unit + */ + /** + * Disconnect all output. + * + * @method disconnect + */ + /** + * Inspired by Simple Reverb by Jordan Santell + * https://github.com/web-audio-components/simple-reverb/blob/master/index.js + * + * Utility function for building an impulse response + * based on the module parameters. + * + * @private + */ + p5.Reverb.prototype._buildImpulse = function () { + var rate = this.ac.sampleRate; + var length = rate * this._seconds; + var decay = this._decay; + var impulse = this.ac.createBuffer(2, length, rate); + var impulseL = impulse.getChannelData(0); + var impulseR = impulse.getChannelData(1); + var n, i; + for (i = 0; i < length; i++) { + n = this._reverse ? length - i : i; + impulseL[i] = (Math.random() * 2 - 1) * Math.pow(1 - n / length, decay); + impulseR[i] = (Math.random() * 2 - 1) * Math.pow(1 - n / length, decay); + } + this._setBuffer(impulse); + }; + p5.Reverb.prototype.dispose = function () { + Effect.prototype.dispose.apply(this); + this._teardownConvolverNode(); + }; + // ======================================================================= + // *** p5.Convolver *** + // ======================================================================= + /** + *

p5.Convolver extends p5.Reverb. It can emulate the sound of real + * physical spaces through a process called + * convolution.

+ * + *

Convolution multiplies any audio input by an "impulse response" + * to simulate the dispersion of sound over time. The impulse response is + * generated from an audio file that you provide. One way to + * generate an impulse response is to pop a balloon in a reverberant space + * and record the echo. Convolution can also be used to experiment with + * sound.

+ * + *

Use the method createConvolution(path) to instantiate a + * p5.Convolver with a path to your impulse response audio file.

+ * + * @class p5.Convolver + * @extends p5.Effect + * @constructor + * @param {String} path path to a sound file + * @param {Function} [callback] function to call when loading succeeds + * @param {Function} [errorCallback] function to call if loading fails. + * This function will receive an error or + * XMLHttpRequest object with information + * about what went wrong. + * @example + *
+ * var cVerb, sound; + * function preload() { + * // We have both MP3 and OGG versions of all sound assets + * soundFormats('ogg', 'mp3'); + * + * // Try replacing 'bx-spring' with other soundfiles like + * // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox' + * cVerb = createConvolver('assets/bx-spring.mp3'); + * + * // Try replacing 'Damscray_DancingTiger' with + * // 'beat', 'doorbell', lucky_dragons_-_power_melody' + * sound = loadSound('assets/Damscray_DancingTiger.mp3'); + * } + * + * function setup() { + * // disconnect from master output... + * sound.disconnect(); + * + * // ...and process with cVerb + * // so that we only hear the convolution + * cVerb.process(sound); + * + * sound.play(); + * } + *
+ */ + p5.Convolver = function (path, callback, errorCallback) { + p5.Reverb.call(this); + /** + * Internally, the p5.Convolver uses the a + * + * Web Audio Convolver Node. + * + * @property {ConvolverNode} convolverNode + */ + this._initConvolverNode(); + // otherwise, Safari distorts + this.input.gain.value = 0.5; + if (path) { + this.impulses = []; + this._loadBuffer(path, callback, errorCallback); + } else { + // parameters + this._seconds = 3; + this._decay = 2; + this._reverse = false; + this._buildImpulse(); + } + }; + p5.Convolver.prototype = Object.create(p5.Reverb.prototype); + p5.prototype.registerPreloadMethod('createConvolver', p5.prototype); + /** + * Create a p5.Convolver. Accepts a path to a soundfile + * that will be used to generate an impulse response. + * + * @method createConvolver + * @param {String} path path to a sound file + * @param {Function} [callback] function to call if loading is successful. + * The object will be passed in as the argument + * to the callback function. + * @param {Function} [errorCallback] function to call if loading is not successful. + * A custom error will be passed in as the argument + * to the callback function. + * @return {p5.Convolver} + * @example + *
+ * var cVerb, sound; + * function preload() { + * // We have both MP3 and OGG versions of all sound assets + * soundFormats('ogg', 'mp3'); + * + * // Try replacing 'bx-spring' with other soundfiles like + * // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox' + * cVerb = createConvolver('assets/bx-spring.mp3'); + * + * // Try replacing 'Damscray_DancingTiger' with + * // 'beat', 'doorbell', lucky_dragons_-_power_melody' + * sound = loadSound('assets/Damscray_DancingTiger.mp3'); + * } + * + * function setup() { + * // disconnect from master output... + * sound.disconnect(); + * + * // ...and process with cVerb + * // so that we only hear the convolution + * cVerb.process(sound); + * + * sound.play(); + * } + *
+ */ + p5.prototype.createConvolver = function (path, callback, errorCallback) { + // if loading locally without a server + if (window.location.origin.indexOf('file://') > -1 && window.cordova === 'undefined') { + alert('This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS'); + } + var self = this; + var cReverb = new p5.Convolver(path, function (buffer) { + if (typeof callback === 'function') { + callback(buffer); + } + if (typeof self._decrementPreload === 'function') { + self._decrementPreload(); + } + }, errorCallback); + cReverb.impulses = []; + return cReverb; + }; + /** + * Private method to load a buffer as an Impulse Response, + * assign it to the convolverNode, and add to the Array of .impulses. + * + * @param {String} path + * @param {Function} callback + * @param {Function} errorCallback + * @private + */ + p5.Convolver.prototype._loadBuffer = function (path, callback, errorCallback) { + var path = p5.prototype._checkFileFormats(path); + var self = this; + var errorTrace = new Error().stack; + var ac = p5.prototype.getAudioContext(); + var request = new XMLHttpRequest(); + request.open('GET', path, true); + request.responseType = 'arraybuffer'; + request.onload = function () { + if (request.status === 200) { + // on success loading file: + ac.decodeAudioData(request.response, function (buff) { + var buffer = {}; + var chunks = path.split('/'); + buffer.name = chunks[chunks.length - 1]; + buffer.audioBuffer = buff; + self.impulses.push(buffer); + self._setBuffer(buffer.audioBuffer); + if (callback) { + callback(buffer); + } + }, // error decoding buffer. "e" is undefined in Chrome 11/22/2015 + function () { + var err = new CustomError('decodeAudioData', errorTrace, self.url); + var msg = 'AudioContext error at decodeAudioData for ' + self.url; + if (errorCallback) { + err.msg = msg; + errorCallback(err); + } else { + console.error(msg + '\n The error stack trace includes: \n' + err.stack); + } + }); + } else { + var err = new CustomError('loadConvolver', errorTrace, self.url); + var msg = 'Unable to load ' + self.url + '. The request status was: ' + request.status + ' (' + request.statusText + ')'; + if (errorCallback) { + err.message = msg; + errorCallback(err); + } else { + console.error(msg + '\n The error stack trace includes: \n' + err.stack); + } + } + }; + // if there is another error, aside from 404... + request.onerror = function () { + var err = new CustomError('loadConvolver', errorTrace, self.url); + var msg = 'There was no response from the server at ' + self.url + '. Check the url and internet connectivity.'; + if (errorCallback) { + err.message = msg; + errorCallback(err); + } else { + console.error(msg + '\n The error stack trace includes: \n' + err.stack); + } + }; + request.send(); + }; + p5.Convolver.prototype.set = null; + /** + * Connect a source to the reverb, and assign reverb parameters. + * + * @method process + * @param {Object} src p5.sound / Web Audio object with a sound + * output. + * @example + *
+ * var cVerb, sound; + * function preload() { + * soundFormats('ogg', 'mp3'); + * + * cVerb = createConvolver('assets/concrete-tunnel.mp3'); + * + * sound = loadSound('assets/beat.mp3'); + * } + * + * function setup() { + * // disconnect from master output... + * sound.disconnect(); + * + * // ...and process with (i.e. connect to) cVerb + * // so that we only hear the convolution + * cVerb.process(sound); + * + * sound.play(); + * } + *
+ */ + p5.Convolver.prototype.process = function (src) { + src.connect(this.input); + }; + /** + * If you load multiple impulse files using the .addImpulse method, + * they will be stored as Objects in this Array. Toggle between them + * with the toggleImpulse(id) method. + * + * @property {Array} impulses + */ + p5.Convolver.prototype.impulses = []; + /** + * Load and assign a new Impulse Response to the p5.Convolver. + * The impulse is added to the .impulses array. Previous + * impulses can be accessed with the .toggleImpulse(id) + * method. + * + * @method addImpulse + * @param {String} path path to a sound file + * @param {Function} callback function (optional) + * @param {Function} errorCallback function (optional) + */ + p5.Convolver.prototype.addImpulse = function (path, callback, errorCallback) { + // if loading locally without a server + if (window.location.origin.indexOf('file://') > -1 && window.cordova === 'undefined') { + alert('This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS'); + } + this._loadBuffer(path, callback, errorCallback); + }; + /** + * Similar to .addImpulse, except that the .impulses + * Array is reset to save memory. A new .impulses + * array is created with this impulse as the only item. + * + * @method resetImpulse + * @param {String} path path to a sound file + * @param {Function} callback function (optional) + * @param {Function} errorCallback function (optional) + */ + p5.Convolver.prototype.resetImpulse = function (path, callback, errorCallback) { + // if loading locally without a server + if (window.location.origin.indexOf('file://') > -1 && window.cordova === 'undefined') { + alert('This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS'); + } + this.impulses = []; + this._loadBuffer(path, callback, errorCallback); + }; + /** + * If you have used .addImpulse() to add multiple impulses + * to a p5.Convolver, then you can use this method to toggle between + * the items in the .impulses Array. Accepts a parameter + * to identify which impulse you wish to use, identified either by its + * original filename (String) or by its position in the .impulses + * Array (Number).
+ * You can access the objects in the .impulses Array directly. Each + * Object has two attributes: an .audioBuffer (type: + * Web Audio + * AudioBuffer) and a .name, a String that corresponds + * with the original filename. + * + * @method toggleImpulse + * @param {String|Number} id Identify the impulse by its original filename + * (String), or by its position in the + * .impulses Array (Number). + */ + p5.Convolver.prototype.toggleImpulse = function (id) { + if (typeof id === 'number' && id < this.impulses.length) { + this._setBuffer(this.impulses[id].audioBuffer); + } + if (typeof id === 'string') { + for (var i = 0; i < this.impulses.length; i++) { + if (this.impulses[i].name === id) { + this._setBuffer(this.impulses[i].audioBuffer); + break; + } + } + } + }; + p5.Convolver.prototype.dispose = function () { + p5.Reverb.prototype.dispose.apply(this); + // remove all the Impulse Response buffers + for (var i in this.impulses) { + if (this.impulses[i]) { + this.impulses[i] = null; + } + } + }; +}(errorHandler, effect); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_core_TimelineState; +Tone_core_TimelineState = function (Tone) { + 'use strict'; + Tone.TimelineState = function (initial) { + Tone.Timeline.call(this); + this._initial = initial; + }; + Tone.extend(Tone.TimelineState, Tone.Timeline); + Tone.TimelineState.prototype.getValueAtTime = function (time) { + var event = this.get(time); + if (event !== null) { + return event.state; + } else { + return this._initial; + } + }; + Tone.TimelineState.prototype.setStateAtTime = function (state, time) { + this.add({ + 'state': state, + 'time': time + }); + }; + return Tone.TimelineState; +}(Tone_core_Tone, Tone_core_Timeline); +/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ +var Tone_core_Clock; +Tone_core_Clock = function (Tone) { + 'use strict'; + Tone.Clock = function () { + Tone.Emitter.call(this); + var options = this.optionsObject(arguments, [ + 'callback', + 'frequency' + ], Tone.Clock.defaults); + this.callback = options.callback; + this._nextTick = 0; + this._lastState = Tone.State.Stopped; + this.frequency = new Tone.TimelineSignal(options.frequency, Tone.Type.Frequency); + this._readOnly('frequency'); + this.ticks = 0; + this._state = new Tone.TimelineState(Tone.State.Stopped); + this._boundLoop = this._loop.bind(this); + this.context.on('tick', this._boundLoop); + }; + Tone.extend(Tone.Clock, Tone.Emitter); + Tone.Clock.defaults = { + 'callback': Tone.noOp, + 'frequency': 1, + 'lookAhead': 'auto' + }; + Object.defineProperty(Tone.Clock.prototype, 'state', { + get: function () { + return this._state.getValueAtTime(this.now()); + } + }); + Tone.Clock.prototype.start = function (time, offset) { + time = this.toSeconds(time); + if (this._state.getValueAtTime(time) !== Tone.State.Started) { + this._state.add({ + 'state': Tone.State.Started, + 'time': time, + 'offset': offset + }); + } + return this; + }; + Tone.Clock.prototype.stop = function (time) { + time = this.toSeconds(time); + this._state.cancel(time); + this._state.setStateAtTime(Tone.State.Stopped, time); + return this; + }; + Tone.Clock.prototype.pause = function (time) { + time = this.toSeconds(time); + if (this._state.getValueAtTime(time) === Tone.State.Started) { + this._state.setStateAtTime(Tone.State.Paused, time); + } + return this; + }; + Tone.Clock.prototype._loop = function () { + var now = this.now(); + var lookAhead = this.context.lookAhead; + var updateInterval = this.context.updateInterval; + var lagCompensation = this.context.lag * 2; + var loopInterval = now + lookAhead + updateInterval + lagCompensation; + while (loopInterval > this._nextTick && this._state) { + var currentState = this._state.getValueAtTime(this._nextTick); + if (currentState !== this._lastState) { + this._lastState = currentState; + var event = this._state.get(this._nextTick); + if (currentState === Tone.State.Started) { + this._nextTick = event.time; + if (!this.isUndef(event.offset)) { + this.ticks = event.offset; + } + this.emit('start', event.time, this.ticks); + } else if (currentState === Tone.State.Stopped) { + this.ticks = 0; + this.emit('stop', event.time); + } else if (currentState === Tone.State.Paused) { + this.emit('pause', event.time); + } + } + var tickTime = this._nextTick; + if (this.frequency) { + this._nextTick += 1 / this.frequency.getValueAtTime(this._nextTick); + if (currentState === Tone.State.Started) { + this.callback(tickTime); + this.ticks++; + } + } + } + }; + Tone.Clock.prototype.getStateAtTime = function (time) { + time = this.toSeconds(time); + return this._state.getValueAtTime(time); + }; + Tone.Clock.prototype.dispose = function () { + Tone.Emitter.prototype.dispose.call(this); + this.context.off('tick', this._boundLoop); + this._writable('frequency'); + this.frequency.dispose(); + this.frequency = null; + this._boundLoop = null; + this._nextTick = Infinity; + this.callback = null; + this._state.dispose(); + this._state = null; + }; + return Tone.Clock; +}(Tone_core_Tone, Tone_signal_TimelineSignal, Tone_core_TimelineState, Tone_core_Emitter); +var metro; +'use strict'; +metro = function () { + var p5sound = master; + // requires the Tone.js library's Clock (MIT license, Yotam Mann) + // https://github.com/TONEnoTONE/Tone.js/ + var Clock = Tone_core_Clock; + p5.Metro = function () { + this.clock = new Clock({ 'callback': this.ontick.bind(this) }); + this.syncedParts = []; + this.bpm = 120; + // gets overridden by p5.Part + this._init(); + this.prevTick = 0; + this.tatumTime = 0; + this.tickCallback = function () { + }; + }; + p5.Metro.prototype.ontick = function (tickTime) { + var elapsedTime = tickTime - this.prevTick; + var secondsFromNow = tickTime - p5sound.audiocontext.currentTime; + if (elapsedTime - this.tatumTime <= -0.02) { + return; + } else { + // console.log('ok', this.syncedParts[0].phrases[0].name); + this.prevTick = tickTime; + // for all of the active things on the metro: + var self = this; + this.syncedParts.forEach(function (thisPart) { + if (!thisPart.isPlaying) + return; + thisPart.incrementStep(secondsFromNow); + // each synced source keeps track of its own beat number + thisPart.phrases.forEach(function (thisPhrase) { + var phraseArray = thisPhrase.sequence; + var bNum = self.metroTicks % phraseArray.length; + if (phraseArray[bNum] !== 0 && (self.metroTicks < phraseArray.length || !thisPhrase.looping)) { + thisPhrase.callback(secondsFromNow, phraseArray[bNum]); + } + }); + }); + this.metroTicks += 1; + this.tickCallback(secondsFromNow); + } + }; + p5.Metro.prototype.setBPM = function (bpm, rampTime) { + var beatTime = 60 / (bpm * this.tatums); + var now = p5sound.audiocontext.currentTime; + this.tatumTime = beatTime; + var rampTime = rampTime || 0; + this.clock.frequency.setValueAtTime(this.clock.frequency.value, now); + this.clock.frequency.linearRampToValueAtTime(bpm, now + rampTime); + this.bpm = bpm; + }; + p5.Metro.prototype.getBPM = function () { + return this.clock.getRate() / this.tatums * 60; + }; + p5.Metro.prototype._init = function () { + this.metroTicks = 0; + }; + // clear existing synced parts, add only this one + p5.Metro.prototype.resetSync = function (part) { + this.syncedParts = [part]; + }; + // push a new synced part to the array + p5.Metro.prototype.pushSync = function (part) { + this.syncedParts.push(part); + }; + p5.Metro.prototype.start = function (timeFromNow) { + var t = timeFromNow || 0; + var now = p5sound.audiocontext.currentTime; + this.clock.start(now + t); + this.setBPM(this.bpm); + }; + p5.Metro.prototype.stop = function (timeFromNow) { + var t = timeFromNow || 0; + var now = p5sound.audiocontext.currentTime; + this.clock.stop(now + t); + }; + p5.Metro.prototype.beatLength = function (tatums) { + this.tatums = 1 / tatums / 4; + }; +}(master, Tone_core_Clock); +var looper; +'use strict'; +looper = function () { + var p5sound = master; + var BPM = 120; + /** + * Set the global tempo, in beats per minute, for all + * p5.Parts. This method will impact all active p5.Parts. + * + * @method setBPM + * @param {Number} BPM Beats Per Minute + * @param {Number} rampTime Seconds from now + */ + p5.prototype.setBPM = function (bpm, rampTime) { + BPM = bpm; + for (var i in p5sound.parts) { + if (p5sound.parts[i]) { + p5sound.parts[i].setBPM(bpm, rampTime); + } + } + }; + /** + *

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

+ * + *

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

+ * + *

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

+ * + * @class p5.Phrase + * @constructor + * @param {String} name Name so that you can access the Phrase. + * @param {Function} callback The name of a function that this phrase + * will call. Typically it will play a sound, + * and accept two parameters: a time at which + * to play the sound (in seconds from now), + * and a value from the sequence array. The + * time should be passed into the play() or + * start() method to ensure precision. + * @param {Array} sequence Array of values to pass into the callback + * at each step of the phrase. + * @example + *
+ * var mySound, myPhrase, myPart; + * var pattern = [1,0,0,2,0,2,0,0]; + * var msg = 'click to play'; + * + * function preload() { + * mySound = loadSound('assets/beatbox.mp3'); + * } + * + * function setup() { + * noStroke(); + * fill(255); + * textAlign(CENTER); + * masterVolume(0.1); + * + * myPhrase = new p5.Phrase('bbox', makeSound, pattern); + * myPart = new p5.Part(); + * myPart.addPhrase(myPhrase); + * myPart.setBPM(60); + * } + * + * function draw() { + * background(0); + * text(msg, width/2, height/2); + * } + * + * function makeSound(time, playbackRate) { + * mySound.rate(playbackRate); + * mySound.play(time); + * } + * + * function mouseClicked() { + * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { + * myPart.start(); + * msg = 'playing pattern'; + * } + * } + * + *
+ */ + p5.Phrase = function (name, callback, sequence) { + this.phraseStep = 0; + this.name = name; + this.callback = callback; + /** + * Array of values to pass into the callback + * at each step of the phrase. Depending on the callback + * function's requirements, these values may be numbers, + * strings, or an object with multiple parameters. + * Zero (0) indicates a rest. + * + * @property {Array} sequence + */ + this.sequence = sequence; + }; + /** + *

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

+ * + *

See p5.Phrase for more about musical timing.

+ * + * @class p5.Part + * @constructor + * @param {Number} [steps] Steps in the part + * @param {Number} [tatums] Divisions of a beat, e.g. use 1/4, or 0.25 for a quater note (default is 1/16, a sixteenth note) + * @example + *
+ * var box, drum, myPart; + * var boxPat = [1,0,0,2,0,2,0,0]; + * var drumPat = [0,1,1,0,2,0,1,0]; + * var msg = 'click to play'; + * + * function preload() { + * box = loadSound('assets/beatbox.mp3'); + * drum = loadSound('assets/drum.mp3'); + * } + * + * function setup() { + * noStroke(); + * fill(255); + * textAlign(CENTER); + * masterVolume(0.1); + * + * var boxPhrase = new p5.Phrase('box', playBox, boxPat); + * var drumPhrase = new p5.Phrase('drum', playDrum, drumPat); + * myPart = new p5.Part(); + * myPart.addPhrase(boxPhrase); + * myPart.addPhrase(drumPhrase); + * myPart.setBPM(60); + * masterVolume(0.1); + * } + * + * function draw() { + * background(0); + * text(msg, width/2, height/2); + * } + * + * function playBox(time, playbackRate) { + * box.rate(playbackRate); + * box.play(time); + * } + * + * function playDrum(time, playbackRate) { + * drum.rate(playbackRate); + * drum.play(time); + * } + * + * function mouseClicked() { + * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { + * myPart.start(); + * msg = 'playing part'; + * } + * } + *
+ */ + p5.Part = function (steps, bLength) { + this.length = steps || 0; + // how many beats + this.partStep = 0; + this.phrases = []; + this.isPlaying = false; + this.noLoop(); + this.tatums = bLength || 0.0625; + // defaults to quarter note + this.metro = new p5.Metro(); + this.metro._init(); + this.metro.beatLength(this.tatums); + this.metro.setBPM(BPM); + p5sound.parts.push(this); + this.callback = function () { + }; + }; + /** + * Set the tempo of this part, in Beats Per Minute. + * + * @method setBPM + * @param {Number} BPM Beats Per Minute + * @param {Number} [rampTime] Seconds from now + */ + p5.Part.prototype.setBPM = function (tempo, rampTime) { + this.metro.setBPM(tempo, rampTime); + }; + /** + * Returns the tempo, in Beats Per Minute, of this part. + * + * @method getBPM + * @return {Number} + */ + p5.Part.prototype.getBPM = function () { + return this.metro.getBPM(); + }; + /** + * Start playback of this part. It will play + * through all of its phrases at a speed + * determined by setBPM. + * + * @method start + * @param {Number} [time] seconds from now + */ + p5.Part.prototype.start = function (time) { + if (!this.isPlaying) { + this.isPlaying = true; + this.metro.resetSync(this); + var t = time || 0; + this.metro.start(t); + } + }; + /** + * Loop playback of this part. It will begin + * looping through all of its phrases at a speed + * determined by setBPM. + * + * @method loop + * @param {Number} [time] seconds from now + */ + p5.Part.prototype.loop = function (time) { + this.looping = true; + // rest onended function + this.onended = function () { + this.partStep = 0; + }; + var t = time || 0; + this.start(t); + }; + /** + * Tell the part to stop looping. + * + * @method noLoop + */ + p5.Part.prototype.noLoop = function () { + this.looping = false; + // rest onended function + this.onended = function () { + this.stop(); + }; + }; + /** + * Stop the part and cue it to step 0. Playback will resume from the begining of the Part when it is played again. + * + * @method stop + * @param {Number} [time] seconds from now + */ + p5.Part.prototype.stop = function (time) { + this.partStep = 0; + this.pause(time); + }; + /** + * Pause the part. Playback will resume + * from the current step. + * + * @method pause + * @param {Number} time seconds from now + */ + p5.Part.prototype.pause = function (time) { + this.isPlaying = false; + var t = time || 0; + this.metro.stop(t); + }; + /** + * Add a p5.Phrase to this Part. + * + * @method addPhrase + * @param {p5.Phrase} phrase reference to a p5.Phrase + */ + p5.Part.prototype.addPhrase = function (name, callback, array) { + var p; + if (arguments.length === 3) { + p = new p5.Phrase(name, callback, array); + } else if (arguments[0] instanceof p5.Phrase) { + p = arguments[0]; + } else { + throw 'invalid input. addPhrase accepts name, callback, array or a p5.Phrase'; + } + this.phrases.push(p); + // reset the length if phrase is longer than part's existing length + if (p.sequence.length > this.length) { + this.length = p.sequence.length; + } + }; + /** + * Remove a phrase from this part, based on the name it was + * given when it was created. + * + * @method removePhrase + * @param {String} phraseName + */ + p5.Part.prototype.removePhrase = function (name) { + for (var i in this.phrases) { + if (this.phrases[i].name === name) { + this.phrases.splice(i, 1); + } + } + }; + /** + * Get a phrase from this part, based on the name it was + * given when it was created. Now you can modify its array. + * + * @method getPhrase + * @param {String} phraseName + */ + p5.Part.prototype.getPhrase = function (name) { + for (var i in this.phrases) { + if (this.phrases[i].name === name) { + return this.phrases[i]; + } + } + }; + /** + * Find all sequences with the specified name, and replace their patterns with the specified array. + * + * @method replaceSequence + * @param {String} phraseName + * @param {Array} sequence Array of values to pass into the callback + * at each step of the phrase. + */ + p5.Part.prototype.replaceSequence = function (name, array) { + for (var i in this.phrases) { + if (this.phrases[i].name === name) { + this.phrases[i].sequence = array; + } + } + }; + p5.Part.prototype.incrementStep = function (time) { + if (this.partStep < this.length - 1) { + this.callback(time); + this.partStep += 1; + } else { + if (!this.looping && this.partStep === this.length - 1) { + console.log('done'); + // this.callback(time); + this.onended(); + } + } + }; + /** + * Set the function that will be called at every step. This will clear the previous function. + * + * @method onStep + * @param {Function} callback The name of the callback + * you want to fire + * on every beat/tatum. + */ + p5.Part.prototype.onStep = function (callback) { + this.callback = callback; + }; + // =============== + // p5.Score + // =============== + /** + * A Score consists of a series of Parts. The parts will + * be played back in order. For example, you could have an + * A part, a B part, and a C part, and play them back in this order + * new p5.Score(a, a, b, a, c) + * + * @class p5.Score + * @constructor + * @param {p5.Part} [...parts] One or multiple parts, to be played in sequence. + */ + p5.Score = function () { + // for all of the arguments + this.parts = []; + this.currentPart = 0; + var thisScore = this; + for (var i in arguments) { + if (arguments[i] && this.parts[i]) { + this.parts[i] = arguments[i]; + this.parts[i].nextPart = this.parts[i + 1]; + this.parts[i].onended = function () { + thisScore.resetPart(i); + playNextPart(thisScore); + }; + } + } + this.looping = false; + }; + p5.Score.prototype.onended = function () { + if (this.looping) { + // this.resetParts(); + this.parts[0].start(); + } else { + this.parts[this.parts.length - 1].onended = function () { + this.stop(); + this.resetParts(); + }; + } + this.currentPart = 0; + }; + /** + * Start playback of the score. + * + * @method start + */ + p5.Score.prototype.start = function () { + this.parts[this.currentPart].start(); + this.scoreStep = 0; + }; + /** + * Stop playback of the score. + * + * @method stop + */ + p5.Score.prototype.stop = function () { + this.parts[this.currentPart].stop(); + this.currentPart = 0; + this.scoreStep = 0; + }; + /** + * Pause playback of the score. + * + * @method pause + */ + p5.Score.prototype.pause = function () { + this.parts[this.currentPart].stop(); + }; + /** + * Loop playback of the score. + * + * @method loop + */ + p5.Score.prototype.loop = function () { + this.looping = true; + this.start(); + }; + /** + * Stop looping playback of the score. If it + * is currently playing, this will go into effect + * after the current round of playback completes. + * + * @method noLoop + */ + p5.Score.prototype.noLoop = function () { + this.looping = false; + }; + p5.Score.prototype.resetParts = function () { + var self = this; + this.parts.forEach(function (part) { + self.resetParts[part]; + }); + }; + p5.Score.prototype.resetPart = function (i) { + this.parts[i].stop(); + this.parts[i].partStep = 0; + for (var p in this.parts[i].phrases) { + if (this.parts[i]) { + this.parts[i].phrases[p].phraseStep = 0; + } + } + }; + /** + * Set the tempo for all parts in the score + * + * @method setBPM + * @param {Number} BPM Beats Per Minute + * @param {Number} rampTime Seconds from now + */ + p5.Score.prototype.setBPM = function (bpm, rampTime) { + for (var i in this.parts) { + if (this.parts[i]) { + this.parts[i].setBPM(bpm, rampTime); + } + } + }; + function playNextPart(aScore) { + aScore.currentPart++; + if (aScore.currentPart >= aScore.parts.length) { + aScore.scoreStep = 0; + aScore.onended(); + } else { + aScore.scoreStep = 0; + aScore.parts[aScore.currentPart - 1].stop(); + aScore.parts[aScore.currentPart].start(); + } + } +}(master); +var soundloop; +'use strict'; +soundloop = function () { + var p5sound = master; + var Clock = Tone_core_Clock; + /** + * SoundLoop + * + * @class p5.SoundLoop + * @constructor + * + * @param {Function} callback this function will be called on each iteration of theloop + * @param {Number|String} [interval] amount of time or beats for each iteration of the loop + * defaults to 1 + * + * @example + *
+ * var click; + * var looper1; + * + * function preload() { + * click = loadSound('assets/drum.mp3'); + * } + * + * function setup() { + * //the looper's callback is passed the timeFromNow + * //this value should be used as a reference point from + * //which to schedule sounds + * looper1 = new p5.SoundLoop(function(timeFromNow){ + * click.play(timeFromNow); + * background(255 * (looper1.iterations % 2)); + * }, 2); + * + * //stop after 10 iteratios; + * looper1.maxIterations = 10; + * //start the loop + * looper1.start(); + * } + *
+ */ + p5.SoundLoop = function (callback, interval) { + this.callback = callback; + /** + * musicalTimeMode uses Tone.Time convention + * true if string, false if number + * @property {Boolean} musicalTimeMode + */ + this.musicalTimeMode = typeof this._interval === 'number' ? false : true; + this._interval = interval || 1; + /** + * musicalTimeMode variables + * modify these only when the interval is specified in musicalTime format as a string + */ + this._timeSignature = 4; + this._bpm = 60; + this.isPlaying = false; + /** + * Set a limit to the number of loops to play. defaults to Infinity + * @property {Number} maxIterations + */ + this.maxIterations = Infinity; + var self = this; + this.clock = new Clock({ + 'callback': function (time) { + var timeFromNow = time - p5sound.audiocontext.currentTime; + /** + * Do not initiate the callback if timeFromNow is < 0 + * This ususually occurs for a few milliseconds when the page + * is not fully loaded + * + * The callback should only be called until maxIterations is reached + */ + if (timeFromNow > 0 && self.iterations <= self.maxIterations) { + self.callback(timeFromNow); + } + }, + 'frequency': this._calcFreq() + }); + }; + /** + * Start the loop + * @method start + * @param {Number} [timeFromNow] schedule a starting time + */ + p5.SoundLoop.prototype.start = function (timeFromNow) { + var t = timeFromNow || 0; + var now = p5sound.audiocontext.currentTime; + if (!this.isPlaying) { + this.clock.start(now + t); + this.isPlaying = true; + } + }; + /** + * Stop the loop + * @method stop + * @param {Number} [timeFromNow] schedule a stopping time + */ + p5.SoundLoop.prototype.stop = function (timeFromNow) { + var t = timeFromNow || 0; + var now = p5sound.audiocontext.currentTime; + if (this.isPlaying) { + this.clock.stop(now + t); + this.isPlaying = false; + } + }; + /** + * Pause the loop + * @method pause + * @param {Number} [timeFromNow] schedule a pausing time + */ + p5.SoundLoop.prototype.pause = function (timeFromNow) { + var t = timeFromNow || 0; + var now = p5sound.audiocontext.currentTime; + if (this.isPlaying) { + this.clock.pause(now + t); + this.isPlaying = false; + } + }; + /** + * Synchronize loops. Use this method to start two more more loops in synchronization + * or to start a loop in synchronization with a loop that is already playing + * This method will schedule the implicit loop in sync with the explicit master loop + * i.e. loopToStart.syncedStart(loopToSyncWith) + * + * @method syncedStart + * @param {Object} otherLoop a p5.SoundLoop to sync with + * @param {Number} [timeFromNow] Start the loops in sync after timeFromNow seconds + */ + p5.SoundLoop.prototype.syncedStart = function (otherLoop, timeFromNow) { + var t = timeFromNow || 0; + var now = p5sound.audiocontext.currentTime; + if (!otherLoop.isPlaying) { + otherLoop.clock.start(now + t); + otherLoop.isPlaying = true; + this.clock.start(now + t); + this.isPlaying = true; + } else if (otherLoop.isPlaying) { + var time = otherLoop.clock._nextTick - p5sound.audiocontext.currentTime; + this.clock.start(now + time); + this.isPlaying = true; + } + }; + /** + * Updates frequency value, reflected in next callback + * @private + * @method _update + */ + p5.SoundLoop.prototype._update = function () { + this.clock.frequency.value = this._calcFreq(); + }; + /** + * Calculate the frequency of the clock's callback based on bpm, interval, and timesignature + * @private + * @method _calcFreq + * @return {Number} new clock frequency value + */ + p5.SoundLoop.prototype._calcFreq = function () { + //Seconds mode, bpm / timesignature has no effect + if (typeof this._interval === 'number') { + this.musicalTimeMode = false; + return 1 / this._interval; + } else if (typeof this._interval === 'string') { + this.musicalTimeMode = true; + return this._bpm / 60 / this._convertNotation(this._interval) * (this._timeSignature / 4); + } + }; + /** + * Convert notation from musical time format to seconds + * Uses Tone.Time convention + * @private + * @method _convertNotation + * @param {String} value value to be converted + * @return {Number} converted value in seconds + */ + p5.SoundLoop.prototype._convertNotation = function (value) { + var type = value.slice(-1); + value = Number(value.slice(0, -1)); + switch (type) { + case 'm': + return this._measure(value); + case 'n': + return this._note(value); + default: + console.warn('Specified interval is not formatted correctly. See Tone.js ' + 'timing reference for more info: https://github.com/Tonejs/Tone.js/wiki/Time'); + } + }; + /** + * Helper conversion methods of measure and note + * @private + * @method _measure + * @private + * @method _note + */ + p5.SoundLoop.prototype._measure = function (value) { + return value * this._timeSignature; + }; + p5.SoundLoop.prototype._note = function (value) { + return this._timeSignature / value; + }; + /** + * Getters and Setters, setting any paramter will result in a change in the clock's + * frequency, that will be reflected after the next callback + * beats per minute (defaults to 60) + * @property {Number} bpm + */ + Object.defineProperty(p5.SoundLoop.prototype, 'bpm', { + get: function () { + return this._bpm; + }, + set: function (bpm) { + if (!this.musicalTimeMode) { + console.warn('Changing the BPM in "seconds" mode has no effect. ' + 'BPM is only relevant in musicalTimeMode ' + 'when the interval is specified as a string ' + '("2n", "4n", "1m"...etc)'); + } + this._bpm = bpm; + this._update(); + } + }); + /** + * number of quarter notes in a measure (defaults to 4) + * @property {Number} timeSignature + */ + Object.defineProperty(p5.SoundLoop.prototype, 'timeSignature', { + get: function () { + return this._timeSignature; + }, + set: function (timeSig) { + if (!this.musicalTimeMode) { + console.warn('Changing the timeSignature in "seconds" mode has no effect. ' + 'BPM is only relevant in musicalTimeMode ' + 'when the interval is specified as a string ' + '("2n", "4n", "1m"...etc)'); + } + this._timeSignature = timeSig; + this._update(); + } + }); + /** + * length of the loops interval + * @property {Number|String} interval + */ + Object.defineProperty(p5.SoundLoop.prototype, 'interval', { + get: function () { + return this._interval; + }, + set: function (interval) { + this.musicalTimeMode = typeof interval === 'Number' ? false : true; + this._interval = interval; + this._update(); + } + }); + /** + * how many times the callback has been called so far + * @property {Number} iterations + * @readonly + */ + Object.defineProperty(p5.SoundLoop.prototype, 'iterations', { + get: function () { + return this.clock.ticks; + } + }); + return p5.SoundLoop; +}(master, Tone_core_Clock); +var compressor; +compressor = function () { + 'use strict'; + var p5sound = master; + var Effect = effect; + var CustomError = errorHandler; + /** + * Compressor is an audio effect class that performs dynamics compression + * on an audio input source. This is a very commonly used technique in music + * and sound production. Compression creates an overall louder, richer, + * and fuller sound by lowering the volume of louds and raising that of softs. + * Compression can be used to avoid clipping (sound distortion due to + * peaks in volume) and is especially useful when many sounds are played + * at once. Compression can be used on indivudal sound sources in addition + * to the master output. + * + * This class extends p5.Effect. + * Methods amp(), chain(), + * drywet(), connect(), and + * disconnect() are available. + * + * @class p5.Compressor + * @constructor + * @extends p5.Effect + * + * + */ + p5.Compressor = function () { + Effect.call(this); + /** + * The p5.Compressor is built with a Web Audio Dynamics Compressor Node + * + * @property {AudioNode} compressor + */ + this.compressor = this.ac.createDynamicsCompressor(); + this.input.connect(this.compressor); + this.compressor.connect(this.wet); + }; + p5.Compressor.prototype = Object.create(Effect.prototype); + /** + * Performs the same function as .connect, but also accepts + * optional parameters to set compressor's audioParams + * @method process + * + * @param {Object} src Sound source to be connected + * + * @param {Number} [attack] The amount of time (in seconds) to reduce the gain by 10dB, + * default = .003, range 0 - 1 + * @param {Number} [knee] A decibel value representing the range above the + * threshold where the curve smoothly transitions to the "ratio" portion. + * default = 30, range 0 - 40 + * @param {Number} [ratio] The amount of dB change in input for a 1 dB change in output + * default = 12, range 1 - 20 + * @param {Number} [threshold] The decibel value above which the compression will start taking effect + * default = -24, range -100 - 0 + * @param {Number} [release] The amount of time (in seconds) to increase the gain by 10dB + * default = .25, range 0 - 1 + */ + p5.Compressor.prototype.process = function (src, attack, knee, ratio, threshold, release) { + src.connect(this.input); + this.set(attack, knee, ratio, threshold, release); + }; + /** + * Set the paramters of a compressor. + * @method set + * @param {Number} attack The amount of time (in seconds) to reduce the gain by 10dB, + * default = .003, range 0 - 1 + * @param {Number} knee A decibel value representing the range above the + * threshold where the curve smoothly transitions to the "ratio" portion. + * default = 30, range 0 - 40 + * @param {Number} ratio The amount of dB change in input for a 1 dB change in output + * default = 12, range 1 - 20 + * @param {Number} threshold The decibel value above which the compression will start taking effect + * default = -24, range -100 - 0 + * @param {Number} release The amount of time (in seconds) to increase the gain by 10dB + * default = .25, range 0 - 1 + */ + p5.Compressor.prototype.set = function (attack, knee, ratio, threshold, release) { + if (typeof attack !== 'undefined') { + this.attack(attack); + } + if (typeof knee !== 'undefined') { + this.knee(knee); + } + if (typeof ratio !== 'undefined') { + this.ratio(ratio); + } + if (typeof threshold !== 'undefined') { + this.threshold(threshold); + } + if (typeof release !== 'undefined') { + this.release(release); + } + }; + /** + * Get current attack or set value w/ time ramp + * + * + * @method attack + * @param {Number} [attack] Attack is the amount of time (in seconds) to reduce the gain by 10dB, + * default = .003, range 0 - 1 + * @param {Number} [time] Assign time value to schedule the change in value + */ + p5.Compressor.prototype.attack = function (attack, time) { + var t = time || 0; + if (typeof attack == 'number') { + this.compressor.attack.value = attack; + this.compressor.attack.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.compressor.attack.linearRampToValueAtTime(attack, this.ac.currentTime + 0.02 + t); + } else if (typeof attack !== 'undefined') { + attack.connect(this.compressor.attack); + } + return this.compressor.attack.value; + }; + /** + * Get current knee or set value w/ time ramp + * + * @method knee + * @param {Number} [knee] A decibel value representing the range above the + * threshold where the curve smoothly transitions to the "ratio" portion. + * default = 30, range 0 - 40 + * @param {Number} [time] Assign time value to schedule the change in value + */ + p5.Compressor.prototype.knee = function (knee, time) { + var t = time || 0; + if (typeof knee == 'number') { + this.compressor.knee.value = knee; + this.compressor.knee.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.compressor.knee.linearRampToValueAtTime(knee, this.ac.currentTime + 0.02 + t); + } else if (typeof knee !== 'undefined') { + knee.connect(this.compressor.knee); + } + return this.compressor.knee.value; + }; + /** + * Get current ratio or set value w/ time ramp + * @method ratio + * + * @param {Number} [ratio] The amount of dB change in input for a 1 dB change in output + * default = 12, range 1 - 20 + * @param {Number} [time] Assign time value to schedule the change in value + */ + p5.Compressor.prototype.ratio = function (ratio, time) { + var t = time || 0; + if (typeof ratio == 'number') { + this.compressor.ratio.value = ratio; + this.compressor.ratio.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.compressor.ratio.linearRampToValueAtTime(ratio, this.ac.currentTime + 0.02 + t); + } else if (typeof ratio !== 'undefined') { + ratio.connect(this.compressor.ratio); + } + return this.compressor.ratio.value; + }; + /** + * Get current threshold or set value w/ time ramp + * @method threshold + * + * @param {Number} threshold The decibel value above which the compression will start taking effect + * default = -24, range -100 - 0 + * @param {Number} [time] Assign time value to schedule the change in value + */ + p5.Compressor.prototype.threshold = function (threshold, time) { + var t = time || 0; + if (typeof threshold == 'number') { + this.compressor.threshold.value = threshold; + this.compressor.threshold.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.compressor.threshold.linearRampToValueAtTime(threshold, this.ac.currentTime + 0.02 + t); + } else if (typeof threshold !== 'undefined') { + threshold.connect(this.compressor.threshold); + } + return this.compressor.threshold.value; + }; + /** + * Get current release or set value w/ time ramp + * @method release + * + * @param {Number} release The amount of time (in seconds) to increase the gain by 10dB + * default = .25, range 0 - 1 + * + * @param {Number} [time] Assign time value to schedule the change in value + */ + p5.Compressor.prototype.release = function (release, time) { + var t = time || 0; + if (typeof release == 'number') { + this.compressor.release.value = release; + this.compressor.release.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.compressor.release.linearRampToValueAtTime(release, this.ac.currentTime + 0.02 + t); + } else if (typeof number !== 'undefined') { + release.connect(this.compressor.release); + } + return this.compressor.release.value; + }; + /** + * Return the current reduction value + * + * @method reduction + * @return {Number} Value of the amount of gain reduction that is applied to the signal + */ + p5.Compressor.prototype.reduction = function () { + return this.compressor.reduction.value; + }; + p5.Compressor.prototype.dispose = function () { + Effect.prototype.dispose.apply(this); + if (this.compressor) { + this.compressor.disconnect(); + delete this.compressor; + } + }; + return p5.Compressor; +}(master, effect, errorHandler); +var soundRecorder; +'use strict'; +soundRecorder = function () { + // inspiration: recorder.js, Tone.js & typedarray.org + var p5sound = master; + var convertToWav = helpers.convertToWav; + var ac = p5sound.audiocontext; + /** + *

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

+ *

The record() method accepts a p5.SoundFile as a parameter. + * When playback is stopped (either after the given amount of time, + * or with the stop() method), the p5.SoundRecorder will send its + * recording to that p5.SoundFile for playback.

+ * + * @class p5.SoundRecorder + * @constructor + * @example + *
+ * var mic, recorder, soundFile; + * var state = 0; + * + * function setup() { + * background(200); + * // create an audio in + * mic = new p5.AudioIn(); + * + * // prompts user to enable their browser mic + * mic.start(); + * + * // create a sound recorder + * recorder = new p5.SoundRecorder(); + * + * // connect the mic to the recorder + * recorder.setInput(mic); + * + * // this sound file will be used to + * // playback & save the recording + * soundFile = new p5.SoundFile(); + * + * text('keyPress to record', 20, 20); + * } + * + * function keyPressed() { + * // make sure user enabled the mic + * if (state === 0 && mic.enabled) { + * + * // record to our p5.SoundFile + * recorder.record(soundFile); + * + * background(255,0,0); + * text('Recording!', 20, 20); + * state++; + * } + * else if (state === 1) { + * background(0,255,0); + * + * // stop recorder and + * // send result to soundFile + * recorder.stop(); + * + * text('Stopped', 20, 20); + * state++; + * } + * + * else if (state === 2) { + * soundFile.play(); // play the result! + * save(soundFile, 'mySound.wav'); + * state++; + * } + * } + *
+ */ + p5.SoundRecorder = function () { + this.input = ac.createGain(); + this.output = ac.createGain(); + this.recording = false; + this.bufferSize = 1024; + this._channels = 2; + // stereo (default) + this._clear(); + // initialize variables + this._jsNode = ac.createScriptProcessor(this.bufferSize, this._channels, 2); + this._jsNode.onaudioprocess = this._audioprocess.bind(this); + /** + * callback invoked when the recording is over + * @private + * @type Function(Float32Array) + */ + this._callback = function () { + }; + // connections + this._jsNode.connect(p5.soundOut._silentNode); + this.setInput(); + // add this p5.SoundFile to the soundArray + p5sound.soundArray.push(this); + }; + /** + * Connect a specific device to the p5.SoundRecorder. + * If no parameter is given, p5.SoundRecorer will record + * all audible p5.sound from your sketch. + * + * @method setInput + * @param {Object} [unit] p5.sound object or a web audio unit + * that outputs sound + */ + p5.SoundRecorder.prototype.setInput = function (unit) { + this.input.disconnect(); + this.input = null; + this.input = ac.createGain(); + this.input.connect(this._jsNode); + this.input.connect(this.output); + if (unit) { + unit.connect(this.input); + } else { + p5.soundOut.output.connect(this.input); + } + }; + /** + * Start recording. To access the recording, provide + * a p5.SoundFile as the first parameter. The p5.SoundRecorder + * will send its recording to that p5.SoundFile for playback once + * recording is complete. Optional parameters include duration + * (in seconds) of the recording, and a callback function that + * will be called once the complete recording has been + * transfered to the p5.SoundFile. + * + * @method record + * @param {p5.SoundFile} soundFile p5.SoundFile + * @param {Number} [duration] Time (in seconds) + * @param {Function} [callback] The name of a function that will be + * called once the recording completes + */ + p5.SoundRecorder.prototype.record = function (sFile, duration, callback) { + this.recording = true; + if (duration) { + this.sampleLimit = Math.round(duration * ac.sampleRate); + } + if (sFile && callback) { + this._callback = function () { + this.buffer = this._getBuffer(); + sFile.setBuffer(this.buffer); + callback(); + }; + } else if (sFile) { + this._callback = function () { + this.buffer = this._getBuffer(); + sFile.setBuffer(this.buffer); + }; + } + }; + /** + * Stop the recording. Once the recording is stopped, + * the results will be sent to the p5.SoundFile that + * was given on .record(), and if a callback function + * was provided on record, that function will be called. + * + * @method stop + */ + p5.SoundRecorder.prototype.stop = function () { + this.recording = false; + this._callback(); + this._clear(); + }; + p5.SoundRecorder.prototype._clear = function () { + this._leftBuffers = []; + this._rightBuffers = []; + this.recordedSamples = 0; + this.sampleLimit = null; + }; + /** + * internal method called on audio process + * + * @private + * @param {AudioProcessorEvent} event + */ + p5.SoundRecorder.prototype._audioprocess = function (event) { + if (this.recording === false) { + return; + } else if (this.recording === true) { + // if we are past the duration, then stop... else: + if (this.sampleLimit && this.recordedSamples >= this.sampleLimit) { + this.stop(); + } else { + // get channel data + var left = event.inputBuffer.getChannelData(0); + var right = event.inputBuffer.getChannelData(1); + // clone the samples + this._leftBuffers.push(new Float32Array(left)); + this._rightBuffers.push(new Float32Array(right)); + this.recordedSamples += this.bufferSize; + } + } + }; + p5.SoundRecorder.prototype._getBuffer = function () { + var buffers = []; + buffers.push(this._mergeBuffers(this._leftBuffers)); + buffers.push(this._mergeBuffers(this._rightBuffers)); + return buffers; + }; + p5.SoundRecorder.prototype._mergeBuffers = function (channelBuffer) { + var result = new Float32Array(this.recordedSamples); + var offset = 0; + var lng = channelBuffer.length; + for (var i = 0; i < lng; i++) { + var buffer = channelBuffer[i]; + result.set(buffer, offset); + offset += buffer.length; + } + return result; + }; + p5.SoundRecorder.prototype.dispose = function () { + this._clear(); + // remove reference from soundArray + var index = p5sound.soundArray.indexOf(this); + p5sound.soundArray.splice(index, 1); + this._callback = function () { + }; + if (this.input) { + this.input.disconnect(); + } + this.input = null; + this._jsNode = null; + }; + /** + * Save a p5.SoundFile as a .wav file. The browser will prompt the user + * to download the file to their device. + * For uploading audio to a server, use + * `p5.SoundFile.saveBlob`. + * + * @for p5 + * @method saveSound + * @param {p5.SoundFile} soundFile p5.SoundFile that you wish to save + * @param {String} fileName name of the resulting .wav file. + */ + // add to p5.prototype as this is used by the p5 `save()` method. + p5.prototype.saveSound = function (soundFile, fileName) { + const dataView = convertToWav(soundFile.buffer); + p5.prototype.writeFile([dataView], fileName, 'wav'); + }; +}(master, helpers); +var peakdetect; +'use strict'; +peakdetect = function () { + /** + *

PeakDetect works in conjunction with p5.FFT to + * look for onsets in some or all of the frequency spectrum. + *

+ *

+ * To use p5.PeakDetect, call update in the draw loop + * and pass in a p5.FFT object. + *

+ *

+ * You can listen for a specific part of the frequency spectrum by + * setting the range between freq1 and freq2. + *

+ * + *

threshold is the threshold for detecting a peak, + * scaled between 0 and 1. It is logarithmic, so 0.1 is half as loud + * as 1.0.

+ * + *

+ * The update method is meant to be run in the draw loop, and + * frames determines how many loops must pass before + * another peak can be detected. + * For example, if the frameRate() = 60, you could detect the beat of a + * 120 beat-per-minute song with this equation: + * framesPerPeak = 60 / (estimatedBPM / 60 ); + *

+ * + *

+ * Based on example contribtued by @b2renger, and a simple beat detection + * explanation by Felix Turner. + *

+ * + * @class p5.PeakDetect + * @constructor + * @param {Number} [freq1] lowFrequency - defaults to 20Hz + * @param {Number} [freq2] highFrequency - defaults to 20000 Hz + * @param {Number} [threshold] Threshold for detecting a beat between 0 and 1 + * scaled logarithmically where 0.1 is 1/2 the loudness + * of 1.0. Defaults to 0.35. + * @param {Number} [framesPerPeak] Defaults to 20. + * @example + *
+ * + * var cnv, soundFile, fft, peakDetect; + * var ellipseWidth = 10; + * + * function preload() { + * soundFile = loadSound('assets/beat.mp3'); + * } + * + * function setup() { + * background(0); + * noStroke(); + * fill(255); + * textAlign(CENTER); + * + * // p5.PeakDetect requires a p5.FFT + * fft = new p5.FFT(); + * peakDetect = new p5.PeakDetect(); + * } + * + * function draw() { + * background(0); + * text('click to play/pause', width/2, height/2); + * + * // peakDetect accepts an fft post-analysis + * fft.analyze(); + * peakDetect.update(fft); + * + * if ( peakDetect.isDetected ) { + * ellipseWidth = 50; + * } else { + * ellipseWidth *= 0.95; + * } + * + * ellipse(width/2, height/2, ellipseWidth, ellipseWidth); + * } + * + * // toggle play/stop when canvas is clicked + * function mouseClicked() { + * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { + * if (soundFile.isPlaying() ) { + * soundFile.stop(); + * } else { + * soundFile.play(); + * } + * } + * } + *
+ */ + p5.PeakDetect = function (freq1, freq2, threshold, _framesPerPeak) { + // framesPerPeak determines how often to look for a beat. + // If a beat is provided, try to look for a beat based on bpm + this.framesPerPeak = _framesPerPeak || 20; + this.framesSinceLastPeak = 0; + this.decayRate = 0.95; + this.threshold = threshold || 0.35; + this.cutoff = 0; + // how much to increase the cutoff + // TO DO: document this / figure out how to make it accessible + this.cutoffMult = 1.5; + this.energy = 0; + this.penergy = 0; + // TO DO: document this property / figure out how to make it accessible + this.currentValue = 0; + /** + * isDetected is set to true when a peak is detected. + * + * @attribute isDetected {Boolean} + * @default false + */ + this.isDetected = false; + this.f1 = freq1 || 40; + this.f2 = freq2 || 20000; + // function to call when a peak is detected + this._onPeak = function () { + }; + }; + /** + * The update method is run in the draw loop. + * + * Accepts an FFT object. You must call .analyze() + * on the FFT object prior to updating the peakDetect + * because it relies on a completed FFT analysis. + * + * @method update + * @param {p5.FFT} fftObject A p5.FFT object + */ + p5.PeakDetect.prototype.update = function (fftObject) { + var nrg = this.energy = fftObject.getEnergy(this.f1, this.f2) / 255; + if (nrg > this.cutoff && nrg > this.threshold && nrg - this.penergy > 0) { + // trigger callback + this._onPeak(); + this.isDetected = true; + // debounce + this.cutoff = nrg * this.cutoffMult; + this.framesSinceLastPeak = 0; + } else { + this.isDetected = false; + if (this.framesSinceLastPeak <= this.framesPerPeak) { + this.framesSinceLastPeak++; + } else { + this.cutoff *= this.decayRate; + this.cutoff = Math.max(this.cutoff, this.threshold); + } + } + this.currentValue = nrg; + this.penergy = nrg; + }; + /** + * onPeak accepts two arguments: a function to call when + * a peak is detected. The value of the peak, + * between 0.0 and 1.0, is passed to the callback. + * + * @method onPeak + * @param {Function} callback Name of a function that will + * be called when a peak is + * detected. + * @param {Object} [val] Optional value to pass + * into the function when + * a peak is detected. + * @example + *
+ * var cnv, soundFile, fft, peakDetect; + * var ellipseWidth = 0; + * + * function preload() { + * soundFile = loadSound('assets/beat.mp3'); + * } + * + * function setup() { + * cnv = createCanvas(100,100); + * textAlign(CENTER); + * + * fft = new p5.FFT(); + * peakDetect = new p5.PeakDetect(); + * + * setupSound(); + * + * // when a beat is detected, call triggerBeat() + * peakDetect.onPeak(triggerBeat); + * } + * + * function draw() { + * background(0); + * fill(255); + * text('click to play', width/2, height/2); + * + * fft.analyze(); + * peakDetect.update(fft); + * + * ellipseWidth *= 0.95; + * ellipse(width/2, height/2, ellipseWidth, ellipseWidth); + * } + * + * // this function is called by peakDetect.onPeak + * function triggerBeat() { + * ellipseWidth = 50; + * } + * + * // mouseclick starts/stops sound + * function setupSound() { + * cnv.mouseClicked( function() { + * if (soundFile.isPlaying() ) { + * soundFile.stop(); + * } else { + * soundFile.play(); + * } + * }); + * } + *
+ */ + p5.PeakDetect.prototype.onPeak = function (callback, val) { + var self = this; + self._onPeak = function () { + callback(self.energy, val); + }; + }; +}(); +var gain; +'use strict'; +gain = function () { + var p5sound = master; + /** + * A gain node is usefull to set the relative volume of sound. + * It's typically used to build mixers. + * + * @class p5.Gain + * @constructor + * @example + *
+ * + * // load two soundfile and crossfade beetween them + * var sound1,sound2; + * var gain1, gain2, gain3; + * + * function preload(){ + * soundFormats('ogg', 'mp3'); + * sound1 = loadSound('assets/Damscray_-_Dancing_Tiger_01'); + * sound2 = loadSound('assets/beat.mp3'); + * } + * + * function setup() { + * createCanvas(400,200); + * + * // create a 'master' gain to which we will connect both soundfiles + * gain3 = new p5.Gain(); + * gain3.connect(); + * + * // setup first sound for playing + * sound1.rate(1); + * sound1.loop(); + * sound1.disconnect(); // diconnect from p5 output + * + * gain1 = new p5.Gain(); // setup a gain node + * gain1.setInput(sound1); // connect the first sound to its input + * gain1.connect(gain3); // connect its output to the 'master' + * + * sound2.rate(1); + * sound2.disconnect(); + * sound2.loop(); + * + * gain2 = new p5.Gain(); + * gain2.setInput(sound2); + * gain2.connect(gain3); + * + * } + * + * function draw(){ + * background(180); + * + * // calculate the horizontal distance beetween the mouse and the right of the screen + * var d = dist(mouseX,0,width,0); + * + * // map the horizontal position of the mouse to values useable for volume control of sound1 + * var vol1 = map(mouseX,0,width,0,1); + * var vol2 = 1-vol1; // when sound1 is loud, sound2 is quiet and vice versa + * + * gain1.amp(vol1,0.5,0); + * gain2.amp(vol2,0.5,0); + * + * // map the vertical position of the mouse to values useable for 'master volume control' + * var vol3 = map(mouseY,0,height,0,1); + * gain3.amp(vol3,0.5,0); + * } + *
+ * + */ + p5.Gain = function () { + this.ac = p5sound.audiocontext; + this.input = this.ac.createGain(); + this.output = this.ac.createGain(); + // otherwise, Safari distorts + this.input.gain.value = 0.5; + this.input.connect(this.output); + // add to the soundArray + p5sound.soundArray.push(this); + }; + /** + * Connect a source to the gain node. + * + * @method setInput + * @param {Object} src p5.sound / Web Audio object with a sound + * output. + */ + p5.Gain.prototype.setInput = function (src) { + src.connect(this.input); + }; + /** + * Send output to a p5.sound or web audio object + * + * @method connect + * @param {Object} unit + */ + p5.Gain.prototype.connect = function (unit) { + var u = unit || p5.soundOut.input; + this.output.connect(u.input ? u.input : u); + }; + /** + * Disconnect all output. + * + * @method disconnect + */ + p5.Gain.prototype.disconnect = function () { + if (this.output) { + this.output.disconnect(); + } + }; + /** + * Set the output level of the gain node. + * + * @method amp + * @param {Number} volume amplitude between 0 and 1.0 + * @param {Number} [rampTime] create a fade that lasts rampTime + * @param {Number} [timeFromNow] schedule this event to happen + * seconds from now + */ + p5.Gain.prototype.amp = function (vol, rampTime, tFromNow) { + var rampTime = rampTime || 0; + var tFromNow = tFromNow || 0; + var now = p5sound.audiocontext.currentTime; + var currentVol = this.output.gain.value; + this.output.gain.cancelScheduledValues(now); + this.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow); + this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime); + }; + p5.Gain.prototype.dispose = function () { + // remove reference from soundArray + var index = p5sound.soundArray.indexOf(this); + p5sound.soundArray.splice(index, 1); + if (this.output) { + this.output.disconnect(); + delete this.output; + } + if (this.input) { + this.input.disconnect(); + delete this.input; + } + }; +}(master); +var audioVoice; +'use strict'; +audioVoice = function () { + var p5sound = master; + /** + * Base class for monophonic synthesizers. Any extensions of this class + * should follow the API and implement the methods below in order to + * remain compatible with p5.PolySynth(); + * + * @class p5.AudioVoice + * @constructor + */ + p5.AudioVoice = function () { + this.ac = p5sound.audiocontext; + this.output = this.ac.createGain(); + this.connect(); + p5sound.soundArray.push(this); + }; + p5.AudioVoice.prototype.play = function (note, velocity, secondsFromNow, sustime) { + }; + p5.AudioVoice.prototype.triggerAttack = function (note, velocity, secondsFromNow) { + }; + p5.AudioVoice.prototype.triggerRelease = function (secondsFromNow) { + }; + p5.AudioVoice.prototype.amp = function (vol, rampTime) { + }; + /** + * Connect to p5 objects or Web Audio Nodes + * @method connect + * @param {Object} unit + */ + p5.AudioVoice.prototype.connect = function (unit) { + var u = unit || p5sound.input; + this.output.connect(u.input ? u.input : u); + }; + /** + * Disconnect from soundOut + * @method disconnect + */ + p5.AudioVoice.prototype.disconnect = function () { + this.output.disconnect(); + }; + p5.AudioVoice.prototype.dispose = function () { + if (this.output) { + this.output.disconnect(); + delete this.output; + } + }; + return p5.AudioVoice; +}(master); +var monosynth; +'use strict'; +monosynth = function () { + var p5sound = master; + var AudioVoice = audioVoice; + var noteToFreq = helpers.noteToFreq; + var DEFAULT_SUSTAIN = 0.15; + /** + * A MonoSynth is used as a single voice for sound synthesis. + * This is a class to be used in conjunction with the PolySynth + * class. Custom synthetisers should be built inheriting from + * this class. + * + * @class p5.MonoSynth + * @constructor + * @example + *
+ * var monoSynth; + * + * function setup() { + * var cnv = createCanvas(100, 100); + * cnv.mousePressed(playSynth); + * + * monoSynth = new p5.MonoSynth(); + * + * textAlign(CENTER); + * text('click to play', width/2, height/2); + * } + * + * function playSynth() { + * // time from now (in seconds) + * var time = 0; + * // note duration (in seconds) + * var dur = 0.25; + * // velocity (volume, from 0 to 1) + * var v = 0.2; + * + * monoSynth.play("G3", v, time, dur); + * monoSynth.play("C4", v, time += dur, dur); + * + * background(random(255), random(255), 255); + * text('click to play', width/2, height/2); + * } + *
+ **/ + p5.MonoSynth = function () { + AudioVoice.call(this); + this.oscillator = new p5.Oscillator(); + this.env = new p5.Envelope(); + this.env.setRange(1, 0); + this.env.setExp(true); + //set params + this.setADSR(0.02, 0.25, 0.05, 0.35); + // oscillator --> env --> this.output (gain) --> p5.soundOut + this.oscillator.disconnect(); + this.oscillator.connect(this.output); + this.env.disconnect(); + this.env.setInput(this.output.gain); + // reset oscillator gain to 1.0 + this.oscillator.output.gain.value = 1; + this.oscillator.start(); + this.connect(); + p5sound.soundArray.push(this); + }; + p5.MonoSynth.prototype = Object.create(p5.AudioVoice.prototype); + /** + * Play tells the MonoSynth to start playing a note. This method schedules + * the calling of .triggerAttack and .triggerRelease. + * + * @method play + * @param {String | Number} note the note you want to play, specified as a + * frequency in Hertz (Number) or as a midi + * value in Note/Octave format ("C4", "Eb3"...etc") + * See + * Tone. Defaults to 440 hz. + * @param {Number} [velocity] velocity of the note to play (ranging from 0 to 1) + * @param {Number} [secondsFromNow] time from now (in seconds) at which to play + * @param {Number} [sustainTime] time to sustain before releasing the envelope + * @example + *
+ * var monoSynth; + * + * function setup() { + * var cnv = createCanvas(100, 100); + * cnv.mousePressed(playSynth); + * + * monoSynth = new p5.MonoSynth(); + * + * textAlign(CENTER); + * text('click to play', width/2, height/2); + * } + * + * function playSynth() { + * // time from now (in seconds) + * var time = 0; + * // note duration (in seconds) + * var dur = 1/6; + * // note velocity (volume, from 0 to 1) + * var v = random(); + * + * monoSynth.play("Fb3", v, 0, dur); + * monoSynth.play("Gb3", v, time += dur, dur); + * + * background(random(255), random(255), 255); + * text('click to play', width/2, height/2); + * } + *
+ * + */ + p5.MonoSynth.prototype.play = function (note, velocity, secondsFromNow, susTime) { + this.triggerAttack(note, velocity, ~~secondsFromNow); + this.triggerRelease(~~secondsFromNow + (susTime || DEFAULT_SUSTAIN)); + }; + /** + * Trigger the Attack, and Decay portion of the Envelope. + * Similar to holding down a key on a piano, but it will + * hold the sustain level until you let go. + * + * @param {String | Number} note the note you want to play, specified as a + * frequency in Hertz (Number) or as a midi + * value in Note/Octave format ("C4", "Eb3"...etc") + * See + * Tone. Defaults to 440 hz + * @param {Number} [velocity] velocity of the note to play (ranging from 0 to 1) + * @param {Number} [secondsFromNow] time from now (in seconds) at which to play + * @method triggerAttack + * @example + *
+ * var monoSynth = new p5.MonoSynth(); + * + * function mousePressed() { + * monoSynth.triggerAttack("E3"); + * } + * + * function mouseReleased() { + * monoSynth.triggerRelease(); + * } + *
+ */ + p5.MonoSynth.prototype.triggerAttack = function (note, velocity, secondsFromNow) { + var secondsFromNow = ~~secondsFromNow; + var freq = noteToFreq(note); + var vel = velocity || 0.1; + this.oscillator.freq(freq, 0, secondsFromNow); + this.env.ramp(this.output.gain, secondsFromNow, vel); + }; + /** + * Trigger the release of the Envelope. This is similar to releasing + * the key on a piano and letting the sound fade according to the + * release level and release time. + * + * @param {Number} secondsFromNow time to trigger the release + * @method triggerRelease + * @example + *
+ * var monoSynth = new p5.MonoSynth(); + * + * function mousePressed() { + * monoSynth.triggerAttack("E3"); + * } + * + * function mouseReleased() { + * monoSynth.triggerRelease(); + * } + *
+ */ + p5.MonoSynth.prototype.triggerRelease = function (secondsFromNow) { + var secondsFromNow = secondsFromNow || 0; + this.env.ramp(this.output.gain, secondsFromNow, 0); + }; + /** + * Set values like a traditional + * + * ADSR envelope + * . + * + * @method setADSR + * @param {Number} attackTime Time (in seconds before envelope + * reaches Attack Level + * @param {Number} [decayTime] Time (in seconds) before envelope + * reaches Decay/Sustain Level + * @param {Number} [susRatio] Ratio between attackLevel and releaseLevel, on a scale from 0 to 1, + * where 1.0 = attackLevel, 0.0 = releaseLevel. + * The susRatio determines the decayLevel and the level at which the + * sustain portion of the envelope will sustain. + * For example, if attackLevel is 0.4, releaseLevel is 0, + * and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is + * increased to 1.0 (using setRange), + * then decayLevel would increase proportionally, to become 0.5. + * @param {Number} [releaseTime] Time in seconds from now (defaults to 0) + */ + p5.MonoSynth.prototype.setADSR = function (attack, decay, sustain, release) { + this.env.setADSR(attack, decay, sustain, release); + }; + /** + * Getters and Setters + * @property {Number} attack + */ + /** + * @property {Number} decay + */ + /** + * @property {Number} sustain + */ + /** + * @property {Number} release + */ + Object.defineProperties(p5.MonoSynth.prototype, { + 'attack': { + get: function () { + return this.env.aTime; + }, + set: function (attack) { + this.env.setADSR(attack, this.env.dTime, this.env.sPercent, this.env.rTime); + } + }, + 'decay': { + get: function () { + return this.env.dTime; + }, + set: function (decay) { + this.env.setADSR(this.env.aTime, decay, this.env.sPercent, this.env.rTime); + } + }, + 'sustain': { + get: function () { + return this.env.sPercent; + }, + set: function (sustain) { + this.env.setADSR(this.env.aTime, this.env.dTime, sustain, this.env.rTime); + } + }, + 'release': { + get: function () { + return this.env.rTime; + }, + set: function (release) { + this.env.setADSR(this.env.aTime, this.env.dTime, this.env.sPercent, release); + } + } + }); + /** + * MonoSynth amp + * @method amp + * @param {Number} vol desired volume + * @param {Number} [rampTime] Time to reach new volume + * @return {Number} new volume value + */ + p5.MonoSynth.prototype.amp = function (vol, rampTime) { + var t = rampTime || 0; + if (typeof vol !== 'undefined') { + this.oscillator.amp(vol, t); + } + return this.oscillator.amp().value; + }; + /** + * Connect to a p5.sound / Web Audio object. + * + * @method connect + * @param {Object} unit A p5.sound or Web Audio object + */ + p5.MonoSynth.prototype.connect = function (unit) { + var u = unit || p5sound.input; + this.output.connect(u.input ? u.input : u); + }; + /** + * Disconnect all outputs + * + * @method disconnect + */ + p5.MonoSynth.prototype.disconnect = function () { + if (this.output) { + this.output.disconnect(); + } + }; + /** + * Get rid of the MonoSynth and free up its resources / memory. + * + * @method dispose + */ + p5.MonoSynth.prototype.dispose = function () { + AudioVoice.prototype.dispose.apply(this); + if (this.env) { + this.env.dispose(); + } + if (this.oscillator) { + this.oscillator.dispose(); + } + }; +}(master, audioVoice, helpers); +var polysynth; +'use strict'; +polysynth = function () { + var p5sound = master; + var TimelineSignal = Tone_signal_TimelineSignal; + var noteToFreq = helpers.noteToFreq; + /** + * An AudioVoice is used as a single voice for sound synthesis. + * The PolySynth class holds an array of AudioVoice, and deals + * with voices allocations, with setting notes to be played, and + * parameters to be set. + * + * @class p5.PolySynth + * @constructor + * + * @param {Number} [synthVoice] A monophonic synth voice inheriting + * the AudioVoice class. Defaults to p5.MonoSynth + * @param {Number} [maxVoices] Number of voices, defaults to 8; + * @example + *
+ * var polySynth; + * + * function setup() { + * var cnv = createCanvas(100, 100); + * cnv.mousePressed(playSynth); + * + * polySynth = new p5.PolySynth(); + * + * textAlign(CENTER); + * text('click to play', width/2, height/2); + * } + * + * function playSynth() { + * // note duration (in seconds) + * var dur = 1.5; + * + * // time from now (in seconds) + * var time = 0; + * + * // velocity (volume, from 0 to 1) + * var vel = 0.1; + * + * // notes can overlap with each other + * polySynth.play("G2", vel, 0, dur); + * polySynth.play("C3", vel, time += 1/3, dur); + * polySynth.play("G3", vel, time += 1/3, dur); + * + * background(random(255), random(255), 255); + * text('click to play', width/2, height/2); + * } + *
+ **/ + p5.PolySynth = function (audioVoice, maxVoices) { + //audiovoices will contain maxVoices many monophonic synths + this.audiovoices = []; + /** + * An object that holds information about which notes have been played and + * which notes are currently being played. New notes are added as keys + * on the fly. While a note has been attacked, but not released, the value of the + * key is the audiovoice which is generating that note. When notes are released, + * the value of the key becomes undefined. + * @property notes + */ + this.notes = {}; + //indices of the most recently used, and least recently used audiovoice + this._newest = 0; + this._oldest = 0; + /** + * A PolySynth must have at least 1 voice, defaults to 8 + * @property polyvalue + */ + this.maxVoices = maxVoices || 8; + /** + * Monosynth that generates the sound for each note that is triggered. The + * p5.PolySynth defaults to using the p5.MonoSynth as its voice. + * @property AudioVoice + */ + this.AudioVoice = audioVoice === undefined ? p5.MonoSynth : audioVoice; + /** + * This value must only change as a note is attacked or released. Due to delay + * and sustain times, Tone.TimelineSignal is required to schedule the change in value. + * @private + * @property {Tone.TimelineSignal} _voicesInUse + */ + this._voicesInUse = new TimelineSignal(0); + this.output = p5sound.audiocontext.createGain(); + this.connect(); + //Construct the appropriate number of audiovoices + this._allocateVoices(); + p5sound.soundArray.push(this); + }; + /** + * Construct the appropriate number of audiovoices + * @private + * @method _allocateVoices + */ + p5.PolySynth.prototype._allocateVoices = function () { + for (var i = 0; i < this.maxVoices; i++) { + this.audiovoices.push(new this.AudioVoice()); + this.audiovoices[i].disconnect(); + this.audiovoices[i].connect(this.output); + } + }; + /** + * Play a note by triggering noteAttack and noteRelease with sustain time + * + * @method play + * @param {Number} [note] midi note to play (ranging from 0 to 127 - 60 being a middle C) + * @param {Number} [velocity] velocity of the note to play (ranging from 0 to 1) + * @param {Number} [secondsFromNow] time from now (in seconds) at which to play + * @param {Number} [sustainTime] time to sustain before releasing the envelope + * @example + *
+ * var polySynth; + * + * function setup() { + * var cnv = createCanvas(100, 100); + * cnv.mousePressed(playSynth); + * + * polySynth = new p5.PolySynth(); + * + * textAlign(CENTER); + * text('click to play', width/2, height/2); + * } + * + * function playSynth() { + * // note duration (in seconds) + * var dur = 0.1; + * + * // time from now (in seconds) + * var time = 0; + * + * // velocity (volume, from 0 to 1) + * var vel = 0.1; + * + * polySynth.play("G2", vel, 0, dur); + * polySynth.play("C3", vel, 0, dur); + * polySynth.play("G3", vel, 0, dur); + * + * background(random(255), random(255), 255); + * text('click to play', width/2, height/2); + * } + *
+ */ + p5.PolySynth.prototype.play = function (note, velocity, secondsFromNow, susTime) { + var susTime = susTime || 1; + this.noteAttack(note, velocity, secondsFromNow); + this.noteRelease(note, secondsFromNow + susTime); + }; + /** + * noteADSR sets the envelope for a specific note that has just been triggered. + * Using this method modifies the envelope of whichever audiovoice is being used + * to play the desired note. The envelope should be reset before noteRelease is called + * in order to prevent the modified envelope from being used on other notes. + * + * @method noteADSR + * @param {Number} [note] Midi note on which ADSR should be set. + * @param {Number} [attackTime] Time (in seconds before envelope + * reaches Attack Level + * @param {Number} [decayTime] Time (in seconds) before envelope + * reaches Decay/Sustain Level + * @param {Number} [susRatio] Ratio between attackLevel and releaseLevel, on a scale from 0 to 1, + * where 1.0 = attackLevel, 0.0 = releaseLevel. + * The susRatio determines the decayLevel and the level at which the + * sustain portion of the envelope will sustain. + * For example, if attackLevel is 0.4, releaseLevel is 0, + * and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is + * increased to 1.0 (using setRange), + * then decayLevel would increase proportionally, to become 0.5. + * @param {Number} [releaseTime] Time in seconds from now (defaults to 0) + **/ + p5.PolySynth.prototype.noteADSR = function (note, a, d, s, r, timeFromNow) { + var now = p5sound.audiocontext.currentTime; + var timeFromNow = timeFromNow || 0; + var t = now + timeFromNow; + this.audiovoices[this.notes[note].getValueAtTime(t)].setADSR(a, d, s, r); + }; + /** + * Set the PolySynths global envelope. This method modifies the envelopes of each + * monosynth so that all notes are played with this envelope. + * + * @method setADSR + * @param {Number} [attackTime] Time (in seconds before envelope + * reaches Attack Level + * @param {Number} [decayTime] Time (in seconds) before envelope + * reaches Decay/Sustain Level + * @param {Number} [susRatio] Ratio between attackLevel and releaseLevel, on a scale from 0 to 1, + * where 1.0 = attackLevel, 0.0 = releaseLevel. + * The susRatio determines the decayLevel and the level at which the + * sustain portion of the envelope will sustain. + * For example, if attackLevel is 0.4, releaseLevel is 0, + * and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is + * increased to 1.0 (using setRange), + * then decayLevel would increase proportionally, to become 0.5. + * @param {Number} [releaseTime] Time in seconds from now (defaults to 0) + **/ + p5.PolySynth.prototype.setADSR = function (a, d, s, r) { + this.audiovoices.forEach(function (voice) { + voice.setADSR(a, d, s, r); + }); + }; + /** + * Trigger the Attack, and Decay portion of a MonoSynth. + * Similar to holding down a key on a piano, but it will + * hold the sustain level until you let go. + * + * @method noteAttack + * @param {Number} [note] midi note on which attack should be triggered. + * @param {Number} [velocity] velocity of the note to play (ranging from 0 to 1)/ + * @param {Number} [secondsFromNow] time from now (in seconds) + * @example + *
+ * var polySynth = new p5.PolySynth(); + * var pitches = ["G", "D", "G", "C"]; + * var octaves = [2, 3, 4]; + * + * function mousePressed() { + * // play a chord: multiple notes at the same time + * for (var i = 0; i < 4; i++) { + * var note = random(pitches) + random(octaves); + * polySynth.noteAttack(note, 0.1); + * } + * } + * + * function mouseReleased() { + * // release all voices + * polySynth.noteRelease(); + * } + *
+ */ + p5.PolySynth.prototype.noteAttack = function (_note, _velocity, secondsFromNow) { + //this value goes to the audiovoices which handle their own scheduling + var secondsFromNow = ~~secondsFromNow; + //this value is used by this._voicesInUse + var acTime = p5sound.audiocontext.currentTime + secondsFromNow; + //Convert note to frequency if necessary. This is because entries into this.notes + //should be based on frequency for the sake of consistency. + var note = noteToFreq(_note); + var velocity = _velocity || 0.1; + var currentVoice; + //Release the note if it is already playing + if (this.notes[note] && this.notes[note].getValueAtTime(acTime) !== null) { + this.noteRelease(note, 0); + } + //Check to see how many voices are in use at the time the note will start + if (this._voicesInUse.getValueAtTime(acTime) < this.maxVoices) { + currentVoice = Math.max(~~this._voicesInUse.getValueAtTime(acTime), 0); + } else { + currentVoice = this._oldest; + var oldestNote = p5.prototype.freqToMidi(this.audiovoices[this._oldest].oscillator.freq().value); + this.noteRelease(oldestNote); + this._oldest = (this._oldest + 1) % (this.maxVoices - 1); + } + //Overrite the entry in the notes object. A note (frequency value) + //corresponds to the index of the audiovoice that is playing it + this.notes[note] = new TimelineSignal(); + this.notes[note].setValueAtTime(currentVoice, acTime); + //Find the scheduled change in this._voicesInUse that will be previous to this new note + //Add 1 and schedule this value at time 't', when this note will start playing + var previousVal = this._voicesInUse._searchBefore(acTime) === null ? 0 : this._voicesInUse._searchBefore(acTime).value; + this._voicesInUse.setValueAtTime(previousVal + 1, acTime); + //Then update all scheduled values that follow to increase by 1 + this._updateAfter(acTime, 1); + this._newest = currentVoice; + //The audiovoice handles the actual scheduling of the note + if (typeof velocity === 'number') { + var maxRange = 1 / this._voicesInUse.getValueAtTime(acTime) * 2; + velocity = velocity > maxRange ? maxRange : velocity; + } + this.audiovoices[currentVoice].triggerAttack(note, velocity, secondsFromNow); + }; + /** + * Private method to ensure accurate values of this._voicesInUse + * Any time a new value is scheduled, it is necessary to increment all subsequent + * scheduledValues after attack, and decrement all subsequent + * scheduledValues after release + * + * @private + * @param {[type]} time [description] + * @param {[type]} value [description] + * @return {[type]} [description] + */ + p5.PolySynth.prototype._updateAfter = function (time, value) { + if (this._voicesInUse._searchAfter(time) === null) { + return; + } else { + this._voicesInUse._searchAfter(time).value += value; + var nextTime = this._voicesInUse._searchAfter(time).time; + this._updateAfter(nextTime, value); + } + }; + /** + * Trigger the Release of an AudioVoice note. This is similar to releasing + * the key on a piano and letting the sound fade according to the + * release level and release time. + * + * @method noteRelease + * @param {Number} [note] midi note on which attack should be triggered. + * If no value is provided, all notes will be released. + * @param {Number} [secondsFromNow] time to trigger the release + * @example + *
+ * var pitches = ["G", "D", "G", "C"]; + * var octaves = [2, 3, 4]; + * var polySynth = new p5.PolySynth(); + * + * function mousePressed() { + * // play a chord: multiple notes at the same time + * for (var i = 0; i < 4; i++) { + * var note = random(pitches) + random(octaves); + * polySynth.noteAttack(note, 0.1); + * } + * } + * + * function mouseReleased() { + * // release all voices + * polySynth.noteRelease(); + * } + *
+ * + */ + p5.PolySynth.prototype.noteRelease = function (_note, secondsFromNow) { + var now = p5sound.audiocontext.currentTime; + var tFromNow = secondsFromNow || 0; + var t = now + tFromNow; + // if a note value is not provided, release all voices + if (!_note) { + this.audiovoices.forEach(function (voice) { + voice.triggerRelease(tFromNow); + }); + this._voicesInUse.setValueAtTime(0, t); + for (var n in this.notes) { + this.notes[n].dispose(); + delete this.notes[n]; + } + return; + } + //Make sure note is in frequency inorder to query the this.notes object + var note = noteToFreq(_note); + if (!this.notes[note] || this.notes[note].getValueAtTime(t) === null) { + console.warn('Cannot release a note that is not already playing'); + } else { + //Find the scheduled change in this._voicesInUse that will be previous to this new note + //subtract 1 and schedule this value at time 't', when this note will stop playing + var previousVal = Math.max(~~this._voicesInUse.getValueAtTime(t).value, 1); + this._voicesInUse.setValueAtTime(previousVal - 1, t); + //Then update all scheduled values that follow to decrease by 1 but never go below 0 + if (previousVal > 0) { + this._updateAfter(t, -1); + } + this.audiovoices[this.notes[note].getValueAtTime(t)].triggerRelease(tFromNow); + this.notes[note].dispose(); + delete this.notes[note]; + this._newest = this._newest === 0 ? 0 : (this._newest - 1) % (this.maxVoices - 1); + } + }; + /** + * Connect to a p5.sound / Web Audio object. + * + * @method connect + * @param {Object} unit A p5.sound or Web Audio object + */ + p5.PolySynth.prototype.connect = function (unit) { + var u = unit || p5sound.input; + this.output.connect(u.input ? u.input : u); + }; + /** + * Disconnect all outputs + * + * @method disconnect + */ + p5.PolySynth.prototype.disconnect = function () { + if (this.output) { + this.output.disconnect(); + } + }; + /** + * Get rid of the MonoSynth and free up its resources / memory. + * + * @method dispose + */ + p5.PolySynth.prototype.dispose = function () { + this.audiovoices.forEach(function (voice) { + voice.dispose(); + }); + if (this.output) { + this.output.disconnect(); + delete this.output; + } + }; +}(master, Tone_signal_TimelineSignal, helpers); +var distortion; +'use strict'; +distortion = function () { + var Effect = effect; + /* + * Adapted from [Kevin Ennis on StackOverflow](http://stackoverflow.com/questions/22312841/waveshaper-node-in-webaudio-how-to-emulate-distortion) + */ + function makeDistortionCurve(amount) { + var k = typeof amount === 'number' ? amount : 50; + var numSamples = 44100; + var curve = new Float32Array(numSamples); + var deg = Math.PI / 180; + var i = 0; + var x; + for (; i < numSamples; ++i) { + x = i * 2 / numSamples - 1; + curve[i] = (3 + k) * x * 20 * deg / (Math.PI + k * Math.abs(x)); + } + return curve; + } + /** + * A Distortion effect created with a Waveshaper Node, + * with an approach adapted from + * [Kevin Ennis](http://stackoverflow.com/questions/22312841/waveshaper-node-in-webaudio-how-to-emulate-distortion) + * + * This class extends p5.Effect. + * Methods amp(), chain(), + * drywet(), connect(), and + * disconnect() are available. + * + * @class p5.Distortion + * @extends p5.Effect + * @constructor + * @param {Number} [amount=0.25] Unbounded distortion amount. + * Normal values range from 0-1. + * @param {String} [oversample='none'] 'none', '2x', or '4x'. + * + */ + p5.Distortion = function (amount, oversample) { + Effect.call(this); + if (typeof amount === 'undefined') { + amount = 0.25; + } + if (typeof amount !== 'number') { + throw new Error('amount must be a number'); + } + if (typeof oversample === 'undefined') { + oversample = '2x'; + } + if (typeof oversample !== 'string') { + throw new Error('oversample must be a String'); + } + var curveAmount = p5.prototype.map(amount, 0, 1, 0, 2000); + /** + * The p5.Distortion is built with a + * + * Web Audio WaveShaper Node. + * + * @property {AudioNode} WaveShaperNode + */ + this.waveShaperNode = this.ac.createWaveShaper(); + this.amount = curveAmount; + this.waveShaperNode.curve = makeDistortionCurve(curveAmount); + this.waveShaperNode.oversample = oversample; + this.input.connect(this.waveShaperNode); + this.waveShaperNode.connect(this.wet); + }; + p5.Distortion.prototype = Object.create(Effect.prototype); + /** + * Process a sound source, optionally specify amount and oversample values. + * + * @method process + * @param {Number} [amount=0.25] Unbounded distortion amount. + * Normal values range from 0-1. + * @param {String} [oversample='none'] 'none', '2x', or '4x'. + */ + p5.Distortion.prototype.process = function (src, amount, oversample) { + src.connect(this.input); + this.set(amount, oversample); + }; + /** + * Set the amount and oversample of the waveshaper distortion. + * + * @method set + * @param {Number} [amount=0.25] Unbounded distortion amount. + * Normal values range from 0-1. + * @param {String} [oversample='none'] 'none', '2x', or '4x'. + */ + p5.Distortion.prototype.set = function (amount, oversample) { + if (amount) { + var curveAmount = p5.prototype.map(amount, 0, 1, 0, 2000); + this.amount = curveAmount; + this.waveShaperNode.curve = makeDistortionCurve(curveAmount); + } + if (oversample) { + this.waveShaperNode.oversample = oversample; + } + }; + /** + * Return the distortion amount, typically between 0-1. + * + * @method getAmount + * @return {Number} Unbounded distortion amount. + * Normal values range from 0-1. + */ + p5.Distortion.prototype.getAmount = function () { + return this.amount; + }; + /** + * Return the oversampling. + * + * @method getOversample + * + * @return {String} Oversample can either be 'none', '2x', or '4x'. + */ + p5.Distortion.prototype.getOversample = function () { + return this.waveShaperNode.oversample; + }; + p5.Distortion.prototype.dispose = function () { + Effect.prototype.dispose.apply(this); + if (this.waveShaperNode) { + this.waveShaperNode.disconnect(); + this.waveShaperNode = null; + } + }; +}(effect); +var src_app; +'use strict'; +src_app = function () { + var p5SOUND = master; + return p5SOUND; +}(shims, audiocontext, master, helpers, errorHandler, panner, soundfile, amplitude, fft, signal, oscillator, envelope, pulse, noise, audioin, filter, eq, panner3d, listener3d, delay, reverb, metro, looper, soundloop, compressor, soundRecorder, peakdetect, gain, monosynth, polysynth, distortion, audioVoice, monosynth, polysynth); +})); \ No newline at end of file diff --git a/pyp5js/static/p5/addons/p5.sound.min.js b/pyp5js/static/p5/addons/p5.sound.min.js new file mode 100644 index 00000000..899f4473 --- /dev/null +++ b/pyp5js/static/p5/addons/p5.sound.min.js @@ -0,0 +1,28 @@ +/*! p5.sound.min.js v0.3.11 2019-03-14 */ + +/** + * p5.sound + * https://p5js.org/reference/#/libraries/p5.sound + * + * From the Processing Foundation and contributors + * https://github.com/processing/p5.js-sound/graphs/contributors + * + * MIT License (MIT) + * https://github.com/processing/p5.js-sound/blob/master/LICENSE + * + * Some of the many audio libraries & resources that inspire p5.sound: + * - TONE.js (c) Yotam Mann. Licensed under The MIT License (MIT). https://github.com/TONEnoTONE/Tone.js + * - buzz.js (c) Jay Salvat. Licensed under The MIT License (MIT). http://buzz.jaysalvat.com/ + * - Boris Smus Web Audio API book, 2013. Licensed under the Apache License http://www.apache.org/licenses/LICENSE-2.0 + * - wavesurfer.js https://github.com/katspaugh/wavesurfer.js + * - Web Audio Components by Jordan Santell https://github.com/web-audio-components + * - Wilm Thoben's Sound library for Processing https://github.com/processing/processing/tree/master/java/libraries/sound + * + * Web Audio API: http://w3.org/TR/webaudio/ + */ + +!function(t,e){"function"==typeof define&&define.amd?define("p5.sound",["p5"],function(t){e(t)}):e("object"==typeof exports?require("../p5"):t.p5)}(this,function(t){var e;e=function(){!function(){function t(t){t&&(t.setTargetAtTime||(t.setTargetAtTime=t.setTargetValueAtTime))}window.hasOwnProperty("webkitAudioContext")&&!window.hasOwnProperty("AudioContext")&&(window.AudioContext=window.webkitAudioContext,"function"!=typeof AudioContext.prototype.createGain&&(AudioContext.prototype.createGain=AudioContext.prototype.createGainNode),"function"!=typeof AudioContext.prototype.createDelay&&(AudioContext.prototype.createDelay=AudioContext.prototype.createDelayNode),"function"!=typeof AudioContext.prototype.createScriptProcessor&&(AudioContext.prototype.createScriptProcessor=AudioContext.prototype.createJavaScriptNode),"function"!=typeof AudioContext.prototype.createPeriodicWave&&(AudioContext.prototype.createPeriodicWave=AudioContext.prototype.createWaveTable),AudioContext.prototype.internal_createGain=AudioContext.prototype.createGain,AudioContext.prototype.createGain=function(){var e=this.internal_createGain();return t(e.gain),e},AudioContext.prototype.internal_createDelay=AudioContext.prototype.createDelay,AudioContext.prototype.createDelay=function(e){var i=e?this.internal_createDelay(e):this.internal_createDelay();return t(i.delayTime),i},AudioContext.prototype.internal_createBufferSource=AudioContext.prototype.createBufferSource,AudioContext.prototype.createBufferSource=function(){var e=this.internal_createBufferSource();return e.start?(e.internal_start=e.start,e.start=function(t,i,n){"undefined"!=typeof n?e.internal_start(t||0,i,n):e.internal_start(t||0,i||0)}):e.start=function(t,e,i){e||i?this.noteGrainOn(t||0,e,i):this.noteOn(t||0)},e.stop?(e.internal_stop=e.stop,e.stop=function(t){e.internal_stop(t||0)}):e.stop=function(t){this.noteOff(t||0)},t(e.playbackRate),e},AudioContext.prototype.internal_createDynamicsCompressor=AudioContext.prototype.createDynamicsCompressor,AudioContext.prototype.createDynamicsCompressor=function(){var e=this.internal_createDynamicsCompressor();return t(e.threshold),t(e.knee),t(e.ratio),t(e.reduction),t(e.attack),t(e.release),e},AudioContext.prototype.internal_createBiquadFilter=AudioContext.prototype.createBiquadFilter,AudioContext.prototype.createBiquadFilter=function(){var e=this.internal_createBiquadFilter();return t(e.frequency),t(e.detune),t(e.Q),t(e.gain),e},"function"!=typeof AudioContext.prototype.createOscillator&&(AudioContext.prototype.internal_createOscillator=AudioContext.prototype.createOscillator,AudioContext.prototype.createOscillator=function(){var e=this.internal_createOscillator();return e.start?(e.internal_start=e.start,e.start=function(t){e.internal_start(t||0)}):e.start=function(t){this.noteOn(t||0)},e.stop?(e.internal_stop=e.stop,e.stop=function(t){e.internal_stop(t||0)}):e.stop=function(t){this.noteOff(t||0)},e.setPeriodicWave||(e.setPeriodicWave=e.setWaveTable),t(e.frequency),t(e.detune),e})),window.hasOwnProperty("webkitOfflineAudioContext")&&!window.hasOwnProperty("OfflineAudioContext")&&(window.OfflineAudioContext=window.webkitOfflineAudioContext)}(window),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia;var e=document.createElement("audio");t.prototype.isSupported=function(){return!!e.canPlayType};var i=function(){return!!e.canPlayType&&e.canPlayType('audio/ogg; codecs="vorbis"')},n=function(){return!!e.canPlayType&&e.canPlayType("audio/mpeg;")},o=function(){return!!e.canPlayType&&e.canPlayType('audio/wav; codecs="1"')},r=function(){return!!e.canPlayType&&(e.canPlayType("audio/x-m4a;")||e.canPlayType("audio/aac;"))},s=function(){return!!e.canPlayType&&e.canPlayType("audio/x-aiff;")};t.prototype.isFileSupported=function(t){switch(t.toLowerCase()){case"mp3":return n();case"wav":return o();case"ogg":return i();case"aac":case"m4a":case"mp4":return r();case"aif":case"aiff":return s();default:return!1}}}();var i;!function(t,e){i=function(){return e()}()}(this,function(){function t(t){var e=t.createBuffer(1,1,t.sampleRate),i=t.createBufferSource();i.buffer=e,i.connect(t.destination),i.start(0),t.resume&&t.resume()}function e(t){return"running"===t.state}function i(t,i){function n(){e(t)?i():(requestAnimationFrame(n),t.resume&&t.resume())}e(t)?i():n()}function n(t,e,i){if(Array.isArray(t)||NodeList&&t instanceof NodeList)for(var o=0;o1&&(this.input=new Array(t)),this.isUndef(e)||1===e?this.output=this.context.createGain():e>1&&(this.output=new Array(t))};t.prototype.set=function(e,i,n){if(this.isObject(e))n=i;else if(this.isString(e)){var o={};o[e]=i,e=o}t:for(var r in e){i=e[r];var s=this;if(-1!==r.indexOf(".")){for(var a=r.split("."),u=0;u1)for(var t=arguments[0],e=1;e0)for(var t=this,e=0;e0)for(var t=0;tn;n++)i[n].apply(this,e)}return this},t.Emitter.mixin=function(e){var i=["on","off","emit"];e._events={};for(var n=0;n1?t.getChannelData(1):e;var s=i(e,r),a=new window.ArrayBuffer(44+2*s.length),u=new window.DataView(a);n(u,0,"RIFF"),u.setUint32(4,36+2*s.length,!0),n(u,8,"WAVE"),n(u,12,"fmt "),u.setUint32(16,16,!0),u.setUint16(20,1,!0),u.setUint16(22,2,!0),u.setUint32(24,o.audiocontext.sampleRate,!0),u.setUint32(28,4*o.audiocontext.sampleRate,!0),u.setUint16(32,4,!0),u.setUint16(34,16,!0),n(u,36,"data"),u.setUint32(40,2*s.length,!0);for(var c=s.length,p=44,h=1,l=0;c>l;l++)u.setInt16(p,s[l]*(32767*h),!0),p+=2;return u}function i(t,e){for(var i=t.length+e.length,n=new Float32Array(i),o=0,r=0;i>r;)n[r++]=t[o],n[r++]=e[o],o++;return n}function n(t,e,i){for(var n=i.length,o=0;n>o;o++)t.setUint8(e+o,i.charCodeAt(o))}var o=a;t.prototype.sampleRate=function(){return o.audiocontext.sampleRate},t.prototype.freqToMidi=function(t){var e=Math.log(t/440)/Math.log(2),i=Math.round(12*e)+69;return i};var r=t.prototype.midiToFreq=function(t){return 440*Math.pow(2,(t-69)/12)},s=function(t){if("string"!=typeof t)return t;var e={A:21,B:23,C:24,D:26,E:28,F:29,G:31},i=e[t[0].toUpperCase()],n=~~t.slice(-1);switch(i+=12*(n-1),t[1]){case"#":i+=1;break;case"b":i-=1}return r(i)};return t.prototype.soundFormats=function(){o.extensions=[];for(var t=0;t-1))throw arguments[t]+" is not a valid sound format!";o.extensions.push(arguments[t])}},t.prototype.disposeSound=function(){for(var t=0;t-1)if(t.prototype.isFileSupported(n))i=i;else for(var r=i.split("."),s=r[r.length-1],a=0;a1?(this.splitter=i.createChannelSplitter(2),this.input.connect(this.splitter),this.splitter.connect(this.left,1),this.splitter.connect(this.right,0)):(this.input.connect(this.left),this.input.connect(this.right)),this.output=i.createChannelMerger(2),this.left.connect(this.output,0,1),this.right.connect(this.output,0,0),this.output.connect(e)},t.Panner.prototype.pan=function(t,e){var n=e||0,o=i.currentTime+n,r=(t+1)/2,s=Math.cos(r*Math.PI/2),a=Math.sin(r*Math.PI/2);this.left.gain.linearRampToValueAtTime(a,o),this.right.gain.linearRampToValueAtTime(s,o)},t.Panner.prototype.inputChannels=function(t){1===t?(this.input.disconnect(),this.input.connect(this.left),this.input.connect(this.right)):2===t&&(this.splitter=i.createChannelSplitter(2),this.input.disconnect(),this.input.connect(this.splitter),this.splitter.connect(this.left,1),this.splitter.connect(this.right,0))},t.Panner.prototype.connect=function(t){this.output.connect(t)},t.Panner.prototype.disconnect=function(){this.output&&this.output.disconnect()})}(a);var h;h=function(){function e(t,e){for(var i={},n=t.length,o=0;n>o;o++){if(t[o]>e){var r=t[o],s=new v(r,o);i[o]=s,o+=6e3}o++}return i}function i(t){for(var e=[],i=Object.keys(t).sort(),n=0;no;o++){var r=t[i[n]],s=t[i[n+o]];if(r&&s){var a=r.sampleIndex,u=s.sampleIndex,c=u-a;c>0&&r.intervals.push(c);var p=e.some(function(t){return t.interval===c?(t.count++,t):void 0});p||e.push({interval:c,count:1})}}return e}function n(t,e){var i=[];return t.forEach(function(t){try{var n=Math.abs(60/(t.interval/e));n=r(n);var o=i.some(function(e){return e.tempo===n?e.count+=t.count:void 0});if(!o){if(isNaN(n))return;i.push({tempo:Math.round(n),count:t.count})}}catch(s){throw s}}),i}function o(t,e,i,n){for(var o=[],s=Object.keys(t).sort(),a=0;a.01?!0:void 0})}function r(t){if(isFinite(t)&&0!==t){for(;90>t;)t*=2;for(;t>180&&t>90;)t/=2;return t}}function s(t){var e=t.inputBuffer.getChannelData(0);this._lastPos=e[e.length-1]||0,this._onTimeUpdate(self._lastPos)}function p(t){const e=t.target,i=this;e._playing=!1,e.removeEventListener("ended",i._clearOnEnd),i._onended(i),i.bufferSourceNodes.forEach(function(t,e){t._playing===!1&&i.bufferSourceNodes.splice(e)}),0===i.bufferSourceNodes.length&&(i._playing=!1)}var h=c,l=a,f=l.audiocontext,d=u.midiToFreq,m=u.convertToWav;t.SoundFile=function(e,i,n,o){if("undefined"!=typeof e){if("string"==typeof e||"string"==typeof e[0]){var r=t.prototype._checkFileFormats(e);this.url=r}else if("object"==typeof e&&!(window.File&&window.FileReader&&window.FileList&&window.Blob))throw"Unable to load file because the File API is not supported";e.file&&(e=e.file),this.file=e}this._onended=function(){},this._looping=!1,this._playing=!1,this._paused=!1,this._pauseTime=0,this._cues=[],this._cueIDCounter=0,this._lastPos=0,this._counterNode=null,this._scopeNode=null,this.bufferSourceNodes=[],this.bufferSourceNode=null,this.buffer=null,this.playbackRate=1,this.input=l.audiocontext.createGain(),this.output=l.audiocontext.createGain(),this.reversed=!1,this.startTime=0,this.endTime=null,this.pauseTime=0,this.mode="sustain",this.startMillis=null,this.panPosition=0,this.panner=new t.Panner(this.output,l.input,2),(this.url||this.file)&&this.load(i,n),l.soundArray.push(this),"function"==typeof o?this._whileLoading=o:this._whileLoading=function(){},this._onAudioProcess=s.bind(this),this._clearOnEnd=p.bind(this)},t.prototype.registerPreloadMethod("loadSound",t.prototype),t.prototype.loadSound=function(e,i,n,o){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&window.alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS");var r=this,s=new t.SoundFile(e,function(){"function"==typeof i&&i.apply(r,arguments),"function"==typeof r._decrementPreload&&r._decrementPreload()},n,o);return s},t.SoundFile.prototype.load=function(t,e){var i=this,n=(new Error).stack;if(void 0!==this.url&&""!==this.url){var o=new XMLHttpRequest;o.addEventListener("progress",function(t){i._updateProgress(t)},!1),o.open("GET",this.url,!0),o.responseType="arraybuffer",o.onload=function(){if(200===o.status){if(!i.panner)return;f.decodeAudioData(o.response,function(e){i.panner&&(i.buffer=e,i.panner.inputChannels(e.numberOfChannels),t&&t(i))},function(){if(i.panner){var t=new h("decodeAudioData",n,i.url),o="AudioContext error at decodeAudioData for "+i.url;e?(t.msg=o,e(t)):console.error(o+"\n The error stack trace includes: \n"+t.stack)}})}else{if(!i.panner)return;var r=new h("loadSound",n,i.url),s="Unable to load "+i.url+". The request status was: "+o.status+" ("+o.statusText+")";e?(r.message=s,e(r)):console.error(s+"\n The error stack trace includes: \n"+r.stack)}},o.onerror=function(){var t=new h("loadSound",n,i.url),o="There was no response from the server at "+i.url+". Check the url and internet connectivity.";e?(t.message=o,e(t)):console.error(o+"\n The error stack trace includes: \n"+t.stack)},o.send()}else if(void 0!==this.file){var r=new FileReader;r.onload=function(){i.panner&&f.decodeAudioData(r.result,function(e){i.panner&&(i.buffer=e,i.panner.inputChannels(e.numberOfChannels),t&&t(i))})},r.onerror=function(t){i.panner&&onerror&&onerror(t)},r.readAsArrayBuffer(this.file)}},t.SoundFile.prototype._updateProgress=function(t){if(t.lengthComputable){var e=t.loaded/t.total*.99;this._whileLoading(e,t)}else this._whileLoading("size unknown")},t.SoundFile.prototype.isLoaded=function(){return this.buffer?!0:!1},t.SoundFile.prototype.play=function(t,e,i,n,o){if(!this.output)return void console.warn("SoundFile.play() called after dispose");var r,s,a=l.audiocontext.currentTime,u=t||0;if(0>u&&(u=0),u+=a,"undefined"!=typeof e&&this.rate(e),"undefined"!=typeof i&&this.setVolume(i),!this.buffer)throw"not ready to play file, buffer has yet to load. Try preload()";if(this._pauseTime=0,"restart"===this.mode&&this.buffer&&this.bufferSourceNode&&(this.bufferSourceNode.stop(u),this._counterNode.stop(u)),"untildone"!==this.mode||!this.isPlaying()){if(this.bufferSourceNode=this._initSourceNode(),delete this._counterNode,this._counterNode=this._initCounterNode(),n){if(!(n>=0&&nt&&!this.reversed?(t=Math.abs(t),e=!0):t>0&&this.reversed&&(e=!0),this.bufferSourceNode){var i=l.audiocontext.currentTime;this.bufferSourceNode.playbackRate.cancelScheduledValues(i),this.bufferSourceNode.playbackRate.linearRampToValueAtTime(Math.abs(t),i),this._counterNode.playbackRate.cancelScheduledValues(i),this._counterNode.playbackRate.linearRampToValueAtTime(Math.abs(t),i)}return e&&this.reverseBuffer(),this.playbackRate},t.SoundFile.prototype.setPitch=function(t){var e=d(t)/d(60);this.rate(e)},t.SoundFile.prototype.getPlaybackRate=function(){return this.playbackRate},t.SoundFile.prototype.duration=function(){return this.buffer?this.buffer.duration:0},t.SoundFile.prototype.currentTime=function(){return this.reversed?Math.abs(this._lastPos-this.buffer.length)/f.sampleRate:this._lastPos/f.sampleRate},t.SoundFile.prototype.jump=function(t,e){if(0>t||t>this.buffer.duration)throw"jump time out of range";if(e>this.buffer.duration-t)throw"end time out of range";var i=t||0,n=e||void 0;this.isPlaying()&&this.stop(0),this.play(0,this.playbackRate,this.output.gain.value,i,n); +},t.SoundFile.prototype.channels=function(){return this.buffer.numberOfChannels},t.SoundFile.prototype.sampleRate=function(){return this.buffer.sampleRate},t.SoundFile.prototype.frames=function(){return this.buffer.length},t.SoundFile.prototype.getPeaks=function(t){if(!this.buffer)throw"Cannot load peaks yet, buffer is not loaded";if(t||(t=5*window.width),this.buffer){for(var e=this.buffer,i=e.length/t,n=~~(i/10)||1,o=e.numberOfChannels,r=new Float32Array(Math.round(t)),s=0;o>s;s++)for(var a=e.getChannelData(s),u=0;t>u;u++){for(var c=~~(u*i),p=~~(c+i),h=0,l=c;p>l;l+=n){var f=a[l];f>h?h=f:-f>h&&(h=f)}(0===s||Math.abs(h)>r[u])&&(r[u]=h)}return r}},t.SoundFile.prototype.reverseBuffer=function(){if(!this.buffer)throw"SoundFile is not done loading";var t=this._lastPos/f.sampleRate,e=this.getVolume();this.setVolume(0,.001);const i=this.buffer.numberOfChannels;for(var n=0;i>n;n++)this.buffer.getChannelData(n).reverse();this.reversed=!this.reversed,t&&this.jump(this.duration()-t),this.setVolume(e,.001)},t.SoundFile.prototype.onended=function(t){return this._onended=t,this},t.SoundFile.prototype.add=function(){},t.SoundFile.prototype.dispose=function(){var t=l.audiocontext.currentTime,e=l.soundArray.indexOf(this);if(l.soundArray.splice(e,1),this.stop(t),this.buffer&&this.bufferSourceNode){for(var i=0;io;o++){var r=n.getChannelData(o);r.set(t[o])}this.buffer=n,this.panner.inputChannels(e)};var y=function(t){const e=t.length,i=f.createBuffer(1,t.length,f.sampleRate),n=i.getChannelData(0);for(var o=0;e>o;o++)n[o]=o;return i};t.SoundFile.prototype._initCounterNode=function(){var e=this,i=f.currentTime,n=f.createBufferSource();return e._scopeNode&&(e._scopeNode.disconnect(),e._scopeNode.removeEventListener("audioprocess",e._onAudioProcess),delete e._scopeNode),e._scopeNode=f.createScriptProcessor(256,1,1),n.buffer=y(e.buffer),n.playbackRate.setValueAtTime(e.playbackRate,i),n.connect(e._scopeNode),e._scopeNode.connect(t.soundOut._silentNode),e._scopeNode.addEventListener("audioprocess",e._onAudioProcess),n},t.SoundFile.prototype._initSourceNode=function(){var t=f.createBufferSource();return t.buffer=this.buffer,t.playbackRate.value=this.playbackRate,t.connect(this.output),t},t.SoundFile.prototype.processPeaks=function(t,r,s,a){var u=this.buffer.length,c=this.buffer.sampleRate,p=this.buffer,h=[],l=r||.9,f=l,d=s||.22,m=a||200,y=new window.OfflineAudioContext(1,u,c),v=y.createBufferSource();v.buffer=p;var g=y.createBiquadFilter();g.type="lowpass",v.connect(g),g.connect(y.destination),v.start(0),y.startRendering(),y.oncomplete=function(r){if(self.panner){var s=r.renderedBuffer,a=s.getChannelData(0);do h=e(a,f),f-=.005;while(Object.keys(h).length=d);var u=i(h),c=n(u,s.sampleRate),p=c.sort(function(t,e){return e.count-t.count}).splice(0,5);this.tempo=p[0].tempo;var l=5,y=o(h,p[0].tempo,s.sampleRate,l);t(y)}}};var v=function(t,e){this.sampleIndex=e,this.amplitude=t,this.tempos=[],this.intervals=[]},g=function(t,e,i,n){this.callback=t,this.time=e,this.id=i,this.val=n};t.SoundFile.prototype.addCue=function(t,e,i){var n=this._cueIDCounter++,o=new g(e,t,n,i);return this._cues.push(o),n},t.SoundFile.prototype.removeCue=function(t){for(var e=this._cues.length,i=0;e>i;i++){var n=this._cues[i];if(n.id===t){this._cues.splice(i,1);break}}0===this._cues.length},t.SoundFile.prototype.clearCues=function(){this._cues=[]},t.SoundFile.prototype._onTimeUpdate=function(t){for(var e=t/this.buffer.sampleRate,i=this._cues.length,n=0;i>n;n++){var o=this._cues[n],r=o.time,s=o.val;this._prevTime=r&&o.callback(s)}this._prevTime=e},t.SoundFile.prototype.save=function(e){const i=m(this.buffer);t.prototype.saveSound([i],e,"wav")},t.SoundFile.prototype.getBlob=function(){const t=m(this.buffer);return new Blob([t],{type:"audio/wav"})}}(c,a,u,u);var l;l=function(){var e=a;t.Amplitude=function(t){this.bufferSize=2048,this.audiocontext=e.audiocontext,this.processor=this.audiocontext.createScriptProcessor(this.bufferSize,2,1),this.input=this.processor,this.output=this.audiocontext.createGain(),this.smoothing=t||0,this.volume=0,this.average=0,this.stereoVol=[0,0],this.stereoAvg=[0,0],this.stereoVolNorm=[0,0],this.volMax=.001,this.normalize=!1,this.processor.onaudioprocess=this._audioProcess.bind(this),this.processor.connect(this.output),this.output.gain.value=0,this.output.connect(this.audiocontext.destination),e.meter.connect(this.processor),e.soundArray.push(this)},t.Amplitude.prototype.setInput=function(i,n){e.meter.disconnect(),n&&(this.smoothing=n),null==i?(console.log("Amplitude input source is not ready! Connecting to master output instead"),e.meter.connect(this.processor)):i instanceof t.Signal?i.output.connect(this.processor):i?(i.connect(this.processor),this.processor.disconnect(),this.processor.connect(this.output)):e.meter.connect(this.processor)},t.Amplitude.prototype.connect=function(t){t?t.hasOwnProperty("input")?this.output.connect(t.input):this.output.connect(t):this.output.connect(this.panner.connect(e.input))},t.Amplitude.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.Amplitude.prototype._audioProcess=function(t){for(var e=0;ea;a++)i=n[a],this.normalize?(r+=Math.max(Math.min(i/this.volMax,1),-1),s+=Math.max(Math.min(i/this.volMax,1),-1)*Math.max(Math.min(i/this.volMax,1),-1)):(r+=i,s+=i*i);var u=r/o,c=Math.sqrt(s/o);this.stereoVol[e]=Math.max(c,this.stereoVol[e]*this.smoothing),this.stereoAvg[e]=Math.max(u,this.stereoVol[e]*this.smoothing),this.volMax=Math.max(this.stereoVol[e],this.volMax)}var p=this,h=this.stereoVol.reduce(function(t,e,i){return p.stereoVolNorm[i-1]=Math.max(Math.min(p.stereoVol[i-1]/p.volMax,1),0),p.stereoVolNorm[i]=Math.max(Math.min(p.stereoVol[i]/p.volMax,1),0),t+e});this.volume=h/this.stereoVol.length,this.volNorm=Math.max(Math.min(this.volume/this.volMax,1),0)},t.Amplitude.prototype.getLevel=function(t){return"undefined"!=typeof t?this.normalize?this.stereoVolNorm[t]:this.stereoVol[t]:this.normalize?this.volNorm:this.volume},t.Amplitude.prototype.toggleNormalize=function(t){"boolean"==typeof t?this.normalize=t:this.normalize=!this.normalize},t.Amplitude.prototype.smooth=function(t){t>=0&&1>t?this.smoothing=t:console.log("Error: smoothing must be between 0 and 1")},t.Amplitude.prototype.dispose=function(){var t=e.soundArray.indexOf(this);e.soundArray.splice(t,1),this.input&&(this.input.disconnect(),delete this.input),this.output&&(this.output.disconnect(),delete this.output),delete this.processor}}(a);var f;f=function(){var e=a;t.FFT=function(t,i){this.input=this.analyser=e.audiocontext.createAnalyser(),Object.defineProperties(this,{bins:{get:function(){return this.analyser.fftSize/2},set:function(t){this.analyser.fftSize=2*t},configurable:!0,enumerable:!0},smoothing:{get:function(){return this.analyser.smoothingTimeConstant},set:function(t){this.analyser.smoothingTimeConstant=t},configurable:!0,enumerable:!0}}),this.smooth(t),this.bins=i||1024,e.fftMeter.connect(this.analyser),this.freqDomain=new Uint8Array(this.analyser.frequencyBinCount),this.timeDomain=new Uint8Array(this.analyser.frequencyBinCount),this.bass=[20,140],this.lowMid=[140,400],this.mid=[400,2600],this.highMid=[2600,5200],this.treble=[5200,14e3],e.soundArray.push(this)},t.FFT.prototype.setInput=function(t){t?(t.output?t.output.connect(this.analyser):t.connect&&t.connect(this.analyser),e.fftMeter.disconnect()):e.fftMeter.connect(this.analyser)},t.FFT.prototype.waveform=function(){for(var e,i,n,s=0;si){var o=i;i=t,t=o}for(var r=Math.round(t/n*this.freqDomain.length),s=Math.round(i/n*this.freqDomain.length),a=0,u=0,c=r;s>=c;c++)a+=this.freqDomain[c],u+=1;var p=a/u;return p}throw"invalid input for getEnergy()"}var h=Math.round(t/n*this.freqDomain.length);return this.freqDomain[h]},t.FFT.prototype.getFreq=function(t,e){console.log("getFreq() is deprecated. Please use getEnergy() instead.");var i=this.getEnergy(t,e);return i},t.FFT.prototype.getCentroid=function(){for(var t=e.audiocontext.sampleRate/2,i=0,n=0,o=0;os;s++)o[r]=void 0!==o[r]?(o[r]+e[s])/2:e[s],s%n===n-1&&r++;return o},t.FFT.prototype.logAverages=function(t){for(var i=e.audiocontext.sampleRate/2,n=this.freqDomain,o=n.length,r=new Array(t.length),s=0,a=0;o>a;a++){var u=Math.round(a*i/this.freqDomain.length);u>t[s].hi&&s++,r[s]=void 0!==r[s]?(r[s]+n[a])/2:n[a]}return r},t.FFT.prototype.getOctaveBands=function(t,i){var t=t||3,i=i||15.625,n=[],o={lo:i/Math.pow(2,1/(2*t)),ctr:i,hi:i*Math.pow(2,1/(2*t))};n.push(o);for(var r=e.audiocontext.sampleRate/2;o.hie;e++){var n=e/(i-1)*2-1;this._curve[e]=t(n,e)}return this._shaper.curve=this._curve,this},Object.defineProperty(t.WaveShaper.prototype,"curve",{get:function(){return this._shaper.curve},set:function(t){this._curve=new Float32Array(t),this._shaper.curve=this._curve}}),Object.defineProperty(t.WaveShaper.prototype,"oversample",{get:function(){return this._shaper.oversample},set:function(t){if(-1===["none","2x","4x"].indexOf(t))throw new RangeError("Tone.WaveShaper: oversampling must be either 'none', '2x', or '4x'");this._shaper.oversample=t}}),t.WaveShaper.prototype.dispose=function(){return t.prototype.dispose.call(this),this._shaper.disconnect(),this._shaper=null,this._curve=null,this},t.WaveShaper}(n);var y;y=function(t){return t.TimeBase=function(e,i){if(!(this instanceof t.TimeBase))return new t.TimeBase(e,i);if(this._expr=this._noOp,e instanceof t.TimeBase)this.copy(e);else if(!this.isUndef(i)||this.isNumber(e)){i=this.defaultArg(i,this._defaultUnits);var n=this._primaryExpressions[i].method;this._expr=n.bind(this,e)}else this.isString(e)?this.set(e):this.isUndef(e)&&(this._expr=this._defaultExpr())},t.extend(t.TimeBase),t.TimeBase.prototype.set=function(t){return this._expr=this._parseExprString(t),this},t.TimeBase.prototype.clone=function(){var t=new this.constructor;return t.copy(this),t},t.TimeBase.prototype.copy=function(t){var e=t._expr();return this.set(e)},t.TimeBase.prototype._primaryExpressions={n:{regexp:/^(\d+)n/i,method:function(t){return t=parseInt(t),1===t?this._beatsToUnits(this._timeSignature()):this._beatsToUnits(4/t)}},t:{regexp:/^(\d+)t/i,method:function(t){return t=parseInt(t),this._beatsToUnits(8/(3*parseInt(t)))}},m:{regexp:/^(\d+)m/i,method:function(t){return this._beatsToUnits(parseInt(t)*this._timeSignature())}},i:{regexp:/^(\d+)i/i,method:function(t){return this._ticksToUnits(parseInt(t))}},hz:{regexp:/^(\d+(?:\.\d+)?)hz/i,method:function(t){return this._frequencyToUnits(parseFloat(t))}},tr:{regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method:function(t,e,i){var n=0;return t&&"0"!==t&&(n+=this._beatsToUnits(this._timeSignature()*parseFloat(t))),e&&"0"!==e&&(n+=this._beatsToUnits(parseFloat(e))),i&&"0"!==i&&(n+=this._beatsToUnits(parseFloat(i)/4)),n}},s:{regexp:/^(\d+(?:\.\d+)?s)/,method:function(t){return this._secondsToUnits(parseFloat(t))}},samples:{regexp:/^(\d+)samples/,method:function(t){return parseInt(t)/this.context.sampleRate}},"default":{regexp:/^(\d+(?:\.\d+)?)/,method:function(t){return this._primaryExpressions[this._defaultUnits].method.call(this,t)}}},t.TimeBase.prototype._binaryExpressions={"+":{regexp:/^\+/,precedence:2,method:function(t,e){return t()+e()}},"-":{regexp:/^\-/,precedence:2,method:function(t,e){return t()-e()}},"*":{regexp:/^\*/,precedence:1,method:function(t,e){return t()*e()}},"/":{regexp:/^\//,precedence:1,method:function(t,e){return t()/e()}}},t.TimeBase.prototype._unaryExpressions={neg:{regexp:/^\-/,method:function(t){return-t()}}},t.TimeBase.prototype._syntaxGlue={"(":{regexp:/^\(/},")":{regexp:/^\)/}},t.TimeBase.prototype._tokenize=function(t){function e(t,e){for(var i=["_binaryExpressions","_unaryExpressions","_primaryExpressions","_syntaxGlue"],n=0;n0;){t=t.trim();var o=e(t,this);n.push(o),t=t.substr(o.value.length)}return{next:function(){return n[++i]},peek:function(){return n[i+1]}}},t.TimeBase.prototype._matchGroup=function(t,e,i){var n=!1;if(!this.isUndef(t))for(var o in e){var r=e[o];if(r.regexp.test(t.value)){if(this.isUndef(i))return r;if(r.precedence===i)return r}}return n},t.TimeBase.prototype._parseBinary=function(t,e){this.isUndef(e)&&(e=2);var i;i=0>e?this._parseUnary(t):this._parseBinary(t,e-1);for(var n=t.peek();n&&this._matchGroup(n,this._binaryExpressions,e);)n=t.next(),i=n.method.bind(this,i,this._parseBinary(t,e-1)),n=t.peek();return i},t.TimeBase.prototype._parseUnary=function(t){var e,i;e=t.peek();var n=this._matchGroup(e,this._unaryExpressions);return n?(e=t.next(),i=this._parseUnary(t),n.method.bind(this,i)):this._parsePrimary(t)},t.TimeBase.prototype._parsePrimary=function(t){var e,i;if(e=t.peek(),this.isUndef(e))throw new SyntaxError("Tone.TimeBase: Unexpected end of expression");if(this._matchGroup(e,this._primaryExpressions)){e=t.next();var n=e.value.match(e.regexp);return e.method.bind(this,n[1],n[2],n[3])}if(e&&"("===e.value){if(t.next(),i=this._parseBinary(t),e=t.next(),!e||")"!==e.value)throw new SyntaxError("Expected )");return i}throw new SyntaxError("Tone.TimeBase: Cannot process token "+e.value)},t.TimeBase.prototype._parseExprString=function(t){this.isString(t)||(t=t.toString());var e=this._tokenize(t),i=this._parseBinary(e);return i},t.TimeBase.prototype._noOp=function(){return 0},t.TimeBase.prototype._defaultExpr=function(){return this._noOp},t.TimeBase.prototype._defaultUnits="s",t.TimeBase.prototype._frequencyToUnits=function(t){return 1/t},t.TimeBase.prototype._beatsToUnits=function(e){return 60/t.Transport.bpm.value*e},t.TimeBase.prototype._secondsToUnits=function(t){return t},t.TimeBase.prototype._ticksToUnits=function(e){return e*(this._beatsToUnits(1)/t.Transport.PPQ)},t.TimeBase.prototype._timeSignature=function(){return t.Transport.timeSignature},t.TimeBase.prototype._pushExpr=function(e,i,n){return e instanceof t.TimeBase||(e=new this.constructor(e,n)),this._expr=this._binaryExpressions[i].method.bind(this,this._expr,e._expr),this},t.TimeBase.prototype.add=function(t,e){return this._pushExpr(t,"+",e)},t.TimeBase.prototype.sub=function(t,e){return this._pushExpr(t,"-",e)},t.TimeBase.prototype.mult=function(t,e){return this._pushExpr(t,"*",e)},t.TimeBase.prototype.div=function(t,e){return this._pushExpr(t,"/",e)},t.TimeBase.prototype.valueOf=function(){return this._expr()},t.TimeBase.prototype.dispose=function(){this._expr=null},t.TimeBase}(n);var v;v=function(t){return t.Time=function(e,i){return this instanceof t.Time?(this._plusNow=!1,void t.TimeBase.call(this,e,i)):new t.Time(e,i)},t.extend(t.Time,t.TimeBase),t.Time.prototype._unaryExpressions=Object.create(t.TimeBase.prototype._unaryExpressions),t.Time.prototype._unaryExpressions.quantize={regexp:/^@/,method:function(e){return t.Transport.nextSubdivision(e())}},t.Time.prototype._unaryExpressions.now={regexp:/^\+/,method:function(t){return this._plusNow=!0,t()}},t.Time.prototype.quantize=function(t,e){return e=this.defaultArg(e,1),this._expr=function(t,e,i){t=t(),e=e.toSeconds();var n=Math.round(t/e),o=n*e,r=o-t;return t+r*i}.bind(this,this._expr,new this.constructor(t),e),this},t.Time.prototype.addNow=function(){return this._plusNow=!0,this},t.Time.prototype._defaultExpr=function(){return this._plusNow=!0,this._noOp},t.Time.prototype.copy=function(e){return t.TimeBase.prototype.copy.call(this,e),this._plusNow=e._plusNow,this},t.Time.prototype.toNotation=function(){var t=this.toSeconds(),e=["1m","2n","4n","8n","16n","32n","64n","128n"],i=this._toNotationHelper(t,e),n=["1m","2n","2t","4n","4t","8n","8t","16n","16t","32n","32t","64n","64t","128n"],o=this._toNotationHelper(t,n);return o.split("+").length1-s%1&&(s+=a),s=Math.floor(s),s>0){if(n+=1===s?e[o]:s.toString()+"*"+e[o],t-=s*r,i>t)break;n+=" + "}}return""===n&&(n="0"),n},t.Time.prototype._notationToUnits=function(t){for(var e=this._primaryExpressions,i=[e.n,e.t,e.m],n=0;n3&&(n=parseFloat(n).toFixed(3));var o=[i,e,n];return o.join(":")},t.Time.prototype.toTicks=function(){var e=this._beatsToUnits(1),i=this.valueOf()/e;return Math.floor(i*t.Transport.PPQ)},t.Time.prototype.toSamples=function(){return this.toSeconds()*this.context.sampleRate},t.Time.prototype.toFrequency=function(){return 1/this.toSeconds()},t.Time.prototype.toSeconds=function(){return this.valueOf()},t.Time.prototype.toMilliseconds=function(){return 1e3*this.toSeconds()},t.Time.prototype.valueOf=function(){var t=this._expr();return t+(this._plusNow?this.now():0)},t.Time}(n);var g;g=function(t){t.Frequency=function(e,i){return this instanceof t.Frequency?void t.TimeBase.call(this,e,i):new t.Frequency(e,i)},t.extend(t.Frequency,t.TimeBase),t.Frequency.prototype._primaryExpressions=Object.create(t.TimeBase.prototype._primaryExpressions),t.Frequency.prototype._primaryExpressions.midi={regexp:/^(\d+(?:\.\d+)?midi)/,method:function(t){return this.midiToFrequency(t)}},t.Frequency.prototype._primaryExpressions.note={regexp:/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i,method:function(t,i){var n=e[t.toLowerCase()],o=n+12*(parseInt(i)+1);return this.midiToFrequency(o)}},t.Frequency.prototype._primaryExpressions.tr={regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method:function(t,e,i){var n=1;return t&&"0"!==t&&(n*=this._beatsToUnits(this._timeSignature()*parseFloat(t))),e&&"0"!==e&&(n*=this._beatsToUnits(parseFloat(e))),i&&"0"!==i&&(n*=this._beatsToUnits(parseFloat(i)/4)),n}},t.Frequency.prototype.transpose=function(t){return this._expr=function(t,e){var i=t();return i*this.intervalToFrequencyRatio(e)}.bind(this,this._expr,t),this},t.Frequency.prototype.harmonize=function(t){return this._expr=function(t,e){for(var i=t(),n=[],o=0;or&&(o+=-12*r);var s=i[o%12];return s+r.toString()},t.Frequency.prototype.toSeconds=function(){return 1/this.valueOf()},t.Frequency.prototype.toFrequency=function(){return this.valueOf()},t.Frequency.prototype.toTicks=function(){var e=this._beatsToUnits(1),i=this.valueOf()/e;return Math.floor(i*t.Transport.PPQ)},t.Frequency.prototype._frequencyToUnits=function(t){return t},t.Frequency.prototype._ticksToUnits=function(e){return 1/(60*e/(t.Transport.bpm.value*t.Transport.PPQ))},t.Frequency.prototype._beatsToUnits=function(e){return 1/t.TimeBase.prototype._beatsToUnits.call(this,e)},t.Frequency.prototype._secondsToUnits=function(t){return 1/t},t.Frequency.prototype._defaultUnits="hz";var e={cbb:-2,cb:-1,c:0,"c#":1,cx:2,dbb:0,db:1,d:2,"d#":3,dx:4,ebb:2,eb:3,e:4,"e#":5,ex:6,fbb:3,fb:4,f:5,"f#":6,fx:7,gbb:5,gb:6,g:7,"g#":8,gx:9,abb:7,ab:8,a:9,"a#":10,ax:11,bbb:9,bb:10,b:11,"b#":12,bx:13},i=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];return t.Frequency.A4=440,t.Frequency.prototype.midiToFrequency=function(e){return t.Frequency.A4*Math.pow(2,(e-69)/12)},t.Frequency.prototype.frequencyToMidi=function(e){return 69+12*Math.log(e/t.Frequency.A4)/Math.LN2},t.Frequency}(n);var _;_=function(t){return t.TransportTime=function(e,i){return this instanceof t.TransportTime?void t.Time.call(this,e,i):new t.TransportTime(e,i)},t.extend(t.TransportTime,t.Time),t.TransportTime.prototype._unaryExpressions=Object.create(t.Time.prototype._unaryExpressions),t.TransportTime.prototype._unaryExpressions.quantize={regexp:/^@/,method:function(e){var i=this._secondsToTicks(e()),n=Math.ceil(t.Transport.ticks/i);return this._ticksToUnits(n*i)}},t.TransportTime.prototype._secondsToTicks=function(e){var i=this._beatsToUnits(1),n=e/i;return Math.round(n*t.Transport.PPQ)},t.TransportTime.prototype.valueOf=function(){var e=this._secondsToTicks(this._expr());return e+(this._plusNow?t.Transport.ticks:0)},t.TransportTime.prototype.toTicks=function(){return this.valueOf()},t.TransportTime.prototype.toSeconds=function(){var e=this._expr();return e+(this._plusNow?t.Transport.seconds:0)},t.TransportTime.prototype.toFrequency=function(){return 1/this.toSeconds()},t.TransportTime}(n);var T;T=function(t){return t.Type={Default:"number",Time:"time",Frequency:"frequency",TransportTime:"transportTime",Ticks:"ticks",NormalRange:"normalRange",AudioRange:"audioRange",Decibels:"db",Interval:"interval",BPM:"bpm",Positive:"positive",Cents:"cents",Degrees:"degrees",MIDI:"midi",BarsBeatsSixteenths:"barsBeatsSixteenths",Samples:"samples",Hertz:"hertz",Note:"note",Milliseconds:"milliseconds",Seconds:"seconds",Notation:"notation"},t.prototype.toSeconds=function(e){return this.isNumber(e)?e:this.isUndef(e)?this.now():this.isString(e)?new t.Time(e).toSeconds():e instanceof t.TimeBase?e.toSeconds():void 0},t.prototype.toFrequency=function(e){return this.isNumber(e)?e:this.isString(e)||this.isUndef(e)?new t.Frequency(e).valueOf():e instanceof t.TimeBase?e.toFrequency():void 0},t.prototype.toTicks=function(e){return this.isNumber(e)||this.isString(e)?new t.TransportTime(e).toTicks():this.isUndef(e)?t.Transport.ticks:e instanceof t.TimeBase?e.toTicks():void 0},t}(n,v,g,_);var b;b=function(t){"use strict";return t.Param=function(){var e=this.optionsObject(arguments,["param","units","convert"],t.Param.defaults);this._param=this.input=e.param,this.units=e.units,this.convert=e.convert,this.overridden=!1,this._lfo=null,this.isObject(e.lfo)?this.value=e.lfo:this.isUndef(e.value)||(this.value=e.value)},t.extend(t.Param),t.Param.defaults={units:t.Type.Default,convert:!0,param:void 0},Object.defineProperty(t.Param.prototype,"value",{get:function(){return this._toUnits(this._param.value)},set:function(e){if(this.isObject(e)){if(this.isUndef(t.LFO))throw new Error("Include 'Tone.LFO' to use an LFO as a Param value.");this._lfo&&this._lfo.dispose(),this._lfo=new t.LFO(e).start(),this._lfo.connect(this.input)}else{var i=this._fromUnits(e);this._param.cancelScheduledValues(0),this._param.value=i}}}),t.Param.prototype._fromUnits=function(e){if(!this.convert&&!this.isUndef(this.convert))return e;switch(this.units){case t.Type.Time:return this.toSeconds(e);case t.Type.Frequency:return this.toFrequency(e);case t.Type.Decibels:return this.dbToGain(e);case t.Type.NormalRange:return Math.min(Math.max(e,0),1);case t.Type.AudioRange:return Math.min(Math.max(e,-1),1);case t.Type.Positive:return Math.max(e,0);default:return e}},t.Param.prototype._toUnits=function(e){if(!this.convert&&!this.isUndef(this.convert))return e;switch(this.units){case t.Type.Decibels:return this.gainToDb(e);default:return e}},t.Param.prototype._minOutput=1e-5,t.Param.prototype.setValueAtTime=function(t,e){return t=this._fromUnits(t),e=this.toSeconds(e),e<=this.now()+this.blockTime?this._param.value=t:this._param.setValueAtTime(t,e),this},t.Param.prototype.setRampPoint=function(t){t=this.defaultArg(t,this.now());var e=this._param.value;return 0===e&&(e=this._minOutput),this._param.setValueAtTime(e,t),this},t.Param.prototype.linearRampToValueAtTime=function(t,e){return t=this._fromUnits(t),this._param.linearRampToValueAtTime(t,this.toSeconds(e)),this},t.Param.prototype.exponentialRampToValueAtTime=function(t,e){return t=this._fromUnits(t),t=Math.max(this._minOutput,t),this._param.exponentialRampToValueAtTime(t,this.toSeconds(e)),this},t.Param.prototype.exponentialRampToValue=function(t,e,i){return i=this.toSeconds(i),this.setRampPoint(i),this.exponentialRampToValueAtTime(t,i+this.toSeconds(e)),this},t.Param.prototype.linearRampToValue=function(t,e,i){return i=this.toSeconds(i),this.setRampPoint(i),this.linearRampToValueAtTime(t,i+this.toSeconds(e)),this},t.Param.prototype.setTargetAtTime=function(t,e,i){return t=this._fromUnits(t),t=Math.max(this._minOutput,t),i=Math.max(this._minOutput,i),this._param.setTargetAtTime(t,this.toSeconds(e),i),this},t.Param.prototype.setValueCurveAtTime=function(t,e,i){for(var n=0;n1&&(this.input=new Array(e)),1===i?this.output=new t.Gain:i>1&&(this.output=new Array(e))},t.Gain}(n,b);var S;S=function(t){"use strict";return t.Signal=function(){var e=this.optionsObject(arguments,["value","units"],t.Signal.defaults);this.output=this._gain=this.context.createGain(),e.param=this._gain.gain,t.Param.call(this,e),this.input=this._param=this._gain.gain,this.context.getConstant(1).chain(this._gain)},t.extend(t.Signal,t.Param),t.Signal.defaults={value:0,units:t.Type.Default,convert:!0},t.Signal.prototype.connect=t.SignalBase.prototype.connect,t.Signal.prototype.dispose=function(){return t.Param.prototype.dispose.call(this),this._param=null,this._gain.disconnect(),this._gain=null,this},t.Signal}(n,m,T,b);var w;w=function(t){"use strict";return t.Add=function(e){this.createInsOuts(2,0),this._sum=this.input[0]=this.input[1]=this.output=new t.Gain,this._param=this.input[1]=new t.Signal(e),this._param.connect(this._sum)},t.extend(t.Add,t.Signal),t.Add.prototype.dispose=function(){return t.prototype.dispose.call(this),this._sum.dispose(),this._sum=null,this._param.dispose(),this._param=null,this},t.Add}(n,S);var A;A=function(t){"use strict";return t.Multiply=function(e){this.createInsOuts(2,0),this._mult=this.input[0]=this.output=new t.Gain,this._param=this.input[1]=this.output.gain,this._param.value=this.defaultArg(e,0)},t.extend(t.Multiply,t.Signal),t.Multiply.prototype.dispose=function(){return t.prototype.dispose.call(this),this._mult.dispose(),this._mult=null, +this._param=null,this},t.Multiply}(n,S);var P;P=function(t){"use strict";return t.Scale=function(e,i){this._outputMin=this.defaultArg(e,0),this._outputMax=this.defaultArg(i,1),this._scale=this.input=new t.Multiply(1),this._add=this.output=new t.Add(0),this._scale.connect(this._add),this._setRange()},t.extend(t.Scale,t.SignalBase),Object.defineProperty(t.Scale.prototype,"min",{get:function(){return this._outputMin},set:function(t){this._outputMin=t,this._setRange()}}),Object.defineProperty(t.Scale.prototype,"max",{get:function(){return this._outputMax},set:function(t){this._outputMax=t,this._setRange()}}),t.Scale.prototype._setRange=function(){this._add.value=this._outputMin,this._scale.value=this._outputMax-this._outputMin},t.Scale.prototype.dispose=function(){return t.prototype.dispose.call(this),this._add.dispose(),this._add=null,this._scale.dispose(),this._scale=null,this},t.Scale}(n,w,A);var k;k=function(){var e=S,i=w,n=A,o=P;t.Signal=function(t){var i=new e(t);return i},e.prototype.fade=e.prototype.linearRampToValueAtTime,n.prototype.fade=e.prototype.fade,i.prototype.fade=e.prototype.fade,o.prototype.fade=e.prototype.fade,e.prototype.setInput=function(t){t.connect(this)},n.prototype.setInput=e.prototype.setInput,i.prototype.setInput=e.prototype.setInput,o.prototype.setInput=e.prototype.setInput,e.prototype.add=function(t){var e=new i(t);return this.connect(e),e},n.prototype.add=e.prototype.add,i.prototype.add=e.prototype.add,o.prototype.add=e.prototype.add,e.prototype.mult=function(t){var e=new n(t);return this.connect(e),e},n.prototype.mult=e.prototype.mult,i.prototype.mult=e.prototype.mult,o.prototype.mult=e.prototype.mult,e.prototype.scale=function(e,i,n,r){var s,a;4===arguments.length?(s=t.prototype.map(n,e,i,0,1)-.5,a=t.prototype.map(r,e,i,0,1)-.5):(s=arguments[0],a=arguments[1]);var u=new o(s,a);return this.connect(u),u},n.prototype.scale=e.prototype.scale,i.prototype.scale=e.prototype.scale,o.prototype.scale=e.prototype.scale}(S,w,A,P);var O;O=function(){var e=a,i=w,n=A,o=P;t.Oscillator=function(i,n){if("string"==typeof i){var o=n;n=i,i=o}if("number"==typeof n){var o=n;n=i,i=o}this.started=!1,this.phaseAmount=void 0,this.oscillator=e.audiocontext.createOscillator(),this.f=i||440,this.oscillator.type=n||"sine",this.oscillator.frequency.setValueAtTime(this.f,e.audiocontext.currentTime),this.output=e.audiocontext.createGain(),this._freqMods=[],this.output.gain.value=.5,this.output.gain.setValueAtTime(.5,e.audiocontext.currentTime),this.oscillator.connect(this.output),this.panPosition=0,this.connection=e.input,this.panner=new t.Panner(this.output,this.connection,1),this.mathOps=[this.output],e.soundArray.push(this)},t.Oscillator.prototype.start=function(t,i){if(this.started){var n=e.audiocontext.currentTime;this.stop(n)}if(!this.started){var o=i||this.f,r=this.oscillator.type;this.oscillator&&(this.oscillator.disconnect(),delete this.oscillator),this.oscillator=e.audiocontext.createOscillator(),this.oscillator.frequency.value=Math.abs(o),this.oscillator.type=r,this.oscillator.connect(this.output),t=t||0,this.oscillator.start(t+e.audiocontext.currentTime),this.freqNode=this.oscillator.frequency;for(var s in this._freqMods)"undefined"!=typeof this._freqMods[s].connect&&this._freqMods[s].connect(this.oscillator.frequency);this.started=!0}},t.Oscillator.prototype.stop=function(t){if(this.started){var i=t||0,n=e.audiocontext.currentTime;this.oscillator.stop(i+n),this.started=!1}},t.Oscillator.prototype.amp=function(t,i,n){var o=this;if("number"==typeof t){var i=i||0,n=n||0,r=e.audiocontext.currentTime;this.output.gain.linearRampToValueAtTime(t,r+n+i)}else{if(!t)return this.output.gain;t.connect(o.output.gain)}},t.Oscillator.prototype.fade=t.Oscillator.prototype.amp,t.Oscillator.prototype.getAmp=function(){return this.output.gain.value},t.Oscillator.prototype.freq=function(t,i,n){if("number"!=typeof t||isNaN(t)){if(!t)return this.oscillator.frequency;t.output&&(t=t.output),t.connect(this.oscillator.frequency),this._freqMods.push(t)}else{this.f=t;var o=e.audiocontext.currentTime,i=i||0,n=n||0;0===i?this.oscillator.frequency.setValueAtTime(t,n+o):t>0?this.oscillator.frequency.exponentialRampToValueAtTime(t,n+i+o):this.oscillator.frequency.linearRampToValueAtTime(t,n+i+o),this.phaseAmount&&this.phase(this.phaseAmount)}},t.Oscillator.prototype.getFreq=function(){return this.oscillator.frequency.value},t.Oscillator.prototype.setType=function(t){this.oscillator.type=t},t.Oscillator.prototype.getType=function(){return this.oscillator.type},t.Oscillator.prototype.connect=function(t){t?t.hasOwnProperty("input")?(this.panner.connect(t.input),this.connection=t.input):(this.panner.connect(t),this.connection=t):this.panner.connect(e.input)},t.Oscillator.prototype.disconnect=function(){this.output&&this.output.disconnect(),this.panner&&(this.panner.disconnect(),this.output&&this.output.connect(this.panner)),this.oscMods=[]},t.Oscillator.prototype.pan=function(t,e){this.panPosition=t,this.panner.pan(t,e)},t.Oscillator.prototype.getPan=function(){return this.panPosition},t.Oscillator.prototype.dispose=function(){var t=e.soundArray.indexOf(this);if(e.soundArray.splice(t,1),this.oscillator){var i=e.audiocontext.currentTime;this.stop(i),this.disconnect(),this.panner=null,this.oscillator=null}this.osc2&&this.osc2.dispose()},t.Oscillator.prototype.phase=function(i){var n=t.prototype.map(i,0,1,0,1/this.f),o=e.audiocontext.currentTime;this.phaseAmount=i,this.dNode||(this.dNode=e.audiocontext.createDelay(),this.oscillator.disconnect(),this.oscillator.connect(this.dNode),this.dNode.connect(this.output)),this.dNode.delayTime.setValueAtTime(n,o)};var r=function(t,e,i,n,o){var r=t.oscillator;for(var s in t.mathOps)t.mathOps[s]instanceof o&&(r.disconnect(),t.mathOps[s].dispose(),i=s,i0&&(r=t.mathOps[s-1]),r.disconnect(),r.connect(e),e.connect(n),t.mathOps[i]=e,t};t.Oscillator.prototype.add=function(t){var e=new i(t),n=this.mathOps.length-1,o=this.output;return r(this,e,n,o,i)},t.Oscillator.prototype.mult=function(t){var e=new n(t),i=this.mathOps.length-1,o=this.output;return r(this,e,i,o,n)},t.Oscillator.prototype.scale=function(e,i,n,s){var a,u;4===arguments.length?(a=t.prototype.map(n,e,i,0,1)-.5,u=t.prototype.map(s,e,i,0,1)-.5):(a=arguments[0],u=arguments[1]);var c=new o(a,u),p=this.mathOps.length-1,h=this.output;return r(this,c,p,h,o)},t.SinOsc=function(e){t.Oscillator.call(this,e,"sine")},t.SinOsc.prototype=Object.create(t.Oscillator.prototype),t.TriOsc=function(e){t.Oscillator.call(this,e,"triangle")},t.TriOsc.prototype=Object.create(t.Oscillator.prototype),t.SawOsc=function(e){t.Oscillator.call(this,e,"sawtooth")},t.SawOsc.prototype=Object.create(t.Oscillator.prototype),t.SqrOsc=function(e){t.Oscillator.call(this,e,"square")},t.SqrOsc.prototype=Object.create(t.Oscillator.prototype)}(a,w,A,P);var F;F=function(t){"use strict";return t.Timeline=function(){var e=this.optionsObject(arguments,["memory"],t.Timeline.defaults);this._timeline=[],this._toRemove=[],this._iterating=!1,this.memory=e.memory},t.extend(t.Timeline),t.Timeline.defaults={memory:1/0},Object.defineProperty(t.Timeline.prototype,"length",{get:function(){return this._timeline.length}}),t.Timeline.prototype.add=function(t){if(this.isUndef(t.time))throw new Error("Tone.Timeline: events must have a time attribute");if(this._timeline.length){var e=this._search(t.time);this._timeline.splice(e+1,0,t)}else this._timeline.push(t);if(this.length>this.memory){var i=this.length-this.memory;this._timeline.splice(0,i)}return this},t.Timeline.prototype.remove=function(t){if(this._iterating)this._toRemove.push(t);else{var e=this._timeline.indexOf(t);-1!==e&&this._timeline.splice(e,1)}return this},t.Timeline.prototype.get=function(t){var e=this._search(t);return-1!==e?this._timeline[e]:null},t.Timeline.prototype.peek=function(){return this._timeline[0]},t.Timeline.prototype.shift=function(){return this._timeline.shift()},t.Timeline.prototype.getAfter=function(t){var e=this._search(t);return e+10&&this._timeline[e-1].time=0?this._timeline[i-1]:null},t.Timeline.prototype.cancel=function(t){if(this._timeline.length>1){var e=this._search(t);if(e>=0)if(this._timeline[e].time===t){for(var i=e;i>=0&&this._timeline[i].time===t;i--)e=i;this._timeline=this._timeline.slice(0,e)}else this._timeline=this._timeline.slice(0,e+1);else this._timeline=[]}else 1===this._timeline.length&&this._timeline[0].time>=t&&(this._timeline=[]);return this},t.Timeline.prototype.cancelBefore=function(t){if(this._timeline.length){var e=this._search(t);e>=0&&(this._timeline=this._timeline.slice(e+1))}return this},t.Timeline.prototype._search=function(t){var e=0,i=this._timeline.length,n=i;if(i>0&&this._timeline[i-1].time<=t)return i-1;for(;n>e;){var o=Math.floor(e+(n-e)/2),r=this._timeline[o],s=this._timeline[o+1];if(r.time===t){for(var a=o;at)return o;r.time>t?n=o:r.time=n;n++)t(this._timeline[n]);if(this._iterating=!1,this._toRemove.length>0){for(var o=0;o=0&&this._timeline[i].time>=t;)i--;return this._iterate(e,i+1),this},t.Timeline.prototype.forEachAtTime=function(t,e){var i=this._search(t);return-1!==i&&this._iterate(function(i){i.time===t&&e(i)},0,i),this},t.Timeline.prototype.dispose=function(){t.prototype.dispose.call(this),this._timeline=null,this._toRemove=null},t.Timeline}(n);var q;q=function(t){"use strict";return t.TimelineSignal=function(){var e=this.optionsObject(arguments,["value","units"],t.Signal.defaults);this._events=new t.Timeline(10),t.Signal.apply(this,e),e.param=this._param,t.Param.call(this,e),this._initial=this._fromUnits(this._param.value)},t.extend(t.TimelineSignal,t.Param),t.TimelineSignal.Type={Linear:"linear",Exponential:"exponential",Target:"target",Curve:"curve",Set:"set"},Object.defineProperty(t.TimelineSignal.prototype,"value",{get:function(){var t=this.now(),e=this.getValueAtTime(t);return this._toUnits(e)},set:function(t){var e=this._fromUnits(t);this._initial=e,this.cancelScheduledValues(),this._param.value=e}}),t.TimelineSignal.prototype.setValueAtTime=function(e,i){return e=this._fromUnits(e),i=this.toSeconds(i),this._events.add({type:t.TimelineSignal.Type.Set,value:e,time:i}),this._param.setValueAtTime(e,i),this},t.TimelineSignal.prototype.linearRampToValueAtTime=function(e,i){return e=this._fromUnits(e),i=this.toSeconds(i),this._events.add({type:t.TimelineSignal.Type.Linear,value:e,time:i}),this._param.linearRampToValueAtTime(e,i),this},t.TimelineSignal.prototype.exponentialRampToValueAtTime=function(e,i){i=this.toSeconds(i);var n=this._searchBefore(i);n&&0===n.value&&this.setValueAtTime(this._minOutput,n.time),e=this._fromUnits(e);var o=Math.max(e,this._minOutput);return this._events.add({type:t.TimelineSignal.Type.Exponential,value:o,time:i}),ee)this.cancelScheduledValues(e),this.linearRampToValueAtTime(i,e);else{var o=this._searchAfter(e);o&&(this.cancelScheduledValues(e),o.type===t.TimelineSignal.Type.Linear?this.linearRampToValueAtTime(i,e):o.type===t.TimelineSignal.Type.Exponential&&this.exponentialRampToValueAtTime(i,e)),this.setValueAtTime(i,e)}return this},t.TimelineSignal.prototype.linearRampToValueBetween=function(t,e,i){return this.setRampPoint(e),this.linearRampToValueAtTime(t,i),this},t.TimelineSignal.prototype.exponentialRampToValueBetween=function(t,e,i){return this.setRampPoint(e),this.exponentialRampToValueAtTime(t,i),this},t.TimelineSignal.prototype._searchBefore=function(t){return this._events.get(t)},t.TimelineSignal.prototype._searchAfter=function(t){return this._events.getAfter(t)},t.TimelineSignal.prototype.getValueAtTime=function(e){e=this.toSeconds(e);var i=this._searchAfter(e),n=this._searchBefore(e),o=this._initial;if(null===n)o=this._initial;else if(n.type===t.TimelineSignal.Type.Target){var r,s=this._events.getBefore(n.time);r=null===s?this._initial:s.value,o=this._exponentialApproach(n.time,r,n.value,n.constant,e)}else o=n.type===t.TimelineSignal.Type.Curve?this._curveInterpolate(n.time,n.value,n.duration,e):null===i?n.value:i.type===t.TimelineSignal.Type.Linear?this._linearInterpolate(n.time,n.value,i.time,i.value,e):i.type===t.TimelineSignal.Type.Exponential?this._exponentialInterpolate(n.time,n.value,i.time,i.value,e):n.value;return o},t.TimelineSignal.prototype.connect=t.SignalBase.prototype.connect,t.TimelineSignal.prototype._exponentialApproach=function(t,e,i,n,o){return i+(e-i)*Math.exp(-(o-t)/n)},t.TimelineSignal.prototype._linearInterpolate=function(t,e,i,n,o){return e+(n-e)*((o-t)/(i-t))},t.TimelineSignal.prototype._exponentialInterpolate=function(t,e,i,n,o){return e=Math.max(this._minOutput,e),e*Math.pow(n/e,(o-t)/(i-t))},t.TimelineSignal.prototype._curveInterpolate=function(t,e,i,n){var o=e.length;if(n>=t+i)return e[o-1];if(t>=n)return e[0];var r=(n-t)/i,s=Math.floor((o-1)*r),a=Math.ceil((o-1)*r),u=e[s],c=e[a];return a===s?u:this._linearInterpolate(s,u,a,c,r*(o-1))},t.TimelineSignal.prototype.dispose=function(){t.Signal.prototype.dispose.call(this),t.Param.prototype.dispose.call(this),this._events.dispose(),this._events=null},t.TimelineSignal}(n,S);var M;M=function(){var e=a,i=w,n=A,o=P,r=q;t.Envelope=function(t,i,n,o,s,a){this.aTime=t||.1,this.aLevel=i||1,this.dTime=n||.5,this.dLevel=o||0,this.rTime=s||0,this.rLevel=a||0,this._rampHighPercentage=.98,this._rampLowPercentage=.02,this.output=e.audiocontext.createGain(),this.control=new r,this._init(),this.control.connect(this.output),this.connection=null,this.mathOps=[this.control],this.isExponential=!1,this.sourceToClear=null,this.wasTriggered=!1,e.soundArray.push(this)},t.Envelope.prototype._init=function(){var t=e.audiocontext.currentTime,i=t;this.control.setTargetAtTime(1e-5,i,.001),this._setRampAD(this.aTime,this.dTime)},t.Envelope.prototype.set=function(t,e,i,n,o,r){this.aTime=t,this.aLevel=e,this.dTime=i||0,this.dLevel=n||0,this.rTime=o||0,this.rLevel=r||0,this._setRampAD(t,i)},t.Envelope.prototype.setADSR=function(t,e,i,n){this.aTime=t,this.dTime=e||0,this.sPercent=i||0,this.dLevel="undefined"!=typeof i?i*(this.aLevel-this.rLevel)+this.rLevel:0,this.rTime=n||0,this._setRampAD(t,e)},t.Envelope.prototype.setRange=function(t,e){this.aLevel=t||1,this.rLevel=e||0},t.Envelope.prototype._setRampAD=function(t,e){this._rampAttackTime=this.checkExpInput(t),this._rampDecayTime=this.checkExpInput(e);var i=1;i=Math.log(1/this.checkExpInput(1-this._rampHighPercentage)),this._rampAttackTC=t/this.checkExpInput(i),i=Math.log(1/this._rampLowPercentage),this._rampDecayTC=e/this.checkExpInput(i)},t.Envelope.prototype.setRampPercentages=function(t,e){this._rampHighPercentage=this.checkExpInput(t),this._rampLowPercentage=this.checkExpInput(e);var i=1;i=Math.log(1/this.checkExpInput(1-this._rampHighPercentage)),this._rampAttackTC=this._rampAttackTime/this.checkExpInput(i),i=Math.log(1/this._rampLowPercentage),this._rampDecayTC=this._rampDecayTime/this.checkExpInput(i)},t.Envelope.prototype.setInput=function(){for(var t=0;t=t&&(t=1e-8),t},t.Envelope.prototype.play=function(t,e,i){var n=e||0,i=i||0;t&&this.connection!==t&&this.connect(t),this.triggerAttack(t,n),this.triggerRelease(t,n+this.aTime+this.dTime+i)},t.Envelope.prototype.triggerAttack=function(t,i){var n=e.audiocontext.currentTime,o=i||0,r=n+o;this.lastAttack=r,this.wasTriggered=!0,t&&this.connection!==t&&this.connect(t);var s=this.control.getValueAtTime(r);this.isExponential===!0?this.control.exponentialRampToValueAtTime(this.checkExpInput(s),r):this.control.linearRampToValueAtTime(s,r),r+=this.aTime,this.isExponential===!0?(this.control.exponentialRampToValueAtTime(this.checkExpInput(this.aLevel),r),s=this.checkExpInput(this.control.getValueAtTime(r)),this.control.cancelScheduledValues(r),this.control.exponentialRampToValueAtTime(s,r)):(this.control.linearRampToValueAtTime(this.aLevel,r),s=this.control.getValueAtTime(r),this.control.cancelScheduledValues(r),this.control.linearRampToValueAtTime(s,r)),r+=this.dTime,this.isExponential===!0?(this.control.exponentialRampToValueAtTime(this.checkExpInput(this.dLevel),r),s=this.checkExpInput(this.control.getValueAtTime(r)),this.control.cancelScheduledValues(r),this.control.exponentialRampToValueAtTime(s,r)):(this.control.linearRampToValueAtTime(this.dLevel,r),s=this.control.getValueAtTime(r),this.control.cancelScheduledValues(r),this.control.linearRampToValueAtTime(s,r))},t.Envelope.prototype.triggerRelease=function(t,i){if(this.wasTriggered){var n=e.audiocontext.currentTime,o=i||0,r=n+o;t&&this.connection!==t&&this.connect(t);var s=this.control.getValueAtTime(r);this.isExponential===!0?this.control.exponentialRampToValueAtTime(this.checkExpInput(s),r):this.control.linearRampToValueAtTime(s,r),r+=this.rTime,this.isExponential===!0?(this.control.exponentialRampToValueAtTime(this.checkExpInput(this.rLevel),r),s=this.checkExpInput(this.control.getValueAtTime(r)),this.control.cancelScheduledValues(r),this.control.exponentialRampToValueAtTime(s,r)):(this.control.linearRampToValueAtTime(this.rLevel,r),s=this.control.getValueAtTime(r),this.control.cancelScheduledValues(r),this.control.linearRampToValueAtTime(s,r)),this.wasTriggered=!1}},t.Envelope.prototype.ramp=function(t,i,n,o){var r=e.audiocontext.currentTime,s=i||0,a=r+s,u=this.checkExpInput(n),c="undefined"!=typeof o?this.checkExpInput(o):void 0;t&&this.connection!==t&&this.connect(t);var p=this.checkExpInput(this.control.getValueAtTime(a));u>p?(this.control.setTargetAtTime(u,a,this._rampAttackTC),a+=this._rampAttackTime):p>u&&(this.control.setTargetAtTime(u,a,this._rampDecayTC),a+=this._rampDecayTime),void 0!==c&&(c>u?this.control.setTargetAtTime(c,a,this._rampAttackTC):u>c&&this.control.setTargetAtTime(c,a,this._rampDecayTC))},t.Envelope.prototype.connect=function(i){this.connection=i,(i instanceof t.Oscillator||i instanceof t.SoundFile||i instanceof t.AudioIn||i instanceof t.Reverb||i instanceof t.Noise||i instanceof t.Filter||i instanceof t.Delay)&&(i=i.output.gain),i instanceof AudioParam&&i.setValueAtTime(0,e.audiocontext.currentTime),i instanceof t.Signal&&i.setValue(0),this.output.connect(i)},t.Envelope.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.Envelope.prototype.add=function(e){var n=new i(e),o=this.mathOps.length,r=this.output;return t.prototype._mathChain(this,n,o,r,i)},t.Envelope.prototype.mult=function(e){var i=new n(e),o=this.mathOps.length,r=this.output;return t.prototype._mathChain(this,i,o,r,n)},t.Envelope.prototype.scale=function(e,i,n,r){var s=new o(e,i,n,r),a=this.mathOps.length,u=this.output;return t.prototype._mathChain(this,s,a,u,o)},t.Envelope.prototype.dispose=function(){var t=e.soundArray.indexOf(this);e.soundArray.splice(t,1),this.disconnect(),this.control&&(this.control.dispose(),this.control=null);for(var i=1;io;o++)n[o]=1;var r=t.createBufferSource();return r.buffer=e,r.loop=!0,r}var i=a;t.Pulse=function(n,o){t.Oscillator.call(this,n,"sawtooth"),this.w=o||0,this.osc2=new t.SawOsc(n),this.dNode=i.audiocontext.createDelay(),this.dcOffset=e(),this.dcGain=i.audiocontext.createGain(),this.dcOffset.connect(this.dcGain),this.dcGain.connect(this.output),this.f=n||440;var r=this.w/this.oscillator.frequency.value;this.dNode.delayTime.value=r,this.dcGain.gain.value=1.7*(.5-this.w),this.osc2.disconnect(),this.osc2.panner.disconnect(),this.osc2.amp(-1),this.osc2.output.connect(this.dNode),this.dNode.connect(this.output),this.output.gain.value=1,this.output.connect(this.panner)},t.Pulse.prototype=Object.create(t.Oscillator.prototype),t.Pulse.prototype.width=function(e){if("number"==typeof e){if(1>=e&&e>=0){this.w=e;var i=this.w/this.oscillator.frequency.value;this.dNode.delayTime.value=i}this.dcGain.gain.value=1.7*(.5-this.w)}else{e.connect(this.dNode.delayTime);var n=new t.SignalAdd(-.5);n.setInput(e),n=n.mult(-1),n=n.mult(1.7),n.connect(this.dcGain.gain)}},t.Pulse.prototype.start=function(t,n){var o=i.audiocontext.currentTime,r=n||0;if(!this.started){var s=t||this.f,a=this.oscillator.type;this.oscillator=i.audiocontext.createOscillator(),this.oscillator.frequency.setValueAtTime(s,o),this.oscillator.type=a,this.oscillator.connect(this.output),this.oscillator.start(r+o),this.osc2.oscillator=i.audiocontext.createOscillator(),this.osc2.oscillator.frequency.setValueAtTime(s,r+o),this.osc2.oscillator.type=a,this.osc2.oscillator.connect(this.osc2.output),this.osc2.start(r+o),this.freqNode=[this.oscillator.frequency,this.osc2.oscillator.frequency],this.dcOffset=e(),this.dcOffset.connect(this.dcGain),this.dcOffset.start(r+o),void 0!==this.mods&&void 0!==this.mods.frequency&&(this.mods.frequency.connect(this.freqNode[0]),this.mods.frequency.connect(this.freqNode[1])),this.started=!0,this.osc2.started=!0}},t.Pulse.prototype.stop=function(t){if(this.started){var e=t||0,n=i.audiocontext.currentTime;this.oscillator.stop(e+n),this.osc2.oscillator&&this.osc2.oscillator.stop(e+n),this.dcOffset.stop(e+n),this.started=!1,this.osc2.started=!1}},t.Pulse.prototype.freq=function(t,e,n){if("number"==typeof t){this.f=t;var o=i.audiocontext.currentTime,e=e||0,n=n||0,r=this.oscillator.frequency.value;this.oscillator.frequency.cancelScheduledValues(o),this.oscillator.frequency.setValueAtTime(r,o+n),this.oscillator.frequency.exponentialRampToValueAtTime(t,n+e+o),this.osc2.oscillator.frequency.cancelScheduledValues(o),this.osc2.oscillator.frequency.setValueAtTime(r,o+n),this.osc2.oscillator.frequency.exponentialRampToValueAtTime(t,n+e+o),this.freqMod&&(this.freqMod.output.disconnect(),this.freqMod=null)}else t.output&&(t.output.disconnect(),t.output.connect(this.oscillator.frequency),t.output.connect(this.osc2.oscillator.frequency),this.freqMod=t)}}(a,O);var V;V=function(){var e=a;t.Noise=function(e){var r;t.Oscillator.call(this),delete this.f,delete this.freq,delete this.oscillator,r="brown"===e?o:"pink"===e?n:i,this.buffer=r},t.Noise.prototype=Object.create(t.Oscillator.prototype);var i=function(){for(var t=2*e.audiocontext.sampleRate,i=e.audiocontext.createBuffer(1,t,e.audiocontext.sampleRate),n=i.getChannelData(0),o=0;t>o;o++)n[o]=2*Math.random()-1;return i.type="white",i}(),n=function(){var t,i,n,o,r,s,a,u=2*e.audiocontext.sampleRate,c=e.audiocontext.createBuffer(1,u,e.audiocontext.sampleRate),p=c.getChannelData(0);t=i=n=o=r=s=a=0;for(var h=0;u>h;h++){var l=2*Math.random()-1;t=.99886*t+.0555179*l,i=.99332*i+.0750759*l,n=.969*n+.153852*l,o=.8665*o+.3104856*l,r=.55*r+.5329522*l,s=-.7616*s-.016898*l,p[h]=t+i+n+o+r+s+a+.5362*l,p[h]*=.11,a=.115926*l}return c.type="pink",c}(),o=function(){for(var t=2*e.audiocontext.sampleRate,i=e.audiocontext.createBuffer(1,t,e.audiocontext.sampleRate),n=i.getChannelData(0),o=0,r=0;t>r;r++){var s=2*Math.random()-1;n[r]=(o+.02*s)/1.02,o=n[r],n[r]*=3.5}return i.type="brown",i}();t.Noise.prototype.setType=function(t){switch(t){case"white":this.buffer=i;break;case"pink":this.buffer=n;break;case"brown":this.buffer=o;break;default:this.buffer=i}if(this.started){var r=e.audiocontext.currentTime;this.stop(r),this.start(r+.01)}},t.Noise.prototype.getType=function(){return this.buffer.type},t.Noise.prototype.start=function(){this.started&&this.stop(),this.noise=e.audiocontext.createBufferSource(),this.noise.buffer=this.buffer,this.noise.loop=!0,this.noise.connect(this.output);var t=e.audiocontext.currentTime;this.noise.start(t),this.started=!0},t.Noise.prototype.stop=function(){var t=e.audiocontext.currentTime;this.noise&&(this.noise.stop(t),this.started=!1)},t.Noise.prototype.dispose=function(){var t=e.audiocontext.currentTime,i=e.soundArray.indexOf(this);e.soundArray.splice(i,1),this.noise&&(this.noise.disconnect(),this.stop(t)),this.output&&this.output.disconnect(),this.panner&&this.panner.disconnect(),this.output=null,this.panner=null,this.buffer=null,this.noise=null}}(a);var R;R=function(){var e=a;e.inputSources=[],t.AudioIn=function(i){this.input=e.audiocontext.createGain(),this.output=e.audiocontext.createGain(),this.stream=null,this.mediaStream=null,this.currentSource=null,this.enabled=!1,this.amplitude=new t.Amplitude,this.output.connect(this.amplitude.input),window.MediaStreamTrack&&window.navigator.mediaDevices&&window.navigator.mediaDevices.getUserMedia||(i?i():window.alert("This browser does not support MediaStreamTrack and mediaDevices")),e.soundArray.push(this)},t.AudioIn.prototype.start=function(t,i){var n=this;this.stream&&this.stop();var o=e.inputSources[n.currentSource],r={audio:{sampleRate:e.audiocontext.sampleRate,echoCancellation:!1}};e.inputSources[this.currentSource]&&(r.audio.deviceId=o.deviceId),window.navigator.mediaDevices.getUserMedia(r).then(function(i){n.stream=i,n.enabled=!0,n.mediaStream=e.audiocontext.createMediaStreamSource(i),n.mediaStream.connect(n.output),n.amplitude.setInput(n.output),t&&t()})["catch"](function(t){i?i(t):console.error(t)})},t.AudioIn.prototype.stop=function(){this.stream&&(this.stream.getTracks().forEach(function(t){t.stop()}),this.mediaStream.disconnect(),delete this.mediaStream,delete this.stream)},t.AudioIn.prototype.connect=function(t){t?t.hasOwnProperty("input")?this.output.connect(t.input):t.hasOwnProperty("analyser")?this.output.connect(t.analyser):this.output.connect(t):this.output.connect(e.input)},t.AudioIn.prototype.disconnect=function(){this.output&&(this.output.disconnect(),this.output.connect(this.amplitude.input))},t.AudioIn.prototype.getLevel=function(t){return t&&(this.amplitude.smoothing=t),this.amplitude.getLevel()},t.AudioIn.prototype.amp=function(t,i){if(i){var n=i||0,o=this.output.gain.value;this.output.gain.cancelScheduledValues(e.audiocontext.currentTime),this.output.gain.setValueAtTime(o,e.audiocontext.currentTime),this.output.gain.linearRampToValueAtTime(t,n+e.audiocontext.currentTime)}else this.output.gain.cancelScheduledValues(e.audiocontext.currentTime),this.output.gain.setValueAtTime(t,e.audiocontext.currentTime)},t.AudioIn.prototype.getSources=function(t,i){return new Promise(function(n,o){window.navigator.mediaDevices.enumerateDevices().then(function(i){e.inputSources=i.filter(function(t){return"audioinput"===t.kind}),n(e.inputSources),t&&t(e.inputSources)})["catch"](function(t){o(t),i?i(t):console.error("This browser does not support MediaStreamTrack.getSources()")})})},t.AudioIn.prototype.setSource=function(t){e.inputSources.length>0&&t=t?0:1},127),this._scale=this.input=new t.Multiply(1e4),this._scale.connect(this._thresh)},t.extend(t.GreaterThanZero,t.SignalBase),t.GreaterThanZero.prototype.dispose=function(){return t.prototype.dispose.call(this),this._scale.dispose(),this._scale=null,this._thresh.dispose(),this._thresh=null,this},t.GreaterThanZero}(n,S,A);var B;B=function(t){"use strict";return t.GreaterThan=function(e){this.createInsOuts(2,0),this._param=this.input[0]=new t.Subtract(e),this.input[1]=this._param.input[1],this._gtz=this.output=new t.GreaterThanZero,this._param.connect(this._gtz)},t.extend(t.GreaterThan,t.Signal),t.GreaterThan.prototype.dispose=function(){return t.prototype.dispose.call(this),this._param.dispose(),this._param=null,this._gtz.dispose(),this._gtz=null,this},t.GreaterThan}(n,N,D);var U;U=function(t){"use strict";return t.Abs=function(){this._abs=this.input=this.output=new t.WaveShaper(function(t){return 0===t?0:Math.abs(t)},127)},t.extend(t.Abs,t.SignalBase),t.Abs.prototype.dispose=function(){return t.prototype.dispose.call(this),this._abs.dispose(),this._abs=null,this},t.Abs}(n,m);var I;I=function(t){"use strict";return t.Modulo=function(e){this.createInsOuts(1,0),this._shaper=new t.WaveShaper(Math.pow(2,16)),this._multiply=new t.Multiply,this._subtract=this.output=new t.Subtract,this._modSignal=new t.Signal(e),this.input.fan(this._shaper,this._subtract),this._modSignal.connect(this._multiply,0,0),this._shaper.connect(this._multiply,0,1),this._multiply.connect(this._subtract,0,1),this._setWaveShaper(e)},t.extend(t.Modulo,t.SignalBase),t.Modulo.prototype._setWaveShaper=function(t){this._shaper.setMap(function(e){var i=Math.floor((e+1e-4)/t);return i; +})},Object.defineProperty(t.Modulo.prototype,"value",{get:function(){return this._modSignal.value},set:function(t){this._modSignal.value=t,this._setWaveShaper(t)}}),t.Modulo.prototype.dispose=function(){return t.prototype.dispose.call(this),this._shaper.dispose(),this._shaper=null,this._multiply.dispose(),this._multiply=null,this._subtract.dispose(),this._subtract=null,this._modSignal.dispose(),this._modSignal=null,this},t.Modulo}(n,m,A);var G;G=function(t){"use strict";return t.Pow=function(e){this._exp=this.defaultArg(e,1),this._expScaler=this.input=this.output=new t.WaveShaper(this._expFunc(this._exp),8192)},t.extend(t.Pow,t.SignalBase),Object.defineProperty(t.Pow.prototype,"value",{get:function(){return this._exp},set:function(t){this._exp=t,this._expScaler.setMap(this._expFunc(this._exp))}}),t.Pow.prototype._expFunc=function(t){return function(e){return Math.pow(Math.abs(e),t)}},t.Pow.prototype.dispose=function(){return t.prototype.dispose.call(this),this._expScaler.dispose(),this._expScaler=null,this},t.Pow}(n);var L;L=function(t){"use strict";return t.AudioToGain=function(){this._norm=this.input=this.output=new t.WaveShaper(function(t){return(t+1)/2})},t.extend(t.AudioToGain,t.SignalBase),t.AudioToGain.prototype.dispose=function(){return t.prototype.dispose.call(this),this._norm.dispose(),this._norm=null,this},t.AudioToGain}(n,m);var j;j=function(t){"use strict";function e(t,e,i){var n=new t;return i._eval(e[0]).connect(n,0,0),i._eval(e[1]).connect(n,0,1),n}function i(t,e,i){var n=new t;return i._eval(e[0]).connect(n,0,0),n}function n(t){return t?parseFloat(t):void 0}function o(t){return t&&t.args?parseFloat(t.args):void 0}return t.Expr=function(){var t=this._replacements(Array.prototype.slice.call(arguments)),e=this._parseInputs(t);this._nodes=[],this.input=new Array(e);for(var i=0;e>i;i++)this.input[i]=this.context.createGain();var n,o=this._parseTree(t);try{n=this._eval(o)}catch(r){throw this._disposeNodes(),new Error("Tone.Expr: Could evaluate expression: "+t)}this.output=n},t.extend(t.Expr,t.SignalBase),t.Expr._Expressions={value:{signal:{regexp:/^\d+\.\d+|^\d+/,method:function(e){var i=new t.Signal(n(e));return i}},input:{regexp:/^\$\d/,method:function(t,e){return e.input[n(t.substr(1))]}}},glue:{"(":{regexp:/^\(/},")":{regexp:/^\)/},",":{regexp:/^,/}},func:{abs:{regexp:/^abs/,method:i.bind(this,t.Abs)},mod:{regexp:/^mod/,method:function(e,i){var n=o(e[1]),r=new t.Modulo(n);return i._eval(e[0]).connect(r),r}},pow:{regexp:/^pow/,method:function(e,i){var n=o(e[1]),r=new t.Pow(n);return i._eval(e[0]).connect(r),r}},a2g:{regexp:/^a2g/,method:function(e,i){var n=new t.AudioToGain;return i._eval(e[0]).connect(n),n}}},binary:{"+":{regexp:/^\+/,precedence:1,method:e.bind(this,t.Add)},"-":{regexp:/^\-/,precedence:1,method:function(n,o){return 1===n.length?i(t.Negate,n,o):e(t.Subtract,n,o)}},"*":{regexp:/^\*/,precedence:0,method:e.bind(this,t.Multiply)}},unary:{"-":{regexp:/^\-/,method:i.bind(this,t.Negate)},"!":{regexp:/^\!/,method:i.bind(this,t.NOT)}}},t.Expr.prototype._parseInputs=function(t){var e=t.match(/\$\d/g),i=0;if(null!==e)for(var n=0;n0;){e=e.trim();var r=i(e);o.push(r),e=e.substr(r.value.length)}return{next:function(){return o[++n]},peek:function(){return o[n+1]}}},t.Expr.prototype._parseTree=function(e){function i(t,e){return!p(t)&&"glue"===t.type&&t.value===e}function n(e,i,n){var o=!1,r=t.Expr._Expressions[i];if(!p(e))for(var s in r){var a=r[s];if(a.regexp.test(e.value)){if(p(n))return!0;if(a.precedence===n)return!0}}return o}function o(t){p(t)&&(t=5);var e;e=0>t?r():o(t-1);for(var i=c.peek();n(i,"binary",t);)i=c.next(),e={operator:i.value,method:i.method,args:[e,o(t-1)]},i=c.peek();return e}function r(){var t,e;return t=c.peek(),n(t,"unary")?(t=c.next(),e=r(),{operator:t.value,method:t.method,args:[e]}):s()}function s(){var t,e;if(t=c.peek(),p(t))throw new SyntaxError("Tone.Expr: Unexpected termination of expression");if("func"===t.type)return t=c.next(),a(t);if("value"===t.type)return t=c.next(),{method:t.method,args:t.value};if(i(t,"(")){if(c.next(),e=o(),t=c.next(),!i(t,")"))throw new SyntaxError("Expected )");return e}throw new SyntaxError("Tone.Expr: Parse error, cannot process token "+t.value)}function a(t){var e,n=[];if(e=c.next(),!i(e,"("))throw new SyntaxError('Tone.Expr: Expected ( in a function call "'+t.value+'"');if(e=c.peek(),i(e,")")||(n=u()),e=c.next(),!i(e,")"))throw new SyntaxError('Tone.Expr: Expected ) in a function call "'+t.value+'"');return{method:t.method,args:n,name:name}}function u(){for(var t,e,n=[];;){if(e=o(),p(e))break;if(n.push(e),t=c.peek(),!i(t,","))break;c.next()}return n}var c=this._tokenize(e),p=this.isUndef.bind(this);return o()},t.Expr.prototype._eval=function(t){if(!this.isUndef(t)){var e=t.method(t.args,this);return this._nodes.push(e),e}},t.Expr.prototype._disposeNodes=function(){for(var t=0;t0){this.connect(arguments[0]);for(var t=1;t=t&&(t=1),"number"==typeof t?(this.biquad.frequency.cancelScheduledValues(this.ac.currentTime+.01+i),this.biquad.frequency.exponentialRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.biquad.frequency),this.biquad.frequency.value},t.Filter.prototype.res=function(t,e){var i=e||0;return"number"==typeof t?(this.biquad.Q.value=t,this.biquad.Q.cancelScheduledValues(this.ac.currentTime+.01+i),this.biquad.Q.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.biquad.Q),this.biquad.Q.value},t.Filter.prototype.gain=function(t,e){var i=e||0;return"number"==typeof t?(this.biquad.gain.value=t,this.biquad.gain.cancelScheduledValues(this.ac.currentTime+.01+i),this.biquad.gain.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.biquad.gain),this.biquad.gain.value},t.Filter.prototype.toggle=function(){return this._on=!this._on,this._on===!0?this.biquad.type=this._untoggledType:this._on===!1&&(this.biquad.type="allpass"),this._on},t.Filter.prototype.setType=function(t){this.biquad.type=t,this._untoggledType=this.biquad.type},t.Filter.prototype.dispose=function(){e.prototype.dispose.apply(this),this.biquad&&(this.biquad.disconnect(),delete this.biquad)},t.LowPass=function(){t.Filter.call(this,"lowpass")},t.LowPass.prototype=Object.create(t.Filter.prototype),t.HighPass=function(){t.Filter.call(this,"highpass")},t.HighPass.prototype=Object.create(t.Filter.prototype),t.BandPass=function(){t.Filter.call(this,"bandpass")},t.BandPass.prototype=Object.create(t.Filter.prototype),t.Filter}(a,Y);var W;W=function(){var e=z,i=a,n=function(t,i){e.call(this,"peaking"),this.disconnect(),this.set(t,i),this.biquad.gain.value=0,delete this.input,delete this.output,delete this._drywet,delete this.wet};return n.prototype=Object.create(e.prototype),n.prototype.amp=function(){console.warn("`amp()` is not available for p5.EQ bands. Use `.gain()`")},n.prototype.drywet=function(){console.warn("`drywet()` is not available for p5.EQ bands.")},n.prototype.connect=function(e){var i=e||t.soundOut.input;this.biquad?this.biquad.connect(i.input?i.input:i):this.output.connect(i.input?i.input:i)},n.prototype.disconnect=function(){this.biquad&&this.biquad.disconnect()},n.prototype.dispose=function(){var t=i.soundArray.indexOf(this);i.soundArray.splice(t,1),this.disconnect(),delete this.biquad},n}(z,a);var Q;Q=function(){var e=Y,i=W;return t.EQ=function(t){e.call(this),t=3===t||8===t?t:3;var i;i=3===t?Math.pow(2,3):2,this.bands=[];for(var n,o,r=0;t>r;r++)r===t-1?(n=21e3,o=.01):0===r?(n=100,o=.1):1===r?(n=3===t?360*i:360,o=1):(n=this.bands[r-1].freq()*i,o=1),this.bands[r]=this._newBand(n,o),r>0?this.bands[r-1].connect(this.bands[r].biquad):this.input.connect(this.bands[r].biquad);this.bands[t-1].connect(this.output)},t.EQ.prototype=Object.create(e.prototype),t.EQ.prototype.process=function(t){t.connect(this.input)},t.EQ.prototype.set=function(){if(arguments.length===2*this.bands.length)for(var t=0;t0;)delete this.bands.pop().dispose();delete this.bands}},t.EQ}(Y,W);var H;H=function(){var e=Y;return t.Panner3D=function(){e.call(this),this.panner=this.ac.createPanner(),this.panner.panningModel="HRTF",this.panner.distanceModel="linear",this.panner.connect(this.output),this.input.connect(this.panner)},t.Panner3D.prototype=Object.create(e.prototype),t.Panner3D.prototype.process=function(t){t.connect(this.input)},t.Panner3D.prototype.set=function(t,e,i,n){return this.positionX(t,n),this.positionY(e,n),this.positionZ(i,n),[this.panner.positionX.value,this.panner.positionY.value,this.panner.positionZ.value]},t.Panner3D.prototype.positionX=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.positionX.value=t,this.panner.positionX.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.positionX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.positionX),this.panner.positionX.value},t.Panner3D.prototype.positionY=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.positionY.value=t,this.panner.positionY.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.positionY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.positionY),this.panner.positionY.value},t.Panner3D.prototype.positionZ=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.positionZ.value=t,this.panner.positionZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.positionZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.positionZ),this.panner.positionZ.value},t.Panner3D.prototype.orient=function(t,e,i,n){return this.orientX(t,n),this.orientY(e,n),this.orientZ(i,n),[this.panner.orientationX.value,this.panner.orientationY.value,this.panner.orientationZ.value]},t.Panner3D.prototype.orientX=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.orientationX.value=t,this.panner.orientationX.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.orientationX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.orientationX),this.panner.orientationX.value},t.Panner3D.prototype.orientY=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.orientationY.value=t,this.panner.orientationY.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.orientationY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.orientationY),this.panner.orientationY.value},t.Panner3D.prototype.orientZ=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.orientationZ.value=t,this.panner.orientationZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.orientationZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.orientationZ),this.panner.orientationZ.value},t.Panner3D.prototype.setFalloff=function(t,e){this.maxDist(t),this.rolloff(e)},t.Panner3D.prototype.maxDist=function(t){return"number"==typeof t&&(this.panner.maxDistance=t),this.panner.maxDistance},t.Panner3D.prototype.rolloff=function(t){return"number"==typeof t&&(this.panner.rolloffFactor=t),this.panner.rolloffFactor},t.Panner3D.dispose=function(){e.prototype.dispose.apply(this),this.panner&&(this.panner.disconnect(),delete this.panner)},t.Panner3D}(a,Y);var $;$=function(){var e=a;return t.Listener3D=function(t){this.ac=e.audiocontext,this.listener=this.ac.listener},t.Listener3D.prototype.process=function(t){t.connect(this.input)},t.Listener3D.prototype.position=function(t,e,i,n){return this.positionX(t,n),this.positionY(e,n),this.positionZ(i,n),[this.listener.positionX.value,this.listener.positionY.value,this.listener.positionZ.value]},t.Listener3D.prototype.positionX=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.positionX.value=t,this.listener.positionX.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.positionX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.positionX),this.listener.positionX.value},t.Listener3D.prototype.positionY=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.positionY.value=t,this.listener.positionY.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.positionY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.positionY),this.listener.positionY.value},t.Listener3D.prototype.positionZ=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.positionZ.value=t,this.listener.positionZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.positionZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.positionZ),this.listener.positionZ.value},t.Listener3D.prototype.orient=function(t,e,i,n,o,r,s){return 3===arguments.length||4===arguments.length?(s=arguments[3],this.orientForward(t,e,i,s)):(6===arguments.length||7===arguments)&&(this.orientForward(t,e,i),this.orientUp(n,o,r,s)),[this.listener.forwardX.value,this.listener.forwardY.value,this.listener.forwardZ.value,this.listener.upX.value,this.listener.upY.value,this.listener.upZ.value]},t.Listener3D.prototype.orientForward=function(t,e,i,n){return this.forwardX(t,n),this.forwardY(e,n),this.forwardZ(i,n),[this.listener.forwardX,this.listener.forwardY,this.listener.forwardZ]},t.Listener3D.prototype.orientUp=function(t,e,i,n){return this.upX(t,n),this.upY(e,n),this.upZ(i,n),[this.listener.upX,this.listener.upY,this.listener.upZ]},t.Listener3D.prototype.forwardX=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.forwardX.value=t,this.listener.forwardX.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.forwardX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.forwardX),this.listener.forwardX.value},t.Listener3D.prototype.forwardY=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.forwardY.value=t,this.listener.forwardY.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.forwardY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.forwardY),this.listener.forwardY.value},t.Listener3D.prototype.forwardZ=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.forwardZ.value=t,this.listener.forwardZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.forwardZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.forwardZ),this.listener.forwardZ.value},t.Listener3D.prototype.upX=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.upX.value=t,this.listener.upX.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.upX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.upX),this.listener.upX.value},t.Listener3D.prototype.upY=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.upY.value=t,this.listener.upY.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.upY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.upY),this.listener.upY.value},t.Listener3D.prototype.upZ=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.upZ.value=t,this.listener.upZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.upZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.upZ),this.listener.upZ.value},t.Listener3D}(a,Y);var J;J=function(){var e=z,i=Y;t.Delay=function(){i.call(this),this._split=this.ac.createChannelSplitter(2),this._merge=this.ac.createChannelMerger(2),this._leftGain=this.ac.createGain(),this._rightGain=this.ac.createGain(),this.leftDelay=this.ac.createDelay(),this.rightDelay=this.ac.createDelay(),this._leftFilter=new e,this._rightFilter=new e,this._leftFilter.disconnect(),this._rightFilter.disconnect(),this._leftFilter.biquad.frequency.setValueAtTime(1200,this.ac.currentTime),this._rightFilter.biquad.frequency.setValueAtTime(1200,this.ac.currentTime),this._leftFilter.biquad.Q.setValueAtTime(.3,this.ac.currentTime),this._rightFilter.biquad.Q.setValueAtTime(.3,this.ac.currentTime),this.input.connect(this._split),this.leftDelay.connect(this._leftGain),this.rightDelay.connect(this._rightGain),this._leftGain.connect(this._leftFilter.input),this._rightGain.connect(this._rightFilter.input),this._merge.connect(this.wet),this._leftFilter.biquad.gain.setValueAtTime(1,this.ac.currentTime),this._rightFilter.biquad.gain.setValueAtTime(1,this.ac.currentTime),this.setType(0),this._maxDelay=this.leftDelay.delayTime.maxValue,this.feedback(.5)},t.Delay.prototype=Object.create(i.prototype),t.Delay.prototype.process=function(t,e,i,n){var o=i||0,r=e||0;if(o>=1)throw new Error("Feedback value will force a positive feedback loop.");if(r>=this._maxDelay)throw new Error("Delay Time exceeds maximum delay time of "+this._maxDelay+" second.");t.connect(this.input),this.leftDelay.delayTime.setValueAtTime(r,this.ac.currentTime),this.rightDelay.delayTime.setValueAtTime(r,this.ac.currentTime),this._leftGain.gain.value=o,this._rightGain.gain.value=o,n&&(this._leftFilter.freq(n),this._rightFilter.freq(n))},t.Delay.prototype.delayTime=function(t){"number"!=typeof t?(t.connect(this.leftDelay.delayTime),t.connect(this.rightDelay.delayTime)):(this.leftDelay.delayTime.cancelScheduledValues(this.ac.currentTime),this.rightDelay.delayTime.cancelScheduledValues(this.ac.currentTime),this.leftDelay.delayTime.linearRampToValueAtTime(t,this.ac.currentTime),this.rightDelay.delayTime.linearRampToValueAtTime(t,this.ac.currentTime))},t.Delay.prototype.feedback=function(t){if(t&&"number"!=typeof t)t.connect(this._leftGain.gain),t.connect(this._rightGain.gain);else{if(t>=1)throw new Error("Feedback value will force a positive feedback loop.");"number"==typeof t&&(this._leftGain.gain.value=t,this._rightGain.gain.value=t)}return this._leftGain.gain.value},t.Delay.prototype.filter=function(t,e){this._leftFilter.set(t,e),this._rightFilter.set(t,e)},t.Delay.prototype.setType=function(t){switch(1===t&&(t="pingPong"),this._split.disconnect(),this._leftFilter.disconnect(),this._rightFilter.disconnect(),this._split.connect(this.leftDelay,0),this._split.connect(this.rightDelay,1),t){case"pingPong":this._rightFilter.setType(this._leftFilter.biquad.type),this._leftFilter.output.connect(this._merge,0,0),this._rightFilter.output.connect(this._merge,0,1),this._leftFilter.output.connect(this.rightDelay),this._rightFilter.output.connect(this.leftDelay);break;default:this._leftFilter.output.connect(this._merge,0,0),this._rightFilter.output.connect(this._merge,0,1),this._leftFilter.output.connect(this.leftDelay),this._rightFilter.output.connect(this.rightDelay)}},t.Delay.prototype.dispose=function(){i.prototype.dispose.apply(this),this._split.disconnect(),this._leftFilter.dispose(),this._rightFilter.dispose(),this._merge.disconnect(),this._leftGain.disconnect(),this._rightGain.disconnect(),this.leftDelay.disconnect(),this.rightDelay.disconnect(),this._split=void 0,this._leftFilter=void 0,this._rightFilter=void 0,this._merge=void 0,this._leftGain=void 0,this._rightGain=void 0,this.leftDelay=void 0,this.rightDelay=void 0}}(z,Y);var K;K=function(){var e=c,i=Y;t.Reverb=function(){i.call(this),this._initConvolverNode(),this.input.gain.value=.5,this._seconds=3,this._decay=2,this._reverse=!1,this._buildImpulse()},t.Reverb.prototype=Object.create(i.prototype),t.Reverb.prototype._initConvolverNode=function(){this.convolverNode=this.ac.createConvolver(),this.input.connect(this.convolverNode),this.convolverNode.connect(this.wet)},t.Reverb.prototype._teardownConvolverNode=function(){this.convolverNode&&(this.convolverNode.disconnect(),delete this.convolverNode)},t.Reverb.prototype._setBuffer=function(t){this._teardownConvolverNode(),this._initConvolverNode(),this.convolverNode.buffer=t},t.Reverb.prototype.process=function(t,e,i,n){t.connect(this.input);var o=!1;e&&(this._seconds=e,o=!0),i&&(this._decay=i),n&&(this._reverse=n),o&&this._buildImpulse()},t.Reverb.prototype.set=function(t,e,i){var n=!1;t&&(this._seconds=t,n=!0),e&&(this._decay=e),i&&(this._reverse=i),n&&this._buildImpulse()},t.Reverb.prototype._buildImpulse=function(){var t,e,i=this.ac.sampleRate,n=i*this._seconds,o=this._decay,r=this.ac.createBuffer(2,n,i),s=r.getChannelData(0),a=r.getChannelData(1);for(e=0;n>e;e++)t=this._reverse?n-e:e,s[e]=(2*Math.random()-1)*Math.pow(1-t/n,o),a[e]=(2*Math.random()-1)*Math.pow(1-t/n,o);this._setBuffer(r)},t.Reverb.prototype.dispose=function(){i.prototype.dispose.apply(this),this._teardownConvolverNode()},t.Convolver=function(e,i,n){t.Reverb.call(this),this._initConvolverNode(),this.input.gain.value=.5,e?(this.impulses=[],this._loadBuffer(e,i,n)):(this._seconds=3,this._decay=2,this._reverse=!1,this._buildImpulse())},t.Convolver.prototype=Object.create(t.Reverb.prototype),t.prototype.registerPreloadMethod("createConvolver",t.prototype),t.prototype.createConvolver=function(e,i,n){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS");var o=this,r=new t.Convolver(e,function(t){"function"==typeof i&&i(t),"function"==typeof o._decrementPreload&&o._decrementPreload()},n);return r.impulses=[],r},t.Convolver.prototype._loadBuffer=function(i,n,o){var i=t.prototype._checkFileFormats(i),r=this,s=(new Error).stack,a=t.prototype.getAudioContext(),u=new XMLHttpRequest;u.open("GET",i,!0),u.responseType="arraybuffer",u.onload=function(){if(200===u.status)a.decodeAudioData(u.response,function(t){var e={},o=i.split("/");e.name=o[o.length-1],e.audioBuffer=t,r.impulses.push(e),r._setBuffer(e.audioBuffer),n&&n(e)},function(){var t=new e("decodeAudioData",s,r.url),i="AudioContext error at decodeAudioData for "+r.url;o?(t.msg=i,o(t)):console.error(i+"\n The error stack trace includes: \n"+t.stack)});else{var t=new e("loadConvolver",s,r.url),c="Unable to load "+r.url+". The request status was: "+u.status+" ("+u.statusText+")";o?(t.message=c,o(t)):console.error(c+"\n The error stack trace includes: \n"+t.stack)}},u.onerror=function(){var t=new e("loadConvolver",s,r.url),i="There was no response from the server at "+r.url+". Check the url and internet connectivity.";o?(t.message=i,o(t)):console.error(i+"\n The error stack trace includes: \n"+t.stack)},u.send()},t.Convolver.prototype.set=null,t.Convolver.prototype.process=function(t){t.connect(this.input)},t.Convolver.prototype.impulses=[],t.Convolver.prototype.addImpulse=function(t,e,i){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS"),this._loadBuffer(t,e,i)},t.Convolver.prototype.resetImpulse=function(t,e,i){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS"),this.impulses=[],this._loadBuffer(t,e,i)},t.Convolver.prototype.toggleImpulse=function(t){if("number"==typeof t&&tthis._nextTick&&this._state;){var s=this._state.getValueAtTime(this._nextTick);if(s!==this._lastState){this._lastState=s;var a=this._state.get(this._nextTick);s===t.State.Started?(this._nextTick=a.time,this.isUndef(a.offset)||(this.ticks=a.offset),this.emit("start",a.time,this.ticks)):s===t.State.Stopped?(this.ticks=0,this.emit("stop",a.time)):s===t.State.Paused&&this.emit("pause",a.time)}var u=this._nextTick;this.frequency&&(this._nextTick+=1/this.frequency.getValueAtTime(this._nextTick),s===t.State.Started&&(this.callback(u),this.ticks++))}},t.Clock.prototype.getStateAtTime=function(t){return t=this.toSeconds(t),this._state.getValueAtTime(t)},t.Clock.prototype.dispose=function(){t.Emitter.prototype.dispose.call(this),this.context.off("tick",this._boundLoop),this._writable("frequency"),this.frequency.dispose(),this.frequency=null,this._boundLoop=null,this._nextTick=1/0,this.callback=null,this._state.dispose(),this._state=null},t.Clock}(n,q,tt,o);var it;it=function(){var e=a,i=et;t.Metro=function(){this.clock=new i({callback:this.ontick.bind(this)}),this.syncedParts=[],this.bpm=120,this._init(),this.prevTick=0,this.tatumTime=0,this.tickCallback=function(){}},t.Metro.prototype.ontick=function(t){var i=t-this.prevTick,n=t-e.audiocontext.currentTime;if(!(i-this.tatumTime<=-.02)){this.prevTick=t;var o=this;this.syncedParts.forEach(function(t){t.isPlaying&&(t.incrementStep(n),t.phrases.forEach(function(t){var e=t.sequence,i=o.metroTicks%e.length;0!==e[i]&&(o.metroTicks=t.parts.length?(t.scoreStep=0,t.onended()):(t.scoreStep=0,t.parts[t.currentPart-1].stop(),t.parts[t.currentPart].start())}var i=a,n=120;t.prototype.setBPM=function(t,e){n=t;for(var o in i.parts)i.parts[o]&&i.parts[o].setBPM(t,e)},t.Phrase=function(t,e,i){this.phraseStep=0,this.name=t,this.callback=e,this.sequence=i},t.Part=function(e,o){this.length=e||0,this.partStep=0, +this.phrases=[],this.isPlaying=!1,this.noLoop(),this.tatums=o||.0625,this.metro=new t.Metro,this.metro._init(),this.metro.beatLength(this.tatums),this.metro.setBPM(n),i.parts.push(this),this.callback=function(){}},t.Part.prototype.setBPM=function(t,e){this.metro.setBPM(t,e)},t.Part.prototype.getBPM=function(){return this.metro.getBPM()},t.Part.prototype.start=function(t){if(!this.isPlaying){this.isPlaying=!0,this.metro.resetSync(this);var e=t||0;this.metro.start(e)}},t.Part.prototype.loop=function(t){this.looping=!0,this.onended=function(){this.partStep=0};var e=t||0;this.start(e)},t.Part.prototype.noLoop=function(){this.looping=!1,this.onended=function(){this.stop()}},t.Part.prototype.stop=function(t){this.partStep=0,this.pause(t)},t.Part.prototype.pause=function(t){this.isPlaying=!1;var e=t||0;this.metro.stop(e)},t.Part.prototype.addPhrase=function(e,i,n){var o;if(3===arguments.length)o=new t.Phrase(e,i,n);else{if(!(arguments[0]instanceof t.Phrase))throw"invalid input. addPhrase accepts name, callback, array or a p5.Phrase";o=arguments[0]}this.phrases.push(o),o.sequence.length>this.length&&(this.length=o.sequence.length)},t.Part.prototype.removePhrase=function(t){for(var e in this.phrases)this.phrases[e].name===t&&this.phrases.splice(e,1)},t.Part.prototype.getPhrase=function(t){for(var e in this.phrases)if(this.phrases[e].name===t)return this.phrases[e]},t.Part.prototype.replaceSequence=function(t,e){for(var i in this.phrases)this.phrases[i].name===t&&(this.phrases[i].sequence=e)},t.Part.prototype.incrementStep=function(t){this.partStep0&&o.iterations<=o.maxIterations&&o.callback(i)},frequency:this._calcFreq()})},t.SoundLoop.prototype.start=function(t){var i=t||0,n=e.audiocontext.currentTime;this.isPlaying||(this.clock.start(n+i),this.isPlaying=!0)},t.SoundLoop.prototype.stop=function(t){var i=t||0,n=e.audiocontext.currentTime;this.isPlaying&&(this.clock.stop(n+i),this.isPlaying=!1)},t.SoundLoop.prototype.pause=function(t){var i=t||0,n=e.audiocontext.currentTime;this.isPlaying&&(this.clock.pause(n+i),this.isPlaying=!1)},t.SoundLoop.prototype.syncedStart=function(t,i){var n=i||0,o=e.audiocontext.currentTime;if(t.isPlaying){if(t.isPlaying){var r=t.clock._nextTick-e.audiocontext.currentTime;this.clock.start(o+r),this.isPlaying=!0}}else t.clock.start(o+n),t.isPlaying=!0,this.clock.start(o+n),this.isPlaying=!0},t.SoundLoop.prototype._update=function(){this.clock.frequency.value=this._calcFreq()},t.SoundLoop.prototype._calcFreq=function(){return"number"==typeof this._interval?(this.musicalTimeMode=!1,1/this._interval):"string"==typeof this._interval?(this.musicalTimeMode=!0,this._bpm/60/this._convertNotation(this._interval)*(this._timeSignature/4)):void 0},t.SoundLoop.prototype._convertNotation=function(t){var e=t.slice(-1);switch(t=Number(t.slice(0,-1)),e){case"m":return this._measure(t);case"n":return this._note(t);default:console.warn("Specified interval is not formatted correctly. See Tone.js timing reference for more info: https://github.com/Tonejs/Tone.js/wiki/Time")}},t.SoundLoop.prototype._measure=function(t){return t*this._timeSignature},t.SoundLoop.prototype._note=function(t){return this._timeSignature/t},Object.defineProperty(t.SoundLoop.prototype,"bpm",{get:function(){return this._bpm},set:function(t){this.musicalTimeMode||console.warn('Changing the BPM in "seconds" mode has no effect. BPM is only relevant in musicalTimeMode when the interval is specified as a string ("2n", "4n", "1m"...etc)'),this._bpm=t,this._update()}}),Object.defineProperty(t.SoundLoop.prototype,"timeSignature",{get:function(){return this._timeSignature},set:function(t){this.musicalTimeMode||console.warn('Changing the timeSignature in "seconds" mode has no effect. BPM is only relevant in musicalTimeMode when the interval is specified as a string ("2n", "4n", "1m"...etc)'),this._timeSignature=t,this._update()}}),Object.defineProperty(t.SoundLoop.prototype,"interval",{get:function(){return this._interval},set:function(t){this.musicalTimeMode="Number"==typeof t?!1:!0,this._interval=t,this._update()}}),Object.defineProperty(t.SoundLoop.prototype,"iterations",{get:function(){return this.clock.ticks}}),t.SoundLoop}(a,et);var rt;rt=function(){"use strict";var e=Y;return t.Compressor=function(){e.call(this),this.compressor=this.ac.createDynamicsCompressor(),this.input.connect(this.compressor),this.compressor.connect(this.wet)},t.Compressor.prototype=Object.create(e.prototype),t.Compressor.prototype.process=function(t,e,i,n,o,r){t.connect(this.input),this.set(e,i,n,o,r)},t.Compressor.prototype.set=function(t,e,i,n,o){"undefined"!=typeof t&&this.attack(t),"undefined"!=typeof e&&this.knee(e),"undefined"!=typeof i&&this.ratio(i),"undefined"!=typeof n&&this.threshold(n),"undefined"!=typeof o&&this.release(o)},t.Compressor.prototype.attack=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.attack.value=t,this.compressor.attack.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.attack.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.attack),this.compressor.attack.value},t.Compressor.prototype.knee=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.knee.value=t,this.compressor.knee.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.knee.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.knee),this.compressor.knee.value},t.Compressor.prototype.ratio=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.ratio.value=t,this.compressor.ratio.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.ratio.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.ratio),this.compressor.ratio.value},t.Compressor.prototype.threshold=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.threshold.value=t,this.compressor.threshold.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.threshold.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.threshold),this.compressor.threshold.value},t.Compressor.prototype.release=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.release.value=t,this.compressor.release.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.release.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof number&&t.connect(this.compressor.release),this.compressor.release.value},t.Compressor.prototype.reduction=function(){return this.compressor.reduction.value},t.Compressor.prototype.dispose=function(){e.prototype.dispose.apply(this),this.compressor&&(this.compressor.disconnect(),delete this.compressor)},t.Compressor}(a,Y,c);var st;st=function(){var e=a,i=u.convertToWav,n=e.audiocontext;t.SoundRecorder=function(){this.input=n.createGain(),this.output=n.createGain(),this.recording=!1,this.bufferSize=1024,this._channels=2,this._clear(),this._jsNode=n.createScriptProcessor(this.bufferSize,this._channels,2),this._jsNode.onaudioprocess=this._audioprocess.bind(this),this._callback=function(){},this._jsNode.connect(t.soundOut._silentNode),this.setInput(),e.soundArray.push(this)},t.SoundRecorder.prototype.setInput=function(e){this.input.disconnect(),this.input=null,this.input=n.createGain(),this.input.connect(this._jsNode),this.input.connect(this.output),e?e.connect(this.input):t.soundOut.output.connect(this.input)},t.SoundRecorder.prototype.record=function(t,e,i){this.recording=!0,e&&(this.sampleLimit=Math.round(e*n.sampleRate)),t&&i?this._callback=function(){this.buffer=this._getBuffer(),t.setBuffer(this.buffer),i()}:t&&(this._callback=function(){this.buffer=this._getBuffer(),t.setBuffer(this.buffer)})},t.SoundRecorder.prototype.stop=function(){this.recording=!1,this._callback(),this._clear()},t.SoundRecorder.prototype._clear=function(){this._leftBuffers=[],this._rightBuffers=[],this.recordedSamples=0,this.sampleLimit=null},t.SoundRecorder.prototype._audioprocess=function(t){if(this.recording!==!1&&this.recording===!0)if(this.sampleLimit&&this.recordedSamples>=this.sampleLimit)this.stop();else{var e=t.inputBuffer.getChannelData(0),i=t.inputBuffer.getChannelData(1);this._leftBuffers.push(new Float32Array(e)),this._rightBuffers.push(new Float32Array(i)),this.recordedSamples+=this.bufferSize}},t.SoundRecorder.prototype._getBuffer=function(){var t=[];return t.push(this._mergeBuffers(this._leftBuffers)),t.push(this._mergeBuffers(this._rightBuffers)),t},t.SoundRecorder.prototype._mergeBuffers=function(t){for(var e=new Float32Array(this.recordedSamples),i=0,n=t.length,o=0;n>o;o++){var r=t[o];e.set(r,i),i+=r.length}return e},t.SoundRecorder.prototype.dispose=function(){this._clear();var t=e.soundArray.indexOf(this);e.soundArray.splice(t,1),this._callback=function(){},this.input&&this.input.disconnect(),this.input=null,this._jsNode=null},t.prototype.saveSound=function(e,n){const o=i(e.buffer);t.prototype.writeFile([o],n,"wav")}}(a,u);var at;at=function(){t.PeakDetect=function(t,e,i,n){this.framesPerPeak=n||20,this.framesSinceLastPeak=0,this.decayRate=.95,this.threshold=i||.35,this.cutoff=0,this.cutoffMult=1.5,this.energy=0,this.penergy=0,this.currentValue=0,this.isDetected=!1,this.f1=t||40,this.f2=e||2e4,this._onPeak=function(){}},t.PeakDetect.prototype.update=function(t){var e=this.energy=t.getEnergy(this.f1,this.f2)/255;e>this.cutoff&&e>this.threshold&&e-this.penergy>0?(this._onPeak(),this.isDetected=!0,this.cutoff=e*this.cutoffMult,this.framesSinceLastPeak=0):(this.isDetected=!1,this.framesSinceLastPeak<=this.framesPerPeak?this.framesSinceLastPeak++:(this.cutoff*=this.decayRate,this.cutoff=Math.max(this.cutoff,this.threshold))),this.currentValue=e,this.penergy=e},t.PeakDetect.prototype.onPeak=function(t,e){var i=this;i._onPeak=function(){t(i.energy,e)}}}();var ut;ut=function(){var e=a;t.Gain=function(){this.ac=e.audiocontext,this.input=this.ac.createGain(),this.output=this.ac.createGain(),this.input.gain.value=.5,this.input.connect(this.output),e.soundArray.push(this)},t.Gain.prototype.setInput=function(t){t.connect(this.input)},t.Gain.prototype.connect=function(e){var i=e||t.soundOut.input;this.output.connect(i.input?i.input:i)},t.Gain.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.Gain.prototype.amp=function(t,i,n){var i=i||0,n=n||0,o=e.audiocontext.currentTime,r=this.output.gain.value;this.output.gain.cancelScheduledValues(o),this.output.gain.linearRampToValueAtTime(r,o+n),this.output.gain.linearRampToValueAtTime(t,o+n+i)},t.Gain.prototype.dispose=function(){var t=e.soundArray.indexOf(this);e.soundArray.splice(t,1),this.output&&(this.output.disconnect(),delete this.output),this.input&&(this.input.disconnect(),delete this.input)}}(a);var ct;ct=function(){var e=a;return t.AudioVoice=function(){this.ac=e.audiocontext,this.output=this.ac.createGain(),this.connect(),e.soundArray.push(this)},t.AudioVoice.prototype.play=function(t,e,i,n){},t.AudioVoice.prototype.triggerAttack=function(t,e,i){},t.AudioVoice.prototype.triggerRelease=function(t){},t.AudioVoice.prototype.amp=function(t,e){},t.AudioVoice.prototype.connect=function(t){var i=t||e.input;this.output.connect(i.input?i.input:i)},t.AudioVoice.prototype.disconnect=function(){this.output.disconnect()},t.AudioVoice.prototype.dispose=function(){this.output&&(this.output.disconnect(),delete this.output)},t.AudioVoice}(a);var pt;pt=function(){var e=a,i=ct,n=u.noteToFreq,o=.15;t.MonoSynth=function(){i.call(this),this.oscillator=new t.Oscillator,this.env=new t.Envelope,this.env.setRange(1,0),this.env.setExp(!0),this.setADSR(.02,.25,.05,.35),this.oscillator.disconnect(),this.oscillator.connect(this.output),this.env.disconnect(),this.env.setInput(this.output.gain),this.oscillator.output.gain.value=1,this.oscillator.start(),this.connect(),e.soundArray.push(this)},t.MonoSynth.prototype=Object.create(t.AudioVoice.prototype),t.MonoSynth.prototype.play=function(t,e,i,n){this.triggerAttack(t,e,~~i),this.triggerRelease(~~i+(n||o))},t.MonoSynth.prototype.triggerAttack=function(t,e,i){var i=~~i,o=n(t),r=e||.1;this.oscillator.freq(o,0,i),this.env.ramp(this.output.gain,i,r)},t.MonoSynth.prototype.triggerRelease=function(t){var t=t||0;this.env.ramp(this.output.gain,t,0)},t.MonoSynth.prototype.setADSR=function(t,e,i,n){this.env.setADSR(t,e,i,n)},Object.defineProperties(t.MonoSynth.prototype,{attack:{get:function(){return this.env.aTime},set:function(t){this.env.setADSR(t,this.env.dTime,this.env.sPercent,this.env.rTime)}},decay:{get:function(){return this.env.dTime},set:function(t){this.env.setADSR(this.env.aTime,t,this.env.sPercent,this.env.rTime)}},sustain:{get:function(){return this.env.sPercent},set:function(t){this.env.setADSR(this.env.aTime,this.env.dTime,t,this.env.rTime)}},release:{get:function(){return this.env.rTime},set:function(t){this.env.setADSR(this.env.aTime,this.env.dTime,this.env.sPercent,t)}}}),t.MonoSynth.prototype.amp=function(t,e){var i=e||0;return"undefined"!=typeof t&&this.oscillator.amp(t,i),this.oscillator.amp().value},t.MonoSynth.prototype.connect=function(t){var i=t||e.input;this.output.connect(i.input?i.input:i)},t.MonoSynth.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.MonoSynth.prototype.dispose=function(){i.prototype.dispose.apply(this),this.env&&this.env.dispose(),this.oscillator&&this.oscillator.dispose()}}(a,ct,u);var ht;ht=function(){var e=a,i=q,n=u.noteToFreq;t.PolySynth=function(n,o){this.audiovoices=[],this.notes={},this._newest=0,this._oldest=0,this.maxVoices=o||8,this.AudioVoice=void 0===n?t.MonoSynth:n,this._voicesInUse=new i(0),this.output=e.audiocontext.createGain(),this.connect(),this._allocateVoices(),e.soundArray.push(this)},t.PolySynth.prototype._allocateVoices=function(){for(var t=0;tf?f:p}this.audiovoices[a].triggerAttack(c,p,s)},t.PolySynth.prototype._updateAfter=function(t,e){if(null!==this._voicesInUse._searchAfter(t)){this._voicesInUse._searchAfter(t).value+=e;var i=this._voicesInUse._searchAfter(t).time;this._updateAfter(i,e)}},t.PolySynth.prototype.noteRelease=function(t,i){var o=e.audiocontext.currentTime,r=i||0,s=o+r;if(t){var a=n(t);if(this.notes[a]&&null!==this.notes[a].getValueAtTime(s)){var u=Math.max(~~this._voicesInUse.getValueAtTime(s).value,1);this._voicesInUse.setValueAtTime(u-1,s),u>0&&this._updateAfter(s,-1),this.audiovoices[this.notes[a].getValueAtTime(s)].triggerRelease(r),this.notes[a].dispose(),delete this.notes[a],this._newest=0===this._newest?0:(this._newest-1)%(this.maxVoices-1)}else console.warn("Cannot release a note that is not already playing")}else{this.audiovoices.forEach(function(t){t.triggerRelease(r)}),this._voicesInUse.setValueAtTime(0,s);for(var c in this.notes)this.notes[c].dispose(),delete this.notes[c]}},t.PolySynth.prototype.connect=function(t){var i=t||e.input;this.output.connect(i.input?i.input:i)},t.PolySynth.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.PolySynth.prototype.dispose=function(){this.audiovoices.forEach(function(t){t.dispose()}),this.output&&(this.output.disconnect(),delete this.output)}}(a,q,u);var lt;lt=function(){function e(t){for(var e,i="number"==typeof t?t:50,n=44100,o=new Float32Array(n),r=Math.PI/180,s=0;n>s;++s)e=2*s/n-1,o[s]=(3+i)*e*20*r/(Math.PI+i*Math.abs(e));return o}var i=Y;t.Distortion=function(n,o){if(i.call(this),"undefined"==typeof n&&(n=.25),"number"!=typeof n)throw new Error("amount must be a number");if("undefined"==typeof o&&(o="2x"),"string"!=typeof o)throw new Error("oversample must be a String");var r=t.prototype.map(n,0,1,0,2e3);this.waveShaperNode=this.ac.createWaveShaper(),this.amount=r,this.waveShaperNode.curve=e(r),this.waveShaperNode.oversample=o,this.input.connect(this.waveShaperNode),this.waveShaperNode.connect(this.wet)},t.Distortion.prototype=Object.create(i.prototype),t.Distortion.prototype.process=function(t,e,i){t.connect(this.input),this.set(e,i)},t.Distortion.prototype.set=function(i,n){if(i){var o=t.prototype.map(i,0,1,0,2e3);this.amount=o,this.waveShaperNode.curve=e(o)}n&&(this.waveShaperNode.oversample=n)},t.Distortion.prototype.getAmount=function(){return this.amount},t.Distortion.prototype.getOversample=function(){return this.waveShaperNode.oversample},t.Distortion.prototype.dispose=function(){i.prototype.dispose.apply(this),this.waveShaperNode&&(this.waveShaperNode.disconnect(),this.waveShaperNode=null)}}(Y);var ft;ft=function(){var t=a;return t}(e,s,a,u,c,p,h,l,f,k,O,M,E,V,R,z,Q,H,$,J,K,it,nt,ot,rt,st,at,ut,pt,ht,lt,ct,pt,ht)}); \ No newline at end of file diff --git a/pyp5js/static/p5/empty-example/index.html b/pyp5js/static/p5/empty-example/index.html new file mode 100644 index 00000000..6242686a --- /dev/null +++ b/pyp5js/static/p5/empty-example/index.html @@ -0,0 +1,15 @@ + + + + + + p5.js example + + + + + + + + + diff --git a/pyp5js/static/p5/empty-example/sketch.js b/pyp5js/static/p5/empty-example/sketch.js new file mode 100644 index 00000000..de6c8626 --- /dev/null +++ b/pyp5js/static/p5/empty-example/sketch.js @@ -0,0 +1,7 @@ +function setup() { + // put setup code here +} + +function draw() { + // put drawing code here +} \ No newline at end of file diff --git a/pyp5js/static/p5.js b/pyp5js/static/p5/p5.js similarity index 90% rename from pyp5js/static/p5.js rename to pyp5js/static/p5/p5.js index a50788bd..6e9769c2 100644 --- a/pyp5js/static/p5.js +++ b/pyp5js/static/p5/p5.js @@ -1,10 +1,10 @@ -/*! p5.js v0.7.2 September 02, 2018 */ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.p5 = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;oThin wrapper around a renderer, to be used for creating a\ngraphics buffer object. Use this class if you need\nto draw into an off-screen graphics buffer. The two parameters define the\nwidth and height in pixels. The fields and methods for this class are\nextensive, but mirror the normal drawing API for p5.

\n" }, "Transform": { @@ -1040,7 +1040,7 @@ module.exports={ }, "namespaces": {}, "file": "src/data/p5.TypedDict.js", - "line": 410 + "line": 422 }, "Dictionary": { "name": "Dictionary", @@ -1060,7 +1060,7 @@ module.exports={ "module": "Data", "namespace": "", "file": "src/data/p5.TypedDict.js", - "line": 410, + "line": 422, "requires": [ "core\n\nThis module defines the p5 methods for the p5 Dictionary classes.\nThe classes StringDict and NumberDict are for storing and working\nwith key-value pairs." ], @@ -1270,7 +1270,7 @@ module.exports={ "module": "IO", "namespace": "", "file": "src/io/files.js", - "line": 1242, + "line": 1231, "description": "

This is the p5 instance constructor.

\n

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

\n

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

\n" }, "Table": { @@ -1425,7 +1425,7 @@ module.exports={ }, "namespaces": {}, "file": "src/typography/p5.Font.js", - "line": 21 + "line": 15 }, "Font": { "name": "Font", @@ -1440,7 +1440,7 @@ module.exports={ "module": "Typography", "namespace": "", "file": "src/typography/p5.Font.js", - "line": 21, + "line": 15, "description": "

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

\n", "requires": [ "core", @@ -1700,8 +1700,8 @@ module.exports={ "namespaces": {}, "module": "p5.dom", "file": "lib/addons/p5.dom.js", - "line": 3083, - "description": "

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

\n

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

\n

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

\n

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

\n", + "line": 3331, + "description": "

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

\n

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

\n

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

\n

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

\n", "tag": "main", "itemtype": "main" }, @@ -1754,8 +1754,8 @@ module.exports={ "namespaces": {}, "module": "p5.sound", "file": "lib/addons/p5.sound.js", - "line": 12501, - "description": "

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

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

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

\n", + "line": 12767, + "description": "

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

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

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

\n", "tag": "main", "itemtype": "main" } @@ -1945,7 +1945,7 @@ module.exports={ "submodule": "Dictionary", "namespace": "", "file": "src/data/p5.TypedDict.js", - "line": 391, + "line": 403, "description": "

A simple Dictionary class for Strings.

\n", "extends": "p5.TypedDict" }, @@ -1961,7 +1961,7 @@ module.exports={ "submodule": "Dictionary", "namespace": "", "file": "src/data/p5.TypedDict.js", - "line": 410, + "line": 422, "description": "

A simple Dictionary class for Numbers.

\n", "extends": "p5.TypedDict" }, @@ -1980,7 +1980,7 @@ module.exports={ "line": 23, "description": "

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

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

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

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

\n", "example": [ - "\n
\nfunction setup() {\n var img = createImage(100, 100); // same as new p5.Image(100, 100);\n img.loadPixels();\n createCanvas(100, 100);\n background(0);\n\n // helper for writing color to array\n function writeColor(image, x, y, red, green, blue, alpha) {\n var index = (x + y * width) * 4;\n image.pixels[index] = red;\n image.pixels[index + 1] = green;\n image.pixels[index + 2] = blue;\n image.pixels[index + 3] = alpha;\n }\n\n var x, y;\n // fill with random colors\n for (y = 0; y < img.height; y++) {\n for (x = 0; x < img.width; x++) {\n var red = random(255);\n var green = random(255);\n var blue = random(255);\n var alpha = 255;\n writeColor(img, x, y, red, green, blue, alpha);\n }\n }\n\n // draw a red line\n y = 0;\n for (x = 0; x < img.width; x++) {\n writeColor(img, x, y, 255, 0, 0, 255);\n }\n\n // draw a green line\n y = img.height - 1;\n for (x = 0; x < img.width; x++) {\n writeColor(img, x, y, 0, 255, 0, 255);\n }\n\n img.updatePixels();\n image(img, 0, 0);\n}\n
" + "\n
\nfunction setup() {\n let img = createImage(100, 100); // same as new p5.Image(100, 100);\n img.loadPixels();\n createCanvas(100, 100);\n background(0);\n\n // helper for writing color to array\n function writeColor(image, x, y, red, green, blue, alpha) {\n let index = (x + y * width) * 4;\n image.pixels[index] = red;\n image.pixels[index + 1] = green;\n image.pixels[index + 2] = blue;\n image.pixels[index + 3] = alpha;\n }\n\n let x, y;\n // fill with random colors\n for (y = 0; y < img.height; y++) {\n for (x = 0; x < img.width; x++) {\n let red = random(255);\n let green = random(255);\n let blue = random(255);\n let alpha = 255;\n writeColor(img, x, y, red, green, blue, alpha);\n }\n }\n\n // draw a red line\n y = 0;\n for (x = 0; x < img.width; x++) {\n writeColor(img, x, y, 255, 0, 0, 255);\n }\n\n // draw a green line\n y = img.height - 1;\n for (x = 0; x < img.width; x++) {\n writeColor(img, x, y, 0, 255, 0, 255);\n }\n\n img.updatePixels();\n image(img, 0, 0);\n}\n
" ], "params": [ { @@ -2007,7 +2007,7 @@ module.exports={ "submodule": "Output", "namespace": "", "file": "src/io/files.js", - "line": 1242, + "line": 1231, "params": [ { "name": "filename", @@ -2092,7 +2092,7 @@ module.exports={ "description": "

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

\n", "is_constructor": 1, "example": [ - "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var children = xml.getChildren('animal');\n\n for (var i = 0; i < children.length; i++) {\n var id = children[i].getNum('id');\n var coloring = children[i].getString('species');\n var name = children[i].getContent();\n print(id + ', ' + coloring + ', ' + name);\n }\n}\n\n// Sketch prints:\n// 0, Capra hircus, Goat\n// 1, Panthera pardus, Leopard\n// 2, Equus zebra, Zebra\n
" + "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let children = xml.getChildren('animal');\n\n for (let i = 0; i < children.length; i++) {\n let id = children[i].getNum('id');\n let coloring = children[i].getString('species');\n let name = children[i].getContent();\n print(id + ', ' + coloring + ', ' + name);\n }\n}\n\n// Sketch prints:\n// 0, Capra hircus, Goat\n// 1, Panthera pardus, Leopard\n// 2, Equus zebra, Zebra\n
" ], "alt": "no image displayed" }, @@ -2131,7 +2131,7 @@ module.exports={ } ], "example": [ - "\n
\n\nvar v1 = createVector(40, 50);\nvar v2 = createVector(40, 50);\n\nellipse(v1.x, v1.y, 50, 50);\nellipse(v2.x, v2.y, 50, 50);\nv1.add(v2);\nellipse(v1.x, v1.y, 50, 50);\n\n
" + "\n
\n\nlet v1 = createVector(40, 50);\nlet v2 = createVector(40, 50);\n\nellipse(v1.x, v1.y, 50, 50);\nellipse(v2.x, v2.y, 50, 50);\nv1.add(v2);\nellipse(v1.x, v1.y, 50, 50);\n\n
" ], "alt": "2 white ellipses. One center-left the other bottom right and off canvas" }, @@ -2147,7 +2147,7 @@ module.exports={ "submodule": "Font", "namespace": "", "file": "src/typography/p5.Font.js", - "line": 21, + "line": 15, "description": "

Base class for font handling

\n", "params": [ { @@ -2180,7 +2180,7 @@ module.exports={ } ], "example": [ - "\n
\n\nvar cam;\nvar delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n // set initial pan angle\n cam.pan(-0.8);\n}\n\nfunction draw() {\n background(200);\n\n // pan camera according to angle 'delta'\n cam.pan(delta);\n\n // every 160 frames, switch direction\n if (frameCount % 160 === 0) {\n delta *= -1;\n }\n\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n\n
" + "\n
\n\nlet cam;\nlet delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n // set initial pan angle\n cam.pan(-0.8);\n}\n\nfunction draw() {\n background(200);\n\n // pan camera according to angle 'delta'\n cam.pan(delta);\n\n // every 160 frames, switch direction\n if (frameCount % 160 === 0) {\n delta *= -1;\n }\n\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n\n
" ], "alt": "camera view pans left and right across a series of rotating 3D boxes." }, @@ -2263,7 +2263,7 @@ module.exports={ "submodule": "p5.dom", "namespace": "", "file": "lib/addons/p5.dom.js", - "line": 1975, + "line": 2228, "description": "

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

\n", "is_constructor": 1, "params": [ @@ -2286,8 +2286,8 @@ module.exports={ "submodule": "p5.dom", "namespace": "", "file": "lib/addons/p5.dom.js", - "line": 3083, - "description": "

Base class for a file\nUsing this for createFileInput

\n", + "line": 3331, + "description": "

Base class for a file.\nUsed for Element.drop and createFileInput.

\n", "is_constructor": 1, "params": [ { @@ -2321,7 +2321,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 808, + "line": 1645, "description": "

SoundFile object with a path to a file.

\n\n

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

\n\n

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

\n\n

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

", "is_constructor": 1, "params": [ @@ -2365,7 +2365,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 2234, + "line": 3179, "description": "

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

\n", "is_constructor": 1, "params": [ @@ -2392,7 +2392,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 2513, + "line": 3458, "description": "

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

\n\n

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

\n\n

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

", "is_constructor": 1, "params": [ @@ -2425,7 +2425,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 4916, + "line": 5223, "description": "

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

\n\n

This is necessary because Web Audio is processed on a seprate clock.\nFor example, the p5 draw loop runs about 60 times per second. But\nthe audio clock must process samples 44100 times per second. If we\nwant to add a value to each of those samples, we can't do it in the\ndraw loop, but we can do it by adding a constant-rate audio signal.</p.\n\n

This class mostly functions behind the scenes in p5.sound, and returns\na Tone.Signal from the Tone.js library by Yotam Mann.\nIf you want to work directly with audio signals for modular\nsynthesis, check out\ntone.js.

", "is_constructor": 1, "return": { @@ -2448,7 +2448,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 5062, + "line": 5369, "description": "

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

\n\n

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

", "is_constructor": 1, "params": [ @@ -2481,7 +2481,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 5503, + "line": 5810, "description": "

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

\n", "is_constructor": 1, "extends": "p5.Oscillator", @@ -2506,7 +2506,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 5520, + "line": 5827, "description": "

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

\n", "is_constructor": 1, "extends": "p5.Oscillator", @@ -2531,7 +2531,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 5537, + "line": 5844, "description": "

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

\n", "is_constructor": 1, "extends": "p5.Oscillator", @@ -2556,7 +2556,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 5554, + "line": 5861, "description": "

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

\n", "is_constructor": 1, "extends": "p5.Oscillator", @@ -2581,11 +2581,11 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 6011, + "line": 6316, "description": "

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

\n

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

\n

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

", "is_constructor": 1, "example": [ - "\n
\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv(){\n env.play();\n}\n
" + "\n
\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001;\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv() {\n env.play();\n}\n
" ] }, "p5.Pulse": { @@ -2600,7 +2600,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 6809, + "line": 7114, "description": "

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

\n", "extends": "p5.Oscillator", "is_constructor": 1, @@ -2634,7 +2634,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 6988, + "line": 7293, "description": "

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

\n", "extends": "p5.Oscillator", "is_constructor": 1, @@ -2658,7 +2658,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 7136, + "line": 7441, "description": "

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

\n\n

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

\n\n

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

\n\n

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

", "is_constructor": 1, "params": [ @@ -2685,7 +2685,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 8033, + "line": 8357, "description": "

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

\n

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

\n", "is_constructor": 1, "params": [ @@ -2733,7 +2733,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 8175, + "line": 8499, "description": "

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

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

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

\n

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

\n", "extends": "p5.Effect", "is_constructor": 1, @@ -2761,7 +2761,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 8407, + "line": 8730, "description": "

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

\n", "is_constructor": 1, "extends": "p5.Filter" @@ -2778,7 +2778,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 8421, + "line": 8744, "description": "

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

\n", "is_constructor": 1, "extends": "p5.Filter" @@ -2795,7 +2795,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 8435, + "line": 8758, "description": "

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

\n", "is_constructor": 1, "extends": "p5.Filter" @@ -2812,7 +2812,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 8506, + "line": 8829, "description": "

p5.EQ is an audio effect that performs the function of a multiband\naudio equalizer. Equalization is used to adjust the balance of\nfrequency compoenents of an audio signal. This process is commonly used\nin sound production and recording to change the waveform before it reaches\na sound output device. EQ can also be used as an audio effect to create\ninteresting distortions by filtering out parts of the spectrum. p5.EQ is\nbuilt using a chain of Web Audio Biquad Filter Nodes and can be\ninstantiated with 3 or 8 bands. Bands can be added or removed from\nthe EQ by directly modifying p5.EQ.bands (the array that stores filters).

\n

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

\n", "is_constructor": 1, "extends": "p5.Effect", @@ -2844,7 +2844,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 8698, + "line": 9021, "description": "

Panner3D is based on the \nWeb Audio Spatial Panner Node.\nThis panner is a spatial processing node that allows audio to be positioned\nand oriented in 3D space.

\n

The position is relative to an \nAudio Context Listener, which can be accessed\nby p5.soundOut.audiocontext.listener

\n", "is_constructor": 1 }, @@ -2860,7 +2860,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 9149, + "line": 9472, "description": "

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

\n

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

\n", "extends": "p5.Effect", "is_constructor": 1, @@ -2880,7 +2880,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 9426, + "line": 9749, "description": "

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

\n

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

\n", "extends": "p5.Effect", "is_constructor": 1, @@ -2900,7 +2900,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 9586, + "line": 9920, "description": "

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

\n\n

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

\n\n

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

", "extends": "p5.Effect", "is_constructor": 1, @@ -2939,7 +2939,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 10148, + "line": 10476, "description": "

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

\n\n

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

\n\n

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

", "is_constructor": 1, "params": [ @@ -2975,8 +2975,8 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 10233, - "description": "

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

\n\n

See p5.Phrase for more about musical timing.

", + "line": 10561, + "description": "

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

\n\n

See p5.Phrase for more about musical timing.

", "is_constructor": 1, "params": [ { @@ -2987,7 +2987,7 @@ module.exports={ }, { "name": "tatums", - "description": "

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

\n", + "description": "

Divisions of a beat, e.g. use 1/4, or 0.25 for a quater note (default is 1/16, a sixteenth note)

\n", "type": "Number", "optional": true } @@ -3008,7 +3008,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 10487, + "line": 10814, "description": "

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

\n", "is_constructor": 1, "params": [ @@ -3033,7 +3033,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 10618, + "line": 10945, "description": "

SoundLoop

\n", "is_constructor": 1, "params": [ @@ -3065,7 +3065,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 10878, + "line": 11205, "description": "

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

\n

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

\n", "is_constructor": 1, "extends": "p5.Effect" @@ -3082,7 +3082,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 11089, + "line": 11417, "description": "

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

\n

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

", "is_constructor": 1, "example": [ @@ -3101,8 +3101,8 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 11378, - "description": "

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

\n

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

\n

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

\n\n

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

\n\n

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

\n\n

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

", + "line": 11655, + "description": "

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

\n

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

\n

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

\n\n

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

\n\n

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

\n\n

\nBased on example contribtued by @b2renger, and a simple beat detection\nexplanation by Felix Turner.\n

", "is_constructor": 1, "params": [ { @@ -3146,7 +3146,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 11602, + "line": 11879, "description": "

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

\n", "is_constructor": 1, "example": [ @@ -3165,7 +3165,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 11743, + "line": 12020, "description": "

Base class for monophonic synthesizers. Any extensions of this class\nshould follow the API and implement the methods below in order to \nremain compatible with p5.PolySynth();

\n", "is_constructor": 1 }, @@ -3181,7 +3181,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 11796, + "line": 12073, "description": "

A MonoSynth is used as a single voice for sound synthesis.\nThis is a class to be used in conjunction with the PolySynth\nclass. Custom synthetisers should be built inheriting from\nthis class.

\n", "is_constructor": 1, "example": [ @@ -3200,7 +3200,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 12096, + "line": 12362, "description": "

An AudioVoice is used as a single voice for sound synthesis.\nThe PolySynth class holds an array of AudioVoice, and deals\nwith voices allocations, with setting notes to be played, and\nparameters to be set.

\n", "is_constructor": 1, "params": [ @@ -3233,7 +3233,7 @@ module.exports={ "submodule": "p5.sound", "namespace": "", "file": "lib/addons/p5.sound.js", - "line": 12501, + "line": 12767, "description": "

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

\n

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

\n", "extends": "p5.Effect", "is_constructor": 1, @@ -3331,9 +3331,9 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nnoStroke();\nvar c = color(0, 126, 255, 102);\nfill(c);\nrect(15, 15, 35, 70);\nvar value = alpha(c); // Sets 'value' to 102\nfill(value);\nrect(50, 15, 35, 70);\n\n
" + "\n
\n\nnoStroke();\nlet c = color(0, 126, 255, 102);\nfill(c);\nrect(15, 15, 35, 70);\nlet value = alpha(c); // Sets 'value' to 102\nfill(value);\nrect(50, 15, 35, 70);\n\n
" ], - "alt": "Left half of canvas light blue and right half light charcoal grey.\nLeft half of canvas light purple and right half a royal blue.\nLeft half of canvas salmon pink and the right half white.\nYellow rect in middle right of canvas, with 55 pixel width and height.\nYellow ellipse in top left canvas, black ellipse in bottom right,both 80x80.\nBright fuschia rect in middle of canvas, 60 pixel width and height.\nTwo bright green rects on opposite sides of the canvas, both 45x80.\nFour blue rects in each corner of the canvas, each are 35x35.\nBright sea green rect on left and darker rect on right of canvas, both 45x80.\nDark green rect on left and light green rect on right of canvas, both 45x80.\nDark blue rect on left and light teal rect on right of canvas, both 45x80.\nblue rect on left and green on right, both with black outlines & 35x60.\nsalmon pink rect on left and black on right, both 35x60.\n4 rects, tan, brown, brownish purple and purple, with white outlines & 20x60.\nlight pastel green rect on left and dark grey rect on right, both 35x60.\nyellow rect on left and red rect on right, both with black outlines & 35x60.\ngrey canvas\ndeep pink rect on left and grey rect on right, both 35x60.", + "alt": "Left half of canvas light blue and right half light charcoal grey.\nLeft half of canvas light purple and right half a royal blue.\nLeft half of canvas salmon pink and the right half white.\nYellow rect in middle right of canvas, with 55 pixel width and height.\nYellow ellipse in top left canvas, black ellipse in bottom right,both 80x80.\nBright fuchsia rect in middle of canvas, 60 pixel width and height.\nTwo bright green rects on opposite sides of the canvas, both 45x80.\nFour blue rects in each corner of the canvas, each are 35x35.\nBright sea green rect on left and darker rect on right of canvas, both 45x80.\nDark green rect on left and light green rect on right of canvas, both 45x80.\nDark blue rect on left and light teal rect on right of canvas, both 45x80.\nblue rect on left and green on right, both with black outlines & 35x60.\nsalmon pink rect on left and black on right, both 35x60.\n4 rects, tan, brown, brownish purple and purple, with white outlines & 20x60.\nlight pastel green rect on left and dark grey rect on right, both 35x60.\nyellow rect on left and red rect on right, both with black outlines & 35x60.\ngrey canvas\ndeep pink rect on left and grey rect on right, both 35x60.", "class": "p5", "module": "Color", "submodule": "Creating & Reading" @@ -3356,7 +3356,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nvar c = color(175, 100, 220); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nvar blueValue = blue(c); // Get blue in 'c'\nprint(blueValue); // Prints \"220.0\"\nfill(0, 0, blueValue); // Use 'blueValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n\n
" + "\n
\n\nlet c = color(175, 100, 220); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nlet blueValue = blue(c); // Get blue in 'c'\nprint(blueValue); // Prints \"220.0\"\nfill(0, 0, blueValue); // Use 'blueValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n\n
" ], "alt": "Left half of canvas light purple and right half a royal blue.", "class": "p5", @@ -3381,16 +3381,16 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nnoStroke();\ncolorMode(HSB, 255);\nvar c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nvar value = brightness(c); // Sets 'value' to 255\nfill(value);\nrect(50, 20, 35, 60);\n\n
" + "\n
\n\nnoStroke();\ncolorMode(HSB, 255);\nlet c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nlet value = brightness(c); // Sets 'value' to 255\nfill(value);\nrect(50, 20, 35, 60);\n\n
\n
\n\nnoStroke();\ncolorMode(HSB, 255);\nlet c = color('hsb(60, 100%, 50%)');\nfill(c);\nrect(15, 20, 35, 60);\nlet value = brightness(c); // A 'value' of 50% is 127.5\nfill(value);\nrect(50, 20, 35, 60);\n\n
" ], - "alt": "Left half of canvas salmon pink and the right half white.", + "alt": "Left half of canvas salmon pink and the right half white.\nLeft half of canvas yellow at half brightness and the right gray .", "class": "p5", "module": "Color", "submodule": "Creating & Reading" }, { "file": "src/color/creating_reading.js", - "line": 121, + "line": 134, "description": "

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

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

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

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

Extracts the green value from a color or pixel array.

\n", "itemtype": "method", "name": "green", @@ -3518,7 +3518,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nvar c = color(20, 75, 200); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nvar greenValue = green(c); // Get green in 'c'\nprint(greenValue); // Print \"75.0\"\nfill(0, greenValue, 0); // Use 'greenValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n\n
" + "\n
\n\nlet c = color(20, 75, 200); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nlet greenValue = green(c); // Get green in 'c'\nprint(greenValue); // Print \"75.0\"\nfill(0, greenValue, 0); // Use 'greenValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n\n
" ], "alt": "blue rect on left and green on right, both with black outlines & 35x60.", "class": "p5", @@ -3527,7 +3527,7 @@ module.exports={ }, { "file": "src/color/creating_reading.js", - "line": 350, + "line": 363, "description": "

Extracts the hue value from a color or pixel array.

\n

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

\n", "itemtype": "method", "name": "hue", @@ -3543,7 +3543,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nnoStroke();\ncolorMode(HSB, 255);\nvar c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nvar value = hue(c); // Sets 'value' to \"0\"\nfill(value);\nrect(50, 20, 35, 60);\n\n
" + "\n
\n\nnoStroke();\ncolorMode(HSB, 255);\nlet c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nlet value = hue(c); // Sets 'value' to \"0\"\nfill(value);\nrect(50, 20, 35, 60);\n\n
" ], "alt": "salmon pink rect on left and black on right, both 35x60.", "class": "p5", @@ -3552,7 +3552,7 @@ module.exports={ }, { "file": "src/color/creating_reading.js", - "line": 387, + "line": 400, "description": "

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

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

\n", "itemtype": "method", "name": "lerpColor", @@ -3578,7 +3578,7 @@ module.exports={ "type": "p5.Color" }, "example": [ - "\n
\n\ncolorMode(RGB);\nstroke(255);\nbackground(51);\nvar from = color(218, 165, 32);\nvar to = color(72, 61, 139);\ncolorMode(RGB); // Try changing to HSB.\nvar interA = lerpColor(from, to, 0.33);\nvar interB = lerpColor(from, to, 0.66);\nfill(from);\nrect(10, 20, 20, 60);\nfill(interA);\nrect(30, 20, 20, 60);\nfill(interB);\nrect(50, 20, 20, 60);\nfill(to);\nrect(70, 20, 20, 60);\n\n
" + "\n
\n\ncolorMode(RGB);\nstroke(255);\nbackground(51);\nlet from = color(218, 165, 32);\nlet to = color(72, 61, 139);\ncolorMode(RGB); // Try changing to HSB.\nlet interA = lerpColor(from, to, 0.33);\nlet interB = lerpColor(from, to, 0.66);\nfill(from);\nrect(10, 20, 20, 60);\nfill(interA);\nrect(30, 20, 20, 60);\nfill(interB);\nrect(50, 20, 20, 60);\nfill(to);\nrect(70, 20, 20, 60);\n\n
" ], "alt": "4 rects one tan, brown, brownish purple, purple, with white outlines & 20x60", "class": "p5", @@ -3587,7 +3587,7 @@ module.exports={ }, { "file": "src/color/creating_reading.js", - "line": 484, + "line": 497, "description": "

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

\n", "itemtype": "method", "name": "lightness", @@ -3603,7 +3603,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nnoStroke();\ncolorMode(HSL);\nvar c = color(156, 100, 50, 1);\nfill(c);\nrect(15, 20, 35, 60);\nvar value = lightness(c); // Sets 'value' to 50\nfill(value);\nrect(50, 20, 35, 60);\n\n
" + "\n
\n\nnoStroke();\ncolorMode(HSL);\nlet c = color(156, 100, 50, 1);\nfill(c);\nrect(15, 20, 35, 60);\nlet value = lightness(c); // Sets 'value' to 50\nfill(value);\nrect(50, 20, 35, 60);\n\n
" ], "alt": "light pastel green rect on left and dark grey rect on right, both 35x60.", "class": "p5", @@ -3612,7 +3612,7 @@ module.exports={ }, { "file": "src/color/creating_reading.js", - "line": 514, + "line": 527, "description": "

Extracts the red value from a color or pixel array.

\n", "itemtype": "method", "name": "red", @@ -3628,7 +3628,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nvar c = color(255, 204, 0); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nvar redValue = red(c); // Get red in 'c'\nprint(redValue); // Print \"255.0\"\nfill(redValue, 0, 0); // Use 'redValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n\n
\n\n
\n\ncolorMode(RGB, 255);\nvar c = color(127, 255, 0);\ncolorMode(RGB, 1);\nvar myColor = red(c);\nprint(myColor);\n\n
" + "\n
\n\nlet c = color(255, 204, 0); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nlet redValue = red(c); // Get red in 'c'\nprint(redValue); // Print \"255.0\"\nfill(redValue, 0, 0); // Use 'redValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n\n
\n\n
\n\ncolorMode(RGB, 255); // Sets the range for red, green, and blue to 255\nlet c = color(127, 255, 0);\ncolorMode(RGB, 1); // Sets the range for red, green, and blue to 1\nlet myColor = red(c);\nprint(myColor); // 0.4980392156862745\n\n
" ], "alt": "yellow rect on left and red rect on right, both with black outlines and 35x60.\ngrey canvas", "class": "p5", @@ -3637,7 +3637,7 @@ module.exports={ }, { "file": "src/color/creating_reading.js", - "line": 554, + "line": 567, "description": "

Extracts the saturation value from a color or pixel array.

\n

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

\n", "itemtype": "method", "name": "saturation", @@ -3653,7 +3653,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nnoStroke();\ncolorMode(HSB, 255);\nvar c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nvar value = saturation(c); // Sets 'value' to 126\nfill(value);\nrect(50, 20, 35, 60);\n\n
" + "\n
\n\nnoStroke();\ncolorMode(HSB, 255);\nlet c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nlet value = saturation(c); // Sets 'value' to 126\nfill(value);\nrect(50, 20, 35, 60);\n\n
" ], "alt": "deep pink rect on left and grey rect on right, both 35x60.", "class": "p5", @@ -3679,7 +3679,7 @@ module.exports={ "type": "String" }, "example": [ - "\n
\n\nvar myColor;\nfunction setup() {\n createCanvas(200, 200);\n stroke(255);\n myColor = color(100, 100, 250);\n fill(myColor);\n}\n\nfunction draw() {\n rotate(HALF_PI);\n text(myColor.toString(), 0, -5);\n text(myColor.toString('#rrggbb'), 0, -30);\n text(myColor.toString('rgba%'), 0, -55);\n}\n\n
" + "\n
\n\nlet myColor;\nfunction setup() {\n createCanvas(200, 200);\n stroke(255);\n myColor = color(100, 100, 250);\n fill(myColor);\n}\n\nfunction draw() {\n rotate(HALF_PI);\n text(myColor.toString(), 0, -5);\n text(myColor.toString('#rrggbb'), 0, -30);\n text(myColor.toString('rgba%'), 0, -55);\n}\n\n
" ], "alt": "canvas with text representation of color", "class": "p5.Color", @@ -3688,7 +3688,7 @@ module.exports={ }, { "file": "src/color/p5.Color.js", - "line": 248, + "line": 253, "itemtype": "method", "name": "setRed", "params": [ @@ -3699,7 +3699,7 @@ module.exports={ } ], "example": [ - "\n
\n\nvar backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setRed(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n}\n\n
" + "\n
\n\nlet backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setRed(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n}\n\n
" ], "alt": "canvas with gradually changing background color", "class": "p5.Color", @@ -3708,7 +3708,7 @@ module.exports={ }, { "file": "src/color/p5.Color.js", - "line": 275, + "line": 280, "itemtype": "method", "name": "setGreen", "params": [ @@ -3719,7 +3719,7 @@ module.exports={ } ], "example": [ - "\n
\n\nvar backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setGreen(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n}\n\n
" + "\n
\n\nlet backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setGreen(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n}\n\n
" ], "alt": "canvas with gradually changing background color", "class": "p5.Color", @@ -3728,7 +3728,7 @@ module.exports={ }, { "file": "src/color/p5.Color.js", - "line": 302, + "line": 307, "itemtype": "method", "name": "setBlue", "params": [ @@ -3739,7 +3739,7 @@ module.exports={ } ], "example": [ - "\n
\n\nvar backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setBlue(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n}\n\n
" + "\n
\n\nlet backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setBlue(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n}\n\n
" ], "alt": "canvas with gradually changing background color", "class": "p5.Color", @@ -3748,7 +3748,7 @@ module.exports={ }, { "file": "src/color/p5.Color.js", - "line": 329, + "line": 334, "itemtype": "method", "name": "setAlpha", "params": [ @@ -3759,7 +3759,7 @@ module.exports={ } ], "example": [ - "\n
\n\nvar squareColor;\n\nfunction setup() {\n ellipseMode(CORNERS);\n strokeWeight(4);\n squareColor = color(100, 50, 150);\n}\n\nfunction draw() {\n background(255);\n\n noFill();\n stroke(0);\n ellipse(10, 10, width - 10, height - 10);\n\n squareColor.setAlpha(128 + 128 * sin(millis() / 1000));\n fill(squareColor);\n noStroke();\n rect(13, 13, width - 26, height - 26);\n}\n\n
" + "\n
\n\nlet squareColor;\n\nfunction setup() {\n ellipseMode(CORNERS);\n strokeWeight(4);\n squareColor = color(100, 50, 150);\n}\n\nfunction draw() {\n background(255);\n\n noFill();\n stroke(0);\n ellipse(10, 10, width - 10, height - 10);\n\n squareColor.setAlpha(128 + 128 * sin(millis() / 1000));\n fill(squareColor);\n noStroke();\n rect(13, 13, width - 26, height - 26);\n}\n\n
" ], "alt": "circle behind a square with gradually changing opacity", "class": "p5.Color", @@ -3768,7 +3768,7 @@ module.exports={ }, { "file": "src/color/p5.Color.js", - "line": 410, + "line": 415, "description": "

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

\n", "class": "p5.Color", "module": "Color", @@ -3776,7 +3776,7 @@ module.exports={ }, { "file": "src/color/p5.Color.js", - "line": 441, + "line": 446, "description": "

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

\n", "class": "p5.Color", "module": "Color", @@ -3784,7 +3784,7 @@ module.exports={ }, { "file": "src/color/p5.Color.js", - "line": 460, + "line": 465, "description": "

CSS named colors.

\n", "class": "p5.Color", "module": "Color", @@ -3792,7 +3792,7 @@ module.exports={ }, { "file": "src/color/p5.Color.js", - "line": 613, + "line": 618, "description": "

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

\n

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

\n", "class": "p5.Color", "module": "Color", @@ -3800,7 +3800,7 @@ module.exports={ }, { "file": "src/color/p5.Color.js", - "line": 626, + "line": 631, "description": "

Full color string patterns. The capture groups are necessary.

\n", "class": "p5.Color", "module": "Color", @@ -3808,7 +3808,7 @@ module.exports={ }, { "file": "src/color/p5.Color.js", - "line": 989, + "line": 994, "description": "

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

\n", "class": "p5.Color", "module": "Color", @@ -3817,7 +3817,7 @@ module.exports={ { "file": "src/color/setting.js", "line": 15, - "description": "

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

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

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

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

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

\n", + "description": "

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

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

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

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

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

\n", "itemtype": "method", "name": "background", "chainable": 1, @@ -3906,7 +3906,7 @@ module.exports={ "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[]" } ], @@ -3933,8 +3933,8 @@ module.exports={ }, { "file": "src/color/setting.js", - "line": 185, - "description": "

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

\n", + "line": 181, + "description": "

Clears the pixels within a buffer. This function only clears the canvas.\nIt will not clear objects created by createX() methods such as\ncreateVideo() or createDiv().\nUnlike the main graphics context, pixels in additional graphics areas created\nwith createGraphics() can be entirely\nor partially transparent. This function clears everything to make all of\nthe pixels 100% transparent.

\n", "itemtype": "method", "name": "clear", "chainable": 1, @@ -3948,21 +3948,21 @@ module.exports={ }, { "file": "src/color/setting.js", - "line": 223, + "line": 220, "description": "

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

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

\n", "itemtype": "method", "name": "colorMode", "chainable": 1, "example": [ - "\n
\n\nnoStroke();\ncolorMode(RGB, 100);\nfor (var i = 0; i < 100; i++) {\n for (var j = 0; j < 100; j++) {\n stroke(i, j, 0);\n point(i, j);\n }\n}\n\n
\n\n
\n\nnoStroke();\ncolorMode(HSB, 100);\nfor (var i = 0; i < 100; i++) {\n for (var j = 0; j < 100; j++) {\n stroke(i, j, 100);\n point(i, j);\n }\n}\n\n
\n\n
\n\ncolorMode(RGB, 255);\nvar c = color(127, 255, 0);\n\ncolorMode(RGB, 1);\nvar myColor = c._getRed();\ntext(myColor, 10, 10, 80, 80);\n\n
\n\n
\n\nnoFill();\ncolorMode(RGB, 255, 255, 255, 1);\nbackground(255);\n\nstrokeWeight(4);\nstroke(255, 0, 10, 0.3);\nellipse(40, 40, 50, 50);\nellipse(50, 50, 40, 40);\n\n
" + "\n
\n\nnoStroke();\ncolorMode(RGB, 100);\nfor (let i = 0; i < 100; i++) {\n for (let j = 0; j < 100; j++) {\n stroke(i, j, 0);\n point(i, j);\n }\n}\n\n
\n\n
\n\nnoStroke();\ncolorMode(HSB, 100);\nfor (let i = 0; i < 100; i++) {\n for (let j = 0; j < 100; j++) {\n stroke(i, j, 100);\n point(i, j);\n }\n}\n\n
\n\n
\n\ncolorMode(RGB, 255);\nlet c = color(127, 255, 0);\n\ncolorMode(RGB, 1);\nlet myColor = c._getRed();\ntext(myColor, 10, 10, 80, 80);\n\n
\n\n
\n\nnoFill();\ncolorMode(RGB, 255, 255, 255, 1);\nbackground(255);\n\nstrokeWeight(4);\nstroke(255, 0, 10, 0.3);\nellipse(40, 40, 50, 50);\nellipse(50, 50, 40, 40);\n\n
" ], - "alt": "Green to red gradient from bottom L to top R. shading originates from top left.\nRainbow gradient from left to right. Brightness increasing to white at top.\nunknown image.\n50x50 ellipse at middle L & 40x40 ellipse at center. Transluscent pink outlines.", + "alt": "Green to red gradient from bottom L to top R. shading originates from top left.\nRainbow gradient from left to right. Brightness increasing to white at top.\nunknown image.\n50x50 ellipse at middle L & 40x40 ellipse at center. Translucent pink outlines.", "class": "p5", "module": "Color", "submodule": "Setting", "overloads": [ { - "line": 223, + "line": 220, "params": [ { "name": "mode", @@ -3979,7 +3979,7 @@ module.exports={ "chainable": 1 }, { - "line": 300, + "line": 297, "params": [ { "name": "mode", @@ -3998,7 +3998,7 @@ module.exports={ }, { "name": "max3", - "description": "

range for the blue or brightness/lighntess\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" }, { @@ -4014,7 +4014,7 @@ module.exports={ }, { "file": "src/color/setting.js", - "line": 344, + "line": 341, "description": "

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

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

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

\n", "itemtype": "method", "name": "fill", @@ -4022,13 +4022,13 @@ module.exports={ "example": [ "\n
\n\n// Grayscale integer value\nfill(51);\nrect(20, 20, 60, 60);\n\n
\n\n
\n\n// R, G & B integer values\nfill(255, 204, 0);\nrect(20, 20, 60, 60);\n\n
\n\n
\n\n// H, S & B integer values\ncolorMode(HSB);\nfill(255, 204, 100);\nrect(20, 20, 60, 60);\n\n
\n\n
\n\n// Named SVG/CSS color string\nfill('red');\nrect(20, 20, 60, 60);\n\n
\n\n
\n\n// three-digit hexadecimal RGB notation\nfill('#fae');\nrect(20, 20, 60, 60);\n\n
\n\n
\n\n// six-digit hexadecimal RGB notation\nfill('#222222');\nrect(20, 20, 60, 60);\n\n
\n\n
\n\n// integer RGB notation\nfill('rgb(0,255,0)');\nrect(20, 20, 60, 60);\n\n
\n\n
\n\n// integer RGBA notation\nfill('rgba(0,255,0, 0.25)');\nrect(20, 20, 60, 60);\n\n
\n\n
\n\n// percentage RGB notation\nfill('rgb(100%,0%,10%)');\nrect(20, 20, 60, 60);\n\n
\n\n
\n\n// percentage RGBA notation\nfill('rgba(100%,0%,100%,0.5)');\nrect(20, 20, 60, 60);\n\n
\n\n
\n\n// p5 Color object\nfill(color(0, 0, 255));\nrect(20, 20, 60, 60);\n\n
" ], - "alt": "60x60 dark charcoal grey rect with black outline in center of canvas.\n60x60 yellow rect with black outline in center of canvas.\n60x60 royal blue rect with black outline in center of canvas.\n60x60 red rect with black outline in center of canvas.\n60x60 pink rect with black outline in center of canvas.\n60x60 black rect with black outline in center of canvas.\n60x60 light green rect with black outline in center of canvas.\n60x60 soft green rect with black outline in center of canvas.\n60x60 red rect with black outline in center of canvas.\n60x60 dark fushcia rect with black outline in center of canvas.\n60x60 blue rect with black outline in center of canvas.", + "alt": "60x60 dark charcoal grey rect with black outline in center of canvas.\n60x60 yellow rect with black outline in center of canvas.\n60x60 royal blue rect with black outline in center of canvas.\n60x60 red rect with black outline in center of canvas.\n60x60 pink rect with black outline in center of canvas.\n60x60 black rect with black outline in center of canvas.\n60x60 light green rect with black outline in center of canvas.\n60x60 soft green rect with black outline in center of canvas.\n60x60 red rect with black outline in center of canvas.\n60x60 dark fuchsia rect with black outline in center of canvas.\n60x60 blue rect with black outline in center of canvas.", "class": "p5", "module": "Color", "submodule": "Setting", "overloads": [ { - "line": 344, + "line": 341, "params": [ { "name": "v1", @@ -4055,7 +4055,7 @@ module.exports={ "chainable": 1 }, { - "line": 469, + "line": 466, "params": [ { "name": "value", @@ -4066,7 +4066,7 @@ module.exports={ "chainable": 1 }, { - "line": 475, + "line": 472, "params": [ { "name": "gray", @@ -4083,7 +4083,7 @@ module.exports={ "chainable": 1 }, { - "line": 482, + "line": 479, "params": [ { "name": "values", @@ -4094,7 +4094,7 @@ module.exports={ "chainable": 1 }, { - "line": 489, + "line": 486, "params": [ { "name": "color", @@ -4108,7 +4108,7 @@ module.exports={ }, { "file": "src/color/setting.js", - "line": 501, + "line": 498, "description": "

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

\n", "itemtype": "method", "name": "noFill", @@ -4123,7 +4123,7 @@ module.exports={ }, { "file": "src/color/setting.js", - "line": 542, + "line": 539, "description": "

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

\n", "itemtype": "method", "name": "noStroke", @@ -4138,7 +4138,7 @@ module.exports={ }, { "file": "src/color/setting.js", - "line": 582, + "line": 579, "description": "

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

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

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

\n", "itemtype": "method", "name": "stroke", @@ -4146,13 +4146,13 @@ module.exports={ "example": [ "\n
\n\n// Grayscale integer value\nstrokeWeight(4);\nstroke(51);\nrect(20, 20, 60, 60);\n\n
\n\n
\n\n// R, G & B integer values\nstroke(255, 204, 0);\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n
\n\n
\n\n// H, S & B integer values\ncolorMode(HSB);\nstrokeWeight(4);\nstroke(255, 204, 100);\nrect(20, 20, 60, 60);\n\n
\n\n
\n\n// Named SVG/CSS color string\nstroke('red');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n
\n\n
\n\n// three-digit hexadecimal RGB notation\nstroke('#fae');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n
\n\n
\n\n// six-digit hexadecimal RGB notation\nstroke('#222222');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n
\n\n
\n\n// integer RGB notation\nstroke('rgb(0,255,0)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n
\n\n
\n\n// integer RGBA notation\nstroke('rgba(0,255,0,0.25)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n
\n\n
\n\n// percentage RGB notation\nstroke('rgb(100%,0%,10%)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n
\n\n
\n\n// percentage RGBA notation\nstroke('rgba(100%,0%,100%,0.5)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n
\n\n
\n\n// p5 Color object\nstroke(color(0, 0, 255));\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n
" ], - "alt": "60x60 white rect at center. Dark charcoal grey outline.\n60x60 white rect at center. Yellow outline.\n60x60 white rect at center. Royal blue outline.\n60x60 white rect at center. Red outline.\n60x60 white rect at center. Pink outline.\n60x60 white rect at center. Black outline.\n60x60 white rect at center. Bright green outline.\n60x60 white rect at center. Soft green outline.\n60x60 white rect at center. Red outline.\n60x60 white rect at center. Dark fushcia outline.\n60x60 white rect at center. Blue outline.", + "alt": "60x60 white rect at center. Dark charcoal grey outline.\n60x60 white rect at center. Yellow outline.\n60x60 white rect at center. Royal blue outline.\n60x60 white rect at center. Red outline.\n60x60 white rect at center. Pink outline.\n60x60 white rect at center. Black outline.\n60x60 white rect at center. Bright green outline.\n60x60 white rect at center. Soft green outline.\n60x60 white rect at center. Red outline.\n60x60 white rect at center. Dark fuchsia outline.\n60x60 white rect at center. Blue outline.", "class": "p5", "module": "Color", "submodule": "Setting", "overloads": [ { - "line": 582, + "line": 579, "params": [ { "name": "v1", @@ -4179,7 +4179,7 @@ module.exports={ "chainable": 1 }, { - "line": 721, + "line": 718, "params": [ { "name": "value", @@ -4190,7 +4190,7 @@ module.exports={ "chainable": 1 }, { - "line": 727, + "line": 724, "params": [ { "name": "gray", @@ -4207,7 +4207,7 @@ module.exports={ "chainable": 1 }, { - "line": 734, + "line": 731, "params": [ { "name": "values", @@ -4218,7 +4218,7 @@ module.exports={ "chainable": 1 }, { - "line": 741, + "line": 738, "params": [ { "name": "color", @@ -4233,7 +4233,15 @@ module.exports={ { "file": "src/core/shape/2d_primitives.js", "line": 16, - "description": "

Draw an arc to the screen. If called with only x, y, w, h, start, and\nstop, the arc will be drawn and filled as an open pie segment. If a mode parameter is provided, the arc\nwill be filled like an open semi-circle (OPEN) , a closed semi-circle (CHORD), or as a closed pie segment (PIE). The\norigin may be changed with the ellipseMode() function.

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

\n", + "description": "

This function does 3 things:

\n
    \n
  1. Bounds the desired start/stop angles for an arc (in radians) so that:

    \n
    0 <= start < TWO_PI ;    start <= stop < start + TWO_PI\n

    This means that the arc rendering functions don't have to be concerned\nwith what happens if stop is smaller than start, or if the arc 'goes\nround more than once', etc.: they can just start at start and increase\nuntil stop and the correct arc will be drawn.

    \n
  2. \n
  3. Optionally adjusts the angles within each quadrant to counter the naive\nscaling of the underlying ellipse up from the unit circle. Without\nthis, the angles become arbitrary when width != height: 45 degrees\nmight be drawn at 5 degrees on a 'wide' ellipse, or at 85 degrees on\na 'tall' ellipse.

    \n
  4. \n
  5. Flags up when start and stop correspond to the same place on the\nunderlying ellipse. This is useful if you want to do something special\nthere (like rendering a whole ellipse instead).

    \n
  6. \n
\n", + "class": "p5", + "module": "Shape", + "submodule": "2D Primitives" + }, + { + "file": "src/core/shape/2d_primitives.js", + "line": 102, + "description": "

Draw an arc to the screen. If called with only x, y, w, h, start, and\nstop, the arc will be drawn and filled as an open pie segment. If a mode parameter is provided, the arc\nwill be filled like an open semi-circle (OPEN) , a closed semi-circle (CHORD), or as a closed pie segment (PIE). The\norigin may be changed with the ellipseMode() function.

\nThe arc is always drawn clockwise from wherever start falls to wherever stop falls on the ellipse.\nAdding or subtracting TWO_PI to either angle does not change where they fall.\nIf both start and stop fall at the same place, a full ellipse will be drawn.

\n", "itemtype": "method", "name": "arc", "params": [ @@ -4291,7 +4299,7 @@ module.exports={ }, { "file": "src/core/shape/2d_primitives.js", - "line": 149, + "line": 210, "description": "

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

\n", "itemtype": "method", "name": "ellipse", @@ -4305,7 +4313,7 @@ module.exports={ "submodule": "2D Primitives", "overloads": [ { - "line": 149, + "line": 210, "params": [ { "name": "x", @@ -4332,7 +4340,7 @@ module.exports={ "chainable": 1 }, { - "line": 174, + "line": 235, "params": [ { "name": "x", @@ -4356,7 +4364,7 @@ module.exports={ }, { "name": "detail", - "description": "

number of radial sectors to draw

\n", + "description": "

number of radial sectors to draw (for WebGL mode)

\n", "type": "Integer" } ] @@ -4365,7 +4373,39 @@ module.exports={ }, { "file": "src/core/shape/2d_primitives.js", - "line": 208, + "line": 270, + "description": "

Draws a circle to the screen. A circle is a simple closed shape.\nIt is the set of all points in a plane that are at a given distance from a given point, the centre.\nThis function is a special case of the ellipse() function, where the width and height of the ellipse are the same.\nHeight and width of the ellipse correspond to the diameter of the circle.\nBy default, the first two parameters set the location of the centre of the circle, the third sets the diameter of the circle.

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

x-coordinate of the centre of the circle.

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

y-coordinate of the centre of the circle.

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

diameter of the circle.

\n", + "type": "Number" + } + ], + "chainable": 1, + "example": [ + "\n
\n\n// Draw a circle at location (30, 30) with a diameter of 20.\ncircle(30, 30, 20);\n\n
" + ], + "alt": "white circle with black outline in mid of canvas that is 55x55.", + "class": "p5", + "module": "Shape", + "submodule": "2D Primitives" + }, + { + "file": "src/core/shape/2d_primitives.js", + "line": 300, "description": "

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

\n", "itemtype": "method", "name": "line", @@ -4379,7 +4419,7 @@ module.exports={ "submodule": "2D Primitives", "overloads": [ { - "line": 208, + "line": 300, "params": [ { "name": "x1", @@ -4405,7 +4445,7 @@ module.exports={ "chainable": 1 }, { - "line": 244, + "line": 336, "params": [ { "name": "x1", @@ -4444,7 +4484,7 @@ module.exports={ }, { "file": "src/core/shape/2d_primitives.js", - "line": 264, + "line": 356, "description": "

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

\n", "itemtype": "method", "name": "point", @@ -4461,7 +4501,7 @@ module.exports={ }, { "name": "z", - "description": "

the z-coordinate (for WEBGL mode)

\n", + "description": "

the z-coordinate (for WebGL mode)

\n", "type": "Number", "optional": true } @@ -4477,8 +4517,8 @@ module.exports={ }, { "file": "src/core/shape/2d_primitives.js", - "line": 299, - "description": "

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

\n", + "line": 391, + "description": "

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

\n", "itemtype": "method", "name": "quad", "chainable": 1, @@ -4491,7 +4531,7 @@ module.exports={ "submodule": "2D Primitives", "overloads": [ { - "line": 299, + "line": 391, "params": [ { "name": "x1", @@ -4537,7 +4577,7 @@ module.exports={ "chainable": 1 }, { - "line": 327, + "line": 421, "params": [ { "name": "x1", @@ -4606,7 +4646,7 @@ module.exports={ }, { "file": "src/core/shape/2d_primitives.js", - "line": 353, + "line": 458, "description": "

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

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

\n", "itemtype": "method", "name": "rect", @@ -4620,7 +4660,7 @@ module.exports={ "submodule": "2D Primitives", "overloads": [ { - "line": 353, + "line": 458, "params": [ { "name": "x", @@ -4670,7 +4710,7 @@ module.exports={ "chainable": 1 }, { - "line": 403, + "line": 508, "params": [ { "name": "x", @@ -4694,13 +4734,13 @@ module.exports={ }, { "name": "detailX", - "description": "

number of segments in the x-direction

\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

\n", + "description": "

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

\n", "type": "Integer", "optional": true } @@ -4711,7 +4751,63 @@ module.exports={ }, { "file": "src/core/shape/2d_primitives.js", - "line": 436, + "line": 541, + "description": "

Draws a square to the screen. A square is a four-sided shape with\nevery angle at ninety degrees, and equal side size.\nThis 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.\nBy default, the first two parameters set the location of the upper-left corner, the third sets the side size of the square.\nThe way these parameters are interpreted, however,\nmay be changed with the rectMode() function.\n

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

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

x-coordinate of the square.

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

y-coordinate of the square.

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

side size of the square.

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

optional radius of top-left corner.

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

optional radius of top-right corner.

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

optional radius of bottom-right corner.

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

optional radius of bottom-left corner.

\n", + "type": "Number", + "optional": true + } + ], + "chainable": 1, + "example": [ + "\n
\n\n// Draw a square at location (30, 20) with a side size of 55.\nsquare(30, 20, 55);\n\n
\n\n
\n\n// Draw a square with rounded corners, each having a radius of 20.\nsquare(30, 20, 55, 20);\n\n
\n\n
\n\n// Draw a square with rounded corners having the following radii:\n// top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5.\nsquare(30, 20, 55, 20, 15, 10, 5);\n\n
" + ], + "alt": "55x55 white square with black outline in mid-right of canvas.\n55x55 white square with black outline and rounded edges in mid-right of canvas.\n55x55 white square with black outline and rounded edges of different radii.", + "class": "p5", + "module": "Shape", + "submodule": "2D Primitives" + }, + { + "file": "src/core/shape/2d_primitives.js", + "line": 595, "description": "

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

\n", "itemtype": "method", "name": "triangle", @@ -4795,7 +4891,7 @@ module.exports={ }, { "file": "src/core/shape/attributes.js", - "line": 113, + "line": 116, "description": "

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

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

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

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

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

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

\n", "itemtype": "method", "name": "rectMode", @@ -4817,7 +4913,7 @@ module.exports={ }, { "file": "src/core/shape/attributes.js", - "line": 182, + "line": 185, "description": "

Draws all geometry with smooth (anti-aliased) edges. smooth() will also\nimprove image quality of resized images. Note that smooth() is active by\ndefault in 2D mode; noSmooth() can be used to disable smoothing of geometry,\nimages, and fonts. In 3D mode, noSmooth() is enabled\nby default, so it is necessary to call smooth() if you would like\nsmooth (antialiased) edges on your geometry.

\n", "itemtype": "method", "name": "smooth", @@ -4832,7 +4928,7 @@ module.exports={ }, { "file": "src/core/shape/attributes.js", - "line": 213, + "line": 219, "description": "

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

\n", "itemtype": "method", "name": "strokeCap", @@ -4854,7 +4950,7 @@ module.exports={ }, { "file": "src/core/shape/attributes.js", - "line": 250, + "line": 256, "description": "

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

\n", "itemtype": "method", "name": "strokeJoin", @@ -4876,7 +4972,7 @@ module.exports={ }, { "file": "src/core/shape/attributes.js", - "line": 317, + "line": 323, "description": "

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

\n", "itemtype": "method", "name": "strokeWeight", @@ -5040,7 +5136,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noFill();\n\n bezierDetail(5);\n}\n\nfunction draw() {\n background(200);\n\n // prettier-ignore\n bezier(-40, -40, 0,\n 90, -40, 0,\n -90, 40, 0,\n 40, 40, 0);\n}\n\n
" + "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noFill();\n\n bezierDetail(5);\n}\n\nfunction draw() {\n background(200);\n\n bezier(-40, -40, 0,\n 90, -40, 0,\n -90, 40, 0,\n 40, 40, 0);\n}\n\n
" ], "alt": "stretched black s-shape with a low level of bezier detail", "class": "p5", @@ -5085,7 +5181,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nnoFill();\nvar x1 = 85,\n x2 = 10,\n x3 = 90,\n x4 = 15;\nvar y1 = 20,\n y2 = 10,\n y3 = 90,\n y4 = 80;\nbezier(x1, y1, x2, y2, x3, y3, x4, y4);\nfill(255);\nvar steps = 10;\nfor (var i = 0; i <= steps; i++) {\n var t = i / steps;\n var x = bezierPoint(x1, x2, x3, x4, t);\n var y = bezierPoint(y1, y2, y3, y4, t);\n ellipse(x, y, 5, 5);\n}\n\n
" + "\n
\n\nnoFill();\nlet x1 = 85,\n x2 = 10,\n x3 = 90,\n x4 = 15;\nlet y1 = 20,\n y2 = 10,\n y3 = 90,\n y4 = 80;\nbezier(x1, y1, x2, y2, x3, y3, x4, y4);\nfill(255);\nlet steps = 10;\nfor (let i = 0; i <= steps; i++) {\n let t = i / steps;\n let x = bezierPoint(x1, x2, x3, x4, t);\n let y = bezierPoint(y1, y2, y3, y4, t);\n ellipse(x, y, 5, 5);\n}\n\n
" ], "alt": "stretched black s-shape with 17 small orange lines extending from under shape.", "class": "p5", @@ -5130,7 +5226,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nnoFill();\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\nvar steps = 6;\nfill(255);\nfor (var i = 0; i <= steps; i++) {\n var t = i / steps;\n // Get the location of the point\n var x = bezierPoint(85, 10, 90, 15, t);\n var y = bezierPoint(20, 10, 90, 80, t);\n // Get the tangent points\n var tx = bezierTangent(85, 10, 90, 15, t);\n var ty = bezierTangent(20, 10, 90, 80, t);\n // Calculate an angle from the tangent points\n var a = atan2(ty, tx);\n a += PI;\n stroke(255, 102, 0);\n line(x, y, cos(a) * 30 + x, sin(a) * 30 + y);\n // The following line of code makes a line\n // inverse of the above line\n //line(x, y, cos(a)*-30 + x, sin(a)*-30 + y);\n stroke(0);\n ellipse(x, y, 5, 5);\n}\n\n
\n\n
\n\nnoFill();\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\nstroke(255, 102, 0);\nvar steps = 16;\nfor (var i = 0; i <= steps; i++) {\n var t = i / steps;\n var x = bezierPoint(85, 10, 90, 15, t);\n var y = bezierPoint(20, 10, 90, 80, t);\n var tx = bezierTangent(85, 10, 90, 15, t);\n var ty = bezierTangent(20, 10, 90, 80, t);\n var a = atan2(ty, tx);\n a -= HALF_PI;\n line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);\n}\n\n
" + "\n
\n\nnoFill();\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\nlet steps = 6;\nfill(255);\nfor (let i = 0; i <= steps; i++) {\n let t = i / steps;\n // Get the location of the point\n let x = bezierPoint(85, 10, 90, 15, t);\n let y = bezierPoint(20, 10, 90, 80, t);\n // Get the tangent points\n let tx = bezierTangent(85, 10, 90, 15, t);\n let ty = bezierTangent(20, 10, 90, 80, t);\n // Calculate an angle from the tangent points\n let a = atan2(ty, tx);\n a += PI;\n stroke(255, 102, 0);\n line(x, y, cos(a) * 30 + x, sin(a) * 30 + y);\n // The following line of code makes a line\n // inverse of the above line\n //line(x, y, cos(a)*-30 + x, sin(a)*-30 + y);\n stroke(0);\n ellipse(x, y, 5, 5);\n}\n\n
\n\n
\n\nnoFill();\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\nstroke(255, 102, 0);\nlet steps = 16;\nfor (let i = 0; i <= steps; i++) {\n let t = i / steps;\n let x = bezierPoint(85, 10, 90, 15, t);\n let y = bezierPoint(20, 10, 90, 80, t);\n let tx = bezierTangent(85, 10, 90, 15, t);\n let ty = bezierTangent(20, 10, 90, 80, t);\n let a = atan2(ty, tx);\n a -= HALF_PI;\n line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);\n}\n\n
" ], "alt": "s-shaped line with 17 short orange lines extending from underside of shape", "class": "p5", @@ -5145,7 +5241,7 @@ module.exports={ "name": "curve", "chainable": 1, "example": [ - "\n
\n\nnoFill();\nstroke(255, 102, 0);\ncurve(5, 26, 5, 26, 73, 24, 73, 61);\nstroke(0);\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nstroke(255, 102, 0);\ncurve(73, 24, 73, 61, 15, 65, 15, 65);\n\n
\n
\n\n// Define the curve points as JavaScript objects\nvar p1 = { x: 5, y: 26 },\n p2 = { x: 73, y: 24 };\nvar p3 = { x: 73, y: 61 },\n p4 = { x: 15, y: 65 };\nnoFill();\nstroke(255, 102, 0);\ncurve(p1.x, p1.y, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);\nstroke(0);\ncurve(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y);\nstroke(255, 102, 0);\ncurve(p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, p4.x, p4.y);\n\n
\n
\n\nnoFill();\nstroke(255, 102, 0);\ncurve(5, 26, 0, 5, 26, 0, 73, 24, 0, 73, 61, 0);\nstroke(0);\ncurve(5, 26, 0, 73, 24, 0, 73, 61, 0, 15, 65, 0);\nstroke(255, 102, 0);\ncurve(73, 24, 0, 73, 61, 0, 15, 65, 0, 15, 65, 0);\n\n
" + "\n
\n\nnoFill();\nstroke(255, 102, 0);\ncurve(5, 26, 5, 26, 73, 24, 73, 61);\nstroke(0);\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nstroke(255, 102, 0);\ncurve(73, 24, 73, 61, 15, 65, 15, 65);\n\n
\n
\n\n// Define the curve points as JavaScript objects\nlet p1 = { x: 5, y: 26 },\n p2 = { x: 73, y: 24 };\nlet p3 = { x: 73, y: 61 },\n p4 = { x: 15, y: 65 };\nnoFill();\nstroke(255, 102, 0);\ncurve(p1.x, p1.y, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);\nstroke(0);\ncurve(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y);\nstroke(255, 102, 0);\ncurve(p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, p4.x, p4.y);\n\n
\n
\n\nnoFill();\nstroke(255, 102, 0);\ncurve(5, 26, 0, 5, 26, 0, 73, 24, 0, 73, 61, 0);\nstroke(0);\ncurve(5, 26, 0, 73, 24, 0, 73, 61, 0, 15, 65, 0);\nstroke(255, 102, 0);\ncurve(73, 24, 0, 73, 61, 0, 15, 65, 0, 15, 65, 0);\n\n
" ], "alt": "horseshoe shape with orange ends facing left and black curved center.\nhorseshoe shape with orange ends facing left and black curved center.\ncurving black and orange lines.", "class": "p5", @@ -5275,7 +5371,7 @@ module.exports={ "params": [ { "name": "resolution", - "description": "

of the curves

\n", + "description": "

resolution of the curves

\n", "type": "Number" } ], @@ -5297,13 +5393,13 @@ module.exports={ "params": [ { "name": "amount", - "description": "

of deformation from the original vertices

\n", + "description": "

amount of deformation from the original vertices

\n", "type": "Number" } ], "chainable": 1, "example": [ - "\n
\n\n// Move the mouse left and right to see the curve change\n\nfunction setup() {\n createCanvas(100, 100);\n noFill();\n}\n\nfunction draw() {\n background(204);\n var t = map(mouseX, 0, width, -5, 5);\n curveTightness(t);\n beginShape();\n curveVertex(10, 26);\n curveVertex(10, 26);\n curveVertex(83, 24);\n curveVertex(83, 61);\n curveVertex(25, 65);\n curveVertex(25, 65);\n endShape();\n}\n\n
" + "\n
\n\n// Move the mouse left and right to see the curve change\n\nfunction setup() {\n createCanvas(100, 100);\n noFill();\n}\n\nfunction draw() {\n background(204);\n let t = map(mouseX, 0, width, -5, 5);\n curveTightness(t);\n beginShape();\n curveVertex(10, 26);\n curveVertex(10, 26);\n curveVertex(83, 24);\n curveVertex(83, 61);\n curveVertex(25, 65);\n curveVertex(25, 65);\n endShape();\n}\n\n
" ], "alt": "Line shaped like right-facing arrow,points move with mouse-x and warp shape.", "class": "p5", @@ -5348,7 +5444,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nnoFill();\ncurve(5, 26, 5, 26, 73, 24, 73, 61);\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nfill(255);\nellipseMode(CENTER);\nvar steps = 6;\nfor (var i = 0; i <= steps; i++) {\n var t = i / steps;\n var x = curvePoint(5, 5, 73, 73, t);\n var y = curvePoint(26, 26, 24, 61, t);\n ellipse(x, y, 5, 5);\n x = curvePoint(5, 73, 73, 15, t);\n y = curvePoint(26, 24, 61, 65, t);\n ellipse(x, y, 5, 5);\n}\n\n
\n\nline hooking down to right-bottom with 13 5x5 white ellipse points" + "\n
\n\nnoFill();\ncurve(5, 26, 5, 26, 73, 24, 73, 61);\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nfill(255);\nellipseMode(CENTER);\nlet steps = 6;\nfor (let i = 0; i <= steps; i++) {\n let t = i / steps;\n let x = curvePoint(5, 5, 73, 73, t);\n let y = curvePoint(26, 26, 24, 61, t);\n ellipse(x, y, 5, 5);\n x = curvePoint(5, 73, 73, 15, t);\n y = curvePoint(26, 24, 61, 65, t);\n ellipse(x, y, 5, 5);\n}\n\n
\n\nline hooking down to right-bottom with 13 5x5 white ellipse points" ], "class": "p5", "module": "Shape", @@ -5392,7 +5488,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nnoFill();\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nvar steps = 6;\nfor (var i = 0; i <= steps; i++) {\n var t = i / steps;\n var x = curvePoint(5, 73, 73, 15, t);\n var y = curvePoint(26, 24, 61, 65, t);\n //ellipse(x, y, 5, 5);\n var tx = curveTangent(5, 73, 73, 15, t);\n var ty = curveTangent(26, 24, 61, 65, t);\n var a = atan2(ty, tx);\n a -= PI / 2.0;\n line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);\n}\n\n
" + "\n
\n\nnoFill();\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nlet steps = 6;\nfor (let i = 0; i <= steps; i++) {\n let t = i / steps;\n let x = curvePoint(5, 73, 73, 15, t);\n let y = curvePoint(26, 24, 61, 65, t);\n //ellipse(x, y, 5, 5);\n let tx = curveTangent(5, 73, 73, 15, t);\n let ty = curveTangent(26, 24, 61, 65, t);\n let a = atan2(ty, tx);\n a -= PI / 2.0;\n line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);\n}\n\n
" ], "alt": "right curving line mid-right of canvas with 7 short lines radiating from it.", "class": "p5", @@ -5445,9 +5541,11 @@ module.exports={ "name": "bezierVertex", "chainable": 1, "example": [ - "\n
\n\nnoFill();\nbeginShape();\nvertex(30, 20);\nbezierVertex(80, 0, 80, 75, 30, 75);\nendShape();\n\n
\n\n
\n\nbeginShape();\nvertex(30, 20);\nbezierVertex(80, 0, 80, 75, 30, 75);\nbezierVertex(50, 80, 60, 25, 30, 20);\nendShape();\n\n
" + "\n
\n\nnoFill();\nbeginShape();\nvertex(30, 20);\nbezierVertex(80, 0, 80, 75, 30, 75);\nendShape();\n\n
", + "\n
\n\nbeginShape();\nvertex(30, 20);\nbezierVertex(80, 0, 80, 75, 30, 75);\nbezierVertex(50, 80, 60, 25, 30, 20);\nendShape();\n\n
", + "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n setAttributes('antialias', true);\n}\nfunction draw() {\n orbitControl();\n background(50);\n strokeWeight(4);\n stroke(255);\n point(-25, 30);\n point(25, 30);\n point(25, -30);\n point(-25, -30);\n\n strokeWeight(1);\n noFill();\n\n beginShape();\n vertex(-25, 30);\n bezierVertex(25, 30, 25, -30, -25, -30);\n endShape();\n\n beginShape();\n vertex(-25, 30, 20);\n bezierVertex(25, 30, 20, 25, -30, 20, -25, -30, 20);\n endShape();\n}\n\n
" ], - "alt": "crescent-shaped line in middle of canvas. Points facing left.\nwhite crescent shape in middle of canvas. Points facing left.", + "alt": "crescent shape in middle of canvas with another crescent shape on positive z-axis.", "class": "p5", "module": "Shape", "submodule": "Vertex", @@ -5489,7 +5587,7 @@ module.exports={ "chainable": 1 }, { - "line": 317, + "line": 358, "params": [ { "name": "x2", @@ -5504,8 +5602,7 @@ module.exports={ { "name": "z2", "description": "

z-coordinate for the first control point (for WebGL mode)

\n", - "type": "Number", - "optional": true + "type": "Number" }, { "name": "x3", @@ -5520,8 +5617,7 @@ module.exports={ { "name": "z3", "description": "

z-coordinate for the second control point (for WebGL mode)

\n", - "type": "Number", - "optional": true + "type": "Number" }, { "name": "x4", @@ -5536,8 +5632,7 @@ module.exports={ { "name": "z4", "description": "

z-coordinate for the anchor point (for WebGL mode)

\n", - "type": "Number", - "optional": true + "type": "Number" } ], "chainable": 1 @@ -5546,7 +5641,7 @@ module.exports={ }, { "file": "src/core/shape/vertex.js", - "line": 390, + "line": 398, "description": "

Specifies vertex coordinates for curves. This function may only\nbe used between beginShape() and endShape() and only when there\nis no MODE parameter specified to beginShape().\nFor WebGL mode curveVertex() can be used in 2D as well as 3D mode.\n2D mode expects 2 parameters, while 3D mode expects 3 parameters.\n

\nThe first and last points in a series of curveVertex() lines will be used to\nguide the beginning and end of a the curve. A minimum of four\npoints is required to draw a tiny curve between the second and\nthird points. Adding a fifth point with curveVertex() will draw\nthe curve between the second, third, and fourth points. The\ncurveVertex() function is an implementation of Catmull-Rom\nsplines.

\n", "itemtype": "method", "name": "curveVertex", @@ -5560,7 +5655,7 @@ module.exports={ "submodule": "Vertex", "overloads": [ { - "line": 390, + "line": 398, "params": [ { "name": "x", @@ -5576,7 +5671,7 @@ module.exports={ "chainable": 1 }, { - "line": 435, + "line": 443, "params": [ { "name": "x", @@ -5601,7 +5696,7 @@ module.exports={ }, { "file": "src/core/shape/vertex.js", - "line": 500, + "line": 508, "description": "

Use the beginContour() and endContour() functions to create negative\nshapes within shapes such as the center of the letter 'O'. beginContour()\nbegins recording vertices for the shape and endContour() stops recording.\nThe vertices that define a negative shape must "wind" in the opposite\ndirection from the exterior shape. First draw vertices for the exterior\nclockwise order, then for internal shapes, draw vertices\nshape in counter-clockwise.\n

\nThese functions can only be used within a beginShape()/endShape() pair and\ntransformations such as translate(), rotate(), and scale() do not work\nwithin a beginContour()/endContour() pair. It is also not possible to use\nother shapes, such as ellipse() or rect() within.

\n", "itemtype": "method", "name": "endContour", @@ -5616,7 +5711,7 @@ module.exports={ }, { "file": "src/core/shape/vertex.js", - "line": 560, + "line": 568, "description": "

The endShape() function is the companion to beginShape() and may only be\ncalled after beginShape(). When endshape() is called, all of image data\ndefined since the previous call to beginShape() is written into the image\nbuffer. The constant CLOSE as the value for the MODE parameter to close\nthe shape (to connect the beginning and the end).

\n", "itemtype": "method", "name": "endShape", @@ -5639,7 +5734,7 @@ module.exports={ }, { "file": "src/core/shape/vertex.js", - "line": 646, + "line": 654, "description": "

Specifies vertex coordinates for quadratic Bezier curves. Each call to\nquadraticVertex() defines the position of one control points and one\nanchor point of a Bezier curve, adding a new segment to a line or shape.\nThe first time quadraticVertex() is used within a beginShape() call, it\nmust be prefaced with a call to vertex() to set the first anchor point.\nFor WebGL mode quadraticVertex() can be used in 2D as well as 3D mode.\n2D mode expects 4 parameters, while 3D mode expects 6 parameters\n(including z coordinates).\n

\nThis function must be used between beginShape() and endShape()\nand only when there is no MODE or POINTS parameter specified to\nbeginShape().

\n", "itemtype": "method", "name": "quadraticVertex", @@ -5653,7 +5748,7 @@ module.exports={ "submodule": "Vertex", "overloads": [ { - "line": 646, + "line": 654, "params": [ { "name": "cx", @@ -5679,7 +5774,7 @@ module.exports={ "chainable": 1 }, { - "line": 709, + "line": 720, "params": [ { "name": "cx", @@ -5694,8 +5789,7 @@ module.exports={ { "name": "cz", "description": "

z-coordinate for the control point (for WebGL mode)

\n", - "type": "Number", - "optional": true + "type": "Number" }, { "name": "x3", @@ -5710,8 +5804,7 @@ module.exports={ { "name": "z3", "description": "

z-coordinate for the anchor point (for WebGL mode)

\n", - "type": "Number", - "optional": true + "type": "Number" } ], "chainable": 1 @@ -5720,7 +5813,7 @@ module.exports={ }, { "file": "src/core/shape/vertex.js", - "line": 800, + "line": 813, "description": "

All shapes are constructed by connecting a series of vertices. vertex()\nis used to specify the vertex coordinates for points, lines, triangles,\nquads, and polygons. It is used exclusively within the beginShape() and\nendShape() functions.

\n", "itemtype": "method", "name": "vertex", @@ -5734,7 +5827,7 @@ module.exports={ "submodule": "Vertex", "overloads": [ { - "line": 800, + "line": 813, "params": [ { "name": "x", @@ -5750,7 +5843,7 @@ module.exports={ "chainable": 1 }, { - "line": 887, + "line": 900, "params": [ { "name": "x", @@ -6326,6 +6419,7 @@ module.exports={ { "file": "src/core/constants.js", "line": 350, + "description": "

AUTO allows us to automatically set the width or height of an element (but not both),\nbased on the current height and width of the element. Only one parameter can\nbe passed to the size function as AUTO, at a time.

\n", "itemtype": "property", "name": "AUTO", "type": "String", @@ -6336,7 +6430,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 373, + "line": 377, "itemtype": "property", "name": "BLEND", "type": "String", @@ -6348,7 +6442,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 379, + "line": 383, "itemtype": "property", "name": "ADD", "type": "String", @@ -6360,7 +6454,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 387, + "line": 391, "itemtype": "property", "name": "DARKEST", "type": "String", @@ -6371,7 +6465,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 392, + "line": 396, "itemtype": "property", "name": "LIGHTEST", "type": "String", @@ -6383,7 +6477,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 398, + "line": 402, "itemtype": "property", "name": "DIFFERENCE", "type": "String", @@ -6394,7 +6488,18 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 403, + "line": 407, + "itemtype": "property", + "name": "SUBTRACT", + "type": "String", + "final": 1, + "class": "p5", + "module": "Constants", + "submodule": "Constants" + }, + { + "file": "src/core/constants.js", + "line": 412, "itemtype": "property", "name": "EXCLUSION", "type": "String", @@ -6405,7 +6510,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 408, + "line": 417, "itemtype": "property", "name": "MULTIPLY", "type": "String", @@ -6416,7 +6521,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 413, + "line": 422, "itemtype": "property", "name": "SCREEN", "type": "String", @@ -6427,7 +6532,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 418, + "line": 427, "itemtype": "property", "name": "REPLACE", "type": "String", @@ -6439,7 +6544,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 424, + "line": 433, "itemtype": "property", "name": "OVERLAY", "type": "String", @@ -6450,7 +6555,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 429, + "line": 438, "itemtype": "property", "name": "HARD_LIGHT", "type": "String", @@ -6461,7 +6566,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 434, + "line": 443, "itemtype": "property", "name": "SOFT_LIGHT", "type": "String", @@ -6472,7 +6577,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 439, + "line": 448, "itemtype": "property", "name": "DODGE", "type": "String", @@ -6484,7 +6589,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 445, + "line": 454, "itemtype": "property", "name": "BURN", "type": "String", @@ -6496,7 +6601,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 453, + "line": 462, "itemtype": "property", "name": "THRESHOLD", "type": "String", @@ -6507,7 +6612,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 458, + "line": 467, "itemtype": "property", "name": "GRAY", "type": "String", @@ -6518,7 +6623,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 463, + "line": 472, "itemtype": "property", "name": "OPAQUE", "type": "String", @@ -6529,7 +6634,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 468, + "line": 477, "itemtype": "property", "name": "INVERT", "type": "String", @@ -6540,7 +6645,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 473, + "line": 482, "itemtype": "property", "name": "POSTERIZE", "type": "String", @@ -6551,7 +6656,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 478, + "line": 487, "itemtype": "property", "name": "DILATE", "type": "String", @@ -6562,7 +6667,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 483, + "line": 492, "itemtype": "property", "name": "ERODE", "type": "String", @@ -6573,7 +6678,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 488, + "line": 497, "itemtype": "property", "name": "BLUR", "type": "String", @@ -6584,7 +6689,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 495, + "line": 504, "itemtype": "property", "name": "NORMAL", "type": "String", @@ -6595,7 +6700,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 500, + "line": 509, "itemtype": "property", "name": "ITALIC", "type": "String", @@ -6606,7 +6711,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 505, + "line": 514, "itemtype": "property", "name": "BOLD", "type": "String", @@ -6617,7 +6722,29 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 536, + "line": 519, + "itemtype": "property", + "name": "BOLDITALIC", + "type": "String", + "final": 1, + "class": "p5", + "module": "Constants", + "submodule": "Constants" + }, + { + "file": "src/core/constants.js", + "line": 544, + "itemtype": "property", + "name": "IMAGE", + "type": "String", + "final": 1, + "class": "p5", + "module": "Constants", + "submodule": "Constants" + }, + { + "file": "src/core/constants.js", + "line": 558, "itemtype": "property", "name": "LANDSCAPE", "type": "String", @@ -6628,7 +6755,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 541, + "line": 563, "itemtype": "property", "name": "PORTRAIT", "type": "String", @@ -6639,7 +6766,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 551, + "line": 573, "itemtype": "property", "name": "GRID", "type": "String", @@ -6650,7 +6777,7 @@ module.exports={ }, { "file": "src/core/constants.js", - "line": 557, + "line": 579, "itemtype": "property", "name": "AXES", "type": "String", @@ -6662,7 +6789,7 @@ module.exports={ { "file": "src/core/environment.js", "line": 22, - "description": "

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

\n", + "description": "

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

\n

Note that calling print() without any arguments invokes the window.print()\nfunction which opens the browser's print dialog. To print a blank line\nto console you can write print('\\n').

\n", "itemtype": "method", "name": "print", "params": [ @@ -6673,7 +6800,7 @@ module.exports={ } ], "example": [ - "\n
\nvar x = 10;\nprint('The value of x is ' + x);\n// prints \"The value of x is 10\"\n
" + "\n
\nlet x = 10;\nprint('The value of x is ' + x);\n// prints \"The value of x is 10\"\n
" ], "alt": "default grey canvas", "class": "p5", @@ -6682,7 +6809,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 49, + "line": 53, "description": "

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

\n", "itemtype": "property", "name": "frameCount", @@ -6698,7 +6825,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 76, + "line": 80, "description": "

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

\n", "itemtype": "property", "name": "focused", @@ -6714,46 +6841,46 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 108, + "line": 112, "description": "

Sets the cursor to a predefined symbol or an image, or makes it visible\nif already hidden. If you are trying to set an image as the cursor, the\nrecommended size is 16x16 or 32x32 pixels. The values for parameters x and y\nmust be less than the dimensions of the image.

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

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

\n", + "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", "type": "String|Constant" }, { "name": "x", - "description": "

the horizontal active spot of the cursor

\n", + "description": "

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

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

the vertical active spot of the cursor

\n", + "description": "

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

\n", "type": "Number", "optional": true } ], "example": [ - "\n
\n// Move the mouse left and right across the image\n// to see the cursor change from a cross to a hand\nfunction draw() {\n line(width / 2, 0, width / 2, height);\n if (mouseX < 50) {\n cursor(CROSS);\n } else {\n cursor(HAND);\n }\n}\n
" + "\n
\n// Move the mouse across the quadrants\n// to see the cursor change\nfunction draw() {\n line(width / 2, 0, width / 2, height);\n line(0, height / 2, width, height / 2);\n if (mouseX < 50 && mouseY < 50) {\n cursor(CROSS);\n } else if (mouseX > 50 && mouseY < 50) {\n cursor('progress');\n } else if (mouseX > 50 && mouseY > 50) {\n cursor('https://s3.amazonaws.com/mupublicdata/cursor.cur');\n } else {\n cursor('grab');\n }\n}\n
" ], - "alt": "horizontal line divides canvas. cursor on left is a cross, right is hand.", + "alt": "canvas is divided into four quadrants. cursor on first is a cross, second is a progress,\nthird is a custom cursor using path to the cursor and fourth is a grab.", "class": "p5", "module": "Environment", "submodule": "Environment" }, { "file": "src/core/environment.js", - "line": 167, + "line": 181, "description": "

Specifies the number of frames to be displayed every second. For example,\nthe function call frameRate(30) will attempt to refresh 30 times a second.\nIf the processor is not fast enough to maintain the specified rate, the\nframe rate will not be achieved. Setting the frame rate within setup() is\nrecommended. The default frame rate is based on the frame rate of the display\n(here also called "refresh rate"), which is set to 60 frames per second on most\ncomputers. A frame rate of 24 frames per second (usual for movies) or above\nwill be enough for smooth animations\nThis is the same as setFrameRate(val).\n

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

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

\n", "itemtype": "method", "name": "frameRate", "chainable": 1, "example": [ - "\n\n
\nvar rectX = 0;\nvar fr = 30; //starting FPS\nvar clr;\n\nfunction setup() {\n background(200);\n frameRate(fr); // Attempt to refresh at starting FPS\n clr = color(255, 0, 0);\n}\n\nfunction draw() {\n background(200);\n rectX = rectX += 1; // Move Rectangle\n\n if (rectX >= width) {\n // If you go off screen.\n if (fr === 30) {\n clr = color(0, 0, 255);\n fr = 10;\n frameRate(fr); // make frameRate 10 FPS\n } else {\n clr = color(255, 0, 0);\n fr = 30;\n frameRate(fr); // make frameRate 30 FPS\n }\n rectX = 0;\n }\n fill(clr);\n rect(rectX, 40, 20, 20);\n}\n
" + "\n\n
\nlet rectX = 0;\nlet fr = 30; //starting FPS\nlet clr;\n\nfunction setup() {\n background(200);\n frameRate(fr); // Attempt to refresh at starting FPS\n clr = color(255, 0, 0);\n}\n\nfunction draw() {\n background(200);\n rectX = rectX += 1; // Move Rectangle\n\n if (rectX >= width) {\n // If you go off screen.\n if (fr === 30) {\n clr = color(0, 0, 255);\n fr = 10;\n frameRate(fr); // make frameRate 10 FPS\n } else {\n clr = color(255, 0, 0);\n fr = 30;\n frameRate(fr); // make frameRate 30 FPS\n }\n rectX = 0;\n }\n fill(clr);\n rect(rectX, 40, 20, 20);\n}\n
" ], "alt": "blue rect moves left to right, followed by red rect moving faster. Loops.", "class": "p5", @@ -6761,7 +6888,7 @@ module.exports={ "submodule": "Environment", "overloads": [ { - "line": 167, + "line": 181, "params": [ { "name": "fps", @@ -6772,7 +6899,7 @@ module.exports={ "chainable": 1 }, { - "line": 228, + "line": 242, "params": [], "return": { "description": "current frameRate", @@ -6783,7 +6910,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 268, + "line": 281, "description": "

Hides the cursor from view.

\n", "itemtype": "method", "name": "noCursor", @@ -6797,7 +6924,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 293, + "line": 306, "description": "

System variable that stores the width of the screen display according to The\ndefault pixelDensity. This is used to run a\nfull-screen program on any display size. To return actual screen size,\nmultiply this by pixelDensity.

\n", "itemtype": "property", "name": "displayWidth", @@ -6813,7 +6940,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 312, + "line": 325, "description": "

System variable that stores the height of the screen display according to The\ndefault pixelDensity. This is used to run a\nfull-screen program on any display size. To return actual screen size,\nmultiply this by pixelDensity.

\n", "itemtype": "property", "name": "displayHeight", @@ -6829,7 +6956,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 331, + "line": 344, "description": "

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

\n", "itemtype": "property", "name": "windowWidth", @@ -6845,7 +6972,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 347, + "line": 360, "description": "

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

\n", "itemtype": "property", "name": "windowHeight", @@ -6861,7 +6988,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 363, + "line": 376, "description": "

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

\n", "itemtype": "method", "name": "windowResized", @@ -6875,7 +7002,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 417, + "line": 430, "description": "

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

\n", "itemtype": "property", "name": "width", @@ -6887,7 +7014,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 429, + "line": 442, "description": "

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

\n", "itemtype": "property", "name": "height", @@ -6899,7 +7026,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 441, + "line": 454, "description": "

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

\n", "itemtype": "method", "name": "fullscreen", @@ -6916,7 +7043,7 @@ module.exports={ "type": "Boolean" }, "example": [ - "\n
\n\n// Clicking in the box toggles fullscreen on and off.\nfunction setup() {\n background(200);\n}\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n var fs = fullscreen();\n fullscreen(!fs);\n }\n}\n\n
" + "\n
\n\n// Clicking in the box toggles fullscreen on and off.\nfunction setup() {\n background(200);\n}\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n let fs = fullscreen();\n fullscreen(!fs);\n }\n}\n\n
" ], "alt": "no display.", "class": "p5", @@ -6925,7 +7052,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 492, + "line": 505, "description": "

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

\n", "itemtype": "method", "name": "pixelDensity", @@ -6939,7 +7066,7 @@ module.exports={ "submodule": "Environment", "overloads": [ { - "line": 492, + "line": 505, "params": [ { "name": "val", @@ -6950,7 +7077,7 @@ module.exports={ "chainable": 1 }, { - "line": 527, + "line": 540, "params": [], "return": { "description": "current pixel density of the sketch", @@ -6961,7 +7088,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 547, + "line": 560, "description": "

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

\n", "itemtype": "method", "name": "displayDensity", @@ -6970,7 +7097,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nfunction setup() {\n var density = displayDensity();\n pixelDensity(density);\n createCanvas(100, 100);\n background(200);\n ellipse(width / 2, height / 2, 50, 50);\n}\n\n
" + "\n
\n\nfunction setup() {\n let density = displayDensity();\n pixelDensity(density);\n createCanvas(100, 100);\n background(200);\n ellipse(width / 2, height / 2, 50, 50);\n}\n\n
" ], "alt": "50x50 white ellipse with black outline in center of canvas.", "class": "p5", @@ -6979,7 +7106,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 604, + "line": 617, "description": "

Gets the current URL.

\n", "itemtype": "method", "name": "getURL", @@ -6988,7 +7115,7 @@ module.exports={ "type": "String" }, "example": [ - "\n
\n\nvar url;\nvar x = 100;\n\nfunction setup() {\n fill(0);\n noStroke();\n url = getURL();\n}\n\nfunction draw() {\n background(200);\n text(url, x, height / 2);\n x--;\n}\n\n
" + "\n
\n\nlet url;\nlet x = 100;\n\nfunction setup() {\n fill(0);\n noStroke();\n url = getURL();\n}\n\nfunction draw() {\n background(200);\n text(url, x, height / 2);\n x--;\n}\n\n
" ], "alt": "current url (http://p5js.org/reference/#/p5/getURL) moves right to left.", "class": "p5", @@ -6997,7 +7124,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 635, + "line": 648, "description": "

Gets the current URL path as an array.

\n", "itemtype": "method", "name": "getURLPath", @@ -7006,7 +7133,7 @@ module.exports={ "type": "String[]" }, "example": [ - "\n
\nfunction setup() {\n var urlPath = getURLPath();\n for (var i = 0; i < urlPath.length; i++) {\n text(urlPath[i], 10, i * 20 + 20);\n }\n}\n
" + "\n
\nfunction setup() {\n let urlPath = getURLPath();\n for (let i = 0; i < urlPath.length; i++) {\n text(urlPath[i], 10, i * 20 + 20);\n }\n}\n
" ], "alt": "no display", "class": "p5", @@ -7015,7 +7142,7 @@ module.exports={ }, { "file": "src/core/environment.js", - "line": 658, + "line": 671, "description": "

Gets the current URL params as an Object.

\n", "itemtype": "method", "name": "getURLParams", @@ -7024,7 +7151,7 @@ module.exports={ "type": "Object" }, "example": [ - "\n
\n\n// Example: http://p5js.org?year=2014&month=May&day=15\n\nfunction setup() {\n var params = getURLParams();\n text(params.day, 10, 20);\n text(params.month, 10, 40);\n text(params.year, 10, 60);\n}\n\n
" + "\n
\n\n// Example: http://p5js.org?year=2014&month=May&day=15\n\nfunction setup() {\n let params = getURLParams();\n text(params.day, 10, 20);\n text(params.month, 10, 40);\n text(params.year, 10, 60);\n}\n\n
" ], "alt": "no display.", "class": "p5", @@ -7042,14 +7169,14 @@ module.exports={ }, { "file": "src/core/error_helpers.js", - "line": 563, + "line": 584, "description": "

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

\n

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

\n

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

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

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

\n", "class": "p5", "module": "Environment" @@ -7081,7 +7208,7 @@ module.exports={ "itemtype": "method", "name": "preload", "example": [ - "\n
\nvar img;\nvar c;\nfunction preload() {\n // preload() runs once\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n // setup() waits until preload() is done\n img.loadPixels();\n // get color of middle pixel\n c = img.get(img.width / 2, img.height / 2);\n}\n\nfunction draw() {\n background(c);\n image(img, 25, 25, 50, 50);\n}\n
" + "\n
\nlet img;\nlet c;\nfunction preload() {\n // preload() runs once\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n // setup() waits until preload() is done\n img.loadPixels();\n // get color of middle pixel\n c = img.get(img.width / 2, img.height / 2);\n}\n\nfunction draw() {\n background(c);\n image(img, 25, 25, 50, 50);\n}\n
" ], "alt": "nothing displayed", "class": "p5", @@ -7095,7 +7222,7 @@ module.exports={ "itemtype": "method", "name": "setup", "example": [ - "\n
\nvar a = 0;\n\nfunction setup() {\n background(0);\n noStroke();\n fill(102);\n}\n\nfunction draw() {\n rect(a++ % width, 10, 2, 80);\n}\n
" + "\n
\nlet a = 0;\n\nfunction setup() {\n background(0);\n noStroke();\n fill(102);\n}\n\nfunction draw() {\n rect(a++ % width, 10, 2, 80);\n}\n
" ], "alt": "nothing displayed", "class": "p5", @@ -7109,7 +7236,7 @@ module.exports={ "itemtype": "method", "name": "draw", "example": [ - "\n
\nvar yPos = 0;\nfunction setup() {\n // setup() runs once\n frameRate(30);\n}\nfunction draw() {\n // draw() loops forever, until stopped\n background(204);\n yPos = yPos - 1;\n if (yPos < 0) {\n yPos = height;\n }\n line(0, yPos, width, yPos);\n}\n
" + "\n
\nlet yPos = 0;\nfunction setup() {\n // setup() runs once\n frameRate(30);\n}\nfunction draw() {\n // draw() loops forever, until stopped\n background(204);\n yPos = yPos - 1;\n if (yPos < 0) {\n yPos = height;\n }\n line(0, yPos, width, yPos);\n}\n
" ], "alt": "nothing displayed", "class": "p5", @@ -7118,7 +7245,7 @@ module.exports={ }, { "file": "src/core/main.js", - "line": 408, + "line": 401, "description": "

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

\n", "itemtype": "method", "name": "remove", @@ -7130,12 +7257,26 @@ module.exports={ "module": "Structure", "submodule": "Structure" }, + { + "file": "src/core/main.js", + "line": 586, + "description": "

Allows for the friendly error system (FES) to be turned off when creating a sketch,\nwhich can give a significant boost to performance when needed.\nSee \ndisabling the friendly error system.

\n", + "itemtype": "property", + "name": "disableFriendlyErrors", + "type": "Boolean", + "example": [ + "\n
\np5.disableFriendlyErrors = true;\n\nfunction setup() {\n createCanvas(100, 50);\n}\n
" + ], + "class": "p5", + "module": "Structure", + "submodule": "Structure" + }, { "file": "src/core/p5.Element.js", "line": 26, "description": "

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

\n", "example": [ - "\n
\n\ncreateCanvas(300, 500);\nbackground(0, 0, 0, 0);\nvar input = createInput();\ninput.position(20, 225);\nvar inputElem = new p5.Element(input.elt);\ninputElem.style('width:450px;');\ninputElem.value('some string');\n\n
" + "\n
\n\nfunction setup() {\n let c = createCanvas(50, 50);\n c.elt.style.border = '5px solid red';\n}\n\nfunction draw() {\n background(220);\n}\n\n
" ], "itemtype": "property", "name": "elt", @@ -7146,13 +7287,13 @@ module.exports={ }, { "file": "src/core/p5.Element.js", - "line": 51, - "description": "

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

\n", + "line": 52, + "description": "

Attaches the element to the parent specified. A way of setting\n the container for the element. Accepts either a string ID, DOM\n node, or p5.Element. If no arguments given, parent node is returned.\n For more ways to position the canvas, see the\n \n positioning the canvas wiki page.\nAll above examples except for the first one require the inclusion of\n the p5.dom library in your index.html. See the\n using a library\n section for information on how to include this library.

\n", "itemtype": "method", "name": "parent", "chainable": 1, "example": [ - "\n
\n // in the html file:\n // <div id=\"myContainer\"></div>\n// in the js file:\n var cnv = createCanvas(100, 100);\n cnv.parent('myContainer');\n
\n
\n var div0 = createDiv('this is the parent');\n var div1 = createDiv('this is the child');\n div1.parent(div0); // use p5.Element\n
\n
\n var div0 = createDiv('this is the parent');\n div0.id('apples');\n var div1 = createDiv('this is the child');\n div1.parent('apples'); // use id\n
\n
\n var elt = document.getElementById('myParentDiv');\n var div1 = createDiv('this is the child');\n div1.parent(elt); // use element from page\n
" + "\n
\n // in the html file:\n // <div id=\"myContainer\"></div>\n// in the js file:\n let cnv = createCanvas(100, 100);\n cnv.parent('myContainer');\n
\n
\n let div0 = createDiv('this is the parent');\n let div1 = createDiv('this is the child');\n div1.parent(div0); // use p5.Element\n
\n
\n let div0 = createDiv('this is the parent');\n div0.id('apples');\n let div1 = createDiv('this is the child');\n div1.parent('apples'); // use id\n
\n
\n let elt = document.getElementById('myParentDiv');\n let div1 = createDiv('this is the child');\n div1.parent(elt); // use element from page\n
" ], "alt": "no display.", "class": "p5.Element", @@ -7160,7 +7301,7 @@ module.exports={ "submodule": "DOM", "overloads": [ { - "line": 51, + "line": 52, "params": [ { "name": "parent", @@ -7171,7 +7312,7 @@ module.exports={ "chainable": 1 }, { - "line": 94, + "line": 100, "params": [], "return": { "description": "", @@ -7182,13 +7323,13 @@ module.exports={ }, { "file": "src/core/p5.Element.js", - "line": 116, - "description": "

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

\n", + "line": 122, + "description": "

Sets the ID of the element. If no ID argument is passed in, it instead\n returns the current ID of the element.\n Note that only one element can have a particular id in a page.\n The .class() function can be used\n to identify multiple elements with the same class name.

\n", "itemtype": "method", "name": "id", "chainable": 1, "example": [ - "\n
\n function setup() {\n var cnv = createCanvas(100, 100);\n // Assigns a CSS selector ID to\n // the canvas element.\n cnv.id('mycanvas');\n }\n
" + "\n
\n function setup() {\n let cnv = createCanvas(100, 100);\n // Assigns a CSS selector ID to\n // the canvas element.\n cnv.id('mycanvas');\n }\n
" ], "alt": "no display.", "class": "p5.Element", @@ -7196,7 +7337,7 @@ module.exports={ "submodule": "DOM", "overloads": [ { - "line": 116, + "line": 122, "params": [ { "name": "id", @@ -7207,7 +7348,7 @@ module.exports={ "chainable": 1 }, { - "line": 138, + "line": 147, "params": [], "return": { "description": "the id of the element", @@ -7218,13 +7359,13 @@ module.exports={ }, { "file": "src/core/p5.Element.js", - "line": 153, + "line": 162, "description": "

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

\n", "itemtype": "method", "name": "class", "chainable": 1, "example": [ - "\n
\n function setup() {\n var cnv = createCanvas(100, 100);\n // Assigns a CSS selector class 'small'\n // to the canvas element.\n cnv.class('small');\n }\n
" + "\n
\n function setup() {\n let cnv = createCanvas(100, 100);\n // Assigns a CSS selector class 'small'\n // to the canvas element.\n cnv.class('small');\n }\n
" ], "alt": "no display.", "class": "p5.Element", @@ -7232,7 +7373,7 @@ module.exports={ "submodule": "DOM", "overloads": [ { - "line": 153, + "line": 162, "params": [ { "name": "class", @@ -7243,7 +7384,7 @@ module.exports={ "chainable": 1 }, { - "line": 175, + "line": 184, "params": [], "return": { "description": "the class of the element", @@ -7254,7 +7395,7 @@ module.exports={ }, { "file": "src/core/p5.Element.js", - "line": 188, + "line": 197, "description": "

The .mousePressed() function is called once after every time a\nmouse button is pressed over the element.\nSome mobile browsers may also trigger this event on a touch screen,\nif the user performs a quick tap.\nThis can be used to attach element specific event listeners.

\n", "itemtype": "method", "name": "mousePressed", @@ -7267,7 +7408,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mousePressed(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any click anywhere\nfunction mousePressed() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
" + "\n
\nlet cnv;\nlet d;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mousePressed(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any click anywhere\nfunction mousePressed() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
" ], "alt": "no display.", "class": "p5.Element", @@ -7276,7 +7417,7 @@ module.exports={ }, { "file": "src/core/p5.Element.js", - "line": 249, + "line": 258, "description": "

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

\n", "itemtype": "method", "name": "doubleClicked", @@ -7292,7 +7433,7 @@ module.exports={ "type": "p5.Element" }, "example": [ - "\n
\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.doubleClicked(changeGray); // attach listener for\n // canvas double click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any double click anywhere\nfunction doubleClicked() {\n d = d + 10;\n}\n\n// this function fires only when cnv is double clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
" + "\n
\nlet cnv;\nlet d;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.doubleClicked(changeGray); // attach listener for\n // canvas double click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any double click anywhere\nfunction doubleClicked() {\n d = d + 10;\n}\n\n// this function fires only when cnv is double clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
" ], "alt": "no display.", "class": "p5.Element", @@ -7301,7 +7442,7 @@ module.exports={ }, { "file": "src/core/p5.Element.js", - "line": 298, + "line": 307, "description": "

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

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

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

\n", "itemtype": "method", "name": "mouseWheel", @@ -7314,7 +7455,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseWheel(changeSize); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with mousewheel movement\n// anywhere on screen\nfunction mouseWheel() {\n g = g + 10;\n}\n\n// this function fires with mousewheel movement\n// over canvas only\nfunction changeSize(event) {\n if (event.deltaY > 0) {\n d = d + 10;\n } else {\n d = d - 10;\n }\n}\n
" + "\n
\nlet cnv;\nlet d;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseWheel(changeSize); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with mousewheel movement\n// anywhere on screen\nfunction mouseWheel() {\n g = g + 10;\n}\n\n// this function fires with mousewheel movement\n// over canvas only\nfunction changeSize(event) {\n if (event.deltaY > 0) {\n d = d + 10;\n } else {\n d = d - 10;\n }\n}\n
" ], "alt": "no display.", "class": "p5.Element", @@ -7323,7 +7464,7 @@ module.exports={ }, { "file": "src/core/p5.Element.js", - "line": 364, + "line": 373, "description": "

The .mouseReleased() function is called once after every time a\nmouse button is released over the element.\nSome mobile browsers may also trigger this event on a touch screen,\nif the user performs a quick tap.\nThis can be used to attach element specific event listeners.

\n", "itemtype": "method", "name": "mouseReleased", @@ -7336,7 +7477,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseReleased(changeGray); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires after the mouse has been\n// released\nfunction mouseReleased() {\n d = d + 10;\n}\n\n// this function fires after the mouse has been\n// released while on canvas\nfunction changeGray() {\n g = random(0, 255);\n}\n
" + "\n
\nlet cnv;\nlet d;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseReleased(changeGray); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires after the mouse has been\n// released\nfunction mouseReleased() {\n d = d + 10;\n}\n\n// this function fires after the mouse has been\n// released while on canvas\nfunction changeGray() {\n g = random(0, 255);\n}\n
" ], "alt": "no display.", "class": "p5.Element", @@ -7345,7 +7486,7 @@ module.exports={ }, { "file": "src/core/p5.Element.js", - "line": 418, + "line": 427, "description": "

The .mouseClicked() function is called once after a mouse button is\npressed and released over the element.\nSome mobile browsers may also trigger this event on a touch screen,\nif the user performs a quick tap.\nThis can be used to attach element specific event listeners.

\n", "itemtype": "method", "name": "mouseClicked", @@ -7358,7 +7499,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\n\nvar cnv;\nvar d;\nvar g;\n\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseClicked(changeGray); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires after the mouse has been\n// clicked anywhere\nfunction mouseClicked() {\n d = d + 10;\n}\n\n// this function fires after the mouse has been\n// clicked on canvas\nfunction changeGray() {\n g = random(0, 255);\n}\n\n
" + "\n
\n\nlet cnv;\nlet d;\nlet g;\n\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseClicked(changeGray); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires after the mouse has been\n// clicked anywhere\nfunction mouseClicked() {\n d = d + 10;\n}\n\n// this function fires after the mouse has been\n// clicked on canvas\nfunction changeGray() {\n g = random(0, 255);\n}\n\n
" ], "alt": "no display.", "class": "p5.Element", @@ -7367,7 +7508,7 @@ module.exports={ }, { "file": "src/core/p5.Element.js", - "line": 474, + "line": 483, "description": "

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

\n", "itemtype": "method", "name": "mouseMoved", @@ -7380,7 +7521,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\nvar cnv;\nvar d = 30;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseMoved(changeSize); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n fill(200);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires when mouse moves anywhere on\n// page\nfunction mouseMoved() {\n g = g + 5;\n if (g > 255) {\n g = 0;\n }\n}\n\n// this function fires when mouse moves over canvas\nfunction changeSize() {\n d = d + 2;\n if (d > 100) {\n d = 0;\n }\n}\n
" + "\n
\nlet cnv;\nlet d = 30;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseMoved(changeSize); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n fill(200);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires when mouse moves anywhere on\n// page\nfunction mouseMoved() {\n g = g + 5;\n if (g > 255) {\n g = 0;\n }\n}\n\n// this function fires when mouse moves over canvas\nfunction changeSize() {\n d = d + 2;\n if (d > 100) {\n d = 0;\n }\n}\n
" ], "alt": "no display.", "class": "p5.Element", @@ -7389,7 +7530,7 @@ module.exports={ }, { "file": "src/core/p5.Element.js", - "line": 532, + "line": 541, "description": "

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

\n", "itemtype": "method", "name": "mouseOver", @@ -7402,7 +7543,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\nvar cnv;\nvar d;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseOver(changeGray);\n d = 10;\n}\n\nfunction draw() {\n ellipse(width / 2, height / 2, d, d);\n}\n\nfunction changeGray() {\n d = d + 10;\n if (d > 100) {\n d = 0;\n }\n}\n
" + "\n
\nlet cnv;\nlet d;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseOver(changeGray);\n d = 10;\n}\n\nfunction draw() {\n ellipse(width / 2, height / 2, d, d);\n}\n\nfunction changeGray() {\n d = d + 10;\n if (d > 100) {\n d = 0;\n }\n}\n
" ], "alt": "no display.", "class": "p5.Element", @@ -7411,51 +7552,7 @@ module.exports={ }, { "file": "src/core/p5.Element.js", - "line": 575, - "description": "

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

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

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

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

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

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

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

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

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

\n", "itemtype": "method", "name": "mouseOut", @@ -7468,7 +7565,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\nvar cnv;\nvar d;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseOut(changeGray);\n d = 10;\n}\n\nfunction draw() {\n ellipse(width / 2, height / 2, d, d);\n}\n\nfunction changeGray() {\n d = d + 10;\n if (d > 100) {\n d = 0;\n }\n}\n
" + "\n
\nlet cnv;\nlet d;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseOut(changeGray);\n d = 10;\n}\n\nfunction draw() {\n ellipse(width / 2, height / 2, d, d);\n}\n\nfunction changeGray() {\n d = d + 10;\n if (d > 100) {\n d = 0;\n }\n}\n
" ], "alt": "no display.", "class": "p5.Element", @@ -7477,7 +7574,7 @@ module.exports={ }, { "file": "src/core/p5.Element.js", - "line": 719, + "line": 626, "description": "

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

\n", "itemtype": "method", "name": "touchStarted", @@ -7490,7 +7587,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchStarted(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any touch anywhere\nfunction touchStarted() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
" + "\n
\nlet cnv;\nlet d;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchStarted(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any touch anywhere\nfunction touchStarted() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
" ], "alt": "no display.", "class": "p5.Element", @@ -7499,7 +7596,7 @@ module.exports={ }, { "file": "src/core/p5.Element.js", - "line": 767, + "line": 674, "description": "

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

\n", "itemtype": "method", "name": "touchMoved", @@ -7512,7 +7609,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\nvar cnv;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchMoved(changeGray); // attach listener for\n // canvas click only\n g = 100;\n}\n\nfunction draw() {\n background(g);\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
" + "\n
\nlet cnv;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchMoved(changeGray); // attach listener for\n // canvas click only\n g = 100;\n}\n\nfunction draw() {\n background(g);\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
" ], "alt": "no display.", "class": "p5.Element", @@ -7521,7 +7618,7 @@ module.exports={ }, { "file": "src/core/p5.Element.js", - "line": 807, + "line": 714, "description": "

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

\n", "itemtype": "method", "name": "touchEnded", @@ -7534,7 +7631,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchEnded(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any touch anywhere\nfunction touchEnded() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
" + "\n
\nlet cnv;\nlet d;\nlet g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchEnded(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any touch anywhere\nfunction touchEnded() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
" ], "alt": "no display.", "class": "p5.Element", @@ -7543,7 +7640,7 @@ module.exports={ }, { "file": "src/core/p5.Element.js", - "line": 856, + "line": 763, "description": "

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

\n", "itemtype": "method", "name": "dragOver", @@ -7556,7 +7653,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\n// To test this sketch, simply drag a\n// file over the canvas\nfunction setup() {\n var c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('Drag file', width / 2, height / 2);\n c.dragOver(dragOverCallback);\n}\n\n// This function will be called whenever\n// a file is dragged over the canvas\nfunction dragOverCallback() {\n background(240);\n text('Dragged over', width / 2, height / 2);\n}\n
" + "\n
\n// To test this sketch, simply drag a\n// file over the canvas\nfunction setup() {\n let c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('Drag file', width / 2, height / 2);\n c.dragOver(dragOverCallback);\n}\n\n// This function will be called whenever\n// a file is dragged over the canvas\nfunction dragOverCallback() {\n background(240);\n text('Dragged over', width / 2, height / 2);\n}\n
" ], "alt": "nothing displayed", "class": "p5.Element", @@ -7565,7 +7662,7 @@ module.exports={ }, { "file": "src/core/p5.Element.js", - "line": 894, + "line": 801, "description": "

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

\n", "itemtype": "method", "name": "dragLeave", @@ -7578,7 +7675,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\n// To test this sketch, simply drag a file\n// over and then out of the canvas area\nfunction setup() {\n var c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('Drag file', width / 2, height / 2);\n c.dragLeave(dragLeaveCallback);\n}\n\n// This function will be called whenever\n// a file is dragged out of the canvas\nfunction dragLeaveCallback() {\n background(240);\n text('Dragged off', width / 2, height / 2);\n}\n
" + "\n
\n// To test this sketch, simply drag a file\n// over and then out of the canvas area\nfunction setup() {\n let c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('Drag file', width / 2, height / 2);\n c.dragLeave(dragLeaveCallback);\n}\n\n// This function will be called whenever\n// a file is dragged out of the canvas\nfunction dragLeaveCallback() {\n background(240);\n text('Dragged off', width / 2, height / 2);\n}\n
" ], "alt": "nothing displayed", "class": "p5.Element", @@ -7587,35 +7684,7 @@ module.exports={ }, { "file": "src/core/p5.Element.js", - "line": 932, - "description": "

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

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

callback triggered when files are dropped.

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

callback to receive loaded file.

\n", - "type": "Function", - "optional": true - } - ], - "chainable": 1, - "example": [ - "\n
\nfunction setup() {\n var c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('drop file', width / 2, height / 2);\n c.drop(gotFile);\n}\n\nfunction gotFile(file) {\n background(200);\n text('received file:', width / 2, height / 2);\n text(file.name, width / 2, height / 2 + 50);\n}\n
\n\n
\nvar img;\n\nfunction setup() {\n var c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('drop image', width / 2, height / 2);\n c.drop(gotFile);\n}\n\nfunction draw() {\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\nfunction gotFile(file) {\n img = createImg(file.data).hide();\n}\n
" - ], - "alt": "Canvas turns into whatever image is dragged/dropped onto it.", - "class": "p5.Element", - "module": "DOM", - "submodule": "DOM" - }, - { - "file": "src/core/p5.Element.js", - "line": 1088, + "line": 865, "description": "

Helper fxn for sharing pixel methods

\n", "class": "p5.Element", "module": "DOM", @@ -7624,11 +7693,25 @@ module.exports={ { "file": "src/core/p5.Graphics.js", "line": 65, + "description": "

Resets certain values such as those modified by functions in the Transform category\nand in the Lights category that are not automatically reset\nwith graphics buffer objects. Calling this in draw() will copy the behavior\nof the standard canvas.

\n", + "itemtype": "method", + "name": "reset", + "example": [ + "\n\n
\nlet pg;\nfunction setup() {\n createCanvas(100, 100);\n background(0);\n pg = createGraphics(50, 100);\n pg.fill(0);\n frameRate(5);\n}\nfunction draw() {\n image(pg, width / 2, 0);\n pg.background(255);\n // p5.Graphics object behave a bit differently in some cases\n // The normal canvas on the left resets the translate\n // with every loop through draw()\n // the graphics object on the right doesn't automatically reset\n // so translate() is additive and it moves down the screen\n rect(0, 0, width / 2, 5);\n pg.rect(0, 0, width / 2, 5);\n translate(0, 5, 0);\n pg.translate(0, 5, 0);\n}\nfunction mouseClicked() {\n // if you click you will see that\n // reset() resets the translate back to the initial state\n // of the Graphics object\n pg.reset();\n}\n
" + ], + "alt": "A white line on a black background stays still on the top-left half.\nA black line animates from top to bottom on a white background on the right half.\nWhen clicked, the black line starts back over at the top.", + "class": "p5.Graphics", + "module": "Rendering", + "submodule": "Rendering" + }, + { + "file": "src/core/p5.Graphics.js", + "line": 117, "description": "

Removes a Graphics object from the page and frees any resources\nassociated with it.

\n", "itemtype": "method", "name": "remove", "example": [ - "\n
\nvar bg;\nfunction setup() {\n bg = createCanvas(100, 100);\n bg.background(0);\n image(bg, 0, 0);\n bg.remove();\n}\n
\n\n
\nvar bg;\nfunction setup() {\n pixelDensity(1);\n createCanvas(100, 100);\n stroke(255);\n fill(0);\n\n // create and draw the background image\n bg = createGraphics(100, 100);\n bg.background(200);\n bg.ellipse(50, 50, 80, 80);\n}\nfunction draw() {\n var t = millis() / 1000;\n // draw the background\n if (bg) {\n image(bg, frameCount % 100, 0);\n image(bg, frameCount % 100 - 100, 0);\n }\n // draw the foreground\n var p = p5.Vector.fromAngle(t, 35).add(50, 50);\n ellipse(p.x, p.y, 30);\n}\nfunction mouseClicked() {\n // remove the background\n if (bg) {\n bg.remove();\n bg = null;\n }\n}\n
" + "\n
\nlet bg;\nfunction setup() {\n bg = createCanvas(100, 100);\n bg.background(0);\n image(bg, 0, 0);\n bg.remove();\n}\n
\n\n
\nlet bg;\nfunction setup() {\n pixelDensity(1);\n createCanvas(100, 100);\n stroke(255);\n fill(0);\n\n // create and draw the background image\n bg = createGraphics(100, 100);\n bg.background(200);\n bg.ellipse(50, 50, 80, 80);\n}\nfunction draw() {\n let t = millis() / 1000;\n // draw the background\n if (bg) {\n image(bg, frameCount % 100, 0);\n image(bg, frameCount % 100 - 100, 0);\n }\n // draw the foreground\n let p = p5.Vector.fromAngle(t, 35).add(50, 50);\n ellipse(p.x, p.y, 30);\n}\nfunction mouseClicked() {\n // remove the background\n if (bg) {\n bg.remove();\n bg = null;\n }\n}\n
" ], "alt": "no image\na multi-colored circle moving back and forth over a scrolling background.", "class": "p5.Graphics", @@ -7637,7 +7720,7 @@ module.exports={ }, { "file": "src/core/p5.Renderer.js", - "line": 96, + "line": 97, "description": "

Resize our canvas element.

\n", "class": "p5.Renderer", "module": "Rendering", @@ -7645,7 +7728,7 @@ module.exports={ }, { "file": "src/core/p5.Renderer.js", - "line": 300, + "line": 335, "description": "

Helper fxn to check font type (system or otf)

\n", "class": "p5.Renderer", "module": "Rendering", @@ -7653,7 +7736,7 @@ module.exports={ }, { "file": "src/core/p5.Renderer.js", - "line": 353, + "line": 388, "description": "

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

\n", "class": "p5.Renderer", "module": "Rendering", @@ -7668,8 +7751,8 @@ module.exports={ }, { "file": "src/core/p5.Renderer2D.js", - "line": 414, - "description": "

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

\n

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

\n", + "line": 405, + "description": "

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

\n

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

\n", "class": "p5", "module": "Rendering" }, @@ -7784,7 +7867,7 @@ module.exports={ "type": "p5.Graphics" }, "example": [ - "\n
\n\nvar pg;\nfunction setup() {\n createCanvas(100, 100);\n pg = createGraphics(100, 100);\n}\nfunction draw() {\n background(200);\n pg.background(100);\n pg.noStroke();\n pg.ellipse(pg.width / 2, pg.height / 2, 50, 50);\n image(pg, 50, 50);\n image(pg, 0, 0, 50, 50);\n}\n\n
" + "\n
\n\nlet pg;\nfunction setup() {\n createCanvas(100, 100);\n pg = createGraphics(100, 100);\n}\nfunction draw() {\n background(200);\n pg.background(100);\n pg.noStroke();\n pg.ellipse(pg.width / 2, pg.height / 2, 50, 50);\n image(pg, 50, 50);\n image(pg, 0, 0, 50, 50);\n}\n\n
" ], "alt": "4 grey squares alternating light and dark grey. White quarter circle mid-left.", "class": "p5", @@ -7794,13 +7877,13 @@ module.exports={ { "file": "src/core/rendering.js", "line": 236, - "description": "

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

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

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

\n

    \n

  • BLEND - linear interpolation of colours: C =\nA*factor + B. This is the default blending mode.
  • \n

  • ADD - sum of A and B
  • \n

  • DARKEST - only the darkest colour succeeds: C =\nmin(A*factor, B).
  • \n

  • LIGHTEST - only the lightest colour succeeds: C =\nmax(A*factor, B).
  • \n

  • DIFFERENCE - subtract colors from underlying image.
  • \n

  • EXCLUSION - similar to DIFFERENCE, but less\nextreme.
  • \n

  • MULTIPLY - multiply the colors, result will always be\ndarker.
  • \n

  • SCREEN - opposite multiply, uses inverse values of the\ncolors.
  • \n

  • REPLACE - the pixels entirely replace the others and\ndon't utilize alpha (transparency) values.
  • \n

  • OVERLAY - mix of MULTIPLY and SCREEN\n. Multiplies dark values, and screens light values. (2D)
  • \n

  • HARD_LIGHT - SCREEN when greater than 50%\ngray, MULTIPLY when lower. (2D)
  • \n

  • SOFT_LIGHT - mix of DARKEST and\nLIGHTEST. Works like OVERLAY, but not as harsh. (2D)\n
  • \n

  • DODGE - lightens light tones and increases contrast,\nignores darks. (2D)
  • \n

  • BURN - darker areas are applied, increasing contrast,\nignores lights. (2D)
  • \n

  • SUBTRACT - remainder of A and B (3D)
  • \n
\n

\n(2D) indicates that this blend mode only works in the 2D renderer.
\n(3D) indicates that this blend mode only works in the WEBGL renderer.

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

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

\n", + "description": "

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

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

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

\n", + "description": "

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

\n

Avoid calling loop() from inside setup().

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

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

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

\n", + "line": 122, + "description": "

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

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

\nIn WEBGL mode additional style settings are stored. These are controlled by the following functions: setCamera(), ambientLight(), directionalLight(),\npointLight(), texture(), specularMaterial(), shininess(), normalMaterial()\nand shader().

\n", "itemtype": "method", "name": "push", "example": [ @@ -7870,8 +7953,8 @@ module.exports={ }, { "file": "src/core/structure.js", - "line": 181, - "description": "

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

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

\n", + "line": 191, + "description": "

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

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

\nIn WEBGL mode additional style settings are stored. These are controlled by the following functions: setCamera(), ambientLight(), directionalLight(),\npointLight(), texture(), specularMaterial(), shininess(), normalMaterial()\nand shader().

\n", "itemtype": "method", "name": "pop", "example": [ @@ -7884,7 +7967,7 @@ module.exports={ }, { "file": "src/core/structure.js", - "line": 247, + "line": 261, "description": "

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

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

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

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

\n", "itemtype": "method", "name": "redraw", @@ -7897,7 +7980,7 @@ module.exports={ } ], "example": [ - "\n
\n var x = 0;\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n }\nfunction draw() {\n background(204);\n line(x, 0, x, height);\n }\nfunction mousePressed() {\n x += 1;\n redraw();\n }\n
\n
\n var x = 0;\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n }\nfunction draw() {\n background(204);\n x += 1;\n line(x, 0, x, height);\n }\nfunction mousePressed() {\n redraw(5);\n }\n
" + "\n
\n let x = 0;\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n }\nfunction draw() {\n background(204);\n line(x, 0, x, height);\n }\nfunction mousePressed() {\n x += 1;\n redraw();\n }\n
\n
\n let x = 0;\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n }\nfunction draw() {\n background(204);\n x += 1;\n line(x, 0, x, height);\n }\nfunction mousePressed() {\n redraw(5);\n }\n
" ], "alt": "black line on far left of canvas\n black line on far left of canvas", "class": "p5", @@ -7944,7 +8027,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n background(200);\n // Equivalent to translate(x, y);\n applyMatrix(1, 0, 0, 1, 40 + step, 50);\n rect(0, 0, 50, 50);\n}\n\n
\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n background(200);\n translate(50, 50);\n // Equivalent to scale(x, y);\n applyMatrix(1 / step, 0, 0, 1 / step, 0, 0);\n rect(0, 0, 50, 50);\n}\n\n
\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n var angle = map(step, 0, 20, 0, TWO_PI);\n var cos_a = cos(angle);\n var sin_a = sin(angle);\n background(200);\n translate(50, 50);\n // Equivalent to rotate(angle);\n applyMatrix(cos_a, sin_a, -sin_a, cos_a, 0, 0);\n rect(0, 0, 50, 50);\n}\n\n
\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n var angle = map(step, 0, 20, -PI / 4, PI / 4);\n background(200);\n translate(50, 50);\n // equivalent to shearX(angle);\n var shear_factor = 1 / tan(PI / 2 - angle);\n applyMatrix(1, 0, shear_factor, 1, 0, 0);\n rect(0, 0, 50, 50);\n}\n\n
" + "\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n background(200);\n // Equivalent to translate(x, y);\n applyMatrix(1, 0, 0, 1, 40 + step, 50);\n rect(0, 0, 50, 50);\n}\n\n
\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n background(200);\n translate(50, 50);\n // Equivalent to scale(x, y);\n applyMatrix(1 / step, 0, 0, 1 / step, 0, 0);\n rect(0, 0, 50, 50);\n}\n\n
\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n var angle = map(step, 0, 20, 0, TWO_PI);\n var cos_a = cos(angle);\n var sin_a = sin(angle);\n background(200);\n translate(50, 50);\n // Equivalent to rotate(angle);\n applyMatrix(cos_a, sin_a, -sin_a, cos_a, 0, 0);\n rect(0, 0, 50, 50);\n}\n\n
\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n var angle = map(step, 0, 20, -PI / 4, PI / 4);\n background(200);\n translate(50, 50);\n // equivalent to shearX(angle);\n var shear_factor = 1 / tan(PI / 2 - angle);\n applyMatrix(1, 0, shear_factor, 1, 0, 0);\n rect(0, 0, 50, 50);\n}\n\n
\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noFill();\n}\n\nfunction draw() {\n background(200);\n rotateY(PI / 6);\n stroke(153);\n box(35);\n var rad = millis() / 1000;\n // Set rotation angles\n var ct = cos(rad);\n var st = sin(rad);\n // Matrix for rotation around the Y axis\n applyMatrix( ct, 0.0, st, 0.0,\n 0.0, 1.0, 0.0, 0.0,\n -st, 0.0, ct, 0.0,\n 0.0, 0.0, 0.0, 1.0);\n stroke(255);\n box(50);\n}\n\n
" ], "alt": "A rectangle translating to the right\nA rectangle shrinking to the center\nA rectangle rotating clockwise about the center\nA rectangle shearing", "class": "p5", @@ -7953,7 +8036,7 @@ module.exports={ }, { "file": "src/core/transform.js", - "line": 135, + "line": 150, "description": "

Replaces the current matrix with the identity matrix.

\n", "itemtype": "method", "name": "resetMatrix", @@ -7968,7 +8051,7 @@ module.exports={ }, { "file": "src/core/transform.js", - "line": 161, + "line": 176, "description": "

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

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

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

\n", "itemtype": "method", "name": "rotate", @@ -7996,7 +8079,7 @@ module.exports={ }, { "file": "src/core/transform.js", - "line": 201, + "line": 216, "description": "

Rotates around X axis.

\n", "itemtype": "method", "name": "rotateX", @@ -8018,7 +8101,7 @@ module.exports={ }, { "file": "src/core/transform.js", - "line": 231, + "line": 246, "description": "

Rotates around Y axis.

\n", "itemtype": "method", "name": "rotateY", @@ -8040,7 +8123,7 @@ module.exports={ }, { "file": "src/core/transform.js", - "line": 261, + "line": 276, "description": "

Rotates around Z axis. Webgl mode only.

\n", "itemtype": "method", "name": "rotateZ", @@ -8062,7 +8145,7 @@ module.exports={ }, { "file": "src/core/transform.js", - "line": 291, + "line": 306, "description": "

Increases or decreases the size of a shape by expanding and contracting\nvertices. Objects always scale from their relative origin to the\ncoordinate system. Scale values are specified as decimal percentages.\nFor example, the function call scale(2.0) increases the dimension of a\nshape by 200%.\n

\nTransformations apply to everything that happens after and subsequent\ncalls to the function multiply the effect. For example, calling scale(2.0)\nand then scale(1.5) is the same as scale(3.0). If scale() is called\nwithin draw(), the transformation is reset when the loop begins again.\n

\nUsing this function with the z parameter is only available in WEBGL mode.\nThis function can be further controlled with push() and pop().

\n", "itemtype": "method", "name": "scale", @@ -8076,7 +8159,7 @@ module.exports={ "submodule": "Transform", "overloads": [ { - "line": 291, + "line": 306, "params": [ { "name": "s", @@ -8099,7 +8182,7 @@ module.exports={ "chainable": 1 }, { - "line": 336, + "line": 351, "params": [ { "name": "scales", @@ -8113,7 +8196,7 @@ module.exports={ }, { "file": "src/core/transform.js", - "line": 366, + "line": 381, "description": "

Shears a shape around the x-axis the amount specified by the angle\nparameter. Angles should be specified in the current angleMode.\nObjects are always sheared around their relative position to the origin\nand positive numbers shear objects in a clockwise direction.\n

\nTransformations apply to everything that happens after and subsequent\ncalls to the function accumulates the effect. For example, calling\nshearX(PI/2) and then shearX(PI/2) is the same as shearX(PI).\nIf shearX() is called within the draw(), the transformation is reset when\nthe loop begins again.\n

\nTechnically, shearX() multiplies the current transformation matrix by a\nrotation matrix. This function can be further controlled by the\npush() and pop() functions.

\n", "itemtype": "method", "name": "shearX", @@ -8135,7 +8218,7 @@ module.exports={ }, { "file": "src/core/transform.js", - "line": 405, + "line": 421, "description": "

Shears a shape around the y-axis the amount specified by the angle\nparameter. Angles should be specified in the current angleMode. Objects\nare always sheared around their relative position to the origin and\npositive numbers shear objects in a clockwise direction.\n

\nTransformations apply to everything that happens after and subsequent\ncalls to the function accumulates the effect. For example, calling\nshearY(PI/2) and then shearY(PI/2) is the same as shearY(PI). If\nshearY() is called within the draw(), the transformation is reset when\nthe loop begins again.\n

\nTechnically, shearY() multiplies the current transformation matrix by a\nrotation matrix. This function can be further controlled by the\npush() and pop() functions.

\n", "itemtype": "method", "name": "shearY", @@ -8157,7 +8240,7 @@ module.exports={ }, { "file": "src/core/transform.js", - "line": 444, + "line": 461, "description": "

Specifies an amount to displace objects within the display window.\nThe x parameter specifies left/right translation, the y parameter\nspecifies up/down translation.\n

\nTransformations are cumulative and apply to everything that happens after\nand subsequent calls to the function accumulates the effect. For example,\ncalling translate(50, 0) and then translate(20, 0) is the same as\ntranslate(70, 0). If translate() is called within draw(), the\ntransformation is reset when the loop begins again. This function can be\nfurther controlled by using push() and pop().

\n", "itemtype": "method", "name": "translate", @@ -8171,7 +8254,7 @@ module.exports={ "submodule": "Transform", "overloads": [ { - "line": 444, + "line": 461, "params": [ { "name": "x", @@ -8193,7 +8276,7 @@ module.exports={ "chainable": 1 }, { - "line": 498, + "line": 515, "params": [ { "name": "vector", @@ -8216,7 +8299,7 @@ module.exports={ "type": "p5.StringDict" }, "example": [ - "\n
\n \n function setup() {\n var myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // logs true to console\n var anotherDictionary = createStringDict({ happy: 'coding' });\n print(anotherDictionary.hasKey('happy')); // logs true to console\n }\n
" + "\n
\n \n function setup() {\n let myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // logs true to console\n let anotherDictionary = createStringDict({ happy: 'coding' });\n print(anotherDictionary.hasKey('happy')); // logs true to console\n }\n
" ], "class": "p5", "module": "Data", @@ -8268,7 +8351,7 @@ module.exports={ "type": "p5.NumberDict" }, "example": [ - "\n
\n \n function setup() {\n var myDictionary = createNumberDict(100, 42);\n print(myDictionary.hasKey(100)); // logs true to console\n var anotherDictionary = createNumberDict({ 200: 84 });\n print(anotherDictionary.hasKey(200)); // logs true to console\n }\n
" + "\n
\n \n function setup() {\n let myDictionary = createNumberDict(100, 42);\n print(myDictionary.hasKey(100)); // logs true to console\n let anotherDictionary = createNumberDict({ 200: 84 });\n print(anotherDictionary.hasKey(200)); // logs true to console\n }\n
" ], "class": "p5", "module": "Data", @@ -8320,7 +8403,7 @@ module.exports={ "type": "Integer" }, "example": [ - "\n
\n\nfunction setup() {\n var myDictionary = createNumberDict(1, 10);\n myDictionary.create(2, 20);\n myDictionary.create(3, 30);\n print(myDictionary.size()); // logs 3 to the console\n}\n
\n" + "\n
\n\nfunction setup() {\n let myDictionary = createNumberDict(1, 10);\n myDictionary.create(2, 20);\n myDictionary.create(3, 30);\n print(myDictionary.size()); // logs 3 to the console\n}\n
\n" ], "class": "p5.TypedDict", "module": "Data", @@ -8344,7 +8427,7 @@ module.exports={ "type": "Boolean" }, "example": [ - "\n
\n\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // logs true to console\n}\n
\n" + "\n
\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // logs true to console\n}\n
\n" ], "class": "p5.TypedDict", "module": "Data", @@ -8368,7 +8451,7 @@ module.exports={ "type": "Number|String" }, "example": [ - "\n
\n\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n var myValue = myDictionary.get('p5');\n print(myValue === 'js'); // logs true to console\n}\n
\n" + "\n
\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n let myValue = myDictionary.get('p5');\n print(myValue === 'js'); // logs true to console\n}\n
\n" ], "class": "p5.TypedDict", "module": "Data", @@ -8393,7 +8476,7 @@ module.exports={ } ], "example": [ - "\n
\n\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n myDictionary.set('p5', 'JS');\n myDictionary.print(); // logs \"key: p5 - value: JS\" to console\n}\n
\n" + "\n
\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.set('p5', 'JS');\n myDictionary.print(); // logs \"key: p5 - value: JS\" to console\n}\n
\n" ], "class": "p5.TypedDict", "module": "Data", @@ -8414,7 +8497,7 @@ module.exports={ "itemtype": "method", "name": "create", "example": [ - "\n
\n\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n}\n
" + "\n
\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n}\n
" ], "class": "p5.TypedDict", "module": "Data", @@ -8454,7 +8537,7 @@ module.exports={ "itemtype": "method", "name": "clear", "example": [ - "\n
\n\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // prints 'true'\n myDictionary.clear();\n print(myDictionary.hasKey('p5')); // prints 'false'\n}\n\n
" + "\n
\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // prints 'true'\n myDictionary.clear();\n print(myDictionary.hasKey('p5')); // prints 'false'\n}\n\n
" ], "class": "p5.TypedDict", "module": "Data", @@ -8474,7 +8557,7 @@ module.exports={ } ], "example": [ - "\n
\n\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n myDictionary.remove('p5');\n myDictionary.print();\n // above logs \"key: happy value: coding\" to console\n}\n
\n" + "\n
\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n myDictionary.remove('p5');\n myDictionary.print();\n // above logs \"key: happy value: coding\" to console\n}\n
\n" ], "class": "p5.TypedDict", "module": "Data", @@ -8487,7 +8570,7 @@ module.exports={ "itemtype": "method", "name": "print", "example": [ - "\n
\n\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n}\n\n
" + "\n
\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n}\n\n
" ], "class": "p5.TypedDict", "module": "Data", @@ -8500,7 +8583,7 @@ module.exports={ "itemtype": "method", "name": "saveTable", "example": [ - "\n
\n\ncreateButton('save')\n .position(10, 10)\n .mousePressed(function() {\n createStringDict({\n john: 1940,\n paul: 1942,\n george: 1943,\n ringo: 1940\n }).saveTable('beatles');\n });\n\n
" + "\n
\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n}\n\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n createStringDict({\n john: 1940,\n paul: 1942,\n george: 1943,\n ringo: 1940\n }).saveTable('beatles');\n }\n}\n\n
" ], "class": "p5.TypedDict", "module": "Data", @@ -8508,12 +8591,12 @@ module.exports={ }, { "file": "src/data/p5.TypedDict.js", - "line": 357, + "line": 363, "description": "

Converts the Dictionary into a JSON file for local download.

\n", "itemtype": "method", "name": "saveJSON", "example": [ - "\n
\n\ncreateButton('save')\n .position(10, 10)\n .mousePressed(function() {\n createStringDict({\n john: 1940,\n paul: 1942,\n george: 1943,\n ringo: 1940\n }).saveJSON('beatles');\n });\n\n
" + "\n
\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n}\n\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n createStringDict({\n john: 1940,\n paul: 1942,\n george: 1943,\n ringo: 1940\n }).saveJSON('beatles');\n }\n}\n\n
" ], "class": "p5.TypedDict", "module": "Data", @@ -8521,7 +8604,7 @@ module.exports={ }, { "file": "src/data/p5.TypedDict.js", - "line": 382, + "line": 394, "description": "

private helper function to ensure that the user passed in valid\nvalues for the Dictionary type

\n", "class": "p5.TypedDict", "module": "Data", @@ -8529,7 +8612,7 @@ module.exports={ }, { "file": "src/data/p5.TypedDict.js", - "line": 425, + "line": 437, "description": "

private helper function to ensure that the user passed in valid\nvalues for the Dictionary type

\n", "class": "p5.NumberDict", "module": "Data", @@ -8537,7 +8620,7 @@ module.exports={ }, { "file": "src/data/p5.TypedDict.js", - "line": 434, + "line": 446, "description": "

Add the given number to the value currently stored at the given key.\nThe sum then replaces the value previously stored in the Dictionary.

\n", "itemtype": "method", "name": "add", @@ -8554,7 +8637,7 @@ module.exports={ } ], "example": [ - "\n
\n\nfunction setup() {\n var myDictionary = createNumberDict(2, 5);\n myDictionary.add(2, 2);\n print(myDictionary.get(2)); // logs 7 to console.\n}\n
\n\n" + "\n
\n\nfunction setup() {\n let myDictionary = createNumberDict(2, 5);\n myDictionary.add(2, 2);\n print(myDictionary.get(2)); // logs 7 to console.\n}\n
\n\n" ], "class": "p5.NumberDict", "module": "Data", @@ -8562,7 +8645,7 @@ module.exports={ }, { "file": "src/data/p5.TypedDict.js", - "line": 462, + "line": 474, "description": "

Subtract the given number from the value currently stored at the given key.\nThe difference then replaces the value previously stored in the Dictionary.

\n", "itemtype": "method", "name": "sub", @@ -8579,7 +8662,7 @@ module.exports={ } ], "example": [ - "\n
\n\nfunction setup() {\n var myDictionary = createNumberDict(2, 5);\n myDictionary.sub(2, 2);\n print(myDictionary.get(2)); // logs 3 to console.\n}\n
\n\n" + "\n
\n\nfunction setup() {\n let myDictionary = createNumberDict(2, 5);\n myDictionary.sub(2, 2);\n print(myDictionary.get(2)); // logs 3 to console.\n}\n
\n\n" ], "class": "p5.NumberDict", "module": "Data", @@ -8587,7 +8670,7 @@ module.exports={ }, { "file": "src/data/p5.TypedDict.js", - "line": 486, + "line": 498, "description": "

Multiply the given number with the value currently stored at the given key.\nThe product then replaces the value previously stored in the Dictionary.

\n", "itemtype": "method", "name": "mult", @@ -8604,7 +8687,7 @@ module.exports={ } ], "example": [ - "\n
\n\nfunction setup() {\n var myDictionary = createNumberDict(2, 4);\n myDictionary.mult(2, 2);\n print(myDictionary.get(2)); // logs 8 to console.\n}\n
\n\n" + "\n
\n\nfunction setup() {\n let myDictionary = createNumberDict(2, 4);\n myDictionary.mult(2, 2);\n print(myDictionary.get(2)); // logs 8 to console.\n}\n
\n\n" ], "class": "p5.NumberDict", "module": "Data", @@ -8612,7 +8695,7 @@ module.exports={ }, { "file": "src/data/p5.TypedDict.js", - "line": 514, + "line": 526, "description": "

Divide the given number with the value currently stored at the given key.\nThe quotient then replaces the value previously stored in the Dictionary.

\n", "itemtype": "method", "name": "div", @@ -8629,7 +8712,7 @@ module.exports={ } ], "example": [ - "\n
\n\nfunction setup() {\n var myDictionary = createNumberDict(2, 8);\n myDictionary.div(2, 2);\n print(myDictionary.get(2)); // logs 4 to console.\n}\n
\n\n" + "\n
\n\nfunction setup() {\n let myDictionary = createNumberDict(2, 8);\n myDictionary.div(2, 2);\n print(myDictionary.get(2)); // logs 4 to console.\n}\n
\n\n" ], "class": "p5.NumberDict", "module": "Data", @@ -8637,7 +8720,7 @@ module.exports={ }, { "file": "src/data/p5.TypedDict.js", - "line": 542, + "line": 554, "description": "

private helper function for finding lowest or highest value\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than'

\n", "class": "p5.NumberDict", "module": "Data", @@ -8645,7 +8728,7 @@ module.exports={ }, { "file": "src/data/p5.TypedDict.js", - "line": 567, + "line": 579, "description": "

Return the lowest number currently stored in the Dictionary.

\n", "itemtype": "method", "name": "minValue", @@ -8654,7 +8737,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nfunction setup() {\n var myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });\n var lowestValue = myDictionary.minValue(); // value is -10\n print(lowestValue);\n}\n
\n" + "\n
\n\nfunction setup() {\n let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });\n let lowestValue = myDictionary.minValue(); // value is -10\n print(lowestValue);\n}\n
\n" ], "class": "p5.NumberDict", "module": "Data", @@ -8662,7 +8745,7 @@ module.exports={ }, { "file": "src/data/p5.TypedDict.js", - "line": 588, + "line": 600, "description": "

Return the highest number currently stored in the Dictionary.

\n", "itemtype": "method", "name": "maxValue", @@ -8671,7 +8754,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nfunction setup() {\n var myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });\n var highestValue = myDictionary.maxValue(); // value is 3\n print(highestValue);\n}\n
\n" + "\n
\n\nfunction setup() {\n let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });\n let highestValue = myDictionary.maxValue(); // value is 3\n print(highestValue);\n}\n
\n" ], "class": "p5.NumberDict", "module": "Data", @@ -8679,7 +8762,7 @@ module.exports={ }, { "file": "src/data/p5.TypedDict.js", - "line": 609, + "line": 621, "description": "

private helper function for finding lowest or highest key\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than'

\n", "class": "p5.NumberDict", "module": "Data", @@ -8687,7 +8770,7 @@ module.exports={ }, { "file": "src/data/p5.TypedDict.js", - "line": 632, + "line": 644, "description": "

Return the lowest key currently used in the Dictionary.

\n", "itemtype": "method", "name": "minKey", @@ -8696,7 +8779,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nfunction setup() {\n var myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });\n var lowestKey = myDictionary.minKey(); // value is 1.2\n print(lowestKey);\n}\n
\n" + "\n
\n\nfunction setup() {\n let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });\n let lowestKey = myDictionary.minKey(); // value is 1.2\n print(lowestKey);\n}\n
\n" ], "class": "p5.NumberDict", "module": "Data", @@ -8704,7 +8787,7 @@ module.exports={ }, { "file": "src/data/p5.TypedDict.js", - "line": 653, + "line": 665, "description": "

Return the highest key currently used in the Dictionary.

\n", "itemtype": "method", "name": "maxKey", @@ -8713,7 +8796,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nfunction setup() {\n var myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });\n var highestKey = myDictionary.maxKey(); // value is 4\n print(highestKey);\n}\n
\n" + "\n
\n\nfunction setup() {\n let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });\n let highestKey = myDictionary.maxKey(); // value is 4\n print(highestKey);\n}\n
\n" ], "class": "p5.NumberDict", "module": "Data", @@ -8739,37 +8822,49 @@ module.exports={ "name": "accelerationX", "type": "Number", "readonly": "", + "example": [ + "\n
\n\n// Move a touchscreen device to register\n// acceleration changes.\nfunction draw() {\n background(220, 50);\n fill('magenta');\n ellipse(width / 2, height / 2, accelerationX);\n}\n\n
" + ], + "alt": "Magnitude of device acceleration is displayed as ellipse size", "class": "p5", "module": "Events", "submodule": "Acceleration" }, { "file": "src/events/acceleration.js", - "line": 32, + "line": 46, "description": "

The system variable accelerationY always contains the acceleration of the\ndevice along the y axis. Value is represented as meters per second squared.

\n", "itemtype": "property", "name": "accelerationY", "type": "Number", "readonly": "", + "example": [ + "\n
\n\n// Move a touchscreen device to register\n// acceleration changes.\nfunction draw() {\n background(220, 50);\n fill('magenta');\n ellipse(width / 2, height / 2, accelerationY);\n}\n\n
" + ], + "alt": "Magnitude of device acceleration is displayed as ellipse size", "class": "p5", "module": "Events", "submodule": "Acceleration" }, { "file": "src/events/acceleration.js", - "line": 41, + "line": 69, "description": "

The system variable accelerationZ always contains the acceleration of the\ndevice along the z axis. Value is represented as meters per second squared.

\n", "itemtype": "property", "name": "accelerationZ", "type": "Number", "readonly": "", + "example": [ + "\n
\n\n// Move a touchscreen device to register\n// acceleration changes.\nfunction draw() {\n background(220, 50);\n fill('magenta');\n ellipse(width / 2, height / 2, accelerationZ);\n}\n\n
" + ], + "alt": "Magnitude of device acceleration is displayed as ellipse size", "class": "p5", "module": "Events", "submodule": "Acceleration" }, { "file": "src/events/acceleration.js", - "line": 50, + "line": 94, "description": "

The system variable pAccelerationX always contains the acceleration of the\ndevice along the x axis in the frame previous to the current frame. Value\nis represented as meters per second squared.

\n", "itemtype": "property", "name": "pAccelerationX", @@ -8781,7 +8876,7 @@ module.exports={ }, { "file": "src/events/acceleration.js", - "line": 60, + "line": 104, "description": "

The system variable pAccelerationY always contains the acceleration of the\ndevice along the y axis in the frame previous to the current frame. Value\nis represented as meters per second squared.

\n", "itemtype": "property", "name": "pAccelerationY", @@ -8793,7 +8888,7 @@ module.exports={ }, { "file": "src/events/acceleration.js", - "line": 70, + "line": 114, "description": "

The system variable pAccelerationZ always contains the acceleration of the\ndevice along the z axis in the frame previous to the current frame. Value\nis represented as meters per second squared.

\n", "itemtype": "property", "name": "pAccelerationZ", @@ -8805,15 +8900,15 @@ module.exports={ }, { "file": "src/events/acceleration.js", - "line": 91, + "line": 135, "description": "

The system variable rotationX always contains the rotation of the\ndevice along the x axis. Value is represented as 0 to +/-180 degrees.\n

\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.

\n", - "example": [ - "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n //rotateZ(radians(rotationZ));\n rotateX(radians(rotationX));\n //rotateY(radians(rotationY));\n box(200, 200, 200);\n}\n\n
" - ], "itemtype": "property", "name": "rotationX", "type": "Number", "readonly": "", + "example": [ + "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n //rotateZ(radians(rotationZ));\n rotateX(radians(rotationX));\n //rotateY(radians(rotationY));\n box(200, 200, 200);\n}\n\n
" + ], "alt": "red horizontal line right, green vertical line bottom. black background.", "class": "p5", "module": "Events", @@ -8821,15 +8916,15 @@ module.exports={ }, { "file": "src/events/acceleration.js", - "line": 125, + "line": 166, "description": "

The system variable rotationY always contains the rotation of the\ndevice along the y axis. Value is represented as 0 to +/-90 degrees.\n

\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.

\n", - "example": [ - "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n //rotateZ(radians(rotationZ));\n //rotateX(radians(rotationX));\n rotateY(radians(rotationY));\n box(200, 200, 200);\n}\n\n
" - ], "itemtype": "property", "name": "rotationY", "type": "Number", "readonly": "", + "example": [ + "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n //rotateZ(radians(rotationZ));\n //rotateX(radians(rotationX));\n rotateY(radians(rotationY));\n box(200, 200, 200);\n}\n\n
" + ], "alt": "red horizontal line right, green vertical line bottom. black background.", "class": "p5", "module": "Events", @@ -8837,7 +8932,7 @@ module.exports={ }, { "file": "src/events/acceleration.js", - "line": 158, + "line": 197, "description": "

The system variable rotationZ always contains the rotation of the\ndevice along the z axis. Value is represented as 0 to 359 degrees.\n

\nUnlike rotationX and rotationY, this variable is available for devices\nwith a built-in compass only.\n

\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.

\n", "example": [ "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateZ(radians(rotationZ));\n //rotateX(radians(rotationX));\n //rotateY(radians(rotationY));\n box(200, 200, 200);\n}\n\n
" @@ -8853,10 +8948,10 @@ module.exports={ }, { "file": "src/events/acceleration.js", - "line": 194, + "line": 233, "description": "

The system variable pRotationX always contains the rotation of the\ndevice along the x axis in the frame previous to the current frame. Value\nis represented as 0 to +/-180 degrees.\n

\npRotationX can also be used with rotationX to determine the rotate\ndirection of the device along the X-axis.

\n", "example": [ - "\n
\n\n// A simple if statement looking at whether\n// rotationX - pRotationX < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nvar rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely necessary but the logic\n// will be different in that case.\n\nvar rX = rotationX + 180;\nvar pRX = pRotationX + 180;\n\nif ((rX - pRX > 0 && rX - pRX < 270) || rX - pRX < -270) {\n rotateDirection = 'clockwise';\n} else if (rX - pRX < 0 || rX - pRX > 270) {\n rotateDirection = 'counter-clockwise';\n}\n\nprint(rotateDirection);\n\n
" + "\n
\n\n// A simple if statement looking at whether\n// rotationX - pRotationX < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nlet rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely necessary but the logic\n// will be different in that case.\n\nlet rX = rotationX + 180;\nlet pRX = pRotationX + 180;\n\nif ((rX - pRX > 0 && rX - pRX < 270) || rX - pRX < -270) {\n rotateDirection = 'clockwise';\n} else if (rX - pRX < 0 || rX - pRX > 270) {\n rotateDirection = 'counter-clockwise';\n}\n\nprint(rotateDirection);\n\n
" ], "alt": "no image to display.", "itemtype": "property", @@ -8869,10 +8964,10 @@ module.exports={ }, { "file": "src/events/acceleration.js", - "line": 239, + "line": 278, "description": "

The system variable pRotationY always contains the rotation of the\ndevice along the y axis in the frame previous to the current frame. Value\nis represented as 0 to +/-90 degrees.\n

\npRotationY can also be used with rotationY to determine the rotate\ndirection of the device along the Y-axis.

\n", "example": [ - "\n
\n\n// A simple if statement looking at whether\n// rotationY - pRotationY < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nvar rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely necessary but the logic\n// will be different in that case.\n\nvar rY = rotationY + 180;\nvar pRY = pRotationY + 180;\n\nif ((rY - pRY > 0 && rY - pRY < 270) || rY - pRY < -270) {\n rotateDirection = 'clockwise';\n} else if (rY - pRY < 0 || rY - pRY > 270) {\n rotateDirection = 'counter-clockwise';\n}\nprint(rotateDirection);\n\n
" + "\n
\n\n// A simple if statement looking at whether\n// rotationY - pRotationY < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nlet rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely necessary but the logic\n// will be different in that case.\n\nlet rY = rotationY + 180;\nlet pRY = pRotationY + 180;\n\nif ((rY - pRY > 0 && rY - pRY < 270) || rY - pRY < -270) {\n rotateDirection = 'clockwise';\n} else if (rY - pRY < 0 || rY - pRY > 270) {\n rotateDirection = 'counter-clockwise';\n}\nprint(rotateDirection);\n\n
" ], "alt": "no image to display.", "itemtype": "property", @@ -8885,10 +8980,10 @@ module.exports={ }, { "file": "src/events/acceleration.js", - "line": 283, + "line": 322, "description": "

The system variable pRotationZ always contains the rotation of the\ndevice along the z axis in the frame previous to the current frame. Value\nis represented as 0 to 359 degrees.\n

\npRotationZ can also be used with rotationZ to determine the rotate\ndirection of the device along the Z-axis.

\n", "example": [ - "\n
\n\n// A simple if statement looking at whether\n// rotationZ - pRotationZ < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nvar rotateDirection = 'clockwise';\n\nif (\n (rotationZ - pRotationZ > 0 && rotationZ - pRotationZ < 270) ||\n rotationZ - pRotationZ < -270\n) {\n rotateDirection = 'clockwise';\n} else if (rotationZ - pRotationZ < 0 || rotationZ - pRotationZ > 270) {\n rotateDirection = 'counter-clockwise';\n}\nprint(rotateDirection);\n\n
" + "\n
\n\n// A simple if statement looking at whether\n// rotationZ - pRotationZ < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nlet rotateDirection = 'clockwise';\n\nif (\n (rotationZ - pRotationZ > 0 && rotationZ - pRotationZ < 270) ||\n rotationZ - pRotationZ < -270\n) {\n rotateDirection = 'clockwise';\n} else if (rotationZ - pRotationZ < 0 || rotationZ - pRotationZ > 270) {\n rotateDirection = 'counter-clockwise';\n}\nprint(rotateDirection);\n\n
" ], "alt": "no image to display.", "itemtype": "property", @@ -8901,18 +8996,23 @@ module.exports={ }, { "file": "src/events/acceleration.js", - "line": 341, + "line": 380, + "description": "

When a device is rotated, the axis that triggers the deviceTurned()\nmethod is stored in the turnAxis variable. The turnAxis variable is only defined within\nthe scope of deviceTurned().

\n", "itemtype": "property", "name": "turnAxis", "type": "String", "readonly": "", + "example": [ + "\n
\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees in the\n// X-axis to change the value.\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceTurned() {\n if (turnAxis === 'X') {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n }\n}\n\n
" + ], + "alt": "50x50 black rect in center of canvas. turns white on mobile when device turns\n50x50 black rect in center of canvas. turns white on mobile when x-axis turns", "class": "p5", "module": "Events", "submodule": "Acceleration" }, { "file": "src/events/acceleration.js", - "line": 350, + "line": 419, "description": "

The setMoveThreshold() function is used to set the movement threshold for\nthe deviceMoved() function. The default threshold is set to 0.5.

\n", "itemtype": "method", "name": "setMoveThreshold", @@ -8924,7 +9024,7 @@ module.exports={ } ], "example": [ - "\n
\n\n// Run this example on a mobile device\n// You will need to move the device incrementally further\n// the closer the square's color gets to white in order to change the value.\n\nvar value = 0;\nvar threshold = 0.5;\nfunction setup() {\n setMoveThreshold(threshold);\n}\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceMoved() {\n value = value + 5;\n threshold = threshold + 0.1;\n if (value > 255) {\n value = 0;\n threshold = 30;\n }\n setMoveThreshold(threshold);\n}\n\n
" + "\n
\n\n// Run this example on a mobile device\n// You will need to move the device incrementally further\n// the closer the square's color gets to white in order to change the value.\n\nlet value = 0;\nlet threshold = 0.5;\nfunction setup() {\n setMoveThreshold(threshold);\n}\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceMoved() {\n value = value + 5;\n threshold = threshold + 0.1;\n if (value > 255) {\n value = 0;\n threshold = 30;\n }\n setMoveThreshold(threshold);\n}\n\n
" ], "alt": "50x50 black rect in center of canvas. turns white on mobile when device moves", "class": "p5", @@ -8933,7 +9033,7 @@ module.exports={ }, { "file": "src/events/acceleration.js", - "line": 393, + "line": 462, "description": "

The setShakeThreshold() function is used to set the movement threshold for\nthe deviceShaken() function. The default threshold is set to 30.

\n", "itemtype": "method", "name": "setShakeThreshold", @@ -8945,7 +9045,7 @@ module.exports={ } ], "example": [ - "\n
\n\n// Run this example on a mobile device\n// You will need to shake the device more firmly\n// the closer the box's fill gets to white in order to change the value.\n\nvar value = 0;\nvar threshold = 30;\nfunction setup() {\n setShakeThreshold(threshold);\n}\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceMoved() {\n value = value + 5;\n threshold = threshold + 5;\n if (value > 255) {\n value = 0;\n threshold = 30;\n }\n setShakeThreshold(threshold);\n}\n\n
" + "\n
\n\n// Run this example on a mobile device\n// You will need to shake the device more firmly\n// the closer the box's fill gets to white in order to change the value.\n\nlet value = 0;\nlet threshold = 30;\nfunction setup() {\n setShakeThreshold(threshold);\n}\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceMoved() {\n value = value + 5;\n threshold = threshold + 5;\n if (value > 255) {\n value = 0;\n threshold = 30;\n }\n setShakeThreshold(threshold);\n}\n\n
" ], "alt": "50x50 black rect in center of canvas. turns white on mobile when device\nis being shaked", "class": "p5", @@ -8954,12 +9054,12 @@ module.exports={ }, { "file": "src/events/acceleration.js", - "line": 437, - "description": "

The deviceMoved() function is called when the device is moved by more than\nthe threshold value along X, Y or Z axis. The default threshold is set to\n0.5.

\n", + "line": 506, + "description": "

The deviceMoved() function is called when the device is moved by more than\nthe threshold value along X, Y or Z axis. The default threshold is set to 0.5.\nThe threshold value can be changed using setMoveThreshold().

\n", "itemtype": "method", "name": "deviceMoved", "example": [ - "\n
\n\n// Run this example on a mobile device\n// Move the device around\n// to change the value.\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n
" + "\n
\n\n// Run this example on a mobile device\n// Move the device around\n// to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n
" ], "alt": "50x50 black rect in center of canvas. turns white on mobile when device moves", "class": "p5", @@ -8968,12 +9068,12 @@ module.exports={ }, { "file": "src/events/acceleration.js", - "line": 468, + "line": 538, "description": "

The deviceTurned() function is called when the device rotates by\nmore than 90 degrees continuously.\n

\nThe axis that triggers the deviceTurned() method is stored in the turnAxis\nvariable. The deviceTurned() method can be locked to trigger on any axis:\nX, Y or Z by comparing the turnAxis variable to 'X', 'Y' or 'Z'.

\n", "itemtype": "method", "name": "deviceTurned", "example": [ - "\n
\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees\n// to change the value.\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceTurned() {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n}\n\n
\n
\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees in the\n// X-axis to change the value.\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceTurned() {\n if (turnAxis === 'X') {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n }\n}\n\n
" + "\n
\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees\n// to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceTurned() {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n}\n\n
\n
\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees in the\n// X-axis to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceTurned() {\n if (turnAxis === 'X') {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n }\n}\n\n
" ], "alt": "50x50 black rect in center of canvas. turns white on mobile when device turns\n50x50 black rect in center of canvas. turns white on mobile when x-axis turns", "class": "p5", @@ -8982,12 +9082,12 @@ module.exports={ }, { "file": "src/events/acceleration.js", - "line": 527, - "description": "

The deviceShaken() function is called when the device total acceleration\nchanges of accelerationX and accelerationY values is more than\nthe threshold value. The default threshold is set to 30.

\n", + "line": 597, + "description": "

The deviceShaken() function is called when the device total acceleration\nchanges of accelerationX and accelerationY values is more than\nthe threshold value. The default threshold is set to 30.\nThe threshold value can be changed using setShakeThreshold().

\n", "itemtype": "method", "name": "deviceShaken", "example": [ - "\n
\n\n// Run this example on a mobile device\n// Shake the device to change the value.\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceShaken() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n
" + "\n
\n\n// Run this example on a mobile device\n// Shake the device to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceShaken() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n
" ], "alt": "50x50 black rect in center of canvas. turns white on mobile when device shakes", "class": "p5", @@ -8996,7 +9096,7 @@ module.exports={ }, { "file": "src/events/keyboard.js", - "line": 18, + "line": 12, "description": "

The boolean system variable keyIsPressed is true if any key is pressed\nand false if no keys are pressed.

\n", "itemtype": "property", "name": "keyIsPressed", @@ -9012,7 +9112,7 @@ module.exports={ }, { "file": "src/events/keyboard.js", - "line": 45, + "line": 39, "description": "

The system variable key always contains the value of the most recent\nkey on the keyboard that was typed. To get the proper capitalization, it\nis best to use it within keyTyped(). For non-ASCII keys, use the keyCode\nvariable.

\n", "itemtype": "property", "name": "key", @@ -9028,28 +9128,28 @@ module.exports={ }, { "file": "src/events/keyboard.js", - "line": 74, + "line": 68, "description": "

The variable keyCode is used to detect special keys such as BACKSPACE,\nDELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL, OPTION, ALT, UP_ARROW,\nDOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.\nYou can also check for custom keys by looking up the keyCode of any key\non a site like this: keycode.info.

\n", "itemtype": "property", "name": "keyCode", "type": "Integer", "readonly": "", "example": [ - "\n
\nvar fillVal = 126;\nfunction draw() {\n fill(fillVal);\n rect(25, 25, 50, 50);\n}\n\nfunction keyPressed() {\n if (keyCode === UP_ARROW) {\n fillVal = 255;\n } else if (keyCode === DOWN_ARROW) {\n fillVal = 0;\n }\n return false; // prevent default\n}\n
" + "\n
\nlet fillVal = 126;\nfunction draw() {\n fill(fillVal);\n rect(25, 25, 50, 50);\n}\n\nfunction keyPressed() {\n if (keyCode === UP_ARROW) {\n fillVal = 255;\n } else if (keyCode === DOWN_ARROW) {\n fillVal = 0;\n }\n return false; // prevent default\n}\n
\n
\nfunction draw() {}\nfunction keyPressed() {\n background('yellow');\n text(`${key} ${keyCode}`, 10, 40);\n print(key, ' ', keyCode);\n return false; // prevent default\n}\n
" ], - "alt": "Grey rect center. turns white when up arrow pressed and black when down", + "alt": "Grey rect center. turns white when up arrow pressed and black when down\nDisplay key pressed and its keyCode in a yellow box", "class": "p5", "module": "Events", "submodule": "Keyboard" }, { "file": "src/events/keyboard.js", - "line": 107, - "description": "

The keyPressed() function is called once every time a key is pressed. The\nkeyCode for the key that was pressed is stored in the keyCode variable.\n

\nFor non-ASCII keys, use the keyCode variable. You can check if the keyCode\nequals BACKSPACE, DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL,\nOPTION, ALT, UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.\n

\nFor ASCII keys that was pressed is stored in the key variable. However, it\ndoes not distinguish between uppercase and lowercase. For this reason, it\nis recommended to use keyTyped() to read the key variable, in which the\ncase of the variable will be distinguished.\n

\nBecause of how operating systems handle key repeats, holding down a key\nmay cause multiple calls to keyTyped() (and keyReleased() as well). The\nrate of repeat is set by the operating system and how each computer is\nconfigured.

\nBrowsers may have different default\nbehaviors attached to various key events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.

\n", + "line": 109, + "description": "

The keyPressed() function is called once every time a key is pressed. The\nkeyCode for the key that was pressed is stored in the keyCode variable.\n

\nFor non-ASCII keys, use the keyCode variable. You can check if the keyCode\nequals BACKSPACE, DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL,\nOPTION, ALT, UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.\n

\nFor ASCII keys, the key that was pressed is stored in the key variable. However, it\ndoes not distinguish between uppercase and lowercase. For this reason, it\nis recommended to use keyTyped() to read the key variable, in which the\ncase of the variable will be distinguished.\n

\nBecause of how operating systems handle key repeats, holding down a key\nmay cause multiple calls to keyTyped() (and keyReleased() as well). The\nrate of repeat is set by the operating system and how each computer is\nconfigured.

\nBrowsers may have different default\nbehaviors attached to various key events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.

\n", "itemtype": "method", "name": "keyPressed", "example": [ - "\n
\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyPressed() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n
\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyPressed() {\n if (keyCode === LEFT_ARROW) {\n value = 255;\n } else if (keyCode === RIGHT_ARROW) {\n value = 0;\n }\n}\n\n
\n
\n\nfunction keyPressed() {\n // Do something\n return false; // prevent any default behaviour\n}\n\n
" + "\n
\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyPressed() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n
\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyPressed() {\n if (keyCode === LEFT_ARROW) {\n value = 255;\n } else if (keyCode === RIGHT_ARROW) {\n value = 0;\n }\n}\n\n
\n
\n\nfunction keyPressed() {\n // Do something\n return false; // prevent any default behaviour\n}\n\n
" ], "alt": "black rect center. turns white when key pressed and black when released\nblack rect center. turns white when left arrow pressed and black when right.", "class": "p5", @@ -9058,12 +9158,12 @@ module.exports={ }, { "file": "src/events/keyboard.js", - "line": 194, + "line": 196, "description": "

The keyReleased() function is called once every time a key is released.\nSee key and keyCode for more information.

\nBrowsers may have different default\nbehaviors attached to various key events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.

\n", "itemtype": "method", "name": "keyReleased", "example": [ - "\n
\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyReleased() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n return false; // prevent any default behavior\n}\n\n
" + "\n
\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyReleased() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n return false; // prevent any default behavior\n}\n\n
" ], "alt": "black rect center. turns white when key pressed and black when pressed again", "class": "p5", @@ -9072,12 +9172,12 @@ module.exports={ }, { "file": "src/events/keyboard.js", - "line": 246, + "line": 248, "description": "

The keyTyped() function is called once every time a key is pressed, but\naction keys such as Ctrl, Shift, and Alt are ignored. The most recent\nkey pressed will be stored in the key variable.\n

\nBecause of how operating systems handle key repeats, holding down a key\nwill cause multiple calls to keyTyped() (and keyReleased() as well). The\nrate of repeat is set by the operating system and how each computer is\nconfigured.

\nBrowsers may have different default behaviors attached to various key\nevents. To prevent any default behavior for this event, add "return false"\nto the end of the method.

\n", "itemtype": "method", "name": "keyTyped", "example": [ - "\n
\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyTyped() {\n if (key === 'a') {\n value = 255;\n } else if (key === 'b') {\n value = 0;\n }\n // uncomment to prevent any default behavior\n // return false;\n}\n\n
" + "\n
\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyTyped() {\n if (key === 'a') {\n value = 255;\n } else if (key === 'b') {\n value = 0;\n }\n // uncomment to prevent any default behavior\n // return false;\n}\n\n
" ], "alt": "black rect center. turns white when 'a' key typed and black when 'b' pressed", "class": "p5", @@ -9086,7 +9186,7 @@ module.exports={ }, { "file": "src/events/keyboard.js", - "line": 300, + "line": 302, "description": "

The onblur function is called when the user is no longer focused\non the p5 element. Because the keyup events will not fire if the user is\nnot focused on the element we must assume all keys currently down have\nbeen released.

\n", "class": "p5", "module": "Events", @@ -9094,7 +9194,7 @@ module.exports={ }, { "file": "src/events/keyboard.js", - "line": 310, + "line": 312, "description": "

The keyIsDown() function checks if the key is currently down, i.e. pressed.\nIt can be used if you have an object that moves, and you want several keys\nto be able to affect its behaviour simultaneously, such as moving a\nsprite diagonally. You can put in any number representing the keyCode of\nthe key, or use any of the variable keyCode names listed\nhere.

\n", "itemtype": "method", "name": "keyIsDown", @@ -9110,7 +9210,7 @@ module.exports={ "type": "Boolean" }, "example": [ - "\n
\nvar x = 100;\nvar y = 100;\n\nfunction setup() {\n createCanvas(512, 512);\n}\n\nfunction draw() {\n if (keyIsDown(LEFT_ARROW)) {\n x -= 5;\n }\n\n if (keyIsDown(RIGHT_ARROW)) {\n x += 5;\n }\n\n if (keyIsDown(UP_ARROW)) {\n y -= 5;\n }\n\n if (keyIsDown(DOWN_ARROW)) {\n y += 5;\n }\n\n clear();\n fill(255, 0, 0);\n ellipse(x, y, 50, 50);\n}\n
\n\n
\nvar diameter = 50;\n\nfunction setup() {\n createCanvas(512, 512);\n}\n\nfunction draw() {\n // 107 and 187 are keyCodes for \"+\"\n if (keyIsDown(107) || keyIsDown(187)) {\n diameter += 1;\n }\n\n // 109 and 189 are keyCodes for \"-\"\n if (keyIsDown(109) || keyIsDown(189)) {\n diameter -= 1;\n }\n\n clear();\n fill(255, 0, 0);\n ellipse(50, 50, diameter, diameter);\n}\n
" + "\n
\nlet x = 100;\nlet y = 100;\n\nfunction setup() {\n createCanvas(512, 512);\n fill(255, 0, 0);\n}\n\nfunction draw() {\n if (keyIsDown(LEFT_ARROW)) {\n x -= 5;\n }\n\n if (keyIsDown(RIGHT_ARROW)) {\n x += 5;\n }\n\n if (keyIsDown(UP_ARROW)) {\n y -= 5;\n }\n\n if (keyIsDown(DOWN_ARROW)) {\n y += 5;\n }\n\n clear();\n ellipse(x, y, 50, 50);\n}\n
\n\n
\nlet diameter = 50;\n\nfunction setup() {\n createCanvas(512, 512);\n}\n\nfunction draw() {\n // 107 and 187 are keyCodes for \"+\"\n if (keyIsDown(107) || keyIsDown(187)) {\n diameter += 1;\n }\n\n // 109 and 189 are keyCodes for \"-\"\n if (keyIsDown(109) || keyIsDown(189)) {\n diameter -= 1;\n }\n\n clear();\n fill(255, 0, 0);\n ellipse(50, 50, diameter, diameter);\n}\n
" ], "alt": "50x50 red ellipse moves left, right, up and down with arrow presses.\n50x50 red ellipse gets bigger or smaller when + or - are pressed.", "class": "p5", @@ -9176,7 +9276,7 @@ module.exports={ "example": [ "\n
\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n //draw a square only if the mouse is not moving\n if (mouseY === pmouseY && mouseX === pmouseX) {\n rect(20, 20, 60, 60);\n }\n\n print(pmouseY + ' -> ' + mouseY);\n}\n\n
" ], - "alt": "60x60 black rect center, fuschia background. rect flickers on mouse movement", + "alt": "60x60 black rect center, fuchsia background. rect flickers on mouse movement", "class": "p5", "module": "Events", "submodule": "Mouse" @@ -9190,64 +9290,64 @@ module.exports={ "type": "Number", "readonly": "", "example": [ - "\n
\n\nvar myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n}\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n //move the canvas to the horizontal mouse position\n //rela tive to the window\n myCanvas.position(winMouseX + 1, windowHeight / 2);\n\n //the y of the square is relative to the canvas\n rect(20, mouseY, 60, 60);\n}\n\n
" + "\n
\n\nlet myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n const body = document.getElementsByTagName('body')[0];\n myCanvas.parent(body);\n}\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n //move the canvas to the horizontal mouse position\n //relative to the window\n myCanvas.position(winMouseX + 1, windowHeight / 2);\n\n //the y of the square is relative to the canvas\n rect(20, mouseY, 60, 60);\n}\n\n
" ], - "alt": "60x60 black rect y moves with mouse y and fuschia canvas moves with mouse x", + "alt": "60x60 black rect y moves with mouse y and fuchsia canvas moves with mouse x", "class": "p5", "module": "Events", "submodule": "Mouse" }, { "file": "src/events/mouse.js", - "line": 174, + "line": 176, "description": "

The system variable winMouseY always contains the current vertical\nposition of the mouse, relative to (0, 0) of the window.

\n", "itemtype": "property", "name": "winMouseY", "type": "Number", "readonly": "", "example": [ - "\n
\n\nvar myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n}\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n //move the canvas to the vertical mouse position\n //rel ative to the window\n myCanvas.position(windowWidth / 2, winMouseY + 1);\n\n //the x of the square is relative to the canvas\n rect(mouseX, 20, 60, 60);\n}\n\n
" + "\n
\n\nlet myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n const body = document.getElementsByTagName('body')[0];\n myCanvas.parent(body);\n}\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n //move the canvas to the vertical mouse position\n //relative to the window\n myCanvas.position(windowWidth / 2, winMouseY + 1);\n\n //the x of the square is relative to the canvas\n rect(mouseX, 20, 60, 60);\n}\n\n
" ], - "alt": "60x60 black rect x moves with mouse x and fuschia canvas y moves with mouse y", + "alt": "60x60 black rect x moves with mouse x and fuchsia canvas y moves with mouse y", "class": "p5", "module": "Events", "submodule": "Mouse" }, { "file": "src/events/mouse.js", - "line": 211, + "line": 215, "description": "

The system variable pwinMouseX always contains the horizontal position\nof the mouse in the frame previous to the current frame, relative to\n(0, 0) of the window. Note: pwinMouseX will be reset to the current winMouseX\nvalue at the start of each touch event.

\n", "itemtype": "property", "name": "pwinMouseX", "type": "Number", "readonly": "", "example": [ - "\n
\n\nvar myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n noStroke();\n fill(237, 34, 93);\n}\n\nfunction draw() {\n clear();\n //the difference between previous and\n //current x position is the horizontal mouse speed\n var speed = abs(winMouseX - pwinMouseX);\n //change the size of the circle\n //according to the horizontal speed\n ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);\n //move the canvas to the mouse position\n myCanvas.position(winMouseX + 1, winMouseY + 1);\n}\n\n
" + "\n
\n\nlet myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n noStroke();\n fill(237, 34, 93);\n}\n\nfunction draw() {\n clear();\n //the difference between previous and\n //current x position is the horizontal mouse speed\n let speed = abs(winMouseX - pwinMouseX);\n //change the size of the circle\n //according to the horizontal speed\n ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);\n //move the canvas to the mouse position\n myCanvas.position(winMouseX + 1, winMouseY + 1);\n}\n\n
" ], - "alt": "fuschia ellipse moves with mouse x and y. Grows and shrinks with mouse speed", + "alt": "fuchsia ellipse moves with mouse x and y. Grows and shrinks with mouse speed", "class": "p5", "module": "Events", "submodule": "Mouse" }, { "file": "src/events/mouse.js", - "line": 252, + "line": 256, "description": "

The system variable pwinMouseY always contains the vertical position of\nthe mouse in the frame previous to the current frame, relative to (0, 0)\nof the window. Note: pwinMouseY will be reset to the current winMouseY\nvalue at the start of each touch event.

\n", "itemtype": "property", "name": "pwinMouseY", "type": "Number", "readonly": "", "example": [ - "\n
\n\nvar myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n noStroke();\n fill(237, 34, 93);\n}\n\nfunction draw() {\n clear();\n //the difference between previous and\n //current y position is the vertical mouse speed\n var speed = abs(winMouseY - pwinMouseY);\n //change the size of the circle\n //according to the vertical speed\n ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);\n //move the canvas to the mouse position\n myCanvas.position(winMouseX + 1, winMouseY + 1);\n}\n\n
" + "\n
\n\nlet myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n noStroke();\n fill(237, 34, 93);\n}\n\nfunction draw() {\n clear();\n //the difference between previous and\n //current y position is the vertical mouse speed\n let speed = abs(winMouseY - pwinMouseY);\n //change the size of the circle\n //according to the vertical speed\n ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);\n //move the canvas to the mouse position\n myCanvas.position(winMouseX + 1, winMouseY + 1);\n}\n\n
" ], - "alt": "fuschia ellipse moves with mouse x and y. Grows and shrinks with mouse speed", + "alt": "fuchsia ellipse moves with mouse x and y. Grows and shrinks with mouse speed", "class": "p5", "module": "Events", "submodule": "Mouse" }, { "file": "src/events/mouse.js", - "line": 294, + "line": 298, "description": "

Processing automatically tracks if the mouse button is pressed and which\nbutton is pressed. The value of the system variable mouseButton is either\nLEFT, RIGHT, or CENTER depending on which button was pressed last.\nWarning: different browsers may track mouseButton differently.

\n", "itemtype": "property", "name": "mouseButton", @@ -9256,14 +9356,14 @@ module.exports={ "example": [ "\n
\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n if (mouseIsPressed) {\n if (mouseButton === LEFT) {\n ellipse(50, 50, 50, 50);\n }\n if (mouseButton === RIGHT) {\n rect(25, 25, 50, 50);\n }\n if (mouseButton === CENTER) {\n triangle(23, 75, 50, 20, 78, 75);\n }\n }\n\n print(mouseButton);\n}\n\n
" ], - "alt": "50x50 black ellipse appears on center of fuschia canvas on mouse click/press.", + "alt": "50x50 black ellipse appears on center of fuchsia canvas on mouse click/press.", "class": "p5", "module": "Events", "submodule": "Mouse" }, { "file": "src/events/mouse.js", - "line": 333, + "line": 337, "description": "

The boolean system variable mouseIsPressed is true if the mouse is pressed\nand false if not.

\n", "itemtype": "property", "name": "mouseIsPressed", @@ -9272,19 +9372,27 @@ module.exports={ "example": [ "\n
\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n if (mouseIsPressed) {\n ellipse(50, 50, 50, 50);\n } else {\n rect(25, 25, 50, 50);\n }\n\n print(mouseIsPressed);\n}\n\n
" ], - "alt": "black 50x50 rect becomes ellipse with mouse click/press. fuschia background.", + "alt": "black 50x50 rect becomes ellipse with mouse click/press. fuchsia background.", "class": "p5", "module": "Events", "submodule": "Mouse" }, { "file": "src/events/mouse.js", - "line": 424, + "line": 428, "description": "

The mouseMoved() function is called every time the mouse moves and a mouse\nbutton is not pressed.

\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.

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

optional MouseEvent callback argument.

\n", + "type": "Object", + "optional": true + } + ], "example": [ - "\n
\n\n// Move the mouse across the page\n// to change its value\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction mouseMoved() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
" + "\n
\n\n// Move the mouse across the page\n// to change its value\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction mouseMoved() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
\n\n
\n\n// returns a MouseEvent object\n// as a callback argument\nfunction mouseMoved(event) {\n console.log(event);\n}\n\n
" ], "alt": "black 50x50 rect becomes lighter with mouse movements until white then resets\nno image displayed", "class": "p5", @@ -9293,12 +9401,20 @@ module.exports={ }, { "file": "src/events/mouse.js", - "line": 468, + "line": 483, "description": "

The mouseDragged() function is called once every time the mouse moves and\na mouse button is pressed. If no mouseDragged() function is defined, the\ntouchMoved() function will be called instead if it is defined.

\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.

\n", "itemtype": "method", "name": "mouseDragged", + "params": [ + { + "name": "event", + "description": "

optional MouseEvent callback argument.

\n", + "type": "Object", + "optional": true + } + ], "example": [ - "\n
\n\n// Drag the mouse across the page\n// to change its value\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseDragged() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction mouseDragged() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
" + "\n
\n\n// Drag the mouse across the page\n// to change its value\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseDragged() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction mouseDragged() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
\n\n
\n\n// returns a MouseEvent object\n// as a callback argument\nfunction mouseDragged(event) {\n console.log(event);\n}\n\n
" ], "alt": "black 50x50 rect turns lighter with mouse click and drag until white, resets\nno image displayed", "class": "p5", @@ -9307,12 +9423,20 @@ module.exports={ }, { "file": "src/events/mouse.js", - "line": 538, + "line": 564, "description": "

The mousePressed() function is called once after every time a mouse button\nis pressed. The mouseButton variable (see the related reference entry)\ncan be used to determine which button has been pressed. If no\nmousePressed() function is defined, the touchStarted() function will be\ncalled instead if it is defined.

\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.

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

optional MouseEvent callback argument.

\n", + "type": "Object", + "optional": true + } + ], "example": [ - "\n
\n\n// Click within the image to change\n// the value of the rectangle\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mousePressed() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction mousePressed() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
" + "\n
\n\n// Click within the image to change\n// the value of the rectangle\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mousePressed() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction mousePressed() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
\n\n
\n\n// returns a MouseEvent object\n// as a callback argument\nfunction mousePressed(event) {\n console.log(event);\n}\n\n
" ], "alt": "black 50x50 rect turns white with mouse click/press.\nno image displayed", "class": "p5", @@ -9321,12 +9445,20 @@ module.exports={ }, { "file": "src/events/mouse.js", - "line": 604, + "line": 641, "description": "

The mouseReleased() function is called every time a mouse button is\nreleased. If no mouseReleased() function is defined, the touchEnded()\nfunction will be called instead if it is defined.

\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.

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

optional MouseEvent callback argument.

\n", + "type": "Object", + "optional": true + } + ], "example": [ - "\n
\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been clicked\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseReleased() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction mouseReleased() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
" + "\n
\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been clicked\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseReleased() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction mouseReleased() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
\n\n
\n\n// returns a MouseEvent object\n// as a callback argument\nfunction mouseReleased(event) {\n console.log(event);\n}\n\n
" ], "alt": "black 50x50 rect turns white with mouse click/press.\nno image displayed", "class": "p5", @@ -9335,12 +9467,20 @@ module.exports={ }, { "file": "src/events/mouse.js", - "line": 671, + "line": 719, "description": "

The mouseClicked() function is called once after a mouse button has been\npressed and then released.

\nBrowsers handle clicks differently, so this function is only guaranteed to be\nrun when the left mouse button is clicked. To handle other mouse buttons\nbeing pressed or released, see mousePressed() or mouseReleased().

\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.

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

optional MouseEvent callback argument.

\n", + "type": "Object", + "optional": true + } + ], "example": [ - "\n
\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been clicked\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\n\nfunction mouseClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction mouseClicked() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
" + "\n
\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been clicked\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\n\nfunction mouseClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction mouseClicked() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
\n\n
\n\n// returns a MouseEvent object\n// as a callback argument\nfunction mouseClicked(event) {\n console.log(event);\n}\n\n
" ], "alt": "black 50x50 rect turns white with mouse click/press.\nno image displayed", "class": "p5", @@ -9349,12 +9489,20 @@ module.exports={ }, { "file": "src/events/mouse.js", - "line": 730, + "line": 789, "description": "

The doubleClicked() function is executed every time a event\nlistener has detected a dblclick event which is a part of the\nDOM L3 specification. The doubleClicked event is fired when a\npointing device button (usually a mouse's primary button)\nis clicked twice on a single element. For more info on the\ndblclick event refer to mozilla's documentation here:\nhttps://developer.mozilla.org/en-US/docs/Web/Events/dblclick

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

optional MouseEvent callback argument.

\n", + "type": "Object", + "optional": true + } + ], "example": [ - "\n
\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been double clicked\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\n\nfunction doubleClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction doubleClicked() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
" + "\n
\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been double clicked\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\n\nfunction doubleClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction doubleClicked() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
\n\n
\n\n// returns a MouseEvent object\n// as a callback argument\nfunction doubleClicked(event) {\n console.log(event);\n}\n\n
" ], "alt": "black 50x50 rect turns white with mouse doubleClick/press.\nno image displayed", "class": "p5", @@ -9363,14 +9511,22 @@ module.exports={ }, { "file": "src/events/mouse.js", - "line": 804, + "line": 874, "description": "

The function mouseWheel() is executed every time a vertical mouse wheel\nevent is detected either triggered by an actual mouse wheel or by a\ntouchpad.

\nThe event.delta property returns the amount the mouse wheel\nhave scrolled. The values can be positive or negative depending on the\nscroll direction (on OS X with "natural" scrolling enabled, the signs\nare inverted).

\nBrowsers may have different default behaviors attached to various\nmouse events. To prevent any default behavior for this event, add\n"return false" to the end of the method.

\nDue to the current support of the "wheel" event on Safari, the function\nmay only work as expected if "return false" is included while using Safari.

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

optional WheelEvent callback argument.

\n", + "type": "Object", + "optional": true + } + ], "example": [ - "\n
\n\nvar pos = 25;\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n rect(25, pos, 50, 50);\n}\n\nfunction mouseWheel(event) {\n print(event.delta);\n //move the square according to the vertical scroll amount\n pos += event.delta;\n //uncomment to block page scrolling\n //return false;\n}\n\n
" + "\n
\n\nlet pos = 25;\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n rect(25, pos, 50, 50);\n}\n\nfunction mouseWheel(event) {\n print(event.delta);\n //move the square according to the vertical scroll amount\n pos += event.delta;\n //uncomment to block page scrolling\n //return false;\n}\n\n
" ], - "alt": "black 50x50 rect moves up and down with vertical scroll. fuschia background", + "alt": "black 50x50 rect moves up and down with vertical scroll. fuchsia background", "class": "p5", "module": "Events", "submodule": "Mouse" @@ -9384,7 +9540,7 @@ module.exports={ "type": "Object[]", "readonly": "", "example": [ - "\n
\n\n// On a touchscreen device, touch\n// the canvas using one or more fingers\n// at the same time\nfunction draw() {\n clear();\n var display = touches.length + ' touches';\n text(display, 5, 10);\n}\n\n
" + "\n
\n\n// On a touchscreen device, touch\n// the canvas using one or more fingers\n// at the same time\nfunction draw() {\n clear();\n let display = touches.length + ' touches';\n text(display, 5, 10);\n}\n\n
" ], "alt": "Number of touches currently registered are displayed on the canvas", "class": "p5", @@ -9397,8 +9553,16 @@ module.exports={ "description": "

The touchStarted() function is called once after every time a touch is\nregistered. If no touchStarted() function is defined, the mousePressed()\nfunction will be called instead if it is defined.

\nBrowsers may have different default behaviors attached to various touch\nevents. To prevent any default behavior for this event, add "return false"\nto the end of the method.

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

optional TouchEvent callback argument.

\n", + "type": "Object", + "optional": true + } + ], "example": [ - "\n
\n\n// Touch within the image to change\n// the value of the rectangle\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchStarted() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction touchStarted() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
" + "\n
\n\n// Touch within the image to change\n// the value of the rectangle\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchStarted() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction touchStarted() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
\n\n
\n\n// returns a TouchEvent object\n// as a callback argument\nfunction touchStarted(event) {\n console.log(event);\n}\n\n
" ], "alt": "50x50 black rect turns white with touch event.\nno image displayed", "class": "p5", @@ -9407,12 +9571,20 @@ module.exports={ }, { "file": "src/events/touch.js", - "line": 138, + "line": 149, "description": "

The touchMoved() function is called every time a touch move is registered.\nIf no touchMoved() function is defined, the mouseDragged() function will\nbe called instead if it is defined.

\nBrowsers may have different default behaviors attached to various touch\nevents. To prevent any default behavior for this event, add "return false"\nto the end of the method.

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

optional TouchEvent callback argument.

\n", + "type": "Object", + "optional": true + } + ], "example": [ - "\n
\n\n// Move your finger across the page\n// to change its value\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction touchMoved() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
" + "\n
\n\n// Move your finger across the page\n// to change its value\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction touchMoved() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
\n\n
\n\n// returns a TouchEvent object\n// as a callback argument\nfunction touchMoved(event) {\n console.log(event);\n}\n\n
" ], "alt": "50x50 black rect turns lighter with touch until white. resets\nno image displayed", "class": "p5", @@ -9421,12 +9593,20 @@ module.exports={ }, { "file": "src/events/touch.js", - "line": 200, + "line": 222, "description": "

The touchEnded() function is called every time a touch ends. If no\ntouchEnded() function is defined, the mouseReleased() function will be\ncalled instead if it is defined.

\nBrowsers may have different default behaviors attached to various touch\nevents. To prevent any default behavior for this event, add "return false"\nto the end of the method.

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

optional TouchEvent callback argument.

\n", + "type": "Object", + "optional": true + } + ], "example": [ - "\n
\n\n// Release touch within the image to\n// change the value of the rectangle\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchEnded() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction touchEnded() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
" + "\n
\n\n// Release touch within the image to\n// change the value of the rectangle\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchEnded() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction touchEnded() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
\n\n
\n\n// returns a TouchEvent object\n// as a callback argument\nfunction touchEnded(event) {\n console.log(event);\n}\n\n
" ], "alt": "50x50 black rect turns white with touch.\nno image displayed", "class": "p5", @@ -9471,7 +9651,7 @@ module.exports={ "type": "p5.Image" }, "example": [ - "\n
\n\nvar img = createImage(66, 66);\nimg.loadPixels();\nfor (var i = 0; i < img.width; i++) {\n for (var j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\n\n
\n\n
\n\nvar img = createImage(66, 66);\nimg.loadPixels();\nfor (var i = 0; i < img.width; i++) {\n for (var j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102, (i % img.width) * 2));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\nimage(img, 34, 34);\n\n
\n\n
\n\nvar pink = color(255, 102, 204);\nvar img = createImage(66, 66);\nimg.loadPixels();\nvar d = pixelDensity();\nvar halfImage = 4 * (img.width * d) * (img.height / 2 * d);\nfor (var i = 0; i < halfImage; i += 4) {\n img.pixels[i] = red(pink);\n img.pixels[i + 1] = green(pink);\n img.pixels[i + 2] = blue(pink);\n img.pixels[i + 3] = alpha(pink);\n}\nimg.updatePixels();\nimage(img, 17, 17);\n\n
" + "\n
\n\nlet img = createImage(66, 66);\nimg.loadPixels();\nfor (let i = 0; i < img.width; i++) {\n for (let j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\n\n
\n\n
\n\nlet img = createImage(66, 66);\nimg.loadPixels();\nfor (let i = 0; i < img.width; i++) {\n for (let j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102, (i % img.width) * 2));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\nimage(img, 34, 34);\n\n
\n\n
\n\nlet pink = color(255, 102, 204);\nlet img = createImage(66, 66);\nimg.loadPixels();\nlet d = pixelDensity();\nlet halfImage = 4 * (img.width * d) * (img.height / 2 * d);\nfor (let i = 0; i < halfImage; i += 4) {\n img.pixels[i] = red(pink);\n img.pixels[i + 1] = green(pink);\n img.pixels[i + 2] = blue(pink);\n img.pixels[i + 3] = alpha(pink);\n}\nimg.updatePixels();\nimage(img, 17, 17);\n\n
" ], "alt": "66x66 dark turquoise rect in center of canvas.\n2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas\nno image displayed", "class": "p5", @@ -9485,7 +9665,7 @@ module.exports={ "itemtype": "method", "name": "saveCanvas", "example": [ - "\n
\n function setup() {\n var c = createCanvas(100, 100);\n background(255, 0, 0);\n saveCanvas(c, 'myCanvas', 'jpg');\n }\n
\n
\n // note that this example has the same result as above\n // if no canvas is specified, defaults to main canvas\n function setup() {\n var c = createCanvas(100, 100);\n background(255, 0, 0);\n saveCanvas('myCanvas', 'jpg');\n\n // all of the following are valid\n saveCanvas(c, 'myCanvas', 'jpg');\n saveCanvas(c, 'myCanvas.jpg');\n saveCanvas(c, 'myCanvas');\n saveCanvas(c);\n saveCanvas('myCanvas', 'png');\n saveCanvas('myCanvas');\n saveCanvas();\n }\n
" + "\n
\n function setup() {\n let c = createCanvas(100, 100);\n background(255, 0, 0);\n saveCanvas(c, 'myCanvas', 'jpg');\n }\n
\n
\n // note that this example has the same result as above\n // if no canvas is specified, defaults to main canvas\n function setup() {\n let c = createCanvas(100, 100);\n background(255, 0, 0);\n saveCanvas('myCanvas', 'jpg');\n\n // all of the following are valid\n saveCanvas(c, 'myCanvas', 'jpg');\n saveCanvas(c, 'myCanvas.jpg');\n saveCanvas(c, 'myCanvas');\n saveCanvas(c);\n saveCanvas('myCanvas', 'png');\n saveCanvas('myCanvas');\n saveCanvas();\n }\n
" ], "alt": "no image displayed\n no image displayed\n no image displayed", "class": "p5", @@ -9568,7 +9748,7 @@ module.exports={ } ], "example": [ - "\n
\n function draw() {\n background(mouseX);\n }\n\n function mousePressed() {\n saveFrames('out', 'png', 1, 25, function(data) {\n print(data);\n });\n }\n
" + "\n
\n function draw() {\n background(mouseX);\n }\n\n function mousePressed() {\n saveFrames('out', 'png', 1, 25, data => {\n print(data);\n });\n }\n
" ], "alt": "canvas background goes from light to dark with mouse x.", "class": "p5", @@ -9605,7 +9785,7 @@ module.exports={ "type": "p5.Image" }, "example": [ - "\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n}\n\n
\n
\n\nfunction setup() {\n // here we use a callback to display the image after loading\n loadImage('assets/laDefense.jpg', function(img) {\n image(img, 0, 0);\n });\n}\n\n
" + "\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n}\n\n
\n
\n\nfunction setup() {\n // here we use a callback to display the image after loading\n loadImage('assets/laDefense.jpg', img => {\n image(img, 0, 0);\n });\n}\n\n
" ], "alt": "image of the underside of a white umbrella and grided ceililng above\nimage of the underside of a white umbrella and grided ceililng above", "class": "p5", @@ -9614,12 +9794,12 @@ module.exports={ }, { "file": "src/image/loading_displaying.js", - "line": 125, + "line": 127, "description": "

Draw an image to the p5.js canvas.

\n

This function can be used with different numbers of parameters. The\nsimplest use requires only three parameters: img, x, and y—where (x, y) is\nthe position of the image. Two more parameters can optionally be added to\nspecify the width and height of the image.

\n

This function can also be used with all eight Number parameters. To\ndifferentiate between all these parameters, p5.js uses the language of\n"destination rectangle" (which corresponds to "dx", "dy", etc.) and "source\nimage" (which corresponds to "sx", "sy", etc.) below. Specifying the\n"source image" dimensions can be useful when you want to display a\nsubsection of the source image instead of the whole thing. Here's a diagram\nto explain further:\n

\n", "itemtype": "method", "name": "image", "example": [ - "\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n // Top-left corner of the img is at (0, 0)\n // Width and height are the img's original width and height\n image(img, 0, 0);\n}\n\n
\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n background(50);\n // Top-left corner of the img is at (10, 10)\n // Width and height are 50 x 50\n image(img, 10, 10, 50, 50);\n}\n\n
\n
\n\nfunction setup() {\n // Here, we use a callback to display the image after loading\n loadImage('assets/laDefense.jpg', function(img) {\n image(img, 0, 0);\n });\n}\n\n
\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/gradient.png');\n}\nfunction setup() {\n // 1. Background image\n // Top-left corner of the img is at (0, 0)\n // Width and height are the img's original width and height, 100 x 100\n image(img, 0, 0);\n // 2. Top right image\n // Top-left corner of destination rectangle is at (50, 0)\n // Destination rectangle width and height are 40 x 20\n // The next parameters are relative to the source image:\n // - Starting at position (50, 50) on the source image, capture a 50 x 50\n // subsection\n // - Draw this subsection to fill the dimensions of the destination rectangle\n image(img, 50, 0, 40, 20, 50, 50, 50, 50);\n}\n\n
" + "\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n // Top-left corner of the img is at (0, 0)\n // Width and height are the img's original width and height\n image(img, 0, 0);\n}\n\n
\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n background(50);\n // Top-left corner of the img is at (10, 10)\n // Width and height are 50 x 50\n image(img, 10, 10, 50, 50);\n}\n\n
\n
\n\nfunction setup() {\n // Here, we use a callback to display the image after loading\n loadImage('assets/laDefense.jpg', img => {\n image(img, 0, 0);\n });\n}\n\n
\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/gradient.png');\n}\nfunction setup() {\n // 1. Background image\n // Top-left corner of the img is at (0, 0)\n // Width and height are the img's original width and height, 100 x 100\n image(img, 0, 0);\n // 2. Top right image\n // Top-left corner of destination rectangle is at (50, 0)\n // Destination rectangle width and height are 40 x 20\n // The next parameters are relative to the source image:\n // - Starting at position (50, 50) on the source image, capture a 50 x 50\n // subsection\n // - Draw this subsection to fill the dimensions of the destination rectangle\n image(img, 50, 0, 40, 20, 50, 50, 50, 50);\n}\n\n
" ], "alt": "image of the underside of a white umbrella and gridded ceiling above\nimage of the underside of a white umbrella and gridded ceiling above", "class": "p5", @@ -9627,7 +9807,7 @@ module.exports={ "submodule": "Loading & Displaying", "overloads": [ { - "line": 125, + "line": 127, "params": [ { "name": "img", @@ -9659,7 +9839,7 @@ module.exports={ ] }, { - "line": 213, + "line": 215, "params": [ { "name": "img", @@ -9714,12 +9894,12 @@ module.exports={ }, { "file": "src/image/loading_displaying.js", - "line": 296, + "line": 298, "description": "

Sets the fill value for displaying images. Images can be tinted to\nspecified colors or made transparent by including an alpha value.\n

\nTo apply transparency to an image without affecting its color, use\nwhite as the tint color and specify an alpha value. For instance,\ntint(255, 128) will make an image 50% transparent (assuming the default\nalpha range of 0-255, which can be changed with colorMode()).\n

\nThe value for the gray parameter must be less than or equal to the current\nmaximum value as specified by colorMode(). The default maximum value is\n255.

\n", "itemtype": "method", "name": "tint", "example": [ - "\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n tint(0, 153, 204); // Tint blue\n image(img, 50, 0);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n tint(0, 153, 204, 126); // Tint blue and set transparency\n image(img, 50, 0);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n tint(255, 126); // Apply transparency without changing color\n image(img, 50, 0);\n}\n\n
" + "\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n tint(0, 153, 204); // Tint blue\n image(img, 50, 0);\n}\n\n
\n\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n tint(0, 153, 204, 126); // Tint blue and set transparency\n image(img, 50, 0);\n}\n\n
\n\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n tint(255, 126); // Apply transparency without changing color\n image(img, 50, 0);\n}\n\n
" ], "alt": "2 side by side images of umbrella and ceiling, one image with blue tint\nImages of umbrella and ceiling, one half of image with blue tint\n2 side by side images of umbrella and ceiling, one image translucent", "class": "p5", @@ -9727,7 +9907,7 @@ module.exports={ "submodule": "Loading & Displaying", "overloads": [ { - "line": 296, + "line": 298, "params": [ { "name": "v1", @@ -9753,7 +9933,7 @@ module.exports={ ] }, { - "line": 369, + "line": 371, "params": [ { "name": "value", @@ -9763,7 +9943,7 @@ module.exports={ ] }, { - "line": 374, + "line": 376, "params": [ { "name": "gray", @@ -9779,7 +9959,7 @@ module.exports={ ] }, { - "line": 380, + "line": 382, "params": [ { "name": "values", @@ -9789,7 +9969,7 @@ module.exports={ ] }, { - "line": 386, + "line": 388, "params": [ { "name": "color", @@ -9802,12 +9982,12 @@ module.exports={ }, { "file": "src/image/loading_displaying.js", - "line": 396, + "line": 398, "description": "

Removes the current fill value for displaying images and reverts to\ndisplaying images with their original hues.

\n", "itemtype": "method", "name": "noTint", "example": [ - "\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n tint(0, 153, 204); // Tint blue\n image(img, 0, 0);\n noTint(); // Disable tint\n image(img, 50, 0);\n}\n\n
" + "\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n tint(0, 153, 204); // Tint blue\n image(img, 0, 0);\n noTint(); // Disable tint\n image(img, 50, 0);\n}\n\n
" ], "alt": "2 side by side images of bricks, left image with blue tint", "class": "p5", @@ -9816,7 +9996,7 @@ module.exports={ }, { "file": "src/image/loading_displaying.js", - "line": 462, + "line": 464, "description": "

Set image mode. Modifies the location from which images are drawn by\nchanging the way in which parameters given to image() are interpreted.\nThe default mode is imageMode(CORNER), which interprets the second and\nthird parameters of image() as the upper-left corner of the image. If\ntwo additional parameters are specified, they are used to set the image's\nwidth and height.\n

\nimageMode(CORNERS) interprets the second and third parameters of image()\nas the location of one corner, and the fourth and fifth parameters as the\nopposite corner.\n

\nimageMode(CENTER) interprets the second and third parameters of image()\nas the image's center point. If two additional parameters are specified,\nthey are used to set the image's width and height.

\n", "itemtype": "method", "name": "imageMode", @@ -9828,7 +10008,7 @@ module.exports={ } ], "example": [ - "\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n imageMode(CORNER);\n image(img, 10, 10, 50, 50);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n imageMode(CORNERS);\n image(img, 10, 10, 90, 40);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n imageMode(CENTER);\n image(img, 50, 50, 80, 80);\n}\n\n
" + "\n\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n imageMode(CORNER);\n image(img, 10, 10, 50, 50);\n}\n\n
\n\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n imageMode(CORNERS);\n image(img, 10, 10, 90, 40);\n}\n\n
\n\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n imageMode(CENTER);\n image(img, 50, 50, 80, 80);\n}\n\n
" ], "alt": "small square image of bricks\nhorizontal rectangle image of bricks\nlarge square image of bricks", "class": "p5", @@ -9852,7 +10032,7 @@ module.exports={ "type": "Number", "readonly": "", "example": [ - "\n
\nvar img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n image(img, 0, 0);\n for (var i = 0; i < img.width; i++) {\n var c = img.get(i, img.height / 2);\n stroke(c);\n line(i, height / 2, i, height);\n }\n}\n
" + "\n
\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n image(img, 0, 0);\n for (let i = 0; i < img.width; i++) {\n let c = img.get(i, img.height / 2);\n stroke(c);\n line(i, height / 2, i, height);\n }\n}\n
" ], "alt": "rocky mountains in top and horizontal lines in corresponding colors in bottom.", "class": "p5.Image", @@ -9868,7 +10048,7 @@ module.exports={ "type": "Number", "readonly": "", "example": [ - "\n
\nvar img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n image(img, 0, 0);\n for (var i = 0; i < img.height; i++) {\n var c = img.get(img.width / 2, i);\n stroke(c);\n line(0, i, width / 2, i);\n }\n}\n
" + "\n
\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n image(img, 0, 0);\n for (let i = 0; i < img.height; i++) {\n let c = img.get(img.width / 2, i);\n stroke(c);\n line(0, i, width / 2, i);\n }\n}\n
" ], "alt": "rocky mountains on right and vertical lines in corresponding colors on left.", "class": "p5.Image", @@ -9877,13 +10057,13 @@ module.exports={ }, { "file": "src/image/p5.Image.js", - "line": 152, - "description": "

Array containing the values for all the pixels in the display window.\nThese values are numbers. This array is the size (include an appropriate\nfactor for pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. Retina and other\nhigh denisty displays may have more pixels (by a factor of\npixelDensity^2).\nFor example, if the image is 100x100 pixels, there will be 40,000. With\npixelDensity = 2, there will be 160,000. The first four values\n(indices 0-3) in the array will be the R, G, B, A values of the pixel at\n(0, 0). The second four values (indices 4-7) will contain the R, G, B, A\nvalues of the pixel at (1, 0). More generally, to set values for a pixel\nat (x, y):

\n
var d = pixelDensity();\nfor (var i = 0; i < d; i++) {\n  for (var j = 0; j < d; j++) {\n    // loop over\n    idx = 4 * ((y * d + j) * width * d + (x * d + i));\n    pixels[idx] = r;\n    pixels[idx+1] = g;\n    pixels[idx+2] = b;\n    pixels[idx+3] = a;\n  }\n}\n
\n



\nBefore accessing this array, the data must loaded with the loadPixels()\nfunction. After the array data has been modified, the updatePixels()\nfunction must be run to update the changes.

\n", + "line": 153, + "description": "

Array containing the values for all the pixels in the display window.\nThese values are numbers. This array is the size (include an appropriate\nfactor for pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. Retina and other\nhigh denisty displays may have more pixels (by a factor of\npixelDensity^2).\nFor example, if the image is 100x100 pixels, there will be 40,000. With\npixelDensity = 2, there will be 160,000. The first four values\n(indices 0-3) in the array will be the R, G, B, A values of the pixel at\n(0, 0). The second four values (indices 4-7) will contain the R, G, B, A\nvalues of the pixel at (1, 0). More generally, to set values for a pixel\nat (x, y):

\n
let d = pixelDensity();\nfor (let i = 0; i < d; i++) {\n  for (let j = 0; j < d; j++) {\n    // loop over\n    index = 4 * ((y * d + j) * width * d + (x * d + i));\n    pixels[index] = r;\n    pixels[index+1] = g;\n    pixels[index+2] = b;\n    pixels[index+3] = a;\n  }\n}\n
\n



\nBefore accessing this array, the data must loaded with the loadPixels()\nfunction. After the array data has been modified, the updatePixels()\nfunction must be run to update the changes.

\n", "itemtype": "property", "name": "pixels", "type": "Number[]", "example": [ - "\n
\n\nvar img = createImage(66, 66);\nimg.loadPixels();\nfor (var i = 0; i < img.width; i++) {\n for (var j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\n\n
\n
\n\nvar pink = color(255, 102, 204);\nvar img = createImage(66, 66);\nimg.loadPixels();\nfor (var i = 0; i < 4 * (width * height / 2); i += 4) {\n img.pixels[i] = red(pink);\n img.pixels[i + 1] = green(pink);\n img.pixels[i + 2] = blue(pink);\n img.pixels[i + 3] = alpha(pink);\n}\nimg.updatePixels();\nimage(img, 17, 17);\n\n
" + "\n
\n\nlet img = createImage(66, 66);\nimg.loadPixels();\nfor (let i = 0; i < img.width; i++) {\n for (let j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\n\n
\n
\n\nlet pink = color(255, 102, 204);\nlet img = createImage(66, 66);\nimg.loadPixels();\nfor (let i = 0; i < 4 * (width * height / 2); i += 4) {\n img.pixels[i] = red(pink);\n img.pixels[i + 1] = green(pink);\n img.pixels[i + 2] = blue(pink);\n img.pixels[i + 3] = alpha(pink);\n}\nimg.updatePixels();\nimage(img, 17, 17);\n\n
" ], "alt": "66x66 turquoise rect in center of canvas\n66x66 pink rect in center of canvas", "class": "p5.Image", @@ -9892,7 +10072,7 @@ module.exports={ }, { "file": "src/image/p5.Image.js", - "line": 222, + "line": 223, "description": "

Helper fxn for sharing pixel methods

\n", "class": "p5.Image", "module": "Image", @@ -9900,12 +10080,12 @@ module.exports={ }, { "file": "src/image/p5.Image.js", - "line": 231, + "line": 232, "description": "

Loads the pixels data for this image into the [pixels] attribute.

\n", "itemtype": "method", "name": "loadPixels", "example": [ - "\n
\nvar myImage;\nvar halfImage;\n\nfunction preload() {\n myImage = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n myImage.loadPixels();\n halfImage = 4 * width * height / 2;\n for (var i = 0; i < halfImage; i++) {\n myImage.pixels[i + halfImage] = myImage.pixels[i];\n }\n myImage.updatePixels();\n}\n\nfunction draw() {\n image(myImage, 0, 0);\n}\n
" + "\n
\nlet myImage;\nlet halfImage;\n\nfunction preload() {\n myImage = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n myImage.loadPixels();\n halfImage = 4 * myImage.width * myImage.height / 2;\n for (let i = 0; i < halfImage; i++) {\n myImage.pixels[i + halfImage] = myImage.pixels[i];\n }\n myImage.updatePixels();\n}\n\nfunction draw() {\n image(myImage, 0, 0, width, height);\n}\n
" ], "alt": "2 images of rocky mountains vertically stacked", "class": "p5.Image", @@ -9914,12 +10094,12 @@ module.exports={ }, { "file": "src/image/p5.Image.js", - "line": 267, + "line": 268, "description": "

Updates the backing canvas for this image with the contents of\nthe [pixels] array.

\n", "itemtype": "method", "name": "updatePixels", "example": [ - "\n
\nvar myImage;\nvar halfImage;\n\nfunction preload() {\n myImage = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n myImage.loadPixels();\n halfImage = 4 * width * height / 2;\n for (var i = 0; i < halfImage; i++) {\n myImage.pixels[i + halfImage] = myImage.pixels[i];\n }\n myImage.updatePixels();\n}\n\nfunction draw() {\n image(myImage, 0, 0);\n}\n
" + "\n
\nlet myImage;\nlet halfImage;\n\nfunction preload() {\n myImage = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n myImage.loadPixels();\n halfImage = 4 * myImage.width * myImage.height / 2;\n for (let i = 0; i < halfImage; i++) {\n myImage.pixels[i + halfImage] = myImage.pixels[i];\n }\n myImage.updatePixels();\n}\n\nfunction draw() {\n image(myImage, 0, 0, width, height);\n}\n
" ], "alt": "2 images of rocky mountains vertically stacked", "class": "p5.Image", @@ -9927,7 +10107,7 @@ module.exports={ "submodule": "Image", "overloads": [ { - "line": 267, + "line": 268, "params": [ { "name": "x", @@ -9952,58 +10132,90 @@ module.exports={ ] }, { - "line": 307, + "line": 308, "params": [] } ] }, { "file": "src/image/p5.Image.js", - "line": 315, - "description": "

Get a region of pixels from an image.

\n

If no params are passed, those whole image is returned,\nif x and y are the only params passed a single pixel is extracted\nif all params are passed a rectangle region is extracted and a p5.Image\nis returned.

\n

Returns undefined if the region is outside the bounds of the image

\n", + "line": 316, + "description": "

Get a region of pixels from an image.

\n

If no params are passed, the whole image is returned.\nIf x and y are the only params passed a single pixel is extracted.\nIf all params are passed a rectangle region is extracted and a p5.Image\nis returned.

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

x-coordinate of the pixel

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

y-coordinate of the pixel

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

width

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

height

\n", - "type": "Number", - "optional": true - } - ], "return": { - "description": "color of pixel at x,y in array format\n [R, G, B, A] or p5.Image", - "type": "Number[]|Color|p5.Image" + "description": "the rectangle p5.Image", + "type": "p5.Image" }, "example": [ - "\n
\nvar myImage;\nvar c;\n\nfunction preload() {\n myImage = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n background(myImage);\n noStroke();\n c = myImage.get(60, 90);\n fill(c);\n rect(25, 25, 50, 50);\n}\n\n//get() returns color here\n
" + "\n
\nlet myImage;\nlet c;\n\nfunction preload() {\n myImage = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n background(myImage);\n noStroke();\n c = myImage.get(60, 90);\n fill(c);\n rect(25, 25, 50, 50);\n}\n\n//get() returns color here\n
" ], "alt": "image of rocky mountains with 50x50 green rect in front", "class": "p5.Image", "module": "Image", - "submodule": "Image" + "submodule": "Image", + "overloads": [ + { + "line": 316, + "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

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

height

\n", + "type": "Number" + } + ], + "return": { + "description": "the rectangle p5.Image", + "type": "p5.Image" + } + }, + { + "line": 354, + "params": [], + "return": { + "description": "the whole p5.Image", + "type": "p5.Image" + } + }, + { + "line": 358, + "params": [ + { + "name": "x", + "description": "", + "type": "Number" + }, + { + "name": "y", + "description": "", + "type": "Number" + } + ], + "return": { + "description": "color of pixel at x,y in array format [R, G, B, A]", + "type": "Number[]" + } + } + ] }, { "file": "src/image/p5.Image.js", - "line": 360, + "line": 371, "description": "

Set the color of a single pixel or write an image into\nthis p5.Image.

\n

Note that for a large number of pixels this will\nbe slower than directly manipulating the pixels array\nand then calling updatePixels().

\n", "itemtype": "method", "name": "set", @@ -10025,7 +10237,7 @@ module.exports={ } ], "example": [ - "\n
\n\nvar img = createImage(66, 66);\nimg.loadPixels();\nfor (var i = 0; i < img.width; i++) {\n for (var j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102, (i % img.width) * 2));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\nimage(img, 34, 34);\n\n
" + "\n
\n\nlet img = createImage(66, 66);\nimg.loadPixels();\nfor (let i = 0; i < img.width; i++) {\n for (let j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102, (i % img.width) * 2));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\nimage(img, 34, 34);\n\n
" ], "alt": "2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas", "class": "p5.Image", @@ -10034,7 +10246,7 @@ module.exports={ }, { "file": "src/image/p5.Image.js", - "line": 398, + "line": 409, "description": "

Resize the image to a new width and height. To make the image scale\nproportionally, use 0 as the value for the wide or high parameter.\nFor instance, to make the width of an image 150 pixels, and change\nthe height using the same proportion, use resize(150, 0).

\n", "itemtype": "method", "name": "resize", @@ -10051,7 +10263,7 @@ module.exports={ } ], "example": [ - "\n
\nvar img;\n\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction draw() {\n image(img, 0, 0);\n}\n\nfunction mousePressed() {\n img.resize(50, 100);\n}\n
" + "\n
\nlet img;\n\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction draw() {\n image(img, 0, 0);\n}\n\nfunction mousePressed() {\n img.resize(50, 100);\n}\n
" ], "alt": "image of rocky mountains. zoomed in", "class": "p5.Image", @@ -10060,12 +10272,12 @@ module.exports={ }, { "file": "src/image/p5.Image.js", - "line": 483, + "line": 494, "description": "

Copies a region of pixels from one image to another. If no\nsrcImage is specified this is used as the source. If the source\nand destination regions aren't the same size, it will\nautomatically resize source pixels to fit the specified\ntarget region.

\n", "itemtype": "method", "name": "copy", "example": [ - "\n
\nvar photo;\nvar bricks;\nvar x;\nvar y;\n\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n x = bricks.width / 2;\n y = bricks.height / 2;\n photo.copy(bricks, 0, 0, x, y, 0, 0, x, y);\n image(photo, 0, 0);\n}\n
" + "\n
\nlet photo;\nlet bricks;\nlet x;\nlet y;\n\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n x = bricks.width / 2;\n y = bricks.height / 2;\n photo.copy(bricks, 0, 0, x, y, 0, 0, x, y);\n image(photo, 0, 0);\n}\n
" ], "alt": "image of rocky mountains and smaller image on top of bricks at top left", "class": "p5.Image", @@ -10073,7 +10285,7 @@ module.exports={ "submodule": "Image", "overloads": [ { - "line": 483, + "line": 494, "params": [ { "name": "srcImage", @@ -10123,7 +10335,7 @@ module.exports={ ] }, { - "line": 524, + "line": 535, "params": [ { "name": "sx", @@ -10171,7 +10383,7 @@ module.exports={ }, { "file": "src/image/p5.Image.js", - "line": 564, + "line": 575, "description": "

Masks part of an image from displaying by loading another\nimage and using it's alpha channel as an alpha channel for\nthis image.

\n", "itemtype": "method", "name": "mask", @@ -10183,7 +10395,7 @@ module.exports={ } ], "example": [ - "\n
\nvar photo, maskImage;\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n maskImage = loadImage('assets/mask2.png');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n photo.mask(maskImage);\n image(photo, 0, 0);\n}\n
" + "\n
\nlet photo, maskImage;\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n maskImage = loadImage('assets/mask2.png');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n photo.mask(maskImage);\n image(photo, 0, 0);\n}\n
" ], "alt": "image of rocky mountains with white at right\n\n\nhttp://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/", "class": "p5.Image", @@ -10192,7 +10404,7 @@ module.exports={ }, { "file": "src/image/p5.Image.js", - "line": 627, + "line": 638, "description": "

Applies an image filter to a p5.Image

\n", "itemtype": "method", "name": "filter", @@ -10210,7 +10422,7 @@ module.exports={ } ], "example": [ - "\n
\nvar photo1;\nvar photo2;\n\nfunction preload() {\n photo1 = loadImage('assets/rockies.jpg');\n photo2 = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n photo2.filter('gray');\n image(photo1, 0, 0);\n image(photo2, width / 2, 0);\n}\n
" + "\n
\nlet photo1;\nlet photo2;\n\nfunction preload() {\n photo1 = loadImage('assets/rockies.jpg');\n photo2 = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n photo2.filter(GRAY);\n image(photo1, 0, 0);\n image(photo2, width / 2, 0);\n}\n
" ], "alt": "2 images of rocky mountains left one in color, right in black and white", "class": "p5.Image", @@ -10219,12 +10431,12 @@ module.exports={ }, { "file": "src/image/p5.Image.js", - "line": 663, + "line": 674, "description": "

Copies a region of pixels from one image to another, using a specified\nblend mode to do the operation.

\n", "itemtype": "method", "name": "blend", "example": [ - "\n
\nvar mountains;\nvar bricks;\n\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
\n
\nvar mountains;\nvar bricks;\n\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
\n
\nvar mountains;\nvar bricks;\n\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
" + "\n
\nlet mountains;\nlet bricks;\n\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
\n
\nlet mountains;\nlet bricks;\n\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
\n
\nlet mountains;\nlet bricks;\n\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
" ], "alt": "image of rocky mountains. Brick images on left and right. Right overexposed\nimage of rockies. Brickwall images on left and right. Right mortar transparent\nimage of rockies. Brickwall images on left and right. Right translucent", "class": "p5.Image", @@ -10232,7 +10444,7 @@ module.exports={ "submodule": "Image", "overloads": [ { - "line": 663, + "line": 674, "params": [ { "name": "srcImage", @@ -10287,7 +10499,7 @@ module.exports={ ] }, { - "line": 742, + "line": 753, "params": [ { "name": "sx", @@ -10340,7 +10552,7 @@ module.exports={ }, { "file": "src/image/p5.Image.js", - "line": 785, + "line": 796, "description": "

Saves the image to a file and force the browser to download it.\nAccepts two strings for filename and file extension\nSupports png (default) and jpg.

\n", "itemtype": "method", "name": "save", @@ -10357,7 +10569,7 @@ module.exports={ } ], "example": [ - "\n
\nvar photo;\n\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n}\n\nfunction draw() {\n image(photo, 0, 0);\n}\n\nfunction keyTyped() {\n if (key === 's') {\n photo.save('photo', 'png');\n }\n}\n
" + "\n
\nlet photo;\n\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n}\n\nfunction draw() {\n image(photo, 0, 0);\n}\n\nfunction keyTyped() {\n if (key === 's') {\n photo.save('photo', 'png');\n }\n}\n
" ], "alt": "image of rocky mountains.", "class": "p5.Image", @@ -10367,12 +10579,12 @@ module.exports={ { "file": "src/image/pixels.js", "line": 14, - "description": "

Uint8ClampedArray\ncontaining the values for all the pixels in the display window.\nThese values are numbers. This array is the size (include an appropriate\nfactor for pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. Retina and other\nhigh density displays will have more pixels[] (by a factor of\npixelDensity^2).\nFor example, if the image is 100x100 pixels, there will be 40,000. On a\nretina display, there will be 160,000.\n

\nThe first four values (indices 0-3) in the array will be the R, G, B, A\nvalues of the pixel at (0, 0). The second four values (indices 4-7) will\ncontain the R, G, B, A values of the pixel at (1, 0). More generally, to\nset values for a pixel at (x, y):

\n
var d = pixelDensity();\nfor (var i = 0; i < d; i++) {\n  for (var j = 0; j < d; j++) {\n    // loop over\n    idx = 4 * ((y * d + j) * width * d + (x * d + i));\n    pixels[idx] = r;\n    pixels[idx+1] = g;\n    pixels[idx+2] = b;\n    pixels[idx+3] = a;\n  }\n}\n
\n

While the above method is complex, it is flexible enough to work with\nany pixelDensity. Note that set() will automatically take care of\nsetting all the appropriate values in pixels[] for a given (x, y) at\nany pixelDensity, but the performance may not be as fast when lots of\nmodifications are made to the pixel array.\n

\nBefore accessing this array, the data must loaded with the loadPixels()\nfunction. After the array data has been modified, the updatePixels()\nfunction must be run to update the changes.\n

\nNote that this is not a standard javascript array. This means that\nstandard javascript functions such as slice() or\narrayCopy() do not\nwork.

", + "description": "

Uint8ClampedArray\ncontaining the values for all the pixels in the display window.\nThese values are numbers. This array is the size (include an appropriate\nfactor for pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. Retina and other\nhigh density displays will have more pixels[] (by a factor of\npixelDensity^2).\nFor example, if the image is 100x100 pixels, there will be 40,000. On a\nretina display, there will be 160,000.\n

\nThe first four values (indices 0-3) in the array will be the R, G, B, A\nvalues of the pixel at (0, 0). The second four values (indices 4-7) will\ncontain the R, G, B, A values of the pixel at (1, 0). More generally, to\nset values for a pixel at (x, y):

\n
let d = pixelDensity();\nfor (let i = 0; i < d; i++) {\n  for (let j = 0; j < d; j++) {\n    // loop over\n    index = 4 * ((y * d + j) * width * d + (x * d + i));\n    pixels[index] = r;\n    pixels[index+1] = g;\n    pixels[index+2] = b;\n    pixels[index+3] = a;\n  }\n}\n
\n

While the above method is complex, it is flexible enough to work with\nany pixelDensity. Note that set() will automatically take care of\nsetting all the appropriate values in pixels[] for a given (x, y) at\nany pixelDensity, but the performance may not be as fast when lots of\nmodifications are made to the pixel array.\n

\nBefore accessing this array, the data must loaded with the loadPixels()\nfunction. After the array data has been modified, the updatePixels()\nfunction must be run to update the changes.\n

\nNote that this is not a standard javascript array. This means that\nstandard javascript functions such as slice() or\narrayCopy() do not\nwork.

", "itemtype": "property", "name": "pixels", "type": "Number[]", "example": [ - "\n
\n\nvar pink = color(255, 102, 204);\nloadPixels();\nvar d = pixelDensity();\nvar halfImage = 4 * (width * d) * (height / 2 * d);\nfor (var i = 0; i < halfImage; i += 4) {\n pixels[i] = red(pink);\n pixels[i + 1] = green(pink);\n pixels[i + 2] = blue(pink);\n pixels[i + 3] = alpha(pink);\n}\nupdatePixels();\n\n
" + "\n
\n\nlet pink = color(255, 102, 204);\nloadPixels();\nlet d = pixelDensity();\nlet halfImage = 4 * (width * d) * (height / 2 * d);\nfor (let i = 0; i < halfImage; i += 4) {\n pixels[i] = red(pink);\n pixels[i + 1] = green(pink);\n pixels[i + 2] = blue(pink);\n pixels[i + 3] = alpha(pink);\n}\nupdatePixels();\n\n
" ], "alt": "top half of canvas pink, bottom grey", "class": "p5", @@ -10386,7 +10598,7 @@ module.exports={ "itemtype": "method", "name": "blend", "example": [ - "\n
\nvar img0;\nvar img1;\n\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n}\n
\n
\nvar img0;\nvar img1;\n\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n}\n
\n
\nvar img0;\nvar img1;\n\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n}\n
" + "\n
\nlet img0;\nlet img1;\n\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n}\n
\n
\nlet img0;\nlet img1;\n\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n}\n
\n
\nlet img0;\nlet img1;\n\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n}\n
" ], "alt": "image of rocky mountains. Brick images on left and right. Right overexposed\nimage of rockies. Brickwall images on left and right. Right mortar transparent\nimage of rockies. Brickwall images on left and right. Right translucent", "class": "p5", @@ -10507,7 +10719,7 @@ module.exports={ "itemtype": "method", "name": "copy", "example": [ - "\n
\nvar img;\n\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n background(img);\n copy(img, 7, 22, 10, 10, 35, 25, 50, 50);\n stroke(255);\n noFill();\n // Rectangle shows area being copied\n rect(7, 22, 10, 10);\n}\n
" + "\n
\nlet img;\n\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n background(img);\n copy(img, 7, 22, 10, 10, 35, 25, 50, 50);\n stroke(255);\n noFill();\n // Rectangle shows area being copied\n rect(7, 22, 10, 10);\n}\n
" ], "alt": "image of rocky mountains. Brick images on left and right. Right overexposed\nimage of rockies. Brickwall images on left and right. Right mortar transparent\nimage of rockies. Brickwall images on left and right. Right translucent", "class": "p5", @@ -10631,7 +10843,7 @@ module.exports={ } ], "example": [ - "\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(THRESHOLD);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(GRAY);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(OPAQUE);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(INVERT);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(POSTERIZE, 3);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(DILATE);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(BLUR, 3);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(ERODE);\n}\n\n
" + "\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(THRESHOLD);\n}\n\n
\n\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(GRAY);\n}\n\n
\n\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(OPAQUE);\n}\n\n
\n\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(INVERT);\n}\n\n
\n\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(POSTERIZE, 3);\n}\n\n
\n\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(DILATE);\n}\n\n
\n\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(BLUR, 3);\n}\n\n
\n\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(ERODE);\n}\n\n
" ], "alt": "black and white image of a brick wall.\ngreyscale image of a brickwall\nimage of a brickwall\njade colored image of a brickwall\nred and pink image of a brickwall\nimage of a brickwall\nblurry image of a brickwall\nimage of a brickwall\nimage of a brickwall with less detail", "class": "p5", @@ -10641,55 +10853,87 @@ module.exports={ { "file": "src/image/pixels.js", "line": 415, - "description": "

Returns an array of [R,G,B,A] values for any pixel or grabs a section of\nan image. If no parameters are specified, the entire image is returned.\nUse the x and y parameters to get the value of one pixel. Get a section of\nthe display window by specifying additional w and h parameters. When\ngetting an image, the x and y parameters define the coordinates for the\nupper-left corner of the image, regardless of the current imageMode().\n

\nIf the pixel requested is outside of the image window, [0,0,0,255] is\nreturned. To get the numbers scaled according to the current color ranges\nand taking into account colorMode, use getColor instead of get.\n

\nGetting the color of a single pixel with get(x, y) is easy, but not as fast\nas grabbing the data directly from pixels[]. The equivalent statement to\nget(x, y) using pixels[] with pixel density d is\n\nvar x, y, d; // set these to the coordinates\nvar off = (y width + x) d * 4;\nvar components = [\n pixels[off],\n pixels[off + 1],\n pixels[off + 2],\n pixels[off + 3]\n];\nprint(components);\n\n

\nSee the reference for pixels[] for more information.

\n

If you want to extract an array of colors or a subimage from an p5.Image object,\ntake a look at p5.Image.get()

\n", + "description": "

Get a region of pixels, or a single pixel, from the canvas.

\n

Returns an array of [R,G,B,A] values for any pixel or grabs a section of\nan image. If no parameters are specified, the entire image is returned.\nUse the x and y parameters to get the value of one pixel. Get a section of\nthe display window by specifying additional w and h parameters. When\ngetting an image, the x and y parameters define the coordinates for the\nupper-left corner of the image, regardless of the current imageMode().\n

\nTo get the color components scaled according to the current color ranges\nand taking into account colorMode, use getColor instead of get.\n

\nGetting the color of a single pixel with get(x, y) is easy, but not as fast\nas grabbing the data directly from pixels[]. The equivalent statement to\nget(x, y) using pixels[] with pixel density d is

\n
let x, y, d; // set these to the coordinates\nlet off = (y * width + x) * d * 4;\nlet components = [\n  pixels[off],\n  pixels[off + 1],\n  pixels[off + 2],\n  pixels[off + 3]\n];\nprint(components);\n
\n



\n

See the reference for pixels[] for more information.

\n

If you want to extract an array of colors or a subimage from an p5.Image object,\ntake a look at p5.Image.get()

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

x-coordinate of the pixel

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

y-coordinate of the pixel

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

width

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

height

\n", - "type": "Number", - "optional": true - } - ], "return": { - "description": "values of pixel at x,y in array format\n [R, G, B, A] or p5.Image", - "type": "Number[]|p5.Image" + "description": "the rectangle p5.Image", + "type": "p5.Image" }, "example": [ - "\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n var c = get();\n image(c, width / 2, 0);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n var c = get(50, 90);\n fill(c);\n noStroke();\n rect(25, 25, 50, 50);\n}\n\n
" + "\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n let c = get();\n image(c, width / 2, 0);\n}\n\n
\n\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n let c = get(50, 90);\n fill(c);\n noStroke();\n rect(25, 25, 50, 50);\n}\n\n
" ], "alt": "2 images of the rocky mountains, side-by-side\nImage of the rocky mountains with 50x50 green rect in center of canvas", "class": "p5", "module": "Image", - "submodule": "Pixels" + "submodule": "Pixels", + "overloads": [ + { + "line": 415, + "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

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

height

\n", + "type": "Number" + } + ], + "return": { + "description": "the rectangle p5.Image", + "type": "p5.Image" + } + }, + { + "line": 491, + "params": [], + "return": { + "description": "the whole p5.Image", + "type": "p5.Image" + } + }, + { + "line": 495, + "params": [ + { + "name": "x", + "description": "", + "type": "Number" + }, + { + "name": "y", + "description": "", + "type": "Number" + } + ], + "return": { + "description": "color of pixel at x,y in array format [R, G, B, A]", + "type": "Number[]" + } + } + ] }, { "file": "src/image/pixels.js", - "line": 494, + "line": 506, "description": "

Loads the pixel data for the display window into the pixels[] array. This\nfunction must always be called before reading from or writing to pixels[].\nNote that only changes made with set() or direct manipulation of pixels[]\nwill occur.

\n", "itemtype": "method", "name": "loadPixels", "example": [ - "\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n image(img, 0, 0);\n var d = pixelDensity();\n var halfImage = 4 * (img.width * d) * (img.height * d / 2);\n loadPixels();\n for (var i = 0; i < halfImage; i++) {\n pixels[i + halfImage] = pixels[i];\n }\n updatePixels();\n}\n\n
" + "\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n image(img, 0, 0, width, height);\n let d = pixelDensity();\n let halfImage = 4 * (width * d) * (height * d / 2);\n loadPixels();\n for (let i = 0; i < halfImage; i++) {\n pixels[i + halfImage] = pixels[i];\n }\n updatePixels();\n}\n\n
" ], "alt": "two images of the rocky mountains. one on top, one on bottom of canvas.", "class": "p5", @@ -10698,7 +10942,7 @@ module.exports={ }, { "file": "src/image/pixels.js", - "line": 531, + "line": 543, "description": "

Changes the color of any pixel, or writes an image directly to the\ndisplay window.

\n

The x and y parameters specify the pixel to change and the c parameter\nspecifies the color value. This can be a p5.Color object, or [R, G, B, A]\npixel array. It can also be a single grayscale value.\nWhen setting an image, the x and y parameters define the coordinates for\nthe upper-left corner of the image, regardless of the current imageMode().\n

\n

\nAfter using set(), you must call updatePixels() for your changes to appear.\nThis should be called once all pixels have been set, and must be called before\ncalling .get() or drawing the image.\n

\n

Setting the color of a single pixel with set(x, y) is easy, but not as\nfast as putting the data directly into pixels[]. Setting the pixels[]\nvalues directly may be complicated when working with a retina display,\nbut will perform better when lots of pixels need to be set directly on\nevery loop.

\n

See the reference for pixels[] for more information.

", "itemtype": "method", "name": "set", @@ -10720,7 +10964,7 @@ module.exports={ } ], "example": [ - "\n
\n\nvar black = color(0);\nset(30, 20, black);\nset(85, 20, black);\nset(85, 75, black);\nset(30, 75, black);\nupdatePixels();\n\n
\n\n
\n\nfor (var i = 30; i < width - 15; i++) {\n for (var j = 20; j < height - 25; j++) {\n var c = color(204 - j, 153 - i, 0);\n set(i, j, c);\n }\n}\nupdatePixels();\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n set(0, 0, img);\n updatePixels();\n line(0, 0, width, height);\n line(0, height, width, 0);\n}\n\n
" + "\n
\n\nlet black = color(0);\nset(30, 20, black);\nset(85, 20, black);\nset(85, 75, black);\nset(30, 75, black);\nupdatePixels();\n\n
\n\n
\n\nfor (let i = 30; i < width - 15; i++) {\n for (let j = 20; j < height - 25; j++) {\n let c = color(204 - j, 153 - i, 0);\n set(i, j, c);\n }\n}\nupdatePixels();\n\n
\n\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n set(0, 0, img);\n updatePixels();\n line(0, 0, width, height);\n line(0, height, width, 0);\n}\n\n
" ], "alt": "4 black points in the shape of a square middle-right of canvas.\nsquare with orangey-brown gradient lightening at bottom right.\nimage of the rocky mountains. with lines like an 'x' through the center.", "class": "p5", @@ -10729,7 +10973,7 @@ module.exports={ }, { "file": "src/image/pixels.js", - "line": 605, + "line": 617, "description": "

Updates the display window with the data in the pixels[] array.\nUse in conjunction with loadPixels(). If you're only reading pixels from\nthe array, there's no need to call updatePixels() — updating is only\nnecessary to apply changes. updatePixels() should be called anytime the\npixels array is manipulated or set() is called, and only changes made with\nset() or direct changes to pixels[] will occur.

\n", "itemtype": "method", "name": "updatePixels", @@ -10760,7 +11004,7 @@ module.exports={ } ], "example": [ - "\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n image(img, 0, 0);\n var d = pixelDensity();\n var halfImage = 4 * (img.width * d) * (img.height * d / 2);\n loadPixels();\n for (var i = 0; i < halfImage; i++) {\n pixels[i + halfImage] = pixels[i];\n }\n updatePixels();\n}\n\n
" + "\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n image(img, 0, 0, width, height);\n let d = pixelDensity();\n let halfImage = 4 * (width * d) * (height * d / 2);\n loadPixels();\n for (let i = 0; i < halfImage; i++) {\n pixels[i + halfImage] = pixels[i];\n }\n updatePixels();\n}\n\n
" ], "alt": "two images of the rocky mountains. one on top, one on bottom of canvas.", "class": "p5", @@ -10778,7 +11022,7 @@ module.exports={ "type": "Object|Array" }, "example": [ - "\n\n

Calling loadJSON() inside preload() guarantees to complete the\noperation before setup() and draw() are called.

\n\n
\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\nvar earthquakes;\nfunction preload() {\n // Get the most recent earthquake in the database\n var url =\n 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +\n 'summary/all_day.geojson';\n earthquakes = loadJSON(url);\n}\n\nfunction setup() {\n noLoop();\n}\n\nfunction draw() {\n background(200);\n // Get the magnitude and name of the earthquake out of the loaded JSON\n var earthquakeMag = earthquakes.features[0].properties.mag;\n var earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n}\n
\n\n\n

Outside of preload(), you may supply a callback function to handle the\nobject:

\n
\nfunction setup() {\n noLoop();\n var url =\n 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +\n 'summary/all_day.geojson';\n loadJSON(url, drawEarthquake);\n}\n\nfunction draw() {\n background(200);\n}\n\nfunction drawEarthquake(earthquakes) {\n // Get the magnitude and name of the earthquake out of the loaded JSON\n var earthquakeMag = earthquakes.features[0].properties.mag;\n var earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n}\n
" + "\n\n

Calling loadJSON() inside preload() guarantees to complete the\noperation before setup() and draw() are called.

\n\n
\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\nlet earthquakes;\nfunction preload() {\n // Get the most recent earthquake in the database\n let url =\n 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +\n 'summary/all_day.geojson';\n earthquakes = loadJSON(url);\n}\n\nfunction setup() {\n noLoop();\n}\n\nfunction draw() {\n background(200);\n // Get the magnitude and name of the earthquake out of the loaded JSON\n let earthquakeMag = earthquakes.features[0].properties.mag;\n let earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n}\n
\n\n\n

Outside of preload(), you may supply a callback function to handle the\nobject:

\n
\nfunction setup() {\n noLoop();\n let url =\n 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +\n 'summary/all_day.geojson';\n loadJSON(url, drawEarthquake);\n}\n\nfunction draw() {\n background(200);\n}\n\nfunction drawEarthquake(earthquakes) {\n // Get the magnitude and name of the earthquake out of the loaded JSON\n let earthquakeMag = earthquakes.features[0].properties.mag;\n let earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n}\n
" ], "alt": "50x50 ellipse that changes from black to white depending on the current humidity\n50x50 ellipse that changes from black to white depending on the current humidity", "class": "p5", @@ -10911,7 +11155,7 @@ module.exports={ "type": "String[]" }, "example": [ - "\n\n

Calling loadStrings() inside preload() guarantees to complete the\noperation before setup() and draw() are called.

\n\n
\nvar result;\nfunction preload() {\n result = loadStrings('assets/test.txt');\n}\n\nfunction setup() {\n background(200);\n var ind = floor(random(result.length));\n text(result[ind], 10, 10, 80, 80);\n}\n
\n\n

Outside of preload(), you may supply a callback function to handle the\nobject:

\n\n
\nfunction setup() {\n loadStrings('assets/test.txt', pickString);\n}\n\nfunction pickString(result) {\n background(200);\n var ind = floor(random(result.length));\n text(result[ind], 10, 10, 80, 80);\n}\n
" + "\n\n

Calling loadStrings() inside preload() guarantees to complete the\noperation before setup() and draw() are called.

\n\n
\nlet result;\nfunction preload() {\n result = loadStrings('assets/test.txt');\n}\n\nfunction setup() {\n background(200);\n let ind = floor(random(result.length));\n text(result[ind], 10, 10, 80, 80);\n}\n
\n\n

Outside of preload(), you may supply a callback function to handle the\nobject:

\n\n
\nfunction setup() {\n loadStrings('assets/test.txt', pickString);\n}\n\nfunction pickString(result) {\n background(200);\n let ind = floor(random(result.length));\n text(result[ind], 10, 10, 80, 80);\n}\n
" ], "alt": "randomly generated text from a file, for example \"i smell like butter\"\nrandomly generated text from a file, for example \"i have three feet\"", "class": "p5", @@ -10929,7 +11173,7 @@ module.exports={ "type": "Object" }, "example": [ - "\n
\n\n// Given the following CSV file called \"mammals.csv\"\n// located in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n //the file can be remote\n //table = loadTable(\"http://p5js.org/reference/assets/mammals.csv\",\n // \"csv\", \"header\");\n}\n\nfunction setup() {\n //count the columns\n print(table.getRowCount() + ' total rows in table');\n print(table.getColumnCount() + ' total columns in table');\n\n print(table.getColumn('name'));\n //[\"Goat\", \"Leopard\", \"Zebra\"]\n\n //cycle through the table\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++) {\n print(table.getString(r, c));\n }\n}\n\n
" + "\n
\n\n// Given the following CSV file called \"mammals.csv\"\n// located in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n //the file can be remote\n //table = loadTable(\"http://p5js.org/reference/assets/mammals.csv\",\n // \"csv\", \"header\");\n}\n\nfunction setup() {\n //count the columns\n print(table.getRowCount() + ' total rows in table');\n print(table.getColumnCount() + ' total columns in table');\n\n print(table.getColumn('name'));\n //[\"Goat\", \"Leopard\", \"Zebra\"]\n\n //cycle through the table\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++) {\n print(table.getString(r, c));\n }\n}\n\n
" ], "alt": "randomly generated text from a file, for example \"i smell like butter\"\nrandomly generated text from a file, for example \"i have three feet\"", "class": "p5", @@ -10997,7 +11241,7 @@ module.exports={ }, { "file": "src/io/files.js", - "line": 626, + "line": 603, "description": "

Reads the contents of a file and creates an XML object with its values.\nIf the name of the file is used as the parameter, as in the above example,\nthe file must be located in the sketch directory/folder.

\n

Alternatively, the file maybe be loaded from anywhere on the local\ncomputer using an absolute path (something that starts with / on Unix and\nLinux, or a drive letter on Windows), or the filename parameter can be a\nURL for a file found on a network.

\n

This method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed. Calling loadXML() inside preload()\nguarantees to complete the operation before setup() and draw() are called.

\n

Outside of preload(), you may supply a callback function to handle the\nobject.

\n

This method is suitable for fetching files up to size of 64MB.

\n", "itemtype": "method", "name": "loadXML", @@ -11025,7 +11269,7 @@ module.exports={ "type": "Object" }, "example": [ - "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var children = xml.getChildren('animal');\n\n for (var i = 0; i < children.length; i++) {\n var id = children[i].getNum('id');\n var coloring = children[i].getString('species');\n var name = children[i].getContent();\n print(id + ', ' + coloring + ', ' + name);\n }\n}\n\n// Sketch prints:\n// 0, Capra hircus, Goat\n// 1, Panthera pardus, Leopard\n// 2, Equus zebra, Zebra\n
" + "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let children = xml.getChildren('animal');\n\n for (let i = 0; i < children.length; i++) {\n let id = children[i].getNum('id');\n let coloring = children[i].getString('species');\n let name = children[i].getContent();\n print(id + ', ' + coloring + ', ' + name);\n }\n}\n\n// Sketch prints:\n// 0, Capra hircus, Goat\n// 1, Panthera pardus, Leopard\n// 2, Equus zebra, Zebra\n
" ], "alt": "no image displayed", "class": "p5", @@ -11034,7 +11278,7 @@ module.exports={ }, { "file": "src/io/files.js", - "line": 737, + "line": 714, "description": "

This method is suitable for fetching files up to size of 64MB.

\n", "itemtype": "method", "name": "loadBytes", @@ -11062,7 +11306,7 @@ module.exports={ "type": "Object" }, "example": [ - "\n
\nvar data;\n\nfunction preload() {\n data = loadBytes('assets/mammals.xml');\n}\n\nfunction setup() {\n for (var i = 0; i < 5; i++) {\n console.log(data.bytes[i].toString(16));\n }\n}\n
" + "\n
\nlet data;\n\nfunction preload() {\n data = loadBytes('assets/mammals.xml');\n}\n\nfunction setup() {\n for (let i = 0; i < 5; i++) {\n console.log(data.bytes[i].toString(16));\n }\n}\n
" ], "alt": "no image displayed", "class": "p5", @@ -11071,7 +11315,7 @@ module.exports={ }, { "file": "src/io/files.js", - "line": 797, + "line": 774, "description": "

Method for executing an HTTP GET request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text. This is equivalent to\ncalling httpDo(path, 'GET'). The 'binary' datatype will return\na Blob object, and the 'arrayBuffer' datatype will return an ArrayBuffer\nwhich can be used to initialize typed arrays (such as Uint8Array).

\n", "itemtype": "method", "name": "httpGet", @@ -11080,14 +11324,14 @@ module.exports={ "type": "Promise" }, "example": [ - "\n
\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\nvar earthquakes;\nfunction preload() {\n // Get the most recent earthquake in the database\n var url =\n 'https://earthquake.usgs.gov/fdsnws/event/1/query?' +\n 'format=geojson&limit=1&orderby=time';\n httpGet(url, 'jsonp', false, function(response) {\n // when the HTTP request completes, populate the variable that holds the\n // earthquake data used in the visualization.\n earthquakes = response;\n });\n}\n\nfunction draw() {\n if (!earthquakes) {\n // Wait until the earthquake data has loaded before drawing.\n return;\n }\n background(200);\n // Get the magnitude and name of the earthquake out of the loaded JSON\n var earthquakeMag = earthquakes.features[0].properties.mag;\n var earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n noLoop();\n}\n
" + "\n
\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\nlet earthquakes;\nfunction preload() {\n // Get the most recent earthquake in the database\n let url =\n 'https://earthquake.usgs.gov/fdsnws/event/1/query?' +\n 'format=geojson&limit=1&orderby=time';\n httpGet(url, 'jsonp', false, function(response) {\n // when the HTTP request completes, populate the variable that holds the\n // earthquake data used in the visualization.\n earthquakes = response;\n });\n}\n\nfunction draw() {\n if (!earthquakes) {\n // Wait until the earthquake data has loaded before drawing.\n return;\n }\n background(200);\n // Get the magnitude and name of the earthquake out of the loaded JSON\n let earthquakeMag = earthquakes.features[0].properties.mag;\n let earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n noLoop();\n}\n
" ], "class": "p5", "module": "IO", "submodule": "Input", "overloads": [ { - "line": 797, + "line": 774, "params": [ { "name": "path", @@ -11125,7 +11369,7 @@ module.exports={ } }, { - "line": 851, + "line": 828, "params": [ { "name": "path", @@ -11156,7 +11400,7 @@ module.exports={ } }, { - "line": 859, + "line": 836, "params": [ { "name": "path", @@ -11184,7 +11428,7 @@ module.exports={ }, { "file": "src/io/files.js", - "line": 874, + "line": 851, "description": "

Method for executing an HTTP POST request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text. This is equivalent to\ncalling httpDo(path, 'POST').

\n", "itemtype": "method", "name": "httpPost", @@ -11193,14 +11437,14 @@ module.exports={ "type": "Promise" }, "example": [ - "\n
\n\n// Examples use jsonplaceholder.typicode.com for a Mock Data API\n\nvar url = 'https://jsonplaceholder.typicode.com/posts';\nvar postData = { userId: 1, title: 'p5 Clicked!', body: 'p5.js is way cool.' };\n\nfunction setup() {\n createCanvas(800, 800);\n}\n\nfunction mousePressed() {\n // Pick new random color values\n var r = random(255);\n var g = random(255);\n var b = random(255);\n\n httpPost(url, 'json', postData, function(result) {\n strokeWeight(2);\n stroke(r, g, b);\n fill(r, g, b, 127);\n ellipse(mouseX, mouseY, 200, 200);\n text(result.body, mouseX, mouseY);\n });\n}\n\n
\n\n\n
\nvar url = 'https://invalidURL'; // A bad URL that will cause errors\nvar postData = { title: 'p5 Clicked!', body: 'p5.js is way cool.' };\n\nfunction setup() {\n createCanvas(800, 800);\n}\n\nfunction mousePressed() {\n // Pick new random color values\n var r = random(255);\n var g = random(255);\n var b = random(255);\n\n httpPost(\n url,\n 'json',\n postData,\n function(result) {\n // ... won't be called\n },\n function(error) {\n strokeWeight(2);\n stroke(r, g, b);\n fill(r, g, b, 127);\n text(error.toString(), mouseX, mouseY);\n }\n );\n}\n
\n" + "\n
\n\n// Examples use jsonplaceholder.typicode.com for a Mock Data API\n\nlet url = 'https://jsonplaceholder.typicode.com/posts';\nlet postData = { userId: 1, title: 'p5 Clicked!', body: 'p5.js is way cool.' };\n\nfunction setup() {\n createCanvas(800, 800);\n}\n\nfunction mousePressed() {\n // Pick new random color values\n let r = random(255);\n let g = random(255);\n let b = random(255);\n\n httpPost(url, 'json', postData, function(result) {\n strokeWeight(2);\n stroke(r, g, b);\n fill(r, g, b, 127);\n ellipse(mouseX, mouseY, 200, 200);\n text(result.body, mouseX, mouseY);\n });\n}\n\n
\n\n\n
\nlet url = 'https://invalidURL'; // A bad URL that will cause errors\nlet postData = { title: 'p5 Clicked!', body: 'p5.js is way cool.' };\n\nfunction setup() {\n createCanvas(800, 800);\n}\n\nfunction mousePressed() {\n // Pick new random color values\n let r = random(255);\n let g = random(255);\n let b = random(255);\n\n httpPost(\n url,\n 'json',\n postData,\n function(result) {\n // ... won't be called\n },\n function(error) {\n strokeWeight(2);\n stroke(r, g, b);\n fill(r, g, b, 127);\n text(error.toString(), mouseX, mouseY);\n }\n );\n}\n
\n" ], "class": "p5", "module": "IO", "submodule": "Input", "overloads": [ { - "line": 874, + "line": 851, "params": [ { "name": "path", @@ -11238,7 +11482,7 @@ module.exports={ } }, { - "line": 956, + "line": 933, "params": [ { "name": "path", @@ -11269,7 +11513,7 @@ module.exports={ } }, { - "line": 964, + "line": 941, "params": [ { "name": "path", @@ -11297,7 +11541,7 @@ module.exports={ }, { "file": "src/io/files.js", - "line": 979, + "line": 956, "description": "

Method for executing an HTTP request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text.

\nFor more advanced use, you may also pass in the path as the first argument\nand a object as the second argument, the signature follows the one specified\nin the Fetch API specification.\nThis method is suitable for fetching files up to size of 64MB when "GET" is used.

\n", "itemtype": "method", "name": "httpDo", @@ -11306,14 +11550,14 @@ module.exports={ "type": "Promise" }, "example": [ - "\n
\n\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\n\n// displays an animation of all USGS earthquakes\nvar earthquakes;\nvar eqFeatureIndex = 0;\n\nfunction preload() {\n var url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson';\n httpDo(\n url,\n {\n method: 'GET',\n // Other Request options, like special headers for apis\n headers: { authorization: 'Bearer secretKey' }\n },\n function(res) {\n earthquakes = res;\n }\n );\n}\n\nfunction draw() {\n // wait until the data is loaded\n if (!earthquakes || !earthquakes.features[eqFeatureIndex]) {\n return;\n }\n clear();\n\n var feature = earthquakes.features[eqFeatureIndex];\n var mag = feature.properties.mag;\n var rad = mag / 11 * ((width + height) / 2);\n fill(255, 0, 0, 100);\n ellipse(width / 2 + random(-2, 2), height / 2 + random(-2, 2), rad, rad);\n\n if (eqFeatureIndex >= earthquakes.features.length) {\n eqFeatureIndex = 0;\n } else {\n eqFeatureIndex += 1;\n }\n}\n\n
" + "\n
\n\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\n\n// displays an animation of all USGS earthquakes\nlet earthquakes;\nlet eqFeatureIndex = 0;\n\nfunction preload() {\n let url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson';\n httpDo(\n url,\n {\n method: 'GET',\n // Other Request options, like special headers for apis\n headers: { authorization: 'Bearer secretKey' }\n },\n function(res) {\n earthquakes = res;\n }\n );\n}\n\nfunction draw() {\n // wait until the data is loaded\n if (!earthquakes || !earthquakes.features[eqFeatureIndex]) {\n return;\n }\n clear();\n\n let feature = earthquakes.features[eqFeatureIndex];\n let mag = feature.properties.mag;\n let rad = mag / 11 * ((width + height) / 2);\n fill(255, 0, 0, 100);\n ellipse(width / 2 + random(-2, 2), height / 2 + random(-2, 2), rad, rad);\n\n if (eqFeatureIndex >= earthquakes.features.length) {\n eqFeatureIndex = 0;\n } else {\n eqFeatureIndex += 1;\n }\n}\n\n
" ], "class": "p5", "module": "IO", "submodule": "Input", "overloads": [ { - "line": 979, + "line": 956, "params": [ { "name": "path", @@ -11357,7 +11601,7 @@ module.exports={ } }, { - "line": 1050, + "line": 1027, "params": [ { "name": "path", @@ -11391,7 +11635,7 @@ module.exports={ }, { "file": "src/io/files.js", - "line": 1203, + "line": 1186, "itemtype": "method", "name": "createWriter", "params": [ @@ -11412,7 +11656,7 @@ module.exports={ "type": "p5.PrintWriter" }, "example": [ - "\n
\n\ncreateButton('save')\n .position(10, 10)\n .mousePressed(function() {\n var writer = createWriter('squares.txt');\n for (var i = 0; i < 10; i++) {\n writer.print(i * i);\n }\n writer.close();\n writer.clear();\n });\n\n
" + "\n
\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n}\n\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n var writer = createWriter('squares.txt');\n for (let i = 0; i < 10; i++) {\n writer.print(i * i);\n }\n writer.close();\n writer.clear();\n }\n}\n\n
" ], "class": "p5", "module": "IO", @@ -11420,7 +11664,7 @@ module.exports={ }, { "file": "src/io/files.js", - "line": 1252, + "line": 1241, "description": "

Writes data to the PrintWriter stream

\n", "itemtype": "method", "name": "write", @@ -11432,7 +11676,7 @@ module.exports={ } ], "example": [ - "\n
\n\n// creates a file called 'newFile.txt'\nvar writer = createWriter('newFile.txt');\n// write 'Hello world!'' to the file\nwriter.write(['Hello world!']);\n// close the PrintWriter and save the file\nwriter.close();\n\n
\n
\n\n// creates a file called 'newFile2.txt'\nvar writer = createWriter('newFile2.txt');\n// write 'apples,bananas,123' to the file\nwriter.write(['apples', 'bananas', 123]);\n// close the PrintWriter and save the file\nwriter.close();\n\n
\n
\n\n// creates a file called 'newFile3.txt'\nvar writer = createWriter('newFile3.txt');\n// write 'My name is: Teddy' to the file\nwriter.write('My name is:');\nwriter.write(' Teddy');\n// close the PrintWriter and save the file\nwriter.close();\n\n
" + "\n
\n\n// creates a file called 'newFile.txt'\nlet writer = createWriter('newFile.txt');\n// write 'Hello world!'' to the file\nwriter.write(['Hello world!']);\n// close the PrintWriter and save the file\nwriter.close();\n\n
\n
\n\n// creates a file called 'newFile2.txt'\nlet writer = createWriter('newFile2.txt');\n// write 'apples,bananas,123' to the file\nwriter.write(['apples', 'bananas', 123]);\n// close the PrintWriter and save the file\nwriter.close();\n\n
\n
\n\n// creates a file called 'newFile3.txt'\nlet writer = createWriter('newFile3.txt');\n// write 'My name is: Teddy' to the file\nwriter.write('My name is:');\nwriter.write(' Teddy');\n// close the PrintWriter and save the file\nwriter.close();\n\n
" ], "class": "p5.PrintWriter", "module": "IO", @@ -11440,7 +11684,7 @@ module.exports={ }, { "file": "src/io/files.js", - "line": 1292, + "line": 1281, "description": "

Writes data to the PrintWriter stream, and adds a new line at the end

\n", "itemtype": "method", "name": "print", @@ -11452,7 +11696,7 @@ module.exports={ } ], "example": [ - "\n
\n\n// creates a file called 'newFile.txt'\nvar writer = createWriter('newFile.txt');\n// creates a file containing\n// My name is:\n// Teddy\nwriter.print('My name is:');\nwriter.print('Teddy');\n// close the PrintWriter and save the file\nwriter.close();\n\n
\n
\n\nvar writer;\n\nfunction setup() {\n createCanvas(400, 400);\n // create a PrintWriter\n writer = createWriter('newFile.txt');\n}\n\nfunction draw() {\n // print all mouseX and mouseY coordinates to the stream\n writer.print([mouseX, mouseY]);\n}\n\nfunction mouseClicked() {\n // close the PrintWriter and save the file\n writer.close();\n}\n\n
" + "\n
\n\n// creates a file called 'newFile.txt'\nlet writer = createWriter('newFile.txt');\n// creates a file containing\n// My name is:\n// Teddy\nwriter.print('My name is:');\nwriter.print('Teddy');\n// close the PrintWriter and save the file\nwriter.close();\n\n
\n
\n\nlet writer;\n\nfunction setup() {\n createCanvas(400, 400);\n // create a PrintWriter\n writer = createWriter('newFile.txt');\n}\n\nfunction draw() {\n // print all mouseX and mouseY coordinates to the stream\n writer.print([mouseX, mouseY]);\n}\n\nfunction mouseClicked() {\n // close the PrintWriter and save the file\n writer.close();\n}\n\n
" ], "class": "p5.PrintWriter", "module": "IO", @@ -11460,12 +11704,12 @@ module.exports={ }, { "file": "src/io/files.js", - "line": 1335, + "line": 1324, "description": "

Clears the data already written to the PrintWriter object

\n", "itemtype": "method", "name": "clear", "example": [ - "\n
\n// create writer object\nvar writer = createWriter('newFile.txt');\nwriter.write(['clear me']);\n// clear writer object here\nwriter.clear();\n// close writer\nwriter.close();\n
\n" + "\n
\n// create writer object\nlet writer = createWriter('newFile.txt');\nwriter.write(['clear me']);\n// clear writer object here\nwriter.clear();\n// close writer\nwriter.close();\n
\n" ], "class": "p5.PrintWriter", "module": "IO", @@ -11473,12 +11717,12 @@ module.exports={ }, { "file": "src/io/files.js", - "line": 1353, + "line": 1342, "description": "

Closes the PrintWriter

\n", "itemtype": "method", "name": "close", "example": [ - "\n
\n\n// create a file called 'newFile.txt'\nvar writer = createWriter('newFile.txt');\n// close the PrintWriter and save the file\nwriter.close();\n\n
\n
\n\n// create a file called 'newFile2.txt'\nvar writer = createWriter('newFile2.txt');\n// write some data to the file\nwriter.write([100, 101, 102]);\n// close the PrintWriter and save the file\nwriter.close();\n\n
" + "\n
\n\n// create a file called 'newFile.txt'\nlet writer = createWriter('newFile.txt');\n// close the PrintWriter and save the file\nwriter.close();\n\n
\n
\n\n// create a file called 'newFile2.txt'\nlet writer = createWriter('newFile2.txt');\n// write some data to the file\nwriter.write([100, 101, 102]);\n// close the PrintWriter and save the file\nwriter.close();\n\n
" ], "class": "p5.PrintWriter", "module": "IO", @@ -11486,8 +11730,8 @@ module.exports={ }, { "file": "src/io/files.js", - "line": 1402, - "description": "

Save an image, text, json, csv, wav, or html. Prompts download to\nthe client's computer. Note that it is not recommended to call save()\nwithin draw if it's looping, as the save() function will open a new save\ndialog every frame.

\n

The default behavior is to save the canvas as an image. You can\noptionally specify a filename.\nFor example:

\n
\n save();\n save('myCanvas.jpg'); // save a specific canvas with a filename\n 
\n\n

Alternately, the first parameter can be a pointer to a canvas\np5.Element, an Array of Strings,\nan Array of JSON, a JSON object, a p5.Table, a p5.Image, or a\np5.SoundFile (requires p5.sound). The second parameter is a filename\n(including extension). The third parameter is for options specific\nto this type of object. This method will save a file that fits the\ngiven paramaters. For example:

\n\n
\n // Saves canvas as an image\n save('myCanvas.jpg');\n\n // Saves pImage as a png image\n var img = createImage(10, 10);\n save(img, 'my.png');\n\n // Saves canvas as an image\n var cnv = createCanvas(100, 100);\n save(cnv, 'myCanvas.jpg');\n\n // Saves p5.Renderer object as an image\n var gb = createGraphics(100, 100);\n save(gb, 'myGraphics.jpg');\n\n var myTable = new p5.Table();\n\n // Saves table as html file\n save(myTable, 'myTable.html');\n\n // Comma Separated Values\n save(myTable, 'myTable.csv');\n\n // Tab Separated Values\n save(myTable, 'myTable.tsv');\n\n var myJSON = { a: 1, b: true };\n\n // Saves pretty JSON\n save(myJSON, 'my.json');\n\n // Optimizes JSON filesize\n save(myJSON, 'my.json', true);\n\n // Saves array of strings to a text file with line breaks after each item\n var arrayOfStrings = ['a', 'b'];\n save(arrayOfStrings, 'my.txt');\n 
", + "line": 1391, + "description": "

Save an image, text, json, csv, wav, or html. Prompts download to\nthe client's computer. Note that it is not recommended to call save()\nwithin draw if it's looping, as the save() function will open a new save\ndialog every frame.

\n

The default behavior is to save the canvas as an image. You can\noptionally specify a filename.\nFor example:

\n
\n save();\n save('myCanvas.jpg'); // save a specific canvas with a filename\n 
\n\n

Alternately, the first parameter can be a pointer to a canvas\np5.Element, an Array of Strings,\nan Array of JSON, a JSON object, a p5.Table, a p5.Image, or a\np5.SoundFile (requires p5.sound). The second parameter is a filename\n(including extension). The third parameter is for options specific\nto this type of object. This method will save a file that fits the\ngiven parameters. For example:

\n\n
\n // Saves canvas as an image\n save('myCanvas.jpg');\n\n // Saves pImage as a png image\n let img = createImage(10, 10);\n save(img, 'my.png');\n\n // Saves canvas as an image\n let cnv = createCanvas(100, 100);\n save(cnv, 'myCanvas.jpg');\n\n // Saves p5.Renderer object as an image\n let gb = createGraphics(100, 100);\n save(gb, 'myGraphics.jpg');\n\n let myTable = new p5.Table();\n\n // Saves table as html file\n save(myTable, 'myTable.html');\n\n // Comma Separated Values\n save(myTable, 'myTable.csv');\n\n // Tab Separated Values\n save(myTable, 'myTable.tsv');\n\n let myJSON = { a: 1, b: true };\n\n // Saves pretty JSON\n save(myJSON, 'my.json');\n\n // Optimizes JSON filesize\n save(myJSON, 'my.json', true);\n\n // Saves array of strings to a text file with line breaks after each item\n let arrayOfStrings = ['a', 'b'];\n save(arrayOfStrings, 'my.txt');\n 
", "itemtype": "method", "name": "save", "params": [ @@ -11516,7 +11760,7 @@ module.exports={ }, { "file": "src/io/files.js", - "line": 1530, + "line": 1519, "description": "

Writes the contents of an Array or a JSON object to a .json file.\nThe file saving process and location of the saved file will\nvary between web browsers.

\n", "itemtype": "method", "name": "saveJSON", @@ -11539,7 +11783,7 @@ module.exports={ } ], "example": [ - "\n
\n var json = {}; // new JSON Object\n\n json.id = 0;\n json.species = 'Panthera leo';\n json.name = 'Lion';\n\n createButton('save')\n .position(10, 10)\n .mousePressed(function() {\n saveJSON(json, 'lion.json');\n });\n\n // saves the following to a file called \"lion.json\":\n // {\n // \"id\": 0,\n // \"species\": \"Panthera leo\",\n // \"name\": \"Lion\"\n // }\n
" + "\n
\n let json = {}; // new JSON Object\n\n json.id = 0;\n json.species = 'Panthera leo';\n json.name = 'Lion';\n\n function setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n }\n\n function mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n saveJSON(json, 'lion.json');\n }\n }\n\n // saves the following to a file called \"lion.json\":\n // {\n // \"id\": 0,\n // \"species\": \"Panthera leo\",\n // \"name\": \"Lion\"\n // }\n
" ], "alt": "no image displayed", "class": "p5", @@ -11548,7 +11792,7 @@ module.exports={ }, { "file": "src/io/files.js", - "line": 1582, + "line": 1577, "description": "

Writes an array of Strings to a text file, one line per String.\nThe file saving process and location of the saved file will\nvary between web browsers.

\n", "itemtype": "method", "name": "saveStrings", @@ -11571,7 +11815,7 @@ module.exports={ } ], "example": [ - "\n
\n var words = 'apple bear cat dog';\n\n // .split() outputs an Array\n var list = split(words, ' ');\n\n createButton('save')\n .position(10, 10)\n .mousePressed(function() {\n saveStrings(list, 'nouns.txt');\n });\n\n // Saves the following to a file called 'nouns.txt':\n //\n // apple\n // bear\n // cat\n // dog\n
" + "\n
\n let words = 'apple bear cat dog';\n\n // .split() outputs an Array\n let list = split(words, ' ');\n\n function setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n }\n\n function mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n saveStrings(list, 'nouns.txt');\n }\n }\n\n // Saves the following to a file called 'nouns.txt':\n //\n // apple\n // bear\n // cat\n // dog\n
" ], "alt": "no image displayed", "class": "p5", @@ -11580,7 +11824,7 @@ module.exports={ }, { "file": "src/io/files.js", - "line": 1644, + "line": 1645, "description": "

Writes the contents of a Table object to a file. Defaults to a\ntext file with comma-separated-values ('csv') but can also\nuse tab separation ('tsv'), or generate an HTML table ('html').\nThe file saving process and location of the saved file will\nvary between web browsers.

\n", "itemtype": "method", "name": "saveTable", @@ -11603,7 +11847,7 @@ module.exports={ } ], "example": [ - "\n
\n var table;\n\n function setup() {\n table = new p5.Table();\n\n table.addColumn('id');\n table.addColumn('species');\n table.addColumn('name');\n\n var newRow = table.addRow();\n newRow.setNum('id', table.getRowCount() - 1);\n newRow.setString('species', 'Panthera leo');\n newRow.setString('name', 'Lion');\n\n // To save, un-comment next line then click 'run'\n // saveTable(table, 'new.csv');\n }\n\n // Saves the following to a file called 'new.csv':\n // id,species,name\n // 0,Panthera leo,Lion\n
" + "\n
\n let table;\n\n function setup() {\n table = new p5.Table();\n\n table.addColumn('id');\n table.addColumn('species');\n table.addColumn('name');\n\n let newRow = table.addRow();\n newRow.setNum('id', table.getRowCount() - 1);\n newRow.setString('species', 'Panthera leo');\n newRow.setString('name', 'Lion');\n\n // To save, un-comment next line then click 'run'\n // saveTable(table, 'new.csv');\n }\n\n // Saves the following to a file called 'new.csv':\n // id,species,name\n // 0,Panthera leo,Lion\n
" ], "alt": "no image displayed", "class": "p5", @@ -11657,7 +11901,7 @@ module.exports={ "type": "p5.TableRow" }, "example": [ - "\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //add a row\n var newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Canis Lupus');\n newRow.setString('name', 'Wolf');\n\n //print the results\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n \n
" + "\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //add a row\n let newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Canis Lupus');\n newRow.setString('name', 'Wolf');\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n \n
" ], "alt": "no image displayed", "class": "p5.Table", @@ -11678,7 +11922,7 @@ module.exports={ } ], "example": [ - "\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //remove the first row\n table.removeRow(0);\n\n //print the results\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n}\n\n
" + "\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //remove the first row\n table.removeRow(0);\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n}\n\n
" ], "alt": "no image displayed", "class": "p5.Table", @@ -11703,7 +11947,7 @@ module.exports={ "type": "p5.TableRow" }, "example": [ - "\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n var row = table.getRow(1);\n //print it column by column\n //note: a row is an object, not an array\n for (var c = 0; c < table.getColumnCount(); c++) {\n print(row.getString(c));\n }\n}\n\n
" + "\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n let row = table.getRow(1);\n //print it column by column\n //note: a row is an object, not an array\n for (let c = 0; c < table.getColumnCount(); c++) {\n print(row.getString(c));\n }\n}\n\n
" ], "alt": "no image displayed", "class": "p5.Table", @@ -11721,7 +11965,7 @@ module.exports={ "type": "p5.TableRow[]" }, "example": [ - "\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n var rows = table.getRows();\n\n //warning: rows is an array of objects\n for (var r = 0; r < rows.length; r++) {\n rows[r].set('name', 'Unicorn');\n }\n\n //print the results\n for (r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n \n
" + "\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n\n //warning: rows is an array of objects\n for (let r = 0; r < rows.length; r++) {\n rows[r].set('name', 'Unicorn');\n }\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n \n
" ], "alt": "no image displayed", "class": "p5.Table", @@ -11751,7 +11995,7 @@ module.exports={ "type": "p5.TableRow" }, "example": [ - "\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //find the animal named zebra\n var row = table.findRow('Zebra', 'name');\n //find the corresponding species\n print(row.getString('species'));\n }\n \n
" + "\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //find the animal named zebra\n let row = table.findRow('Zebra', 'name');\n //find the corresponding species\n print(row.getString('species'));\n }\n \n
" ], "alt": "no image displayed", "class": "p5.Table", @@ -11781,7 +12025,7 @@ module.exports={ "type": "p5.TableRow[]" }, "example": [ - "\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //add another goat\n var newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Scape Goat');\n newRow.setString('name', 'Goat');\n\n //find the rows containing animals named Goat\n var rows = table.findRows('Goat', 'name');\n print(rows.length + ' Goats found');\n }\n \n
" + "\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //add another goat\n let newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Scape Goat');\n newRow.setString('name', 'Goat');\n\n //find the rows containing animals named Goat\n let rows = table.findRows('Goat', 'name');\n print(rows.length + ' Goats found');\n }\n \n
" ], "alt": "no image displayed", "class": "p5.Table", @@ -11811,7 +12055,7 @@ module.exports={ "type": "p5.TableRow" }, "example": [ - "\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //Search using specified regex on a given column, return TableRow object\n var mammal = table.matchRow(new RegExp('ant'), 1);\n print(mammal.getString(1));\n //Output \"Panthera pardus\"\n}\n\n
\n" + "\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //Search using specified regex on a given column, return TableRow object\n let mammal = table.matchRow(new RegExp('ant'), 1);\n print(mammal.getString(1));\n //Output \"Panthera pardus\"\n}\n\n
\n" ], "class": "p5.Table", "module": "IO", @@ -11841,7 +12085,7 @@ module.exports={ "type": "p5.TableRow[]" }, "example": [ - "\n
\n\nvar table;\n\nfunction setup() {\n table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n var newRow = table.addRow();\n newRow.setString('name', 'Lion');\n newRow.setString('type', 'Mammal');\n\n newRow = table.addRow();\n newRow.setString('name', 'Snake');\n newRow.setString('type', 'Reptile');\n\n newRow = table.addRow();\n newRow.setString('name', 'Mosquito');\n newRow.setString('type', 'Insect');\n\n newRow = table.addRow();\n newRow.setString('name', 'Lizard');\n newRow.setString('type', 'Reptile');\n\n var rows = table.matchRows('R.*', 'type');\n for (var i = 0; i < rows.length; i++) {\n print(rows[i].getString('name') + ': ' + rows[i].getString('type'));\n }\n}\n// Sketch prints:\n// Snake: Reptile\n// Lizard: Reptile\n\n
" + "\n
\n\nlet table;\n\nfunction setup() {\n table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n let newRow = table.addRow();\n newRow.setString('name', 'Lion');\n newRow.setString('type', 'Mammal');\n\n newRow = table.addRow();\n newRow.setString('name', 'Snake');\n newRow.setString('type', 'Reptile');\n\n newRow = table.addRow();\n newRow.setString('name', 'Mosquito');\n newRow.setString('type', 'Insect');\n\n newRow = table.addRow();\n newRow.setString('name', 'Lizard');\n newRow.setString('type', 'Reptile');\n\n let rows = table.matchRows('R.*', 'type');\n for (let i = 0; i < rows.length; i++) {\n print(rows[i].getString('name') + ': ' + rows[i].getString('type'));\n }\n}\n// Sketch prints:\n// Snake: Reptile\n// Lizard: Reptile\n\n
" ], "class": "p5.Table", "module": "IO", @@ -11865,7 +12109,7 @@ module.exports={ "type": "Array" }, "example": [ - "\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //getColumn returns an array that can be printed directly\n print(table.getColumn('species'));\n //outputs [\"Capra hircus\", \"Panthera pardus\", \"Equus zebra\"]\n }\n \n
" + "\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //getColumn returns an array that can be printed directly\n print(table.getColumn('species'));\n //outputs [\"Capra hircus\", \"Panthera pardus\", \"Equus zebra\"]\n }\n \n
" ], "alt": "no image displayed", "class": "p5.Table", @@ -11879,7 +12123,7 @@ module.exports={ "itemtype": "method", "name": "clearRows", "example": [ - "\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.clearRows();\n print(table.getRowCount() + ' total rows in table');\n print(table.getColumnCount() + ' total columns in table');\n }\n \n
" + "\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.clearRows();\n print(table.getRowCount() + ' total rows in table');\n print(table.getColumnCount() + ' total columns in table');\n }\n \n
" ], "alt": "no image displayed", "class": "p5.Table", @@ -11901,7 +12145,7 @@ module.exports={ } ], "example": [ - "\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.addColumn('carnivore');\n table.set(0, 'carnivore', 'no');\n table.set(1, 'carnivore', 'yes');\n table.set(2, 'carnivore', 'no');\n\n //print the results\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n \n
" + "\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.addColumn('carnivore');\n table.set(0, 'carnivore', 'no');\n table.set(1, 'carnivore', 'yes');\n table.set(2, 'carnivore', 'no');\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n \n
" ], "alt": "no image displayed", "class": "p5.Table", @@ -11919,7 +12163,7 @@ module.exports={ "type": "Integer" }, "example": [ - "\n
\n \n // given the cvs file \"blobs.csv\" in /assets directory\n // ID, Name, Flavor, Shape, Color\n // Blob1, Blobby, Sweet, Blob, Pink\n // Blob2, Saddy, Savory, Blob, Blue\n\n var table;\n\n function preload() {\n table = loadTable('assets/blobs.csv');\n }\n\n function setup() {\n createCanvas(200, 100);\n textAlign(CENTER);\n background(255);\n }\n\n function draw() {\n var numOfColumn = table.getColumnCount();\n text('There are ' + numOfColumn + ' columns in the table.', 100, 50);\n }\n \n
" + "\n
\n \n // given the cvs file \"blobs.csv\" in /assets directory\n // ID, Name, Flavor, Shape, Color\n // Blob1, Blobby, Sweet, Blob, Pink\n // Blob2, Saddy, Savory, Blob, Blue\n\n let table;\n\n function preload() {\n table = loadTable('assets/blobs.csv');\n }\n\n function setup() {\n createCanvas(200, 100);\n textAlign(CENTER);\n background(255);\n }\n\n function draw() {\n let numOfColumn = table.getColumnCount();\n text('There are ' + numOfColumn + ' columns in the table.', 100, 50);\n }\n \n
" ], "class": "p5.Table", "module": "IO", @@ -11936,7 +12180,7 @@ module.exports={ "type": "Integer" }, "example": [ - "\n
\n \n // given the cvs file \"blobs.csv\" in /assets directory\n //\n // ID, Name, Flavor, Shape, Color\n // Blob1, Blobby, Sweet, Blob, Pink\n // Blob2, Saddy, Savory, Blob, Blue\n\n var table;\n\n function preload() {\n table = loadTable('assets/blobs.csv');\n }\n\n function setup() {\n createCanvas(200, 100);\n textAlign(CENTER);\n background(255);\n }\n\n function draw() {\n text('There are ' + table.getRowCount() + ' rows in the table.', 100, 50);\n }\n \n
" + "\n
\n \n // given the cvs file \"blobs.csv\" in /assets directory\n //\n // ID, Name, Flavor, Shape, Color\n // Blob1, Blobby, Sweet, Blob, Pink\n // Blob2, Saddy, Savory, Blob, Blue\n\n let table;\n\n function preload() {\n table = loadTable('assets/blobs.csv');\n }\n\n function setup() {\n createCanvas(200, 100);\n textAlign(CENTER);\n background(255);\n }\n\n function draw() {\n text('There are ' + table.getRowCount() + ' rows in the table.', 100, 50);\n }\n \n
" ], "class": "p5.Table", "module": "IO", @@ -11962,7 +12206,7 @@ module.exports={ } ], "example": [ - "\n
\n function setup() {\n var table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n var newRow = table.addRow();\n newRow.setString('name', ' $Lion ,');\n newRow.setString('type', ',,,Mammal');\n\n newRow = table.addRow();\n newRow.setString('name', '$Snake ');\n newRow.setString('type', ',,,Reptile');\n\n table.removeTokens(',$ ');\n print(table.getArray());\n }\n\n // prints:\n // 0 \"Lion\" \"Mamal\"\n // 1 \"Snake\" \"Reptile\"\n
" + "\n
\n function setup() {\n let table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n let newRow = table.addRow();\n newRow.setString('name', ' $Lion ,');\n newRow.setString('type', ',,,Mammal');\n\n newRow = table.addRow();\n newRow.setString('name', '$Snake ');\n newRow.setString('type', ',,,Reptile');\n\n table.removeTokens(',$ ');\n print(table.getArray());\n }\n\n // prints:\n // 0 \"Lion\" \"Mamal\"\n // 1 \"Snake\" \"Reptile\"\n
" ], "class": "p5.Table", "module": "IO", @@ -11983,7 +12227,7 @@ module.exports={ } ], "example": [ - "\n
\n function setup() {\n var table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n var newRow = table.addRow();\n newRow.setString('name', ' Lion ,');\n newRow.setString('type', ' Mammal ');\n\n newRow = table.addRow();\n newRow.setString('name', ' Snake ');\n newRow.setString('type', ' Reptile ');\n\n table.trim();\n print(table.getArray());\n }\n\n // prints:\n // 0 \"Lion\" \"Mamal\"\n // 1 \"Snake\" \"Reptile\"\n
" + "\n
\n function setup() {\n let table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n let newRow = table.addRow();\n newRow.setString('name', ' Lion ,');\n newRow.setString('type', ' Mammal ');\n\n newRow = table.addRow();\n newRow.setString('name', ' Snake ');\n newRow.setString('type', ' Reptile ');\n\n table.trim();\n print(table.getArray());\n }\n\n // prints:\n // 0 \"Lion\" \"Mamal\"\n // 1 \"Snake\" \"Reptile\"\n
" ], "class": "p5.Table", "module": "IO", @@ -12003,7 +12247,7 @@ module.exports={ } ], "example": [ - "\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.removeColumn('id');\n print(table.getColumnCount());\n }\n \n
" + "\n
\n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.removeColumn('id');\n print(table.getColumnCount());\n }\n \n
" ], "alt": "no image displayed", "class": "p5.Table", @@ -12034,7 +12278,7 @@ module.exports={ } ], "example": [ - "\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n table.set(0, 'species', 'Canis Lupus');\n table.set(0, 'name', 'Wolf');\n\n //print the results\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n}\n\n
" + "\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n table.set(0, 'species', 'Canis Lupus');\n table.set(0, 'name', 'Wolf');\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n}\n\n
" ], "alt": "no image displayed", "class": "p5.Table", @@ -12065,7 +12309,7 @@ module.exports={ } ], "example": [ - "\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n table.setNum(1, 'id', 1);\n\n print(table.getColumn(0));\n //[\"0\", 1, \"2\"]\n}\n\n
" + "\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n table.setNum(1, 'id', 1);\n\n print(table.getColumn(0));\n //[\"0\", 1, \"2\"]\n}\n\n
" ], "alt": "no image displayed", "class": "p5.Table", @@ -12096,7 +12340,7 @@ module.exports={ } ], "example": [ - "\n
\n// Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //add a row\n var newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Canis Lupus');\n newRow.setString('name', 'Wolf');\n\n print(table.getArray());\n}\n
" + "\n
\n// Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //add a row\n let newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Canis Lupus');\n newRow.setString('name', 'Wolf');\n\n print(table.getArray());\n}\n
" ], "alt": "no image displayed", "class": "p5.Table", @@ -12126,7 +12370,7 @@ module.exports={ "type": "String|Number" }, "example": [ - "\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.get(0, 1));\n //Capra hircus\n print(table.get(0, 'species'));\n //Capra hircus\n}\n\n
" + "\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.get(0, 1));\n //Capra hircus\n print(table.get(0, 'species'));\n //Capra hircus\n}\n\n
" ], "alt": "no image displayed", "class": "p5.Table", @@ -12156,7 +12400,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.getNum(1, 0) + 100);\n //id 1 + 100 = 101\n}\n\n
" + "\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.getNum(1, 0) + 100);\n //id 1 + 100 = 101\n}\n\n
" ], "alt": "no image displayed", "class": "p5.Table", @@ -12186,7 +12430,7 @@ module.exports={ "type": "String" }, "example": [ - "\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n // table is comma separated value \"CSV\"\n // and has specifiying header for column labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.getString(0, 0)); // 0\n print(table.getString(0, 1)); // Capra hircus\n print(table.getString(0, 2)); // Goat\n print(table.getString(1, 0)); // 1\n print(table.getString(1, 1)); // Panthera pardus\n print(table.getString(1, 2)); // Leopard\n print(table.getString(2, 0)); // 2\n print(table.getString(2, 1)); // Equus zebra\n print(table.getString(2, 2)); // Zebra\n}\n\n
" + "\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n // table is comma separated value \"CSV\"\n // and has specifiying header for column labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.getString(0, 0)); // 0\n print(table.getString(0, 1)); // Capra hircus\n print(table.getString(0, 2)); // Goat\n print(table.getString(1, 0)); // 1\n print(table.getString(1, 1)); // Panthera pardus\n print(table.getString(1, 2)); // Leopard\n print(table.getString(2, 0)); // 2\n print(table.getString(2, 1)); // Equus zebra\n print(table.getString(2, 2)); // Zebra\n}\n\n
" ], "alt": "no image displayed", "class": "p5.Table", @@ -12212,7 +12456,7 @@ module.exports={ "type": "Object" }, "example": [ - "\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n var tableObject = table.getObject();\n\n print(tableObject);\n //outputs an object\n}\n\n
" + "\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n let tableObject = table.getObject();\n\n print(tableObject);\n //outputs an object\n}\n\n
" ], "alt": "no image displayed", "class": "p5.Table", @@ -12230,7 +12474,7 @@ module.exports={ "type": "Array" }, "example": [ - "\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leoperd\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n // table is comma separated value \"CSV\"\n // and has specifiying header for column labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n var tableArray = table.getArray();\n for (var i = 0; i < tableArray.length; i++) {\n print(tableArray[i]);\n }\n}\n\n
" + "\n
\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leoperd\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n // table is comma separated value \"CSV\"\n // and has specifiying header for column labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n let tableArray = table.getArray();\n for (let i = 0; i < tableArray.length; i++) {\n print(tableArray[i]);\n }\n}\n\n
" ], "alt": "no image displayed", "class": "p5.Table", @@ -12256,7 +12500,7 @@ module.exports={ } ], "example": [ - "\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n var rows = table.getRows();\n for (var r = 0; r < rows.length; r++) {\n rows[r].set('name', 'Unicorn');\n }\n\n //print the results\n print(table.getArray());\n }\n
" + "\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n rows[r].set('name', 'Unicorn');\n }\n\n //print the results\n print(table.getArray());\n }\n
" ], "alt": "no image displayed", "class": "p5.TableRow", @@ -12282,7 +12526,7 @@ module.exports={ } ], "example": [ - "\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n var rows = table.getRows();\n for (var r = 0; r < rows.length; r++) {\n rows[r].setNum('id', r + 10);\n }\n\n print(table.getArray());\n }\n
" + "\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n rows[r].setNum('id', r + 10);\n }\n\n print(table.getArray());\n }\n
" ], "alt": "no image displayed", "class": "p5.TableRow", @@ -12308,7 +12552,7 @@ module.exports={ } ], "example": [ - "\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n var rows = table.getRows();\n for (var r = 0; r < rows.length; r++) {\n var name = rows[r].getString('name');\n rows[r].setString('name', 'A ' + name + ' named George');\n }\n\n print(table.getArray());\n }\n
" + "\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n let name = rows[r].getString('name');\n rows[r].setString('name', 'A ' + name + ' named George');\n }\n\n print(table.getArray());\n }\n
" ], "alt": "no image displayed", "class": "p5.TableRow", @@ -12333,7 +12577,7 @@ module.exports={ "type": "String|Number" }, "example": [ - "\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n var names = [];\n var rows = table.getRows();\n for (var r = 0; r < rows.length; r++) {\n names.push(rows[r].get('name'));\n }\n\n print(names);\n }\n
" + "\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let names = [];\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n names.push(rows[r].get('name'));\n }\n\n print(names);\n }\n
" ], "alt": "no image displayed", "class": "p5.TableRow", @@ -12358,7 +12602,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n var rows = table.getRows();\n var minId = Infinity;\n var maxId = -Infinity;\n for (var r = 0; r < rows.length; r++) {\n var id = rows[r].getNum('id');\n minId = min(minId, id);\n maxId = min(maxId, id);\n }\n print('minimum id = ' + minId + ', maximum id = ' + maxId);\n }\n
" + "\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n let minId = Infinity;\n let maxId = -Infinity;\n for (let r = 0; r < rows.length; r++) {\n let id = rows[r].getNum('id');\n minId = min(minId, id);\n maxId = min(maxId, id);\n }\n print('minimum id = ' + minId + ', maximum id = ' + maxId);\n }\n
" ], "alt": "no image displayed", "class": "p5.TableRow", @@ -12383,7 +12627,7 @@ module.exports={ "type": "String" }, "example": [ - "\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n var rows = table.getRows();\n var longest = '';\n for (var r = 0; r < rows.length; r++) {\n var species = rows[r].getString('species');\n if (longest.length < species.length) {\n longest = species;\n }\n }\n\n print('longest: ' + longest);\n }\n
" + "\n
\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n let longest = '';\n for (let r = 0; r < rows.length; r++) {\n let species = rows[r].getString('species');\n if (longest.length < species.length) {\n longest = species;\n }\n }\n\n print('longest: ' + longest);\n }\n
" ], "alt": "no image displayed", "class": "p5.TableRow", @@ -12392,7 +12636,7 @@ module.exports={ }, { "file": "src/io/p5.XML.js", - "line": 64, + "line": 65, "description": "

Gets a copy of the element's parent. Returns the parent as another\np5.XML object.

\n", "itemtype": "method", "name": "getParent", @@ -12401,7 +12645,7 @@ module.exports={ "type": "p5.XML" }, "example": [ - "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var children = xml.getChildren('animal');\n var parent = children[1].getParent();\n print(parent.getName());\n}\n\n// Sketch prints:\n// mammals\n
" + "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let children = xml.getChildren('animal');\n let parent = children[1].getParent();\n print(parent.getName());\n}\n\n// Sketch prints:\n// mammals\n
" ], "class": "p5.XML", "module": "IO", @@ -12409,7 +12653,7 @@ module.exports={ }, { "file": "src/io/p5.XML.js", - "line": 102, + "line": 103, "description": "

Gets the element's full name, which is returned as a String.

\n", "itemtype": "method", "name": "getName", @@ -12418,7 +12662,7 @@ module.exports={ "type": "String" }, "example": [ - "<animal\n
\n // The following short XML file called \"mammals.xml\" is parsed\n // in the code below.\n //\n // \n // <mammals>\n // <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n // <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n // <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n // </mammals>\n\n var xml;\n\n function preload() {\n xml = loadXML('assets/mammals.xml');\n }\n\n function setup() {\n print(xml.getName());\n }\n\n // Sketch prints:\n // mammals\n
" + "<animal\n
\n // The following short XML file called \"mammals.xml\" is parsed\n // in the code below.\n //\n // \n // <mammals>\n // <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n // <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n // <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n // </mammals>\n\n let xml;\n\n function preload() {\n xml = loadXML('assets/mammals.xml');\n }\n\n function setup() {\n print(xml.getName());\n }\n\n // Sketch prints:\n // mammals\n
" ], "class": "p5.XML", "module": "IO", @@ -12426,7 +12670,7 @@ module.exports={ }, { "file": "src/io/p5.XML.js", - "line": 137, + "line": 138, "description": "

Sets the element's name, which is specified as a String.

\n", "itemtype": "method", "name": "setName", @@ -12438,7 +12682,7 @@ module.exports={ } ], "example": [ - "<animal\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.getName());\n xml.setName('fish');\n print(xml.getName());\n}\n\n// Sketch prints:\n// mammals\n// fish\n
" + "<animal\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.getName());\n xml.setName('fish');\n print(xml.getName());\n}\n\n// Sketch prints:\n// mammals\n// fish\n
" ], "class": "p5.XML", "module": "IO", @@ -12446,7 +12690,7 @@ module.exports={ }, { "file": "src/io/p5.XML.js", - "line": 175, + "line": 184, "description": "

Checks whether or not the element has any children, and returns the result\nas a boolean.

\n", "itemtype": "method", "name": "hasChildren", @@ -12455,7 +12699,7 @@ module.exports={ "type": "Boolean" }, "example": [ - "<animal\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.hasChildren());\n}\n\n// Sketch prints:\n// true\n
" + "<animal\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.hasChildren());\n}\n\n// Sketch prints:\n// true\n
" ], "class": "p5.XML", "module": "IO", @@ -12463,7 +12707,7 @@ module.exports={ }, { "file": "src/io/p5.XML.js", - "line": 211, + "line": 220, "description": "

Get the names of all of the element's children, and returns the names as an\narray of Strings. This is the same as looping through and calling getName()\non each child element individually.

\n", "itemtype": "method", "name": "listChildren", @@ -12472,7 +12716,7 @@ module.exports={ "type": "String[]" }, "example": [ - "<animal\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.listChildren());\n}\n\n// Sketch prints:\n// [\"animal\", \"animal\", \"animal\"]\n
" + "<animal\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.listChildren());\n}\n\n// Sketch prints:\n// [\"animal\", \"animal\", \"animal\"]\n
" ], "class": "p5.XML", "module": "IO", @@ -12480,7 +12724,7 @@ module.exports={ }, { "file": "src/io/p5.XML.js", - "line": 250, + "line": 261, "description": "

Returns all of the element's children as an array of p5.XML objects. When\nthe name parameter is specified, then it will return all children that match\nthat name.

\n", "itemtype": "method", "name": "getChildren", @@ -12497,7 +12741,7 @@ module.exports={ "type": "p5.XML[]" }, "example": [ - "<animal\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var animals = xml.getChildren('animal');\n\n for (var i = 0; i < animals.length; i++) {\n print(animals[i].getContent());\n }\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Leopard\"\n// \"Zebra\"\n
" + "<animal\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let animals = xml.getChildren('animal');\n\n for (let i = 0; i < animals.length; i++) {\n print(animals[i].getContent());\n }\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Leopard\"\n// \"Zebra\"\n
" ], "class": "p5.XML", "module": "IO", @@ -12505,7 +12749,7 @@ module.exports={ }, { "file": "src/io/p5.XML.js", - "line": 300, + "line": 317, "description": "

Returns the first of the element's children that matches the name parameter\nor the child of the given index.It returns undefined if no matching\nchild is found.

\n", "itemtype": "method", "name": "getChild", @@ -12521,7 +12765,7 @@ module.exports={ "type": "p5.XML" }, "example": [ - "<animal\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n
\n
\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var secondChild = xml.getChild(1);\n print(secondChild.getContent());\n}\n\n// Sketch prints:\n// \"Leopard\"\n
" + "<animal\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n
\n
\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let secondChild = xml.getChild(1);\n print(secondChild.getContent());\n}\n\n// Sketch prints:\n// \"Leopard\"\n
" ], "class": "p5.XML", "module": "IO", @@ -12529,7 +12773,7 @@ module.exports={ }, { "file": "src/io/p5.XML.js", - "line": 361, + "line": 378, "description": "

Appends a new child to the element. The child can be specified with\neither a String, which will be used as the new tag's name, or as a\nreference to an existing p5.XML object.\nA reference to the newly created child is returned as an p5.XML object.

\n", "itemtype": "method", "name": "addChild", @@ -12541,7 +12785,7 @@ module.exports={ } ], "example": [ - "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var child = new p5.XML();\n child.setAttribute('id', '3');\n child.setAttribute('species', 'Ornithorhynchus anatinus');\n child.setContent('Platypus');\n xml.addChild(child);\n\n var animals = xml.getChildren('animal');\n print(animals[animals.length - 1].getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Leopard\"\n// \"Zebra\"\n
" + "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let child = new p5.XML();\n child.setName('animal');\n child.setAttribute('id', '3');\n child.setAttribute('species', 'Ornithorhynchus anatinus');\n child.setContent('Platypus');\n xml.addChild(child);\n\n let animals = xml.getChildren('animal');\n print(animals[animals.length - 1].getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Leopard\"\n// \"Zebra\"\n
" ], "class": "p5.XML", "module": "IO", @@ -12549,7 +12793,7 @@ module.exports={ }, { "file": "src/io/p5.XML.js", - "line": 412, + "line": 430, "description": "

Removes the element specified by name or index.

\n", "itemtype": "method", "name": "removeChild", @@ -12561,7 +12805,7 @@ module.exports={ } ], "example": [ - "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n xml.removeChild('animal');\n var children = xml.getChildren();\n for (var i = 0; i < children.length; i++) {\n print(children[i].getContent());\n }\n}\n\n// Sketch prints:\n// \"Leopard\"\n// \"Zebra\"\n
\n
\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n xml.removeChild(1);\n var children = xml.getChildren();\n for (var i = 0; i < children.length; i++) {\n print(children[i].getContent());\n }\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Zebra\"\n
" + "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n xml.removeChild('animal');\n let children = xml.getChildren();\n for (let i = 0; i < children.length; i++) {\n print(children[i].getContent());\n }\n}\n\n// Sketch prints:\n// \"Leopard\"\n// \"Zebra\"\n
\n
\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n xml.removeChild(1);\n let children = xml.getChildren();\n for (let i = 0; i < children.length; i++) {\n print(children[i].getContent());\n }\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Zebra\"\n
" ], "class": "p5.XML", "module": "IO", @@ -12569,7 +12813,7 @@ module.exports={ }, { "file": "src/io/p5.XML.js", - "line": 484, + "line": 502, "description": "

Counts the specified element's number of attributes, returned as an Number.

\n", "itemtype": "method", "name": "getAttributeCount", @@ -12578,7 +12822,7 @@ module.exports={ "type": "Integer" }, "example": [ - "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getAttributeCount());\n}\n\n// Sketch prints:\n// 2\n
" + "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.getAttributeCount());\n}\n\n// Sketch prints:\n// 2\n
" ], "class": "p5.XML", "module": "IO", @@ -12586,7 +12830,7 @@ module.exports={ }, { "file": "src/io/p5.XML.js", - "line": 520, + "line": 538, "description": "

Gets all of the specified element's attributes, and returns them as an\narray of Strings.

\n", "itemtype": "method", "name": "listAttributes", @@ -12595,7 +12839,7 @@ module.exports={ "type": "String[]" }, "example": [ - "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.listAttributes());\n}\n\n// Sketch prints:\n// [\"id\", \"species\"]\n
" + "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.listAttributes());\n}\n\n// Sketch prints:\n// [\"id\", \"species\"]\n
" ], "class": "p5.XML", "module": "IO", @@ -12603,7 +12847,7 @@ module.exports={ }, { "file": "src/io/p5.XML.js", - "line": 557, + "line": 580, "description": "

Checks whether or not an element has the specified attribute.

\n", "itemtype": "method", "name": "hasAttribute", @@ -12619,7 +12863,7 @@ module.exports={ "type": "Boolean" }, "example": [ - "\n
\n // The following short XML file called \"mammals.xml\" is parsed\n // in the code below.\n //\n // \n // <mammals>\n // <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n // <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n // <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n // </mammals>\n\n var xml;\n\n function preload() {\n xml = loadXML('assets/mammals.xml');\n }\n\n function setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.hasAttribute('species'));\n print(firstChild.hasAttribute('color'));\n }\n\n // Sketch prints:\n // true\n // false\n
" + "\n
\n // The following short XML file called \"mammals.xml\" is parsed\n // in the code below.\n //\n // \n // <mammals>\n // <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n // <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n // <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n // </mammals>\n\n let xml;\n\n function preload() {\n xml = loadXML('assets/mammals.xml');\n }\n\n function setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.hasAttribute('species'));\n print(firstChild.hasAttribute('color'));\n }\n\n // Sketch prints:\n // true\n // false\n
" ], "class": "p5.XML", "module": "IO", @@ -12627,7 +12871,7 @@ module.exports={ }, { "file": "src/io/p5.XML.js", - "line": 596, + "line": 624, "description": "

Returns an attribute value of the element as an Number. If the defaultValue\nparameter is specified and the attribute doesn't exist, then defaultValue\nis returned. If no defaultValue is specified and the attribute doesn't\nexist, the value 0 is returned.

\n", "itemtype": "method", "name": "getNum", @@ -12649,7 +12893,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getNum('id'));\n}\n\n// Sketch prints:\n// 0\n
" + "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.getNum('id'));\n}\n\n// Sketch prints:\n// 0\n
" ], "class": "p5.XML", "module": "IO", @@ -12657,7 +12901,7 @@ module.exports={ }, { "file": "src/io/p5.XML.js", - "line": 637, + "line": 670, "description": "

Returns an attribute value of the element as an String. If the defaultValue\nparameter is specified and the attribute doesn't exist, then defaultValue\nis returned. If no defaultValue is specified and the attribute doesn't\nexist, null is returned.

\n", "itemtype": "method", "name": "getString", @@ -12679,7 +12923,7 @@ module.exports={ "type": "String" }, "example": [ - "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getString('species'));\n}\n\n// Sketch prints:\n// \"Capra hircus\"\n
" + "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.getString('species'));\n}\n\n// Sketch prints:\n// \"Capra hircus\"\n
" ], "class": "p5.XML", "module": "IO", @@ -12687,7 +12931,7 @@ module.exports={ }, { "file": "src/io/p5.XML.js", - "line": 678, + "line": 716, "description": "

Sets the content of an element's attribute. The first parameter specifies\nthe attribute name, while the second specifies the new content.

\n", "itemtype": "method", "name": "setAttribute", @@ -12704,7 +12948,7 @@ module.exports={ } ], "example": [ - "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getString('species'));\n firstChild.setAttribute('species', 'Jamides zebra');\n print(firstChild.getString('species'));\n}\n\n// Sketch prints:\n// \"Capra hircus\"\n// \"Jamides zebra\"\n
" + "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.getString('species'));\n firstChild.setAttribute('species', 'Jamides zebra');\n print(firstChild.getString('species'));\n}\n\n// Sketch prints:\n// \"Capra hircus\"\n// \"Jamides zebra\"\n
" ], "class": "p5.XML", "module": "IO", @@ -12712,7 +12956,7 @@ module.exports={ }, { "file": "src/io/p5.XML.js", - "line": 721, + "line": 757, "description": "

Returns the content of an element. If there is no such content,\ndefaultValue is returned if specified, otherwise null is returned.

\n", "itemtype": "method", "name": "getContent", @@ -12729,7 +12973,7 @@ module.exports={ "type": "String" }, "example": [ - "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n
" + "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n
" ], "class": "p5.XML", "module": "IO", @@ -12737,7 +12981,7 @@ module.exports={ }, { "file": "src/io/p5.XML.js", - "line": 759, + "line": 798, "description": "

Sets the element's content.

\n", "itemtype": "method", "name": "setContent", @@ -12749,7 +12993,7 @@ module.exports={ } ], "example": [ - "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getContent());\n firstChild.setContent('Mountain Goat');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Mountain Goat\"\n
" + "\n
\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n let firstChild = xml.getChild('animal');\n print(firstChild.getContent());\n firstChild.setContent('Mountain Goat');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Mountain Goat\"\n
" ], "class": "p5.XML", "module": "IO", @@ -12757,16 +13001,17 @@ module.exports={ }, { "file": "src/io/p5.XML.js", - "line": 801, - "description": "

This method is called while the parsing of XML (when loadXML() is\ncalled). The difference between this method and the setContent()\nmethod defined later is that this one is used to set the content\nwhen the node in question has more nodes under it and so on and\nnot directly text content. While in the other one is used when\nthe node in question directly has text inside it.

\n", - "class": "p5.XML", - "module": "IO", - "submodule": "XML" - }, - { - "file": "src/io/p5.XML.js", - "line": 818, - "description": "

This method is called while the parsing of XML (when loadXML() is\ncalled). The XML node is passed and its attributes are stored in the\np5.XML's attribute Object.

\n", + "line": 839, + "description": "

Serializes the element into a string. This function is useful for preparing\nthe content to be sent over a http request or saved to file.

\n", + "itemtype": "method", + "name": "serialize", + "return": { + "description": "Serialized string of the element", + "type": "String" + }, + "example": [ + "\n
\nlet xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.serialize());\n}\n\n// Sketch prints:\n// \n// Goat\n// Leopard\n// Zebra\n// \n
" + ], "class": "p5.XML", "module": "IO", "submodule": "XML" @@ -12789,7 +13034,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\nfunction setup() {\n var x = -3;\n var y = abs(x);\n\n print(x); // -3\n print(y); // 3\n}\n
" + "\n
\nfunction setup() {\n let x = -3;\n let y = abs(x);\n\n print(x); // -3\n print(y); // 3\n}\n
" ], "alt": "no image displayed", "class": "p5", @@ -12814,7 +13059,7 @@ module.exports={ "type": "Integer" }, "example": [ - "\n
\nfunction draw() {\n background(200);\n // map, mouseX between 0 and 5.\n var ax = map(mouseX, 0, 100, 0, 5);\n var ay = 66;\n\n //Get the ceiling of the mapped number.\n var bx = ceil(map(mouseX, 0, 100, 0, 5));\n var by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n}\n
" + "\n
\nfunction draw() {\n background(200);\n // map, mouseX between 0 and 5.\n let ax = map(mouseX, 0, 100, 0, 5);\n let ay = 66;\n\n //Get the ceiling of the mapped number.\n let bx = ceil(map(mouseX, 0, 100, 0, 5));\n let by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n}\n
" ], "alt": "2 horizontal lines & number sets. increase with mouse x. bottom to 2 decimals", "class": "p5", @@ -12849,7 +13094,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\nfunction draw() {\n background(200);\n\n var leftWall = 25;\n var rightWall = 75;\n\n // xm is just the mouseX, while\n // xc is the mouseX, but constrained\n // between the leftWall and rightWall!\n var xm = mouseX;\n var xc = constrain(mouseX, leftWall, rightWall);\n\n // Draw the walls.\n stroke(150);\n line(leftWall, 0, leftWall, height);\n line(rightWall, 0, rightWall, height);\n\n // Draw xm and xc as circles.\n noStroke();\n fill(150);\n ellipse(xm, 33, 9, 9); // Not Constrained\n fill(0);\n ellipse(xc, 66, 9, 9); // Constrained\n}\n
" + "\n
\nfunction draw() {\n background(200);\n\n let leftWall = 25;\n let rightWall = 75;\n\n // xm is just the mouseX, while\n // xc is the mouseX, but constrained\n // between the leftWall and rightWall!\n let xm = mouseX;\n let xc = constrain(mouseX, leftWall, rightWall);\n\n // Draw the walls.\n stroke(150);\n line(leftWall, 0, leftWall, height);\n line(rightWall, 0, rightWall, height);\n\n // Draw xm and xc as circles.\n noStroke();\n fill(150);\n ellipse(xm, 33, 9, 9); // Not Constrained\n fill(0);\n ellipse(xc, 66, 9, 9); // Constrained\n}\n
" ], "alt": "2 vertical lines. 2 ellipses move with mouse X 1 does not move passed lines", "class": "p5", @@ -12867,7 +13112,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n// Move your mouse inside the canvas to see the\n// change in distance between two points!\nfunction draw() {\n background(200);\n fill(0);\n\n var x1 = 10;\n var y1 = 90;\n var x2 = mouseX;\n var y2 = mouseY;\n\n line(x1, y1, x2, y2);\n ellipse(x1, y1, 7, 7);\n ellipse(x2, y2, 7, 7);\n\n // d is the length of the line\n // the distance from point 1 to point 2.\n var d = int(dist(x1, y1, x2, y2));\n\n // Let's write d along the line we are drawing!\n push();\n translate((x1 + x2) / 2, (y1 + y2) / 2);\n rotate(atan2(y2 - y1, x2 - x1));\n text(nfc(d, 1), 0, -5);\n pop();\n // Fancy!\n}\n
" + "\n
\n// Move your mouse inside the canvas to see the\n// change in distance between two points!\nfunction draw() {\n background(200);\n fill(0);\n\n let x1 = 10;\n let y1 = 90;\n let x2 = mouseX;\n let y2 = mouseY;\n\n line(x1, y1, x2, y2);\n ellipse(x1, y1, 7, 7);\n ellipse(x2, y2, 7, 7);\n\n // d is the length of the line\n // the distance from point 1 to point 2.\n let d = int(dist(x1, y1, x2, y2));\n\n // Let's write d along the line we are drawing!\n push();\n translate((x1 + x2) / 2, (y1 + y2) / 2);\n rotate(atan2(y2 - y1, x2 - x1));\n text(nfc(d, 1), 0, -5);\n pop();\n // Fancy!\n}\n
" ], "alt": "2 ellipses joined by line. 1 ellipse moves with mouse X&Y. Distance displayed.", "class": "p5", @@ -12962,7 +13207,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\nfunction draw() {\n background(200);\n\n // Compute the exp() function with a value between 0 and 2\n var xValue = map(mouseX, 0, width, 0, 2);\n var yValue = exp(xValue);\n\n var y = map(yValue, 0, 8, height, 0);\n\n var legend = 'exp (' + nfc(xValue, 3) + ')\\n= ' + nf(yValue, 1, 4);\n stroke(150);\n line(mouseX, y, mouseX, height);\n fill(0);\n text(legend, 5, 15);\n noStroke();\n ellipse(mouseX, y, 7, 7);\n\n // Draw the exp(x) curve,\n // over the domain of x from 0 to 2\n noFill();\n stroke(0);\n beginShape();\n for (var x = 0; x < width; x++) {\n xValue = map(x, 0, width, 0, 2);\n yValue = exp(xValue);\n y = map(yValue, 0, 8, height, 0);\n vertex(x, y);\n }\n\n endShape();\n line(0, 0, 0, height);\n line(0, height - 1, width, height - 1);\n}\n
" + "\n
\nfunction draw() {\n background(200);\n\n // Compute the exp() function with a value between 0 and 2\n let xValue = map(mouseX, 0, width, 0, 2);\n let yValue = exp(xValue);\n\n let y = map(yValue, 0, 8, height, 0);\n\n let legend = 'exp (' + nfc(xValue, 3) + ')\\n= ' + nf(yValue, 1, 4);\n stroke(150);\n line(mouseX, y, mouseX, height);\n fill(0);\n text(legend, 5, 15);\n noStroke();\n ellipse(mouseX, y, 7, 7);\n\n // Draw the exp(x) curve,\n // over the domain of x from 0 to 2\n noFill();\n stroke(0);\n beginShape();\n for (let x = 0; x < width; x++) {\n xValue = map(x, 0, width, 0, 2);\n yValue = exp(xValue);\n y = map(yValue, 0, 8, height, 0);\n vertex(x, y);\n }\n\n endShape();\n line(0, 0, 0, height);\n line(0, height - 1, width, height - 1);\n}\n
" ], "alt": "ellipse moves along a curve with mouse x. e^n displayed.", "class": "p5", @@ -12987,7 +13232,7 @@ module.exports={ "type": "Integer" }, "example": [ - "\n
\nfunction draw() {\n background(200);\n //map, mouseX between 0 and 5.\n var ax = map(mouseX, 0, 100, 0, 5);\n var ay = 66;\n\n //Get the floor of the mapped number.\n var bx = floor(map(mouseX, 0, 100, 0, 5));\n var by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n}\n
" + "\n
\nfunction draw() {\n background(200);\n //map, mouseX between 0 and 5.\n let ax = map(mouseX, 0, 100, 0, 5);\n let ay = 66;\n\n //Get the floor of the mapped number.\n let bx = floor(map(mouseX, 0, 100, 0, 5));\n let by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n}\n
" ], "alt": "2 horizontal lines & number sets. increase with mouse x. bottom to 2 decimals", "class": "p5", @@ -12997,7 +13242,7 @@ module.exports={ { "file": "src/math/calculation.js", "line": 279, - "description": "

Calculates a number between two numbers at a specific increment. The amt\nparameter is the amount to interpolate between the two values where 0.0\nequal to the first point, 0.1 is very near the first point, 0.5 is\nhalf-way in between, etc. The lerp function is convenient for creating\nmotion along a straight path and for drawing dotted lines.

\n", + "description": "

Calculates a number between two numbers at a specific increment. The amt\nparameter is the amount to interpolate between the two values where 0.0\nequal to the first point, 0.1 is very near the first point, 0.5 is\nhalf-way in between, and 1.0 is equal to the second point. If the\nvalue of amt is more than 1.0 or less than 0.0, the number will be\ncalculated accordingly in the ratio of the two given numbers. The lerp\nfunction is convenient for creating motion along a straight\npath and for drawing dotted lines.

\n", "itemtype": "method", "name": "lerp", "params": [ @@ -13013,7 +13258,7 @@ module.exports={ }, { "name": "amt", - "description": "

number between 0.0 and 1.0

\n", + "description": "

number

\n", "type": "Number" } ], @@ -13022,7 +13267,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\nfunction setup() {\n background(200);\n var a = 20;\n var b = 80;\n var c = lerp(a, b, 0.2);\n var d = lerp(a, b, 0.5);\n var e = lerp(a, b, 0.8);\n\n var y = 50;\n\n strokeWeight(5);\n stroke(0); // Draw the original points in black\n point(a, y);\n point(b, y);\n\n stroke(100); // Draw the lerp points in gray\n point(c, y);\n point(d, y);\n point(e, y);\n}\n
" + "\n
\nfunction setup() {\n background(200);\n let a = 20;\n let b = 80;\n let c = lerp(a, b, 0.2);\n let d = lerp(a, b, 0.5);\n let e = lerp(a, b, 0.8);\n\n let y = 50;\n\n strokeWeight(5);\n stroke(0); // Draw the original points in black\n point(a, y);\n point(b, y);\n\n stroke(100); // Draw the lerp points in gray\n point(c, y);\n point(d, y);\n point(e, y);\n}\n
" ], "alt": "5 points horizontally staggered mid-canvas. mid 3 are grey, outer black", "class": "p5", @@ -13031,7 +13276,7 @@ module.exports={ }, { "file": "src/math/calculation.js", - "line": 324, + "line": 327, "description": "

Calculates the natural logarithm (the base-e logarithm) of a number. This\nfunction expects the n parameter to be a value greater than 0.0. Maps to\nMath.log().

\n", "itemtype": "method", "name": "log", @@ -13047,7 +13292,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\nfunction draw() {\n background(200);\n var maxX = 2.8;\n var maxY = 1.5;\n\n // Compute the natural log of a value between 0 and maxX\n var xValue = map(mouseX, 0, width, 0, maxX);\n if (xValue > 0) {\n // Cannot take the log of a negative number.\n var yValue = log(xValue);\n var y = map(yValue, -maxY, maxY, height, 0);\n\n // Display the calculation occurring.\n var legend = 'log(' + nf(xValue, 1, 2) + ')\\n= ' + nf(yValue, 1, 3);\n stroke(150);\n line(mouseX, y, mouseX, height);\n fill(0);\n text(legend, 5, 15);\n noStroke();\n ellipse(mouseX, y, 7, 7);\n }\n\n // Draw the log(x) curve,\n // over the domain of x from 0 to maxX\n noFill();\n stroke(0);\n beginShape();\n for (var x = 0; x < width; x++) {\n xValue = map(x, 0, width, 0, maxX);\n yValue = log(xValue);\n y = map(yValue, -maxY, maxY, height, 0);\n vertex(x, y);\n }\n endShape();\n line(0, 0, 0, height);\n line(0, height / 2, width, height / 2);\n}\n
" + "\n
\nfunction draw() {\n background(200);\n let maxX = 2.8;\n let maxY = 1.5;\n\n // Compute the natural log of a value between 0 and maxX\n let xValue = map(mouseX, 0, width, 0, maxX);\n let yValue, y;\n if (xValue > 0) {\n // Cannot take the log of a negative number.\n yValue = log(xValue);\n y = map(yValue, -maxY, maxY, height, 0);\n\n // Display the calculation occurring.\n let legend = 'log(' + nf(xValue, 1, 2) + ')\\n= ' + nf(yValue, 1, 3);\n stroke(150);\n line(mouseX, y, mouseX, height);\n fill(0);\n text(legend, 5, 15);\n noStroke();\n ellipse(mouseX, y, 7, 7);\n }\n\n // Draw the log(x) curve,\n // over the domain of x from 0 to maxX\n noFill();\n stroke(0);\n beginShape();\n for (let x = 0; x < width; x++) {\n xValue = map(x, 0, width, 0, maxX);\n yValue = log(xValue);\n y = map(yValue, -maxY, maxY, height, 0);\n vertex(x, y);\n }\n endShape();\n line(0, 0, 0, height);\n line(0, height / 2, width, height / 2);\n}\n
" ], "alt": "ellipse moves along a curve with mouse x. natural logarithm of n displayed.", "class": "p5", @@ -13056,7 +13301,7 @@ module.exports={ }, { "file": "src/math/calculation.js", - "line": 379, + "line": 383, "description": "

Calculates the magnitude (or length) of a vector. A vector is a direction\nin space commonly used in computer graphics and linear algebra. Because it\nhas no "start" position, the magnitude of a vector can be thought of as\nthe distance from the coordinate 0,0 to its x,y value. Therefore, mag() is\na shortcut for writing dist(0, 0, x, y).

\n", "itemtype": "method", "name": "mag", @@ -13077,7 +13322,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\nfunction setup() {\n var x1 = 20;\n var x2 = 80;\n var y1 = 30;\n var y2 = 70;\n\n line(0, 0, x1, y1);\n print(mag(x1, y1)); // Prints \"36.05551275463989\"\n line(0, 0, x2, y1);\n print(mag(x2, y1)); // Prints \"85.44003745317531\"\n line(0, 0, x1, y2);\n print(mag(x1, y2)); // Prints \"72.80109889280519\"\n line(0, 0, x2, y2);\n print(mag(x2, y2)); // Prints \"106.3014581273465\"\n}\n
" + "\n
\nfunction setup() {\n let x1 = 20;\n let x2 = 80;\n let y1 = 30;\n let y2 = 70;\n\n line(0, 0, x1, y1);\n print(mag(x1, y1)); // Prints \"36.05551275463989\"\n line(0, 0, x2, y1);\n print(mag(x2, y1)); // Prints \"85.44003745317531\"\n line(0, 0, x1, y2);\n print(mag(x1, y2)); // Prints \"72.80109889280519\"\n line(0, 0, x2, y2);\n print(mag(x2, y2)); // Prints \"106.3014581273465\"\n}\n
" ], "alt": "4 lines of different length radiate from top left of canvas.", "class": "p5", @@ -13086,7 +13331,7 @@ module.exports={ }, { "file": "src/math/calculation.js", - "line": 418, + "line": 422, "description": "

Re-maps a number from one range to another.\n

\nIn the first example above, the number 25 is converted from a value in the\nrange of 0 to 100 into a value that ranges from the left edge of the\nwindow (0) to the right edge (width).

\n", "itemtype": "method", "name": "map", @@ -13128,7 +13373,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\nvar value = 25;\nvar m = map(value, 0, 100, 0, width);\nellipse(m, 50, 10, 10);\n
\n\n
\nfunction setup() {\n noStroke();\n}\n\nfunction draw() {\n background(204);\n var x1 = map(mouseX, 0, width, 25, 75);\n ellipse(x1, 25, 25, 25);\n //This ellipse is constrained to the 0-100 range\n //after setting withinBounds to true\n var x2 = map(mouseX, 0, width, 0, 100, true);\n ellipse(x2, 75, 25, 25);\n}\n
" + "\n
\nlet value = 25;\nlet m = map(value, 0, 100, 0, width);\nellipse(m, 50, 10, 10);\n
\n\n
\nfunction setup() {\n noStroke();\n}\n\nfunction draw() {\n background(204);\n let x1 = map(mouseX, 0, width, 25, 75);\n ellipse(x1, 25, 25, 25);\n //This ellipse is constrained to the 0-100 range\n //after setting withinBounds to true\n let x2 = map(mouseX, 0, width, 0, 100, true);\n ellipse(x2, 75, 25, 25);\n}\n
" ], "alt": "10 by 10 white ellipse with in mid left canvas\n2 25 by 25 white ellipses move with mouse x. Bottom has more range from X", "class": "p5", @@ -13137,7 +13382,7 @@ module.exports={ }, { "file": "src/math/calculation.js", - "line": 474, + "line": 478, "description": "

Determines the largest value in a sequence of numbers, and then returns\nthat value. max() accepts any number of Number parameters, or an Array\nof any length.

\n", "itemtype": "method", "name": "max", @@ -13146,7 +13391,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\nfunction setup() {\n // Change the elements in the array and run the sketch\n // to show how max() works!\n var numArray = [2, 1, 5, 4, 8, 9];\n fill(0);\n noStroke();\n text('Array Elements', 0, 10);\n // Draw all numbers in the array\n var spacing = 15;\n var elemsY = 25;\n for (var i = 0; i < numArray.length; i++) {\n text(numArray[i], i * spacing, elemsY);\n }\n var maxX = 33;\n var maxY = 80;\n // Draw the Maximum value in the array.\n textSize(32);\n text(max(numArray), maxX, maxY);\n}\n
" + "\n
\nfunction setup() {\n // Change the elements in the array and run the sketch\n // to show how max() works!\n let numArray = [2, 1, 5, 4, 8, 9];\n fill(0);\n noStroke();\n text('Array Elements', 0, 10);\n // Draw all numbers in the array\n let spacing = 15;\n let elemsY = 25;\n for (let i = 0; i < numArray.length; i++) {\n text(numArray[i], i * spacing, elemsY);\n }\n let maxX = 33;\n let maxY = 80;\n // Draw the Maximum value in the array.\n textSize(32);\n text(max(numArray), maxX, maxY);\n}\n
" ], "alt": "Small text at top reads: Array Elements 2 1 5 4 8 9. Large text at center: 9", "class": "p5", @@ -13154,7 +13399,7 @@ module.exports={ "submodule": "Calculation", "overloads": [ { - "line": 474, + "line": 478, "params": [ { "name": "n0", @@ -13173,7 +13418,7 @@ module.exports={ } }, { - "line": 510, + "line": 514, "params": [ { "name": "nums", @@ -13190,7 +13435,7 @@ module.exports={ }, { "file": "src/math/calculation.js", - "line": 524, + "line": 528, "description": "

Determines the smallest value in a sequence of numbers, and then returns\nthat value. min() accepts any number of Number parameters, or an Array\nof any length.

\n", "itemtype": "method", "name": "min", @@ -13199,7 +13444,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\nfunction setup() {\n // Change the elements in the array and run the sketch\n // to show how min() works!\n var numArray = [2, 1, 5, 4, 8, 9];\n fill(0);\n noStroke();\n text('Array Elements', 0, 10);\n // Draw all numbers in the array\n var spacing = 15;\n var elemsY = 25;\n for (var i = 0; i < numArray.length; i++) {\n text(numArray[i], i * spacing, elemsY);\n }\n var maxX = 33;\n var maxY = 80;\n // Draw the Minimum value in the array.\n textSize(32);\n text(min(numArray), maxX, maxY);\n}\n
" + "\n
\nfunction setup() {\n // Change the elements in the array and run the sketch\n // to show how min() works!\n let numArray = [2, 1, 5, 4, 8, 9];\n fill(0);\n noStroke();\n text('Array Elements', 0, 10);\n // Draw all numbers in the array\n let spacing = 15;\n let elemsY = 25;\n for (let i = 0; i < numArray.length; i++) {\n text(numArray[i], i * spacing, elemsY);\n }\n let maxX = 33;\n let maxY = 80;\n // Draw the Minimum value in the array.\n textSize(32);\n text(min(numArray), maxX, maxY);\n}\n
" ], "alt": "Small text at top reads: Array Elements 2 1 5 4 8 9. Large text at center: 1", "class": "p5", @@ -13207,7 +13452,7 @@ module.exports={ "submodule": "Calculation", "overloads": [ { - "line": 524, + "line": 528, "params": [ { "name": "n0", @@ -13226,7 +13471,7 @@ module.exports={ } }, { - "line": 560, + "line": 564, "params": [ { "name": "nums", @@ -13243,8 +13488,8 @@ module.exports={ }, { "file": "src/math/calculation.js", - "line": 574, - "description": "

Normalizes a number from another range into a value between 0 and 1.\nIdentical to map(value, low, high, 0, 1).\nNumbers outside of the range are not clamped to 0 and 1, because\nout-of-range values are often intentional and useful. (See the second\nexample above.)

\n", + "line": 578, + "description": "

Normalizes a number from another range into a value between 0 and 1.\nIdentical to map(value, low, high, 0, 1).\nNumbers outside of the range are not clamped to 0 and 1, because\nout-of-range values are often intentional and useful. (See the example above.)

\n", "itemtype": "method", "name": "norm", "params": [ @@ -13269,7 +13514,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\nfunction draw() {\n background(200);\n var currentNum = mouseX;\n var lowerBound = 0;\n var upperBound = width; //100;\n var normalized = norm(currentNum, lowerBound, upperBound);\n var lineY = 70;\n line(0, lineY, width, lineY);\n //Draw an ellipse mapped to the non-normalized value.\n noStroke();\n fill(50);\n var s = 7; // ellipse size\n ellipse(currentNum, lineY, s, s);\n\n // Draw the guide\n var guideY = lineY + 15;\n text('0', 0, guideY);\n textAlign(RIGHT);\n text('100', width, guideY);\n\n // Draw the normalized value\n textAlign(LEFT);\n fill(0);\n textSize(32);\n var normalY = 40;\n var normalX = 20;\n text(normalized, normalX, normalY);\n}\n
" + "\n
\nfunction draw() {\n background(200);\n let currentNum = mouseX;\n let lowerBound = 0;\n let upperBound = width; //100;\n let normalized = norm(currentNum, lowerBound, upperBound);\n let lineY = 70;\n stroke(3);\n line(0, lineY, width, lineY);\n //Draw an ellipse mapped to the non-normalized value.\n noStroke();\n fill(50);\n let s = 7; // ellipse size\n ellipse(currentNum, lineY, s, s);\n\n // Draw the guide\n let guideY = lineY + 15;\n text('0', 0, guideY);\n textAlign(RIGHT);\n text('100', width, guideY);\n\n // Draw the normalized value\n textAlign(LEFT);\n fill(0);\n textSize(32);\n let normalY = 40;\n let normalX = 20;\n text(normalized, normalX, normalY);\n}\n
" ], "alt": "ellipse moves with mouse. 0 shown left & 100 right and updating values center", "class": "p5", @@ -13278,7 +13523,7 @@ module.exports={ }, { "file": "src/math/calculation.js", - "line": 627, + "line": 631, "description": "

Facilitates exponential expressions. The pow() function is an efficient\nway of multiplying numbers by themselves (or their reciprocals) in large\nquantities. For example, pow(3, 5) is equivalent to the expression\n33333 and pow(3, -5) is equivalent to 1 / 33333. Maps to\nMath.pow().

\n", "itemtype": "method", "name": "pow", @@ -13299,7 +13544,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\nfunction setup() {\n //Exponentially increase the size of an ellipse.\n var eSize = 3; // Original Size\n var eLoc = 10; // Original Location\n\n ellipse(eLoc, eLoc, eSize, eSize);\n\n ellipse(eLoc * 2, eLoc * 2, pow(eSize, 2), pow(eSize, 2));\n\n ellipse(eLoc * 4, eLoc * 4, pow(eSize, 3), pow(eSize, 3));\n\n ellipse(eLoc * 8, eLoc * 8, pow(eSize, 4), pow(eSize, 4));\n}\n
" + "\n
\nfunction setup() {\n //Exponentially increase the size of an ellipse.\n let eSize = 3; // Original Size\n let eLoc = 10; // Original Location\n\n ellipse(eLoc, eLoc, eSize, eSize);\n\n ellipse(eLoc * 2, eLoc * 2, pow(eSize, 2), pow(eSize, 2));\n\n ellipse(eLoc * 4, eLoc * 4, pow(eSize, 3), pow(eSize, 3));\n\n ellipse(eLoc * 8, eLoc * 8, pow(eSize, 4), pow(eSize, 4));\n}\n
" ], "alt": "small to large ellipses radiating from top left of canvas", "class": "p5", @@ -13308,7 +13553,7 @@ module.exports={ }, { "file": "src/math/calculation.js", - "line": 661, + "line": 665, "description": "

Calculates the integer closest to the n parameter. For example,\nround(133.8) returns the value 134. Maps to Math.round().

\n", "itemtype": "method", "name": "round", @@ -13324,7 +13569,7 @@ module.exports={ "type": "Integer" }, "example": [ - "\n
\nfunction draw() {\n background(200);\n //map, mouseX between 0 and 5.\n var ax = map(mouseX, 0, 100, 0, 5);\n var ay = 66;\n\n // Round the mapped number.\n var bx = round(map(mouseX, 0, 100, 0, 5));\n var by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n}\n
" + "\n
\nfunction draw() {\n background(200);\n //map, mouseX between 0 and 5.\n let ax = map(mouseX, 0, 100, 0, 5);\n let ay = 66;\n\n // Round the mapped number.\n let bx = round(map(mouseX, 0, 100, 0, 5));\n let by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n}\n
" ], "alt": "horizontal center line squared values displayed on top and regular on bottom.", "class": "p5", @@ -13333,7 +13578,7 @@ module.exports={ }, { "file": "src/math/calculation.js", - "line": 700, + "line": 704, "description": "

Squares a number (multiplies a number by itself). The result is always a\npositive number, as multiplying two negative numbers always yields a\npositive result. For example, -1 * -1 = 1.

\n", "itemtype": "method", "name": "sq", @@ -13349,7 +13594,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\nfunction draw() {\n background(200);\n var eSize = 7;\n var x1 = map(mouseX, 0, width, 0, 10);\n var y1 = 80;\n var x2 = sq(x1);\n var y2 = 20;\n\n // Draw the non-squared.\n line(0, y1, width, y1);\n ellipse(x1, y1, eSize, eSize);\n\n // Draw the squared.\n line(0, y2, width, y2);\n ellipse(x2, y2, eSize, eSize);\n\n // Draw dividing line.\n stroke(100);\n line(0, height / 2, width, height / 2);\n\n // Draw text.\n var spacing = 15;\n noStroke();\n fill(0);\n text('x = ' + x1, 0, y1 + spacing);\n text('sq(x) = ' + x2, 0, y2 + spacing);\n}\n
" + "\n
\nfunction draw() {\n background(200);\n let eSize = 7;\n let x1 = map(mouseX, 0, width, 0, 10);\n let y1 = 80;\n let x2 = sq(x1);\n let y2 = 20;\n\n // Draw the non-squared.\n line(0, y1, width, y1);\n ellipse(x1, y1, eSize, eSize);\n\n // Draw the squared.\n line(0, y2, width, y2);\n ellipse(x2, y2, eSize, eSize);\n\n // Draw dividing line.\n stroke(100);\n line(0, height / 2, width, height / 2);\n\n // Draw text.\n let spacing = 15;\n noStroke();\n fill(0);\n text('x = ' + x1, 0, y1 + spacing);\n text('sq(x) = ' + x2, 0, y2 + spacing);\n}\n
" ], "alt": "horizontal center line squared values displayed on top and regular on bottom.", "class": "p5", @@ -13358,7 +13603,7 @@ module.exports={ }, { "file": "src/math/calculation.js", - "line": 747, + "line": 751, "description": "

Calculates the square root of a number. The square root of a number is\nalways positive, even though there may be a valid negative root. The\nsquare root s of number a is such that s*s = a. It is the opposite of\nsquaring. Maps to Math.sqrt().

\n", "itemtype": "method", "name": "sqrt", @@ -13374,7 +13619,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\nfunction draw() {\n background(200);\n var eSize = 7;\n var x1 = mouseX;\n var y1 = 80;\n var x2 = sqrt(x1);\n var y2 = 20;\n\n // Draw the non-squared.\n line(0, y1, width, y1);\n ellipse(x1, y1, eSize, eSize);\n\n // Draw the squared.\n line(0, y2, width, y2);\n ellipse(x2, y2, eSize, eSize);\n\n // Draw dividing line.\n stroke(100);\n line(0, height / 2, width, height / 2);\n\n // Draw text.\n noStroke();\n fill(0);\n var spacing = 15;\n text('x = ' + x1, 0, y1 + spacing);\n text('sqrt(x) = ' + x2, 0, y2 + spacing);\n}\n
" + "\n
\nfunction draw() {\n background(200);\n let eSize = 7;\n let x1 = mouseX;\n let y1 = 80;\n let x2 = sqrt(x1);\n let y2 = 20;\n\n // Draw the non-squared.\n line(0, y1, width, y1);\n ellipse(x1, y1, eSize, eSize);\n\n // Draw the squared.\n line(0, y2, width, y2);\n ellipse(x2, y2, eSize, eSize);\n\n // Draw dividing line.\n stroke(100);\n line(0, height / 2, width, height / 2);\n\n // Draw text.\n noStroke();\n fill(0);\n let spacing = 15;\n text('x = ' + x1, 0, y1 + spacing);\n text('sqrt(x) = ' + x2, 0, y2 + spacing);\n}\n
" ], "alt": "horizontal center line squareroot values displayed on top and regular on bottom.", "class": "p5", @@ -13449,7 +13694,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nvar xoff = 0.0;\n\nfunction draw() {\n background(204);\n xoff = xoff + 0.01;\n var n = noise(xoff) * width;\n line(n, 0, n, height);\n}\n\n
\n
\nvar noiseScale=0.02;\n\nfunction draw() {\n background(0);\n for (var x=0; x < width; x++) {\n var noiseVal = noise((mouseX+x)*noiseScale, mouseY*noiseScale);\n stroke(noiseVal*255);\n line(x, mouseY+noiseVal*80, x, height);\n }\n}\n\n
" + "\n
\n\nlet xoff = 0.0;\n\nfunction draw() {\n background(204);\n xoff = xoff + 0.01;\n let n = noise(xoff) * width;\n line(n, 0, n, height);\n}\n\n
\n
\nlet noiseScale=0.02;\n\nfunction draw() {\n background(0);\n for (let x=0; x < width; x++) {\n let noiseVal = noise((mouseX+x)*noiseScale, mouseY*noiseScale);\n stroke(noiseVal*255);\n line(x, mouseY+noiseVal*80, x, height);\n }\n}\n\n
" ], "alt": "vertical line moves left to right with updating noise values.\nhorizontal wave pattern effected by mouse x-position & updating noise values.", "class": "p5", @@ -13475,7 +13720,7 @@ module.exports={ } ], "example": [ - "\n
\n \n var noiseVal;\n var noiseScale = 0.02;\nfunction setup() {\n createCanvas(100, 100);\n }\nfunction draw() {\n background(0);\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width / 2; x++) {\n noiseDetail(2, 0.2);\n noiseVal = noise((mouseX + x) * noiseScale, (mouseY + y) * noiseScale);\n stroke(noiseVal * 255);\n point(x, y);\n noiseDetail(8, 0.65);\n noiseVal = noise(\n (mouseX + x + width / 2) * noiseScale,\n (mouseY + y) * noiseScale\n );\n stroke(noiseVal * 255);\n point(x + width / 2, y);\n }\n }\n }\n \n
" + "\n
\n \n let noiseVal;\n let noiseScale = 0.02;\nfunction setup() {\n createCanvas(100, 100);\n }\nfunction draw() {\n background(0);\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width / 2; x++) {\n noiseDetail(2, 0.2);\n noiseVal = noise((mouseX + x) * noiseScale, (mouseY + y) * noiseScale);\n stroke(noiseVal * 255);\n point(x, y);\n noiseDetail(8, 0.65);\n noiseVal = noise(\n (mouseX + x + width / 2) * noiseScale,\n (mouseY + y) * noiseScale\n );\n stroke(noiseVal * 255);\n point(x + width / 2, y);\n }\n }\n }\n \n
" ], "alt": "2 vertical grey smokey patterns affected my mouse x-position and noise.", "class": "p5", @@ -13496,7 +13741,7 @@ module.exports={ } ], "example": [ - "\n
\nvar xoff = 0.0;\n\nfunction setup() {\n noiseSeed(99);\n stroke(0, 10);\n}\n\nfunction draw() {\n xoff = xoff + .01;\n var n = noise(xoff) * width;\n line(n, 0, n, height);\n}\n\n
" + "\n
\nlet xoff = 0.0;\n\nfunction setup() {\n noiseSeed(99);\n stroke(0, 10);\n}\n\nfunction draw() {\n xoff = xoff + .01;\n let n = noise(xoff) * width;\n line(n, 0, n, height);\n}\n\n
" ], "alt": "vertical grey lines drawing in pattern affected by noise.", "class": "p5", @@ -13547,7 +13792,7 @@ module.exports={ "type": "String" }, "example": [ - "\n
\n\nfunction setup() {\n var v = createVector(20, 30);\n print(String(v)); // prints \"p5.Vector Object : [20, 30, 0]\"\n}\n\n
\n\n
\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'black');\n\n noStroke();\n text(v1.toString(), 10, 25, 90, 75);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" + "\n
\n\nfunction setup() {\n let v = createVector(20, 30);\n print(String(v)); // prints \"p5.Vector Object : [20, 30, 0]\"\n}\n\n
\n\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'black');\n\n noStroke();\n text(v1.toString(), 10, 25, 90, 75);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -13561,7 +13806,7 @@ module.exports={ "name": "set", "chainable": 1, "example": [ - "\n
\n\nfunction setup() {\n var v = createVector(1, 2, 3);\n v.set(4, 5, 6); // Sets vector to [4, 5, 6]\n\n var v1 = createVector(0, 0, 0);\n var arr = [1, 2, 3];\n v1.set(arr); // Sets vector to [1, 2, 3]\n}\n\n
\n\n
\n\nvar v0, v1;\nfunction setup() {\n createCanvas(100, 100);\n\n v0 = createVector(0, 0);\n v1 = createVector(50, 50);\n}\n\nfunction draw() {\n background(240);\n\n drawArrow(v0, v1, 'black');\n v1.set(v1.x + random(-1, 1), v1.y + random(-1, 1));\n\n noStroke();\n text('x: ' + round(v1.x) + ' y: ' + round(v1.y), 20, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" + "\n
\n\nfunction setup() {\n let v = createVector(1, 2, 3);\n v.set(4, 5, 6); // Sets vector to [4, 5, 6]\n\n let v1 = createVector(0, 0, 0);\n let arr = [1, 2, 3];\n v1.set(arr); // Sets vector to [1, 2, 3]\n}\n\n
\n\n
\n\nlet v0, v1;\nfunction setup() {\n createCanvas(100, 100);\n\n v0 = createVector(0, 0);\n v1 = createVector(50, 50);\n}\n\nfunction draw() {\n background(240);\n\n drawArrow(v0, v1, 'black');\n v1.set(v1.x + random(-1, 1), v1.y + random(-1, 1));\n\n noStroke();\n text('x: ' + round(v1.x) + ' y: ' + round(v1.y), 20, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -13615,7 +13860,7 @@ module.exports={ "type": "p5.Vector" }, "example": [ - "\n
\n\nvar v1 = createVector(1, 2, 3);\nvar v2 = v1.copy();\nprint(v1.x === v2.x && v1.y === v2.y && v1.z === v2.z);\n// Prints \"true\"\n\n
" + "\n
\n\nlet v1 = createVector(1, 2, 3);\nlet v2 = v1.copy();\nprint(v1.x === v2.x && v1.y === v2.y && v1.z === v2.z);\n// Prints \"true\"\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -13629,7 +13874,7 @@ module.exports={ "name": "add", "chainable": 1, "example": [ - "\n
\n\nvar v = createVector(1, 2, 3);\nv.add(4, 5, 6);\n// v's components are set to [5, 7, 9]\n\n
\n\n
\n\n// Static method\nvar v1 = createVector(1, 2, 3);\nvar v2 = createVector(2, 3, 4);\n\nvar v3 = p5.Vector.add(v1, v2);\n// v3 has components [3, 5, 7]\nprint(v3);\n\n
\n\n
\n\n// red vector + blue vector = purple vector\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'red');\n\n var v2 = createVector(-30, 20);\n drawArrow(v1, v2, 'blue');\n\n var v3 = p5.Vector.add(v1, v2);\n drawArrow(v0, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" + "\n
\n\nlet v = createVector(1, 2, 3);\nv.add(4, 5, 6);\n// v's components are set to [5, 7, 9]\n\n
\n\n
\n\n// Static method\nlet v1 = createVector(1, 2, 3);\nlet v2 = createVector(2, 3, 4);\n\nlet v3 = p5.Vector.add(v1, v2);\n// v3 has components [3, 5, 7]\nprint(v3);\n\n
\n\n
\n\n// red vector + blue vector = purple vector\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'red');\n\n let v2 = createVector(-30, 20);\n drawArrow(v1, v2, 'blue');\n\n let v3 = p5.Vector.add(v1, v2);\n drawArrow(v0, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -13720,7 +13965,7 @@ module.exports={ "name": "sub", "chainable": 1, "example": [ - "\n
\n\nvar v = createVector(4, 5, 6);\nv.sub(1, 1, 1);\n// v's components are set to [3, 4, 5]\n\n
\n\n
\n\n// Static method\nvar v1 = createVector(2, 3, 4);\nvar v2 = createVector(1, 2, 3);\n\nvar v3 = p5.Vector.sub(v1, v2);\n// v3 has components [1, 1, 1]\nprint(v3);\n\n
\n\n
\n\n// red vector - blue vector = purple vector\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(70, 50);\n drawArrow(v0, v1, 'red');\n\n var v2 = createVector(mouseX, mouseY);\n drawArrow(v0, v2, 'blue');\n\n var v3 = p5.Vector.sub(v1, v2);\n drawArrow(v2, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" + "\n
\n\nlet v = createVector(4, 5, 6);\nv.sub(1, 1, 1);\n// v's components are set to [3, 4, 5]\n\n
\n\n
\n\n// Static method\nlet v1 = createVector(2, 3, 4);\nlet v2 = createVector(1, 2, 3);\n\nlet v3 = p5.Vector.sub(v1, v2);\n// v3 has components [1, 1, 1]\nprint(v3);\n\n
\n\n
\n\n// red vector - blue vector = purple vector\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(70, 50);\n drawArrow(v0, v1, 'red');\n\n let v2 = createVector(mouseX, mouseY);\n drawArrow(v0, v2, 'blue');\n\n let v3 = p5.Vector.sub(v1, v2);\n drawArrow(v2, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -13811,7 +14056,7 @@ module.exports={ "name": "mult", "chainable": 1, "example": [ - "\n
\n\nvar v = createVector(1, 2, 3);\nv.mult(2);\n// v's components are set to [2, 4, 6]\n\n
\n\n
\n\n// Static method\nvar v1 = createVector(1, 2, 3);\nvar v2 = p5.Vector.mult(v1, 2);\n// v2 has components [2, 4, 6]\nprint(v2);\n\n
\n\n
\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = createVector(25, -25);\n drawArrow(v0, v1, 'red');\n\n var num = map(mouseX, 0, width, -2, 2, true);\n var v2 = p5.Vector.mult(v1, num);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('multiplied by ' + num.toFixed(2), 5, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" + "\n
\n\nlet v = createVector(1, 2, 3);\nv.mult(2);\n// v's components are set to [2, 4, 6]\n\n
\n\n
\n\n// Static method\nlet v1 = createVector(1, 2, 3);\nlet v2 = p5.Vector.mult(v1, 2);\n// v2 has components [2, 4, 6]\nprint(v2);\n\n
\n\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = createVector(25, -25);\n drawArrow(v0, v1, 'red');\n\n let num = map(mouseX, 0, width, -2, 2, true);\n let v2 = p5.Vector.mult(v1, num);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('multiplied by ' + num.toFixed(2), 5, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -13879,7 +14124,7 @@ module.exports={ "name": "div", "chainable": 1, "example": [ - "\n
\n\nvar v = createVector(6, 4, 2);\nv.div(2); //v's components are set to [3, 2, 1]\n\n
\n\n
\n\n// Static method\nvar v1 = createVector(6, 4, 2);\nvar v2 = p5.Vector.div(v1, 2);\n// v2 has components [3, 2, 1]\nprint(v2);\n\n
\n\n
\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 100);\n var v1 = createVector(50, -50);\n drawArrow(v0, v1, 'red');\n\n var num = map(mouseX, 0, width, 10, 0.5, true);\n var v2 = p5.Vector.div(v1, num);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('divided by ' + num.toFixed(2), 10, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" + "\n
\n\nlet v = createVector(6, 4, 2);\nv.div(2); //v's components are set to [3, 2, 1]\n\n
\n\n
\n\n// Static method\nlet v1 = createVector(6, 4, 2);\nlet v2 = p5.Vector.div(v1, 2);\n// v2 has components [3, 2, 1]\nprint(v2);\n\n
\n\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 100);\n let v1 = createVector(50, -50);\n drawArrow(v0, v1, 'red');\n\n let num = map(mouseX, 0, width, 10, 0.5, true);\n let v2 = p5.Vector.div(v1, num);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('divided by ' + num.toFixed(2), 10, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -13950,7 +14195,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'black');\n\n noStroke();\n text('vector length: ' + v1.mag().toFixed(2), 10, 70, 90, 30);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
\n
\n\nvar v = createVector(20.0, 30.0, 40.0);\nvar m = v.mag();\nprint(m); // Prints \"53.85164807134504\"\n\n
" + "\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'black');\n\n noStroke();\n text('vector length: ' + v1.mag().toFixed(2), 10, 70, 90, 30);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
\n
\n\nlet v = createVector(20.0, 30.0, 40.0);\nlet m = v.mag();\nprint(m); // Prints \"53.85164807134504\"\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -13992,7 +14237,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\n// Static method\nvar v1 = createVector(6, 4, 2);\nprint(v1.magSq()); // Prints \"56\"\n\n
\n\n
\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'black');\n\n noStroke();\n text('vector length squared: ' + v1.magSq().toFixed(2), 10, 45, 90, 55);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" + "\n
\n\n// Static method\nlet v1 = createVector(6, 4, 2);\nprint(v1.magSq()); // Prints \"56\"\n\n
\n\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'black');\n\n noStroke();\n text('vector length squared: ' + v1.magSq().toFixed(2), 10, 45, 90, 55);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -14009,7 +14254,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nvar v1 = createVector(1, 2, 3);\nvar v2 = createVector(2, 3, 4);\n\nprint(v1.dot(v2)); // Prints \"20\"\n\n
\n\n
\n\n//Static method\nvar v1 = createVector(1, 2, 3);\nvar v2 = createVector(3, 2, 1);\nprint(p5.Vector.dot(v1, v2)); // Prints \"10\"\n\n
" + "\n
\n\nlet v1 = createVector(1, 2, 3);\nlet v2 = createVector(2, 3, 4);\n\nprint(v1.dot(v2)); // Prints \"20\"\n\n
\n\n
\n\n//Static method\nlet v1 = createVector(1, 2, 3);\nlet v2 = createVector(3, 2, 1);\nprint(p5.Vector.dot(v1, v2)); // Prints \"10\"\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -14088,7 +14333,7 @@ module.exports={ "type": "p5.Vector" }, "example": [ - "\n
\n\nvar v1 = createVector(1, 2, 3);\nvar v2 = createVector(1, 2, 3);\n\nv1.cross(v2); // v's components are [0, 0, 0]\n\n
\n\n
\n\n// Static method\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar crossProduct = p5.Vector.cross(v1, v2);\n// crossProduct has components [0, 0, 1]\nprint(crossProduct);\n\n
" + "\n
\n\nlet v1 = createVector(1, 2, 3);\nlet v2 = createVector(1, 2, 3);\n\nv1.cross(v2); // v's components are [0, 0, 0]\n\n
\n\n
\n\n// Static method\nlet v1 = createVector(1, 0, 0);\nlet v2 = createVector(0, 1, 0);\n\nlet crossProduct = p5.Vector.cross(v1, v2);\n// crossProduct has components [0, 0, 1]\nprint(crossProduct);\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -14141,7 +14386,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar distance = v1.dist(v2); // distance is 1.4142...\nprint(distance);\n\n
\n\n
\n\n// Static method\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar distance = p5.Vector.dist(v1, v2);\n// distance is 1.4142...\nprint(distance);\n\n
\n\n
\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n\n var v1 = createVector(70, 50);\n drawArrow(v0, v1, 'red');\n\n var v2 = createVector(mouseX, mouseY);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('distance between vectors: ' + v2.dist(v1).toFixed(2), 5, 50, 95, 50);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" + "\n
\n\nlet v1 = createVector(1, 0, 0);\nlet v2 = createVector(0, 1, 0);\n\nlet distance = v1.dist(v2); // distance is 1.4142...\nprint(distance);\n\n
\n\n
\n\n// Static method\nlet v1 = createVector(1, 0, 0);\nlet v2 = createVector(0, 1, 0);\n\nlet distance = p5.Vector.dist(v1, v2);\n// distance is 1.4142...\nprint(distance);\n\n
\n\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n\n let v1 = createVector(70, 50);\n drawArrow(v0, v1, 'red');\n\n let v2 = createVector(mouseX, mouseY);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('distance between vectors: ' + v2.dist(v1).toFixed(2), 5, 50, 95, 50);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -14194,7 +14439,7 @@ module.exports={ "type": "p5.Vector" }, "example": [ - "\n
\n\nvar v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.normalize();\n// v's components are set to\n// [0.4454354, 0.8908708, 0.089087084]\n\n
\n
\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'red');\n v1.normalize();\n drawArrow(v0, v1.mult(35), 'blue');\n\n noFill();\n ellipse(50, 50, 35 * 2);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" + "\n
\n\nlet v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.normalize();\n// v's components are set to\n// [0.4454354, 0.8908708, 0.089087084]\n\n
\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'red');\n v1.normalize();\n drawArrow(v0, v1.mult(35), 'blue');\n\n noFill();\n ellipse(50, 50, 35 * 2);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -14215,7 +14460,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\n\nvar v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.limit(5);\n// v's components are set to\n// [2.2271771, 4.4543543, 0.4454354]\n\n
\n
\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'red');\n drawArrow(v0, v1.limit(35), 'blue');\n\n noFill();\n ellipse(50, 50, 35 * 2);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" + "\n
\n\nlet v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.limit(5);\n// v's components are set to\n// [2.2271771, 4.4543543, 0.4454354]\n\n
\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'red');\n drawArrow(v0, v1.limit(35), 'blue');\n\n noFill();\n ellipse(50, 50, 35 * 2);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -14236,7 +14481,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\n\nvar v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.setMag(10);\n// v's components are set to [6.0, 8.0, 0.0]\n\n
\n\n
\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(50, 50);\n\n drawArrow(v0, v1, 'red');\n\n var length = map(mouseX, 0, width, 0, 141, true);\n v1.setMag(length);\n drawArrow(v0, v1, 'blue');\n\n noStroke();\n text('magnitude set to: ' + length.toFixed(2), 10, 70, 90, 30);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" + "\n
\n\nlet v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.setMag(10);\n// v's components are set to [6.0, 8.0, 0.0]\n\n
\n\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(0, 0);\n let v1 = createVector(50, 50);\n\n drawArrow(v0, v1, 'red');\n\n let length = map(mouseX, 0, width, 0, 141, true);\n v1.setMag(length);\n drawArrow(v0, v1, 'blue');\n\n noStroke();\n text('magnitude set to: ' + length.toFixed(2), 10, 70, 90, 30);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -14253,7 +14498,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nfunction setup() {\n var v1 = createVector(30, 50);\n print(v1.heading()); // 1.0303768265243125\n\n v1 = createVector(40, 50);\n print(v1.heading()); // 0.8960553845713439\n\n v1 = createVector(30, 70);\n print(v1.heading()); // 1.1659045405098132\n}\n\n
\n\n
\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'black');\n\n var myHeading = v1.heading();\n noStroke();\n text(\n 'vector heading: ' +\n myHeading.toFixed(2) +\n ' radians or ' +\n degrees(myHeading).toFixed(2) +\n ' degrees',\n 10,\n 50,\n 90,\n 50\n );\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" + "\n
\n\nfunction setup() {\n let v1 = createVector(30, 50);\n print(v1.heading()); // 1.0303768265243125\n\n v1 = createVector(40, 50);\n print(v1.heading()); // 0.8960553845713439\n\n v1 = createVector(30, 70);\n print(v1.heading()); // 1.1659045405098132\n}\n\n
\n\n
\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'black');\n\n let myHeading = v1.heading();\n noStroke();\n text(\n 'vector heading: ' +\n myHeading.toFixed(2) +\n ' radians or ' +\n degrees(myHeading).toFixed(2) +\n ' degrees',\n 10,\n 50,\n 90,\n 50\n );\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -14274,7 +14519,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\n\nvar v = createVector(10.0, 20.0);\n// v has components [10.0, 20.0, 0.0]\nv.rotate(HALF_PI);\n// v's components are set to [-20.0, 9.999999, 0.0]\n\n
\n\n
\n\nvar angle = 0;\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = createVector(50, 0);\n\n drawArrow(v0, v1.rotate(angle), 'black');\n angle += 0.01;\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" + "\n
\n\nlet v = createVector(10.0, 20.0);\n// v has components [10.0, 20.0, 0.0]\nv.rotate(HALF_PI);\n// v's components are set to [-20.0, 9.999999, 0.0]\n\n
\n\n
\n\nlet angle = 0;\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = createVector(50, 0);\n\n drawArrow(v0, v1.rotate(angle), 'black');\n angle += 0.01;\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -14298,7 +14543,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar angle = v1.angleBetween(v2);\n// angle is PI/2\nprint(angle);\n\n
\n\n
\n\nfunction draw() {\n background(240);\n var v0 = createVector(50, 50);\n\n var v1 = createVector(50, 0);\n drawArrow(v0, v1, 'red');\n\n var v2 = createVector(mouseX - 50, mouseY - 50);\n drawArrow(v0, v2, 'blue');\n\n var angleBetween = v1.angleBetween(v2);\n noStroke();\n text(\n 'angle between: ' +\n angleBetween.toFixed(2) +\n ' radians or ' +\n degrees(angleBetween).toFixed(2) +\n ' degrees',\n 10,\n 50,\n 90,\n 50\n );\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" + "\n
\n\nlet v1 = createVector(1, 0, 0);\nlet v2 = createVector(0, 1, 0);\n\nlet angle = v1.angleBetween(v2);\n// angle is PI/2\nprint(angle);\n\n
\n\n
\n\nfunction draw() {\n background(240);\n let v0 = createVector(50, 50);\n\n let v1 = createVector(50, 0);\n drawArrow(v0, v1, 'red');\n\n let v2 = createVector(mouseX - 50, mouseY - 50);\n drawArrow(v0, v2, 'blue');\n\n let angleBetween = v1.angleBetween(v2);\n noStroke();\n text(\n 'angle between: ' +\n angleBetween.toFixed(2) +\n ' radians or ' +\n degrees(angleBetween).toFixed(2) +\n ' degrees',\n 10,\n 50,\n 90,\n 50\n );\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -14312,7 +14557,7 @@ module.exports={ "name": "lerp", "chainable": 1, "example": [ - "\n
\n\nvar v = createVector(1, 1, 0);\n\nv.lerp(3, 3, 0, 0.5); // v now has components [2,2,0]\n\n
\n\n
\n\nvar v1 = createVector(0, 0, 0);\nvar v2 = createVector(100, 100, 0);\n\nvar v3 = p5.Vector.lerp(v1, v2, 0.5);\n// v3 has components [50,50,0]\nprint(v3);\n\n
\n\n
\n\nvar step = 0.01;\nvar amount = 0;\n\nfunction draw() {\n background(240);\n var v0 = createVector(0, 0);\n\n var v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'red');\n\n var v2 = createVector(90, 90);\n drawArrow(v0, v2, 'blue');\n\n if (amount > 1 || amount < 0) {\n step *= -1;\n }\n amount += step;\n var v3 = p5.Vector.lerp(v1, v2, amount);\n\n drawArrow(v0, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" + "\n
\n\nlet v = createVector(1, 1, 0);\n\nv.lerp(3, 3, 0, 0.5); // v now has components [2,2,0]\n\n
\n\n
\n\nlet v1 = createVector(0, 0, 0);\nlet v2 = createVector(100, 100, 0);\n\nlet v3 = p5.Vector.lerp(v1, v2, 0.5);\n// v3 has components [50,50,0]\nprint(v3);\n\n
\n\n
\n\nlet step = 0.01;\nlet amount = 0;\n\nfunction draw() {\n background(240);\n let v0 = createVector(0, 0);\n\n let v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'red');\n\n let v2 = createVector(90, 90);\n drawArrow(v0, v2, 'blue');\n\n if (amount > 1 || amount < 0) {\n step *= -1;\n }\n amount += step;\n let v3 = p5.Vector.lerp(v1, v2, amount);\n\n drawArrow(v0, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -14424,7 +14669,7 @@ module.exports={ "type": "Number[]" }, "example": [ - "\n
\n\nfunction setup() {\n var v = createVector(20, 30);\n print(v.array()); // Prints : Array [20, 30, 0]\n}\n\n
\n\n
\n\nvar v = createVector(10.0, 20.0, 30.0);\nvar f = v.array();\nprint(f[0]); // Prints \"10.0\"\nprint(f[1]); // Prints \"20.0\"\nprint(f[2]); // Prints \"30.0\"\n\n
" + "\n
\n\nfunction setup() {\n let v = createVector(20, 30);\n print(v.array()); // Prints : Array [20, 30, 0]\n}\n\n
\n\n
\n\nlet v = createVector(10.0, 20.0, 30.0);\nlet f = v.array();\nprint(f[0]); // Prints \"10.0\"\nprint(f[1]); // Prints \"20.0\"\nprint(f[2]); // Prints \"30.0\"\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -14441,7 +14686,7 @@ module.exports={ "type": "Boolean" }, "example": [ - "\n
\n\nvar v1 = createVector(5, 10, 20);\nvar v2 = createVector(5, 10, 20);\nvar v3 = createVector(13, 10, 19);\n\nprint(v1.equals(v2.x, v2.y, v2.z)); // true\nprint(v1.equals(v3.x, v3.y, v3.z)); // false\n\n
\n\n
\n\nvar v1 = createVector(10.0, 20.0, 30.0);\nvar v2 = createVector(10.0, 20.0, 30.0);\nvar v3 = createVector(0.0, 0.0, 0.0);\nprint(v1.equals(v2)); // true\nprint(v1.equals(v3)); // false\n\n
" + "\n
\n\nlet v1 = createVector(5, 10, 20);\nlet v2 = createVector(5, 10, 20);\nlet v3 = createVector(13, 10, 19);\n\nprint(v1.equals(v2.x, v2.y, v2.z)); // true\nprint(v1.equals(v3.x, v3.y, v3.z)); // false\n\n
\n\n
\n\nlet v1 = createVector(10.0, 20.0, 30.0);\nlet v2 = createVector(10.0, 20.0, 30.0);\nlet v3 = createVector(0.0, 0.0, 0.0);\nprint(v1.equals(v2)); // true\nprint(v1.equals(v3)); // false\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -14515,7 +14760,7 @@ module.exports={ "type": "p5.Vector" }, "example": [ - "\n
\n\nfunction draw() {\n background(200);\n\n // Create a variable, proportional to the mouseX,\n // varying from 0-360, to represent an angle in degrees.\n angleMode(DEGREES);\n var myDegrees = map(mouseX, 0, width, 0, 360);\n\n // Display that variable in an onscreen text.\n // (Note the nfc() function to truncate additional decimal places,\n // and the \"\\xB0\" character for the degree symbol.)\n var readout = 'angle = ' + nfc(myDegrees, 1) + '\\xB0';\n noStroke();\n fill(0);\n text(readout, 5, 15);\n\n // Create a p5.Vector using the fromAngle function,\n // and extract its x and y components.\n var v = p5.Vector.fromAngle(radians(myDegrees), 30);\n var vx = v.x;\n var vy = v.y;\n\n push();\n translate(width / 2, height / 2);\n noFill();\n stroke(150);\n line(0, 0, 30, 0);\n stroke(0);\n line(0, 0, vx, vy);\n pop();\n}\n\n
" + "\n
\n\nfunction draw() {\n background(200);\n\n // Create a variable, proportional to the mouseX,\n // varying from 0-360, to represent an angle in degrees.\n angleMode(DEGREES);\n let myDegrees = map(mouseX, 0, width, 0, 360);\n\n // Display that variable in an onscreen text.\n // (Note the nfc() function to truncate additional decimal places,\n // and the \"\\xB0\" character for the degree symbol.)\n let readout = 'angle = ' + nfc(myDegrees, 1) + '\\xB0';\n noStroke();\n fill(0);\n text(readout, 5, 15);\n\n // Create a p5.Vector using the fromAngle function,\n // and extract its x and y components.\n let v = p5.Vector.fromAngle(radians(myDegrees), 30);\n let vx = v.x;\n let vy = v.y;\n\n push();\n translate(width / 2, height / 2);\n noFill();\n stroke(150);\n line(0, 0, 30, 0);\n stroke(0);\n line(0, 0, vx, vy);\n pop();\n}\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -14551,7 +14796,7 @@ module.exports={ "type": "p5.Vector" }, "example": [ - "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n fill(255);\n noStroke();\n}\nfunction draw() {\n background(255);\n\n var t = millis() / 1000;\n\n // add three point lights\n pointLight(color('#f00'), p5.Vector.fromAngles(t * 1.0, t * 1.3, 100));\n pointLight(color('#0f0'), p5.Vector.fromAngles(t * 1.1, t * 1.2, 100));\n pointLight(color('#00f'), p5.Vector.fromAngles(t * 1.2, t * 1.1, 100));\n\n sphere(35);\n}\n\n
" + "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n fill(255);\n noStroke();\n}\nfunction draw() {\n background(255);\n\n let t = millis() / 1000;\n\n // add three point lights\n pointLight(color('#f00'), p5.Vector.fromAngles(t * 1.0, t * 1.3, 100));\n pointLight(color('#0f0'), p5.Vector.fromAngles(t * 1.1, t * 1.2, 100));\n pointLight(color('#00f'), p5.Vector.fromAngles(t * 1.2, t * 1.1, 100));\n\n sphere(35);\n}\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -14569,7 +14814,7 @@ module.exports={ "type": "p5.Vector" }, "example": [ - "\n
\n\nvar v = p5.Vector.random2D();\n// May make v's attributes something like:\n// [0.61554617, -0.51195765, 0.0] or\n// [-0.4695841, -0.14366731, 0.0] or\n// [0.6091097, -0.22805278, 0.0]\nprint(v);\n\n
\n\n
\n\nfunction setup() {\n frameRate(1);\n}\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = p5.Vector.random2D();\n drawArrow(v0, v1.mult(50), 'black');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" + "\n
\n\nlet v = p5.Vector.random2D();\n// May make v's attributes something like:\n// [0.61554617, -0.51195765, 0.0] or\n// [-0.4695841, -0.14366731, 0.0] or\n// [0.6091097, -0.22805278, 0.0]\nprint(v);\n\n
\n\n
\n\nfunction setup() {\n frameRate(1);\n}\n\nfunction draw() {\n background(240);\n\n let v0 = createVector(50, 50);\n let v1 = p5.Vector.random2D();\n drawArrow(v0, v1.mult(50), 'black');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n let arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -14587,7 +14832,7 @@ module.exports={ "type": "p5.Vector" }, "example": [ - "\n
\n\nvar v = p5.Vector.random3D();\n// May make v's attributes something like:\n// [0.61554617, -0.51195765, 0.599168] or\n// [-0.4695841, -0.14366731, -0.8711202] or\n// [0.6091097, -0.22805278, -0.7595902]\nprint(v);\n\n
" + "\n
\n\nlet v = p5.Vector.random3D();\n// May make v's attributes something like:\n// [0.61554617, -0.51195765, 0.599168] or\n// [-0.4695841, -0.14366731, -0.8711202] or\n// [0.6091097, -0.22805278, -0.7595902]\nprint(v);\n\n
" ], "class": "p5.Vector", "module": "Math", @@ -14655,7 +14900,7 @@ module.exports={ } ], "example": [ - "\n
\n\nrandomSeed(99);\nfor (var i = 0; i < 100; i++) {\n var r = random(0, 255);\n stroke(r);\n line(i, 0, i, 100);\n}\n\n
" + "\n
\n\nrandomSeed(99);\nfor (let i = 0; i < 100; i++) {\n let r = random(0, 255);\n stroke(r);\n line(i, 0, i, 100);\n}\n\n
" ], "alt": "many vertical lines drawn in white, black or grey.", "class": "p5", @@ -14673,7 +14918,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nfor (var i = 0; i < 100; i++) {\n var r = random(50);\n stroke(r * 5);\n line(50, i, 50 + r, i);\n}\n\n
\n
\n\nfor (var i = 0; i < 100; i++) {\n var r = random(-50, 50);\n line(50, i, 50 + r, i);\n}\n\n
\n
\n\n// Get a random element from an array using the random(Array) syntax\nvar words = ['apple', 'bear', 'cat', 'dog'];\nvar word = random(words); // select random word\ntext(word, 10, 50); // draw the word\n\n
" + "\n
\n\nfor (let i = 0; i < 100; i++) {\n let r = random(50);\n stroke(r * 5);\n line(50, i, 50 + r, i);\n}\n\n
\n
\n\nfor (let i = 0; i < 100; i++) {\n let r = random(-50, 50);\n line(50, i, 50 + r, i);\n}\n\n
\n
\n\n// Get a random element from an array using the random(Array) syntax\nlet words = ['apple', 'bear', 'cat', 'dog'];\nlet word = random(words); // select random word\ntext(word, 10, 50); // draw the word\n\n
" ], "alt": "100 horizontal lines from center canvas to right. size+fill change each time\n100 horizontal lines from center of canvas. height & side change each render\nword displayed at random. Either apple, bear, cat, or dog", "class": "p5", @@ -14740,7 +14985,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n \n for (var y = 0; y < 100; y++) {\n var x = randomGaussian(50, 15);\n line(50, y, x, y);\n }\n \n
\n
\n \n var distribution = new Array(360);\nfunction setup() {\n createCanvas(100, 100);\n for (var i = 0; i < distribution.length; i++) {\n distribution[i] = floor(randomGaussian(0, 15));\n }\n }\nfunction draw() {\n background(204);\n translate(width / 2, width / 2);\n for (var i = 0; i < distribution.length; i++) {\n rotate(TWO_PI / distribution.length);\n stroke(0);\n var dist = abs(distribution[i]);\n line(0, 0, dist, 0);\n }\n }\n \n
" + "\n
\n \n for (let y = 0; y < 100; y++) {\n let x = randomGaussian(50, 15);\n line(50, y, x, y);\n }\n \n
\n
\n \n let distribution = new Array(360);\nfunction setup() {\n createCanvas(100, 100);\n for (let i = 0; i < distribution.length; i++) {\n distribution[i] = floor(randomGaussian(0, 15));\n }\n }\nfunction draw() {\n background(204);\n translate(width / 2, width / 2);\n for (let i = 0; i < distribution.length; i++) {\n rotate(TWO_PI / distribution.length);\n stroke(0);\n let dist = abs(distribution[i]);\n line(0, 0, dist, 0);\n }\n }\n \n
" ], "alt": "100 horizontal lines from center of canvas. height & side change each render\n black lines radiate from center of canvas. size determined each render", "class": "p5", @@ -14765,7 +15010,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nvar a = PI;\nvar c = cos(a);\nvar ac = acos(c);\n// Prints: \"3.1415927 : -1.0 : 3.1415927\"\nprint(a + ' : ' + c + ' : ' + ac);\n\n
\n\n
\n\nvar a = PI + PI / 4.0;\nvar c = cos(a);\nvar ac = acos(c);\n// Prints: \"3.926991 : -0.70710665 : 2.3561943\"\nprint(a + ' : ' + c + ' : ' + ac);\n\n
" + "\n
\n\nlet a = PI;\nlet c = cos(a);\nlet ac = acos(c);\n// Prints: \"3.1415927 : -1.0 : 3.1415927\"\nprint(a + ' : ' + c + ' : ' + ac);\n\n
\n\n
\n\nlet a = PI + PI / 4.0;\nlet c = cos(a);\nlet ac = acos(c);\n// Prints: \"3.926991 : -0.70710665 : 2.3561943\"\nprint(a + ' : ' + c + ' : ' + ac);\n\n
" ], "class": "p5", "module": "Math", @@ -14789,7 +15034,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nvar a = PI + PI / 3;\nvar s = sin(a);\nvar as = asin(s);\n// Prints: \"1.0471976 : 0.86602545 : 1.0471976\"\nprint(a + ' : ' + s + ' : ' + as);\n\n
\n\n
\n\nvar a = PI + PI / 3.0;\nvar s = sin(a);\nvar as = asin(s);\n// Prints: \"4.1887903 : -0.86602545 : -1.0471976\"\nprint(a + ' : ' + s + ' : ' + as);\n\n
\n" + "\n
\n\nlet a = PI + PI / 3;\nlet s = sin(a);\nlet as = asin(s);\n// Prints: \"1.0471976 : 0.86602545 : 1.0471976\"\nprint(a + ' : ' + s + ' : ' + as);\n\n
\n\n
\n\nlet a = PI + PI / 3.0;\nlet s = sin(a);\nlet as = asin(s);\n// Prints: \"4.1887903 : -0.86602545 : -1.0471976\"\nprint(a + ' : ' + s + ' : ' + as);\n\n
\n" ], "class": "p5", "module": "Math", @@ -14813,7 +15058,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nvar a = PI + PI / 3;\nvar t = tan(a);\nvar at = atan(t);\n// Prints: \"1.0471976 : 1.7320509 : 1.0471976\"\nprint(a + ' : ' + t + ' : ' + at);\n\n
\n\n
\n\nvar a = PI + PI / 3.0;\nvar t = tan(a);\nvar at = atan(t);\n// Prints: \"4.1887903 : 1.7320513 : 1.0471977\"\nprint(a + ' : ' + t + ' : ' + at);\n\n
\n" + "\n
\n\nlet a = PI + PI / 3;\nlet t = tan(a);\nlet at = atan(t);\n// Prints: \"1.0471976 : 1.7320509 : 1.0471976\"\nprint(a + ' : ' + t + ' : ' + at);\n\n
\n\n
\n\nlet a = PI + PI / 3.0;\nlet t = tan(a);\nlet at = atan(t);\n// Prints: \"4.1887903 : 1.7320513 : 1.0471977\"\nprint(a + ' : ' + t + ' : ' + at);\n\n
\n" ], "class": "p5", "module": "Math", @@ -14842,7 +15087,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nfunction draw() {\n background(204);\n translate(width / 2, height / 2);\n var a = atan2(mouseY - height / 2, mouseX - width / 2);\n rotate(a);\n rect(-30, -5, 60, 10);\n}\n\n
" + "\n
\n\nfunction draw() {\n background(204);\n translate(width / 2, height / 2);\n let a = atan2(mouseY - height / 2, mouseX - width / 2);\n rotate(a);\n rect(-30, -5, 60, 10);\n}\n\n
" ], "alt": "60 by 10 rect at center of canvas rotates with mouse movements", "class": "p5", @@ -14867,7 +15112,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nvar a = 0.0;\nvar inc = TWO_PI / 25.0;\nfor (var i = 0; i < 25; i++) {\n line(i * 4, 50, i * 4, 50 + cos(a) * 40.0);\n a = a + inc;\n}\n\n
" + "\n
\n\nlet a = 0.0;\nlet inc = TWO_PI / 25.0;\nfor (let i = 0; i < 25; i++) {\n line(i * 4, 50, i * 4, 50 + cos(a) * 40.0);\n a = a + inc;\n}\n\n
" ], "alt": "vertical black lines form wave patterns, extend-down on left and right side", "class": "p5", @@ -14892,7 +15137,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nvar a = 0.0;\nvar inc = TWO_PI / 25.0;\nfor (var i = 0; i < 25; i++) {\n line(i * 4, 50, i * 4, 50 + sin(a) * 40.0);\n a = a + inc;\n}\n\n
" + "\n
\n\nlet a = 0.0;\nlet inc = TWO_PI / 25.0;\nfor (let i = 0; i < 25; i++) {\n line(i * 4, 50, i * 4, 50 + sin(a) * 40.0);\n a = a + inc;\n}\n\n
" ], "alt": "vertical black lines extend down and up from center to form wave pattern", "class": "p5", @@ -14917,7 +15162,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nvar a = 0.0;\nvar inc = TWO_PI / 50.0;\nfor (var i = 0; i < 100; i = i + 2) {\n line(i, 50, i, 50 + tan(a) * 2.0);\n a = a + inc;\n}\n" + "\n
\n\nlet a = 0.0;\nlet inc = TWO_PI / 50.0;\nfor (let i = 0; i < 100; i = i + 2) {\n line(i, 50, i, 50 + tan(a) * 2.0);\n a = a + inc;\n}\n" ], "alt": "vertical black lines end down and up from center to form spike pattern", "class": "p5", @@ -14942,7 +15187,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nvar rad = PI / 4;\nvar deg = degrees(rad);\nprint(rad + ' radians is ' + deg + ' degrees');\n// Prints: 0.7853981633974483 radians is 45 degrees\n\n
\n" + "\n
\n\nlet rad = PI / 4;\nlet deg = degrees(rad);\nprint(rad + ' radians is ' + deg + ' degrees');\n// Prints: 0.7853981633974483 radians is 45 degrees\n\n
\n" ], "class": "p5", "module": "Math", @@ -14966,7 +15211,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nvar deg = 45.0;\nvar rad = radians(deg);\nprint(deg + ' degrees is ' + rad + ' radians');\n// Prints: 45 degrees is 0.7853981633974483 radians\n\n
" + "\n
\n\nlet deg = 45.0;\nlet rad = radians(deg);\nprint(deg + ' degrees is ' + rad + ' radians');\n// Prints: 45 degrees is 0.7853981633974483 radians\n\n
" ], "class": "p5", "module": "Math", @@ -14986,7 +15231,7 @@ module.exports={ } ], "example": [ - "\n
\n\nfunction draw() {\n background(204);\n angleMode(DEGREES); // Change the mode to DEGREES\n var a = atan2(mouseY - height / 2, mouseX - width / 2);\n translate(width / 2, height / 2);\n push();\n rotate(a);\n rect(-20, -5, 40, 10); // Larger rectangle is rotating in degrees\n pop();\n angleMode(RADIANS); // Change the mode to RADIANS\n rotate(a); // var a stays the same\n rect(-40, -5, 20, 10); // Smaller rectangle is rotating in radians\n}\n\n
" + "\n
\n\nfunction draw() {\n background(204);\n angleMode(DEGREES); // Change the mode to DEGREES\n let a = atan2(mouseY - height / 2, mouseX - width / 2);\n translate(width / 2, height / 2);\n push();\n rotate(a);\n rect(-20, -5, 40, 10); // Larger rectangle is rotating in degrees\n pop();\n angleMode(RADIANS); // Change the mode to RADIANS\n rotate(a); // variable a stays the same\n rect(-40, -5, 20, 10); // Smaller rectangle is rotating in radians\n}\n\n
" ], "alt": "40 by 10 rect in center rotates with mouse moves. 20 by 10 rect moves faster.", "class": "p5", @@ -15043,7 +15288,7 @@ module.exports={ "name": "textLeading", "chainable": 1, "example": [ - "\n
\n\n// Text to display. The \"\\n\" is a \"new line\" character\nvar lines = 'L1\\nL2\\nL3';\ntextSize(12);\n\ntextLeading(10); // Set leading to 10\ntext(lines, 10, 25);\n\ntextLeading(20); // Set leading to 20\ntext(lines, 40, 25);\n\ntextLeading(30); // Set leading to 30\ntext(lines, 70, 25);\n\n
" + "\n
\n\n// Text to display. The \"\\n\" is a \"new line\" character\nlet lines = 'L1\\nL2\\nL3';\ntextSize(12);\n\ntextLeading(10); // Set leading to 10\ntext(lines, 10, 25);\n\ntextLeading(20); // Set leading to 20\ntext(lines, 40, 25);\n\ntextLeading(30); // Set leading to 30\ntext(lines, 70, 25);\n\n
" ], "alt": "set L1 L2 & L3 displayed vertically 3 times. spacing increases for each set", "class": "p5", @@ -15110,14 +15355,14 @@ module.exports={ { "file": "src/typography/attributes.js", "line": 154, - "description": "

Sets/gets the style of the text for system fonts to NORMAL, ITALIC, or BOLD.\nNote: this may be is overridden by CSS styling. For non-system fonts\n(opentype, truetype, etc.) please load styled fonts instead.

\n", + "description": "

Sets/gets the style of the text for system fonts to NORMAL, ITALIC, BOLD or BOLDITALIC.\nNote: this may be is overridden by CSS styling. For non-system fonts\n(opentype, truetype, etc.) please load styled fonts instead.

\n", "itemtype": "method", "name": "textStyle", "chainable": 1, "example": [ - "\n
\n\nstrokeWeight(0);\ntextSize(12);\ntextStyle(NORMAL);\ntext('Font Style Normal', 10, 30);\ntextStyle(ITALIC);\ntext('Font Style Italic', 10, 60);\ntextStyle(BOLD);\ntext('Font Style Bold', 10, 90);\n\n
" + "\n
\n\nstrokeWeight(0);\ntextSize(12);\ntextStyle(NORMAL);\ntext('Font Style Normal', 10, 15);\ntextStyle(ITALIC);\ntext('Font Style Italic', 10, 40);\ntextStyle(BOLD);\ntext('Font Style Bold', 10, 65);\ntextStyle(BOLDITALIC);\ntext('Font Style Bold Italic', 10, 90);\n\n
" ], - "alt": "words Font Style Normal displayed normally, Italic in italic and bold in bold", + "alt": "words Font Style Normal displayed normally, Italic in italic, bold in bold and bold italic in bold italics.", "class": "p5", "module": "Typography", "submodule": "Attributes", @@ -15127,14 +15372,14 @@ module.exports={ "params": [ { "name": "theStyle", - "description": "

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

\n", + "description": "

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

\n", "type": "Constant" } ], "chainable": 1 }, { - "line": 180, + "line": 182, "params": [], "return": { "description": "", @@ -15145,7 +15390,7 @@ module.exports={ }, { "file": "src/typography/attributes.js", - "line": 189, + "line": 191, "description": "

Calculates and returns the width of any character or text string.

\n", "itemtype": "method", "name": "textWidth", @@ -15161,7 +15406,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\ntextSize(28);\n\nvar aChar = 'P';\nvar cWidth = textWidth(aChar);\ntext(aChar, 0, 40);\nline(cWidth, 0, cWidth, 50);\n\nvar aString = 'p5.js';\nvar sWidth = textWidth(aString);\ntext(aString, 0, 85);\nline(sWidth, 50, sWidth, 100);\n\n
" + "\n
\n\ntextSize(28);\n\nlet aChar = 'P';\nlet cWidth = textWidth(aChar);\ntext(aChar, 0, 40);\nline(cWidth, 0, cWidth, 50);\n\nlet aString = 'p5.js';\nlet sWidth = textWidth(aString);\ntext(aString, 0, 85);\nline(sWidth, 50, sWidth, 100);\n\n
" ], "alt": "Letter P and p5.js are displayed with vertical lines at end. P is wide", "class": "p5", @@ -15170,7 +15415,7 @@ module.exports={ }, { "file": "src/typography/attributes.js", - "line": 224, + "line": 226, "description": "

Returns the ascent of the current font at its current size. The ascent\nrepresents the distance, in pixels, of the tallest character above\nthe baseline.

\n", "itemtype": "method", "name": "textAscent", @@ -15179,7 +15424,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nvar base = height * 0.75;\nvar scalar = 0.8; // Different for each font\n\ntextSize(32); // Set initial text size\nvar asc = textAscent() * scalar; // Calc ascent\nline(0, base - asc, width, base - asc);\ntext('dp', 0, base); // Draw text on baseline\n\ntextSize(64); // Increase text size\nasc = textAscent() * scalar; // Recalc ascent\nline(40, base - asc, width, base - asc);\ntext('dp', 40, base); // Draw text on baseline\n\n
" + "\n
\n\nlet base = height * 0.75;\nlet scalar = 0.8; // Different for each font\n\ntextSize(32); // Set initial text size\nlet asc = textAscent() * scalar; // Calc ascent\nline(0, base - asc, width, base - asc);\ntext('dp', 0, base); // Draw text on baseline\n\ntextSize(64); // Increase text size\nasc = textAscent() * scalar; // Recalc ascent\nline(40, base - asc, width, base - asc);\ntext('dp', 40, base); // Draw text on baseline\n\n
" ], "class": "p5", "module": "Typography", @@ -15187,7 +15432,7 @@ module.exports={ }, { "file": "src/typography/attributes.js", - "line": 253, + "line": 255, "description": "

Returns the descent of the current font at its current size. The descent\nrepresents the distance, in pixels, of the character with the longest\ndescender below the baseline.

\n", "itemtype": "method", "name": "textDescent", @@ -15196,7 +15441,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\n\nvar base = height * 0.75;\nvar scalar = 0.8; // Different for each font\n\ntextSize(32); // Set initial text size\nvar desc = textDescent() * scalar; // Calc ascent\nline(0, base + desc, width, base + desc);\ntext('dp', 0, base); // Draw text on baseline\n\ntextSize(64); // Increase text size\ndesc = textDescent() * scalar; // Recalc ascent\nline(40, base + desc, width, base + desc);\ntext('dp', 40, base); // Draw text on baseline\n\n
" + "\n
\n\nlet base = height * 0.75;\nlet scalar = 0.8; // Different for each font\n\ntextSize(32); // Set initial text size\nlet desc = textDescent() * scalar; // Calc ascent\nline(0, base + desc, width, base + desc);\ntext('dp', 0, base); // Draw text on baseline\n\ntextSize(64); // Increase text size\ndesc = textDescent() * scalar; // Recalc ascent\nline(40, base + desc, width, base + desc);\ntext('dp', 40, base); // Draw text on baseline\n\n
" ], "class": "p5", "module": "Typography", @@ -15204,7 +15449,7 @@ module.exports={ }, { "file": "src/typography/attributes.js", - "line": 282, + "line": 284, "description": "

Helper function to measure ascent and descent.

\n", "class": "p5", "module": "Typography", @@ -15213,7 +15458,7 @@ module.exports={ { "file": "src/typography/loading_displaying.js", "line": 16, - "description": "

Loads an opentype font file (.otf, .ttf) from a file or a URL,\nand returns a PFont Object. This method is asynchronous,\nmeaning it may not finish before the next line in your sketch\nis executed.\n

\nThe path to the font should be relative to the HTML file\nthat links in your sketch. Loading an from a URL or other\nremote location may be blocked due to your browser's built-in\nsecurity.

\n", + "description": "

Loads an opentype font file (.otf, .ttf) from a file or a URL,\nand returns a PFont Object. This method is asynchronous,\nmeaning it may not finish before the next line in your sketch\nis executed.\n

\nThe path to the font should be relative to the HTML file\nthat links in your sketch. Loading fonts from a URL or other\nremote location may be blocked due to your browser's built-in\nsecurity.

\n", "itemtype": "method", "name": "loadFont", "params": [ @@ -15240,7 +15485,7 @@ module.exports={ "type": "p5.Font" }, "example": [ - "\n\n

Calling loadFont() inside preload() guarantees that the load\noperation will have completed before setup() and draw() are called.

\n\n
\nvar myFont;\nfunction preload() {\n myFont = loadFont('assets/AvenirNextLTPro-Demi.otf');\n}\n\nfunction setup() {\n fill('#ED225D');\n textFont(myFont);\n textSize(36);\n text('p5*js', 10, 50);\n}\n
\n\nOutside of preload(), you may supply a callback function to handle the\nobject:\n\n
\nfunction setup() {\n loadFont('assets/AvenirNextLTPro-Demi.otf', drawText);\n}\n\nfunction drawText(font) {\n fill('#ED225D');\n textFont(font, 36);\n text('p5*js', 10, 50);\n}\n
\n\n

You can also use the string name of the font to style other HTML\nelements.

\n\n
\nfunction preload() {\n loadFont('assets/Avenir.otf');\n}\n\nfunction setup() {\n var myDiv = createDiv('hello there');\n myDiv.style('font-family', 'Avenir');\n}\n
" + "\n\n

Calling loadFont() inside preload() guarantees that the load\noperation will have completed before setup() and draw() are called.

\n\n
\nlet myFont;\nfunction preload() {\n myFont = loadFont('assets/inconsolata.otf');\n}\n\nfunction setup() {\n fill('#ED225D');\n textFont(myFont);\n textSize(36);\n text('p5*js', 10, 50);\n}\n
\n\nOutside of preload(), you may supply a callback function to handle the\nobject:\n\n
\nfunction setup() {\n loadFont('assets/inconsolata.otf', drawText);\n}\n\nfunction drawText(font) {\n fill('#ED225D');\n textFont(font, 36);\n text('p5*js', 10, 50);\n}\n
\n\n

You can also use the font filename string (without the file extension) to style other HTML\nelements.

\n\n
\nfunction preload() {\n loadFont('assets/inconsolata.otf');\n}\n\nfunction setup() {\n let myDiv = createDiv('hello there');\n myDiv.style('font-family', 'Inconsolata');\n}\n
" ], "alt": "p5*js in p5's theme dark pink\np5*js in p5's theme dark pink", "class": "p5", @@ -15284,7 +15529,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\n\ntextSize(32);\ntext('word', 10, 30);\nfill(0, 102, 153);\ntext('word', 10, 60);\nfill(0, 102, 153, 51);\ntext('word', 10, 90);\n\n
\n
\n\nvar s = 'The quick brown fox jumped over the lazy dog.';\nfill(50);\ntext(s, 10, 10, 70, 80); // Text wraps within text box\n\n
\n\n
\n\nvar avenir;\nfunction preload() {\n avenir = loadFont('assets/Avenir.otf');\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n textFont(avenir);\n textSize(width / 3);\n textAlign(CENTER, CENTER);\n}\nfunction draw() {\n background(0);\n var time = millis();\n rotateX(time / 1000);\n rotateZ(time / 1234);\n text('p5.js', 0, 0);\n}\n\n
" + "\n
\n\ntextSize(32);\ntext('word', 10, 30);\nfill(0, 102, 153);\ntext('word', 10, 60);\nfill(0, 102, 153, 51);\ntext('word', 10, 90);\n\n
\n
\n\nlet s = 'The quick brown fox jumped over the lazy dog.';\nfill(50);\ntext(s, 10, 10, 70, 80); // Text wraps within text box\n\n
\n\n
\n\nlet inconsolata;\nfunction preload() {\n inconsolata = loadFont('assets/inconsolata.otf');\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n textFont(inconsolata);\n textSize(width / 3);\n textAlign(CENTER, CENTER);\n}\nfunction draw() {\n background(0);\n let time = millis();\n rotateX(time / 1000);\n rotateZ(time / 1234);\n text('p5.js', 0, 0);\n}\n\n
" ], "alt": "'word' displayed 3 times going from black, blue to translucent blue\nThe quick brown fox jumped over the lazy dog.\nthe text 'p5.js' spinning in 3d", "class": "p5", @@ -15302,7 +15547,7 @@ module.exports={ "type": "Object" }, "example": [ - "\n
\n\nfill(0);\ntextSize(12);\ntextFont('Georgia');\ntext('Georgia', 12, 30);\ntextFont('Helvetica');\ntext('Helvetica', 12, 60);\n\n
\n
\n\nvar fontRegular, fontItalic, fontBold;\nfunction preload() {\n fontRegular = loadFont('assets/Regular.otf');\n fontItalic = loadFont('assets/Italic.ttf');\n fontBold = loadFont('assets/Bold.ttf');\n}\nfunction setup() {\n background(210);\n fill(0)\n .strokeWeight(0)\n .textSize(10);\n textFont(fontRegular);\n text('Font Style Normal', 10, 30);\n textFont(fontItalic);\n text('Font Style Italic', 10, 50);\n textFont(fontBold);\n text('Font Style Bold', 10, 70);\n}\n\n
" + "\n
\n\nfill(0);\ntextSize(12);\ntextFont('Georgia');\ntext('Georgia', 12, 30);\ntextFont('Helvetica');\ntext('Helvetica', 12, 60);\n\n
\n
\n\nlet fontRegular, fontItalic, fontBold;\nfunction preload() {\n fontRegular = loadFont('assets/Regular.otf');\n fontItalic = loadFont('assets/Italic.ttf');\n fontBold = loadFont('assets/Bold.ttf');\n}\nfunction setup() {\n background(210);\n fill(0)\n .strokeWeight(0)\n .textSize(10);\n textFont(fontRegular);\n text('Font Style Normal', 10, 30);\n textFont(fontItalic);\n text('Font Style Italic', 10, 50);\n textFont(fontBold);\n text('Font Style Bold', 10, 70);\n}\n\n
" ], "alt": "words Font Style Normal displayed normally, Italic in italic and bold in bold", "class": "p5", @@ -15338,7 +15583,7 @@ module.exports={ }, { "file": "src/typography/p5.Font.js", - "line": 31, + "line": 25, "description": "

Underlying opentype font implementation

\n", "itemtype": "property", "name": "font", @@ -15348,7 +15593,7 @@ module.exports={ }, { "file": "src/typography/p5.Font.js", - "line": 43, + "line": 32, "description": "

Returns a tight bounding box for the given text string using this\nfont (currently only supports single lines)

\n", "itemtype": "method", "name": "textBounds", @@ -15370,13 +15615,13 @@ module.exports={ }, { "name": "fontSize", - "description": "

font size to use (optional)

\n", + "description": "

font size to use (optional) Default is 12.

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

opentype options (optional)

\n", + "description": "

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

\n", "type": "Object", "optional": true } @@ -15386,7 +15631,7 @@ module.exports={ "type": "Object" }, "example": [ - "\n
\n\nvar font;\nvar textString = 'Lorem ipsum dolor sit amet.';\nfunction preload() {\n font = loadFont('./assets/Regular.otf');\n}\nfunction setup() {\n background(210);\n\n var bbox = font.textBounds(textString, 10, 30, 12);\n fill(255);\n stroke(0);\n rect(bbox.x, bbox.y, bbox.w, bbox.h);\n fill(0);\n noStroke();\n\n textFont(font);\n textSize(12);\n text(textString, 10, 30);\n}\n\n
" + "\n
\n\nlet font;\nlet textString = 'Lorem ipsum dolor sit amet.';\nfunction preload() {\n font = loadFont('./assets/Regular.otf');\n}\nfunction setup() {\n background(210);\n\n let bbox = font.textBounds(textString, 10, 30, 12);\n fill(255);\n stroke(0);\n rect(bbox.x, bbox.y, bbox.w, bbox.h);\n fill(0);\n noStroke();\n\n textFont(font);\n textSize(12);\n text(textString, 10, 30);\n}\n\n
" ], "alt": "words Lorem ipsum dol go off canvas and contained by white bounding box", "class": "p5.Font", @@ -15395,7 +15640,7 @@ module.exports={ }, { "file": "src/typography/p5.Font.js", - "line": 157, + "line": 156, "description": "

Computes an array of points following the path for specified text

\n", "itemtype": "method", "name": "textToPoints", @@ -15422,7 +15667,7 @@ module.exports={ }, { "name": "options", - "description": "

an (optional) object that can contain:

\n


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

\n


simplifyThreshold - if set to a non-zero value, collinear points will be\nbe removed from the polygon; the value represents the threshold angle to use\nwhen determining whether two edges are collinear

\n", + "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", "type": "Object", "optional": true } @@ -15432,7 +15677,7 @@ module.exports={ "type": "Array" }, "example": [ - "\n
\n\nvar font;\nfunction preload() {\n font = loadFont('./assets/Avenir.otf');\n}\n\nvar points;\nvar bounds;\nfunction setup() {\n createCanvas(100, 100);\n stroke(0);\n fill(255, 104, 204);\n\n points = font.textToPoints('p5', 0, 0, 10, {\n sampleFactor: 5,\n simplifyThreshold: 0\n });\n bounds = font.textBounds(' p5 ', 0, 0, 10);\n}\n\nfunction draw() {\n background(255);\n beginShape();\n translate(-bounds.x * width / bounds.w, -bounds.y * height / bounds.h);\n for (var i = 0; i < points.length; i++) {\n var p = points[i];\n vertex(\n p.x * width / bounds.w +\n sin(20 * p.y / bounds.h + millis() / 1000) * width / 30,\n p.y * height / bounds.h\n );\n }\n endShape(CLOSE);\n}\n\n
\n" + "\n
\n\nlet font;\nfunction preload() {\n font = loadFont('assets/inconsolata.otf');\n}\n\nlet points;\nlet bounds;\nfunction setup() {\n createCanvas(100, 100);\n stroke(0);\n fill(255, 104, 204);\n\n points = font.textToPoints('p5', 0, 0, 10, {\n sampleFactor: 5,\n simplifyThreshold: 0\n });\n bounds = font.textBounds(' p5 ', 0, 0, 10);\n}\n\nfunction draw() {\n background(255);\n beginShape();\n translate(-bounds.x * width / bounds.w, -bounds.y * height / bounds.h);\n for (let i = 0; i < points.length; i++) {\n let p = points[i];\n vertex(\n p.x * width / bounds.w +\n sin(20 * p.y / bounds.h + millis() / 1000) * width / 30,\n p.y * height / bounds.h\n );\n }\n endShape(CLOSE);\n}\n\n
\n" ], "class": "p5.Font", "module": "Typography", @@ -15625,8 +15870,6 @@ module.exports={ "description": "

Randomizes the order of the elements of an array. Implements\n\nFisher-Yates Shuffle Algorithm.

\n", "itemtype": "method", "name": "shuffle", - "deprecated": true, - "deprecationMessage": "See shuffling an array with JS instead.", "params": [ { "name": "array", @@ -15653,7 +15896,7 @@ module.exports={ }, { "file": "src/utilities/array_functions.js", - "line": 234, + "line": 233, "description": "

Sorts an array of numbers from smallest to largest, or puts an array of\nwords in alphabetical order. The original array is not modified; a\nre-ordered array is returned. The count parameter states the number of\nelements to sort. For example, if there are 12 elements in an array and\ncount is set to 5, only the first 5 elements in the array will be sorted.

\n", "itemtype": "method", "name": "sort", @@ -15685,7 +15928,7 @@ module.exports={ }, { "file": "src/utilities/array_functions.js", - "line": 282, + "line": 281, "description": "

Inserts a value or an array of values into an existing array. The first\nparameter specifies the initial array to be modified, and the second\nparameter defines the data to be inserted. The third parameter is an index\nvalue which specifies the array position from which to insert data.\n(Remember that array index numbering starts at zero, so the first position\nis 0, the second position is 1, and so on.)

\n", "itemtype": "method", "name": "splice", @@ -15721,7 +15964,7 @@ module.exports={ }, { "file": "src/utilities/array_functions.js", - "line": 317, + "line": 316, "description": "

Extracts an array of elements from an existing array. The list parameter\ndefines the array from which the elements will be copied, and the start\nand count parameters specify which elements to extract. If no count is\ngiven, elements will be extracted from the start to the end of the array.\nWhen specifying the start, remember that the first array element is 0.\nThis function does not change the source array.

\n", "itemtype": "method", "name": "subset", @@ -15774,7 +16017,7 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\nvar str = '20';\nvar diameter = float(str);\nellipse(width / 2, height / 2, diameter, diameter);\n
" + "\n
\nvar str = '20';\nvar diameter = float(str);\nellipse(width / 2, height / 2, diameter, diameter);\n
\n
\nprint(float('10.31')); // 10.31\nprint(float('Infinity')); // Infinity\nprint(float('-Infinity')); // -Infinity\n
" ], "alt": "20 by 20 white ellipse in the center of the canvas", "class": "p5", @@ -15783,7 +16026,7 @@ module.exports={ }, { "file": "src/utilities/conversion.js", - "line": 42, + "line": 47, "description": "

Converts a boolean, string, or float to its integer representation.\nWhen an array of values is passed in, then an int array of the same length\nis returned.

\n", "itemtype": "method", "name": "int", @@ -15792,14 +16035,14 @@ module.exports={ "type": "Number" }, "example": [ - "\n
\nprint(int('10')); // 10\nprint(int(10.31)); // 10\nprint(int(-10)); // -10\nprint(int(true)); // 1\nprint(int(false)); // 0\nprint(int([false, true, '10.3', 9.8])); // [0, 1, 10, 9]\n
" + "\n
\nprint(int('10')); // 10\nprint(int(10.31)); // 10\nprint(int(-10)); // -10\nprint(int(true)); // 1\nprint(int(false)); // 0\nprint(int([false, true, '10.3', 9.8])); // [0, 1, 10, 9]\nprint(int(Infinity)); // Infinity\nprint(int('-Infinity')); // -Infinity\n
" ], "class": "p5", "module": "Data", "submodule": "Conversion", "overloads": [ { - "line": 42, + "line": 47, "params": [ { "name": "n", @@ -15819,7 +16062,7 @@ module.exports={ } }, { - "line": 62, + "line": 69, "params": [ { "name": "ns", @@ -15836,7 +16079,7 @@ module.exports={ }, { "file": "src/utilities/conversion.js", - "line": 82, + "line": 93, "description": "

Converts a boolean, string or number to its string representation.\nWhen an array of values is passed in, then an array of strings of the same\nlength is returned.

\n", "itemtype": "method", "name": "str", @@ -15860,7 +16103,7 @@ module.exports={ }, { "file": "src/utilities/conversion.js", - "line": 108, + "line": 119, "description": "

Converts a number or string to its boolean representation.\nFor a number, any non-zero value (positive or negative) evaluates to true,\nwhile zero evaluates to false. For a string, the value "true" evaluates to\ntrue, while any other value evaluates to false. When an array of number or\nstring values is passed in, then a array of booleans of the same length is\nreturned.

\n", "itemtype": "method", "name": "boolean", @@ -15876,7 +16119,7 @@ module.exports={ "type": "Boolean" }, "example": [ - "\n
\nprint(boolean(0)); // false\nprint(boolean(1)); // true\nprint(boolean('true')); // true\nprint(boolean('abcd')); // false\nprint(boolean([0, 12, 'true'])); // [false, true, false]\n
" + "\n
\nprint(boolean(0)); // false\nprint(boolean(1)); // true\nprint(boolean('true')); // true\nprint(boolean('abcd')); // false\nprint(boolean([0, 12, 'true'])); // [false, true, true]\n
" ], "class": "p5", "module": "Data", @@ -15884,7 +16127,7 @@ module.exports={ }, { "file": "src/utilities/conversion.js", - "line": 140, + "line": 151, "description": "

Converts a number, string representation of a number, or boolean to its byte\nrepresentation. A byte can be only a whole number between -128 and 127, so\nwhen a value outside of this range is converted, it wraps around to the\ncorresponding byte representation. When an array of number, string or boolean\nvalues is passed in, then an array of bytes the same length is returned.

\n", "itemtype": "method", "name": "byte", @@ -15900,7 +16143,7 @@ module.exports={ "submodule": "Conversion", "overloads": [ { - "line": 140, + "line": 151, "params": [ { "name": "n", @@ -15914,7 +16157,7 @@ module.exports={ } }, { - "line": 162, + "line": 173, "params": [ { "name": "ns", @@ -15931,7 +16174,7 @@ module.exports={ }, { "file": "src/utilities/conversion.js", - "line": 176, + "line": 187, "description": "

Converts a number or string to its corresponding single-character\nstring representation. If a string parameter is provided, it is first\nparsed as an integer and then translated into a single-character string.\nWhen an array of number or string values is passed in, then an array of\nsingle-character strings of the same length is returned.

\n", "itemtype": "method", "name": "char", @@ -15947,7 +16190,7 @@ module.exports={ "submodule": "Conversion", "overloads": [ { - "line": 176, + "line": 187, "params": [ { "name": "n", @@ -15961,7 +16204,7 @@ module.exports={ } }, { - "line": 195, + "line": 206, "params": [ { "name": "ns", @@ -15978,7 +16221,7 @@ module.exports={ }, { "file": "src/utilities/conversion.js", - "line": 210, + "line": 221, "description": "

Converts a single-character string to its corresponding integer\nrepresentation. When an array of single-character string values is passed\nin, then an array of integers of the same length is returned.

\n", "itemtype": "method", "name": "unchar", @@ -15994,7 +16237,7 @@ module.exports={ "submodule": "Conversion", "overloads": [ { - "line": 210, + "line": 221, "params": [ { "name": "n", @@ -16008,7 +16251,7 @@ module.exports={ } }, { - "line": 226, + "line": 237, "params": [ { "name": "ns", @@ -16025,7 +16268,7 @@ module.exports={ }, { "file": "src/utilities/conversion.js", - "line": 239, + "line": 250, "description": "

Converts a number to a string in its equivalent hexadecimal notation. If a\nsecond parameter is passed, it is used to set the number of characters to\ngenerate in the hexadecimal notation. When an array is passed in, an\narray of strings in hexadecimal notation of the same length is returned.

\n", "itemtype": "method", "name": "hex", @@ -16034,14 +16277,14 @@ module.exports={ "type": "String" }, "example": [ - "\n
\nprint(hex(255)); // \"000000FF\"\nprint(hex(255, 6)); // \"0000FF\"\nprint(hex([0, 127, 255], 6)); // [ \"000000\", \"00007F\", \"0000FF\" ]\n
" + "\n
\nprint(hex(255)); // \"000000FF\"\nprint(hex(255, 6)); // \"0000FF\"\nprint(hex([0, 127, 255], 6)); // [ \"000000\", \"00007F\", \"0000FF\" ]\nprint(Infinity); // \"FFFFFFFF\"\nprint(-Infinity); // \"00000000\"\n
" ], "class": "p5", "module": "Data", "submodule": "Conversion", "overloads": [ { - "line": 239, + "line": 250, "params": [ { "name": "n", @@ -16061,7 +16304,7 @@ module.exports={ } }, { - "line": 257, + "line": 270, "params": [ { "name": "ns", @@ -16084,7 +16327,7 @@ module.exports={ }, { "file": "src/utilities/conversion.js", - "line": 286, + "line": 302, "description": "

Converts a string representation of a hexadecimal number to its equivalent\ninteger value. When an array of strings in hexadecimal notation is passed\nin, an array of integers of the same length is returned.

\n", "itemtype": "method", "name": "unhex", @@ -16100,7 +16343,7 @@ module.exports={ "submodule": "Conversion", "overloads": [ { - "line": 286, + "line": 302, "params": [ { "name": "n", @@ -16114,7 +16357,7 @@ module.exports={ } }, { - "line": 302, + "line": 318, "params": [ { "name": "ns", @@ -16221,7 +16464,7 @@ module.exports={ { "file": "src/utilities/string_functions.js", "line": 132, - "description": "

Utility function for formatting numbers into strings. There are two\nversions: one for formatting floats, and one for formatting ints.\nThe values for the digits, left, and right parameters should always\nbe positive integers.

\n", + "description": "

Utility function for formatting numbers into strings. There are two\nversions: one for formatting floats, and one for formatting ints.\nThe values for the digits, left, and right parameters should always\nbe positive integers.\n(NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter\nif greater than the current length of the number.\nFor example if number is 123.2 and left parameter passed is 4 which is greater than length of 123\n(integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than\nthe result will be 123.200.

\n", "itemtype": "method", "name": "nf", "return": { @@ -16229,9 +16472,9 @@ module.exports={ "type": "String" }, "example": [ - "\n
\n\nfunction setup() {\n background(200);\n var num = 112.53106115;\n\n noStroke();\n fill(0);\n textSize(14);\n // Draw formatted numbers\n text(nf(num, 5, 2), 10, 20);\n\n text(nf(num, 4, 3), 10, 55);\n\n text(nf(num, 3, 6), 10, 85);\n\n // Draw dividing lines\n stroke(120);\n line(0, 30, width, 30);\n line(0, 65, width, 65);\n}\n\n
" + "\n
\n\nvar myFont;\nfunction preload() {\n myFont = loadFont('assets/fonts/inconsolata.ttf');\n}\nfunction setup() {\n background(200);\n var num1 = 321;\n var num2 = -1321;\n\n noStroke();\n fill(0);\n textFont(myFont);\n textSize(22);\n\n text(nf(num1, 4, 2), 10, 30);\n text(nf(num2, 4, 2), 10, 80);\n // Draw dividing line\n stroke(120);\n line(0, 50, width, 50);\n}\n\n
" ], - "alt": "\"0011253\" top left, \"0112.531\" mid left, \"112.531061\" bottom left canvas", + "alt": "\"0321.00\" middle top, -1321.00\" middle bottom canvas", "class": "p5", "module": "Data", "submodule": "String Functions", @@ -16263,7 +16506,7 @@ module.exports={ } }, { - "line": 174, + "line": 180, "params": [ { "name": "nums", @@ -16292,7 +16535,7 @@ module.exports={ }, { "file": "src/utilities/string_functions.js", - "line": 237, + "line": 243, "description": "

Utility function for formatting numbers into strings and placing\nappropriate commas to mark units of 1000. There are two versions: one\nfor formatting ints, and one for formatting an array of ints. The value\nfor the right parameter should always be a positive integer.

\n", "itemtype": "method", "name": "nfc", @@ -16309,7 +16552,7 @@ module.exports={ "submodule": "String Functions", "overloads": [ { - "line": 237, + "line": 243, "params": [ { "name": "num", @@ -16329,7 +16572,7 @@ module.exports={ } }, { - "line": 275, + "line": 281, "params": [ { "name": "nums", @@ -16352,7 +16595,7 @@ module.exports={ }, { "file": "src/utilities/string_functions.js", - "line": 313, + "line": 319, "description": "

Utility function for formatting numbers into strings. Similar to nf() but\nputs a "+" in front of positive numbers and a "-" in front of negative\nnumbers. There are two versions: one for formatting floats, and one for\nformatting ints. The values for left, and right parameters\nshould always be positive integers.

\n", "itemtype": "method", "name": "nfp", @@ -16369,7 +16612,7 @@ module.exports={ "submodule": "String Functions", "overloads": [ { - "line": 313, + "line": 319, "params": [ { "name": "num", @@ -16395,7 +16638,7 @@ module.exports={ } }, { - "line": 354, + "line": 360, "params": [ { "name": "nums", @@ -16424,8 +16667,8 @@ module.exports={ }, { "file": "src/utilities/string_functions.js", - "line": 375, - "description": "

Utility function for formatting numbers into strings. Similar to nf() but\nputs a " " (space) in front of positive numbers and a "-" in front of\nnegative numbers. There are two versions: one for formatting floats, and\none for formatting ints. The values for the digits, left, and right\nparameters should always be positive integers.

\n", + "line": 381, + "description": "

Utility function for formatting numbers into strings. Similar to nf() but\nputs an additional "_" (space) in front of positive numbers just in case to align it with negative\nnumbers which includes "-" (minus) sign.\nThe main usecase of nfs() can be seen when one wants to align the digits (place values) of a positive\nnumber with some negative number (See the example to get a clear picture).\nThere are two versions: one for formatting float, and one for formatting int.\nThe values for the digits, left, and right parameters should always be positive integers.\n(IMP): The result on the canvas basically the expected alignment can vary based on the typeface you are using.\n(NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter\nif greater than the current length of the number.\nFor example if number is 123.2 and left parameter passed is 4 which is greater than length of 123\n(integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than\nthe result will be 123.200.

\n", "itemtype": "method", "name": "nfs", "return": { @@ -16433,15 +16676,15 @@ module.exports={ "type": "String" }, "example": [ - "\n
\n\nfunction setup() {\n background(200);\n var num1 = 11253106.115;\n var num2 = -11253106.115;\n\n noStroke();\n fill(0);\n textSize(12);\n // Draw formatted numbers\n text(nfs(num1, 4, 2), 10, 30);\n\n text(nfs(num2, 4, 2), 10, 80);\n\n // Draw dividing line\n stroke(120);\n line(0, 50, width, 50);\n}\n\n
" + "\n
\n\nvar myFont;\nfunction preload() {\n myFont = loadFont('assets/fonts/inconsolata.ttf');\n}\nfunction setup() {\n background(200);\n var num1 = 321;\n var num2 = -1321;\n\n noStroke();\n fill(0);\n textFont(myFont);\n textSize(22);\n\n // nfs() aligns num1 (positive number) with num2 (negative number) by\n // adding a blank space in front of the num1 (positive number)\n // [left = 4] in num1 add one 0 in front, to align the digits with num2\n // [right = 2] in num1 and num2 adds two 0's after both numbers\n // To see the differences check the example of nf() too.\n text(nfs(num1, 4, 2), 10, 30);\n text(nfs(num2, 4, 2), 10, 80);\n // Draw dividing line\n stroke(120);\n line(0, 50, width, 50);\n}\n\n
" ], - "alt": "\"11253106.11\" top middle and \"-11253106.11\" displayed bottom middle", + "alt": "\"0321.00\" top middle and \"-1321.00\" displayed bottom middle", "class": "p5", "module": "Data", "submodule": "String Functions", "overloads": [ { - "line": 375, + "line": 381, "params": [ { "name": "num", @@ -16467,7 +16710,7 @@ module.exports={ } }, { - "line": 416, + "line": 438, "params": [ { "name": "nums", @@ -16496,7 +16739,7 @@ module.exports={ }, { "file": "src/utilities/string_functions.js", - "line": 437, + "line": 459, "description": "

The split() function maps to String.split(), it breaks a String into\npieces using a character or string as the delimiter. The delim parameter\nspecifies the character or characters that mark the boundaries between\neach piece. A String[] array is returned that contains each of the pieces.

\n

The splitTokens() function works in a similar fashion, except that it\nsplits using a range of characters instead of a specific character or\nsequence.

\n", "itemtype": "method", "name": "split", @@ -16526,7 +16769,7 @@ module.exports={ }, { "file": "src/utilities/string_functions.js", - "line": 471, + "line": 493, "description": "

The splitTokens() function splits a String at one or many character\ndelimiters or "tokens." The delim parameter specifies the character or\ncharacters to be used as a boundary.\n

\nIf no delim characters are specified, any whitespace character is used to\nsplit. Whitespace characters include tab (\\t), line feed (\\n), carriage\nreturn (\\r), form feed (\\f), and space.

\n", "itemtype": "method", "name": "splitTokens", @@ -16556,7 +16799,7 @@ module.exports={ }, { "file": "src/utilities/string_functions.js", - "line": 526, + "line": 548, "description": "

Removes whitespace characters from the beginning and end of a String. In\naddition to standard whitespace characters such as space, carriage return,\nand tab, this function also removes the Unicode "nbsp" character.

\n", "itemtype": "method", "name": "trim", @@ -16573,7 +16816,7 @@ module.exports={ "submodule": "String Functions", "overloads": [ { - "line": 526, + "line": 548, "params": [ { "name": "str", @@ -16587,7 +16830,7 @@ module.exports={ } }, { - "line": 546, + "line": 568, "params": [ { "name": "strs", @@ -16730,7 +16973,7 @@ module.exports={ }, { "file": "src/webgl/3d_primitives.js", - "line": 15, + "line": 14, "description": "

Draw a plane with given a width and height

\n", "itemtype": "method", "name": "plane", @@ -16762,7 +17005,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\n\n//draw a plane with width 50 and height 50\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n plane(50, 50);\n}\n\n
" + "\n
\n\n// draw a plane\n// with width 50 and height 50\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n plane(50, 50);\n}\n\n
" ], "alt": "Nothing displayed on canvas\nRotating interior view of a box with sides that change color.\n3d red and green gradient.\nRotating interior view of a cylinder with sides that change color.\nRotating view of a cylinder with sides that change color.\n3d red and green gradient.\nrotating view of a multi-colored cylinder with concave sides.", "class": "p5", @@ -16809,7 +17052,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\n\n//draw a spinning box with width, height and depth 200\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(50);\n}\n\n
" + "\n
\n\n// draw a spinning box\n// with width, height and depth of 50\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(50);\n}\n\n
" ], "class": "p5", "module": "Shape", @@ -16817,7 +17060,7 @@ module.exports={ }, { "file": "src/webgl/3d_primitives.js", - "line": 215, + "line": 216, "description": "

Draw a sphere with given radius

\n", "itemtype": "method", "name": "sphere", @@ -16843,7 +17086,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\n\n// draw a sphere with radius 200\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n sphere(40);\n}\n\n
" + "\n
\n\n// draw a sphere with radius 40\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n sphere(40);\n}\n\n
" ], "class": "p5", "module": "Shape", @@ -16851,7 +17094,7 @@ module.exports={ }, { "file": "src/webgl/3d_primitives.js", - "line": 393, + "line": 378, "description": "

Draw a cylinder with given radius and height

\n", "itemtype": "method", "name": "cylinder", @@ -16895,7 +17138,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\n\n//draw a spinning cylinder with radius 20 and height 50\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateZ(frameCount * 0.01);\n cylinder(20, 50);\n}\n\n
" + "\n
\n\n// draw a spinning cylinder\n// with radius 20 and height 50\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateZ(frameCount * 0.01);\n cylinder(20, 50);\n}\n\n
" ], "class": "p5", "module": "Shape", @@ -16903,7 +17146,7 @@ module.exports={ }, { "file": "src/webgl/3d_primitives.js", - "line": 484, + "line": 470, "description": "

Draw a cone with given radius and height

\n", "itemtype": "method", "name": "cone", @@ -16941,7 +17184,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\n\n//draw a spinning cone with radius 40 and height 70\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateZ(frameCount * 0.01);\n cone(40, 70);\n}\n\n
" + "\n
\n\n// draw a spinning cone\n// with radius 40 and height 70\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateZ(frameCount * 0.01);\n cone(40, 70);\n}\n\n
" ], "class": "p5", "module": "Shape", @@ -16949,26 +17192,26 @@ module.exports={ }, { "file": "src/webgl/3d_primitives.js", - "line": 555, + "line": 540, "description": "

Draw an ellipsoid with given radius

\n", "itemtype": "method", "name": "ellipsoid", "params": [ { "name": "radiusx", - "description": "

xradius of circle

\n", + "description": "

x-radius of ellipsoid

\n", "type": "Number", "optional": true }, { "name": "radiusy", - "description": "

yradius of circle

\n", + "description": "

y-radius of ellipsoid

\n", "type": "Number", "optional": true }, { "name": "radiusz", - "description": "

zradius of circle

\n", + "description": "

z-radius of ellipsoid

\n", "type": "Number", "optional": true }, @@ -16987,7 +17230,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\n\n// draw an ellipsoid with radius 20, 30 and 40.\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n ellipsoid(20, 30, 40);\n}\n\n
" + "\n
\n\n// draw an ellipsoid\n// with radius 30, 40 and 40.\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n ellipsoid(30, 40, 40);\n}\n\n
" ], "class": "p5", "module": "Shape", @@ -16995,7 +17238,7 @@ module.exports={ }, { "file": "src/webgl/3d_primitives.js", - "line": 645, + "line": 631, "description": "

Draw a torus with given radius and tube radius

\n", "itemtype": "method", "name": "torus", @@ -17027,7 +17270,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\n\n//draw a spinning torus with radius 200 and tube radius 60\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n torus(50, 15);\n}\n\n
" + "\n
\n\n// draw a spinning torus\n// with ring radius 30 and tube radius 15\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n torus(30, 15);\n}\n\n
" ], "class": "p5", "module": "Shape", @@ -17184,19 +17427,19 @@ module.exports={ "optional": true }, { - "name": "xOff", + "name": "gridXOff", "description": "", "type": "Number", "optional": true }, { - "name": "yOff", + "name": "gridYOff", "description": "", "type": "Number", "optional": true }, { - "name": "zOff", + "name": "gridZOff", "description": "", "type": "Number", "optional": true @@ -17208,19 +17451,19 @@ module.exports={ "optional": true }, { - "name": "xOff", + "name": "axesXOff", "description": "", "type": "Number", "optional": true }, { - "name": "yOff", + "name": "axesYOff", "description": "", "type": "Number", "optional": true }, { - "name": "zOff", + "name": "axesZOff", "description": "", "type": "Number", "optional": true @@ -17251,7 +17494,7 @@ module.exports={ "name": "ambientLight", "chainable": 1, "example": [ - "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n ambientLight(150);\n ambientMaterial(250);\n noStroke();\n sphere(25);\n}\n\n
" + "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n ambientLight(150);\n ambientMaterial(250);\n noStroke();\n sphere(40);\n}\n\n
" ], "alt": "evenly distributed light across a sphere", "class": "p5", @@ -17339,13 +17582,13 @@ module.exports={ }, { "file": "src/webgl/light.js", - "line": 101, + "line": 87, "description": "

Creates a directional light with a color and a direction

\n", "itemtype": "method", "name": "directionalLight", "chainable": 1, "example": [ - "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n //move your mouse to change light direction\n var dirX = (mouseX / width - 0.5) * 2;\n var dirY = (mouseY / height - 0.5) * 2;\n directionalLight(250, 250, 250, -dirX, -dirY, 0.25);\n ambientMaterial(250);\n noStroke();\n sphere(25);\n}\n\n
" + "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n //move your mouse to change light direction\n let dirX = (mouseX / width - 0.5) * 2;\n let dirY = (mouseY / height - 0.5) * 2;\n directionalLight(250, 250, 250, -dirX, -dirY, -1);\n noStroke();\n sphere(40);\n}\n\n
" ], "alt": "light source on canvas changeable with mouse position", "class": "p5", @@ -17353,7 +17596,7 @@ module.exports={ "submodule": "Lights", "overloads": [ { - "line": 101, + "line": 87, "params": [ { "name": "v1", @@ -17379,7 +17622,7 @@ module.exports={ "chainable": 1 }, { - "line": 134, + "line": 119, "params": [ { "name": "color", @@ -17405,7 +17648,7 @@ module.exports={ "chainable": 1 }, { - "line": 144, + "line": 129, "params": [ { "name": "color", @@ -17421,7 +17664,7 @@ module.exports={ "chainable": 1 }, { - "line": 151, + "line": 136, "params": [ { "name": "v1", @@ -17460,13 +17703,13 @@ module.exports={ }, { "file": "src/webgl/light.js", - "line": 212, + "line": 185, "description": "

Creates a point light with a color and a light position

\n", "itemtype": "method", "name": "pointLight", "chainable": 1, "example": [ - "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n //move your mouse to change light position\n var locX = mouseX - width / 2;\n var locY = mouseY - height / 2;\n // to set the light position,\n // think of the world's coordinate as:\n // -width/2,-height/2 -------- width/2,-height/2\n // | |\n // | 0,0 |\n // | |\n // -width/2,height/2--------width/2,height/2\n pointLight(250, 250, 250, locX, locY, 50);\n ambientMaterial(250);\n noStroke();\n sphere(25);\n}\n\n
" + "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n //move your mouse to change light position\n let locX = mouseX - width / 2;\n let locY = mouseY - height / 2;\n // to set the light position,\n // think of the world's coordinate as:\n // -width/2,-height/2 -------- width/2,-height/2\n // | |\n // | 0,0 |\n // | |\n // -width/2,height/2--------width/2,height/2\n pointLight(250, 250, 250, locX, locY, 50);\n noStroke();\n sphere(40);\n}\n\n
" ], "alt": "spot light on canvas changes position with mouse", "class": "p5", @@ -17474,7 +17717,7 @@ module.exports={ "submodule": "Lights", "overloads": [ { - "line": 212, + "line": 185, "params": [ { "name": "v1", @@ -17510,7 +17753,7 @@ module.exports={ "chainable": 1 }, { - "line": 254, + "line": 226, "params": [ { "name": "v1", @@ -17536,7 +17779,7 @@ module.exports={ "chainable": 1 }, { - "line": 263, + "line": 235, "params": [ { "name": "color", @@ -17562,7 +17805,7 @@ module.exports={ "chainable": 1 }, { - "line": 273, + "line": 245, "params": [ { "name": "color", @@ -17579,6 +17822,21 @@ module.exports={ } ] }, + { + "file": "src/webgl/light.js", + "line": 287, + "description": "

Sets the default ambient and directional light. The defaults are ambientLight(128, 128, 128) and directionalLight(128, 128, 128, 0, 0, -1). Lights need to be included in the draw() to remain persistent in a looping program. Placing them in the setup() of a looping program will cause them to only have an effect the first time through the loop.

\n", + "itemtype": "method", + "name": "lights", + "chainable": 1, + "example": [ + "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n lights();\n rotateX(millis() / 1000);\n rotateY(millis() / 1000);\n rotateZ(millis() / 1000);\n box();\n}\n\n
" + ], + "alt": "the light is partially ambient and partially directional", + "class": "p5", + "module": "Lights, Camera", + "submodule": "Lights" + }, { "file": "src/webgl/loading.js", "line": 14, @@ -17590,8 +17848,8 @@ module.exports={ "type": "p5.Geometry" }, "example": [ - "\n
\n\n//draw a spinning octahedron\nvar octahedron;\n\nfunction preload() {\n octahedron = loadModel('assets/octahedron.obj');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n model(octahedron);\n}\n\n
", - "\n
\n\n//draw a spinning teapot\nvar teapot;\n\nfunction preload() {\n // Load model with normalise parameter set to true\n teapot = loadModel('assets/teapot.obj', true);\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n scale(0.4); // Scaled to make model fit into canvas\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n normalMaterial(); // For effect\n model(teapot);\n}\n\n
" + "\n
\n\n//draw a spinning octahedron\nlet octahedron;\n\nfunction preload() {\n octahedron = loadModel('assets/octahedron.obj');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n model(octahedron);\n}\n\n
", + "\n
\n\n//draw a spinning teapot\nlet teapot;\n\nfunction preload() {\n // Load model with normalise parameter set to true\n teapot = loadModel('assets/teapot.obj', true);\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n scale(0.4); // Scaled to make model fit into canvas\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n normalMaterial(); // For effect\n model(teapot);\n}\n\n
" ], "alt": "Vertically rotating 3-d teapot with red, green and blue gradient.", "class": "p5", @@ -17679,7 +17937,7 @@ module.exports={ } ], "example": [ - "\n
\n\n//draw a spinning octahedron\nvar octahedron;\n\nfunction preload() {\n octahedron = loadModel('assets/octahedron.obj');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n model(octahedron);\n}\n\n
" + "\n
\n\n//draw a spinning octahedron\nlet octahedron;\n\nfunction preload() {\n octahedron = loadModel('assets/octahedron.obj');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n model(octahedron);\n}\n\n
" ], "alt": "Vertically rotating 3-d octahedron.", "class": "p5", @@ -17696,13 +17954,23 @@ module.exports={ { "name": "vertFilename", "description": "

path to file containing vertex shader\nsource code

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

path to file containing fragment shader\nsource code

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

callback to be executed after loadShader\ncompletes. On success, the Shader object is passed as the first argument.

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

callback to be executed when an error\noccurs inside loadShader. On error, the error is passed as the first\nargument.

\n", + "type": "Function", "optional": true } ], @@ -17711,7 +17979,7 @@ module.exports={ "type": "p5.Shader" }, "example": [ - "\n
\n\nvar mandel;\nfunction preload() {\n // load the shader definitions from files\n mandel = loadShader('assets/shader.vert', 'assets/shader.frag');\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n // use the shader\n shader(mandel);\n noStroke();\n mandel.setUniform('p', [-0.74364388703, 0.13182590421]);\n}\n\nfunction draw() {\n mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000))));\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n\n
" + "\n
\n\nlet mandel;\nfunction preload() {\n // load the shader definitions from files\n mandel = loadShader('assets/shader.vert', 'assets/shader.frag');\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n // use the shader\n shader(mandel);\n noStroke();\n mandel.setUniform('p', [-0.74364388703, 0.13182590421]);\n}\n\nfunction draw() {\n mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000))));\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n\n
" ], "alt": "zooming Mandelbrot set. a colorful, infinitely detailed fractal.", "class": "p5", @@ -17720,7 +17988,7 @@ module.exports={ }, { "file": "src/webgl/material.js", - "line": 83, + "line": 113, "itemtype": "method", "name": "createShader", "params": [ @@ -17740,7 +18008,7 @@ module.exports={ "type": "p5.Shader" }, "example": [ - "\n
\n\n// the 'varying's are shared between both vertex & fragment shaders\nvar varying = 'precision highp float; varying vec2 vPos;';\n\n// the vertex shader is called for each vertex\nvar vs =\n varying +\n 'attribute vec3 aPosition;' +\n 'void main() { vPos = (gl_Position = vec4(aPosition,1.0)).xy; }';\n\n// the fragment shader is called for each pixel\nvar fs =\n varying +\n 'uniform vec2 p;' +\n 'uniform float r;' +\n 'const int I = 500;' +\n 'void main() {' +\n ' vec2 c = p + vPos * r, z = c;' +\n ' float n = 0.0;' +\n ' for (int i = I; i > 0; i --) {' +\n ' if(z.x*z.x+z.y*z.y > 4.0) {' +\n ' n = float(i)/float(I);' +\n ' break;' +\n ' }' +\n ' z = vec2(z.x*z.x-z.y*z.y, 2.0*z.x*z.y) + c;' +\n ' }' +\n ' 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);' +\n '}';\n\nvar mandel;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // create and initialize the shader\n mandel = createShader(vs, fs);\n shader(mandel);\n noStroke();\n\n // 'p' is the center point of the Mandelbrot image\n mandel.setUniform('p', [-0.74364388703, 0.13182590421]);\n}\n\nfunction draw() {\n // 'r' is the size of the image in Mandelbrot-space\n mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000))));\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n\n
" + "\n
\n\n// the 'varying's are shared between both vertex & fragment shaders\nlet varying = 'precision highp float; varying vec2 vPos;';\n\n// the vertex shader is called for each vertex\nlet vs =\n varying +\n 'attribute vec3 aPosition;' +\n 'void main() { vPos = (gl_Position = vec4(aPosition,1.0)).xy; }';\n\n// the fragment shader is called for each pixel\nlet fs =\n varying +\n 'uniform vec2 p;' +\n 'uniform float r;' +\n 'const int I = 500;' +\n 'void main() {' +\n ' vec2 c = p + vPos * r, z = c;' +\n ' float n = 0.0;' +\n ' for (int i = I; i > 0; i --) {' +\n ' if(z.x*z.x+z.y*z.y > 4.0) {' +\n ' n = float(i)/float(I);' +\n ' break;' +\n ' }' +\n ' z = vec2(z.x*z.x-z.y*z.y, 2.0*z.x*z.y) + c;' +\n ' }' +\n ' 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);' +\n '}';\n\nlet mandel;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // create and initialize the shader\n mandel = createShader(vs, fs);\n shader(mandel);\n noStroke();\n\n // 'p' is the center point of the Mandelbrot image\n mandel.setUniform('p', [-0.74364388703, 0.13182590421]);\n}\n\nfunction draw() {\n // 'r' is the size of the image in Mandelbrot-space\n mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000))));\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n\n
" ], "alt": "zooming Mandelbrot set. a colorful, infinitely detailed fractal.", "class": "p5", @@ -17749,7 +18017,7 @@ module.exports={ }, { "file": "src/webgl/material.js", - "line": 151, + "line": 181, "description": "

The shader() function lets the user provide a custom shader\nto fill in shapes in WEBGL mode. Users can create their\nown shaders by loading vertex and fragment shaders with\nloadShader().

\n", "itemtype": "method", "name": "shader", @@ -17768,13 +18036,24 @@ module.exports={ }, { "file": "src/webgl/material.js", - "line": 176, + "line": 212, + "description": "

This function restores the default shaders in WEBGL mode. Code that runs\nafter resetShader() will not be affected by previously defined\nshaders. Should be run after shader().

\n", + "itemtype": "method", + "name": "resetShader", + "chainable": 1, + "class": "p5", + "module": "Lights, Camera", + "submodule": "Material" + }, + { + "file": "src/webgl/material.js", + "line": 225, "description": "

Normal material for geometry. You can view all\npossible materials in this\nexample.

\n", "itemtype": "method", "name": "normalMaterial", "chainable": 1, "example": [ - "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n normalMaterial();\n sphere(50);\n}\n\n
" + "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n normalMaterial();\n sphere(40);\n}\n\n
" ], "alt": "Red, green and blue gradient.", "class": "p5", @@ -17783,7 +18062,7 @@ module.exports={ }, { "file": "src/webgl/material.js", - "line": 211, + "line": 262, "description": "

Texture for geometry. You can view other possible materials in this\nexample.

\n", "itemtype": "method", "name": "texture", @@ -17796,7 +18075,7 @@ module.exports={ ], "chainable": 1, "example": [ - "\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(0);\n rotateZ(frameCount * 0.01);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n //pass image as texture\n texture(img);\n box(200, 200, 200);\n}\n\n
\n\n
\n\nvar pg;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n pg = createGraphics(200, 200);\n pg.textSize(100);\n}\n\nfunction draw() {\n background(0);\n pg.background(255);\n pg.text('hello!', 0, 100);\n //pass image as texture\n texture(pg);\n plane(200);\n}\n\n
\n\n
\n\nvar vid;\nfunction preload() {\n vid = createVideo('assets/fingers.mov');\n vid.hide();\n vid.loop();\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(0);\n //pass video frame as texture\n texture(vid);\n plane(200);\n}\n\n
" + "\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(0);\n rotateZ(frameCount * 0.01);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n //pass image as texture\n texture(img);\n box(200, 200, 200);\n}\n\n
\n\n
\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n pg = createGraphics(200, 200);\n pg.textSize(75);\n}\n\nfunction draw() {\n background(0);\n pg.background(255);\n pg.text('hello!', 0, 100);\n //pass image as texture\n texture(pg);\n rotateX(0.5);\n noStroke();\n plane(50);\n}\n\n
\n\n
\n\nlet vid;\nfunction preload() {\n vid = createVideo('assets/fingers.mov');\n vid.hide();\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(0);\n //pass video frame as texture\n texture(vid);\n rect(-40, -40, 80, 80);\n}\n\nfunction mousePressed() {\n vid.loop();\n}\n\n
" ], "alt": "Rotating view of many images umbrella and grid roof on a 3d plane\nblack canvas\nblack canvas", "class": "p5", @@ -17805,13 +18084,61 @@ module.exports={ }, { "file": "src/webgl/material.js", - "line": 301, + "line": 359, + "description": "

Sets the coordinate space for texture mapping. The default mode is IMAGE\nwhich refers to the actual coordinates of the image.\nNORMAL refers to a normalized space of values ranging from 0 to 1.\nThis function only works in WEBGL mode.

\n

With IMAGE, if an image is 100 x 200 pixels, mapping the image onto the entire\nsize of a quad would require the points (0,0) (100, 0) (100,200) (0,200).\nThe same mapping in NORMAL is (0,0) (1,0) (1,1) (0,1).

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

either IMAGE or NORMAL

\n", + "type": "Constant" + } + ], + "example": [ + "\n
\n\nlet img;\n\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n texture(img);\n textureMode(NORMAL);\n beginShape();\n vertex(-50, -50, 0, 0);\n vertex(50, -50, 1, 0);\n vertex(50, 50, 1, 1);\n vertex(-50, 50, 0, 1);\n endShape();\n}\n\n
" + ], + "alt": "the underside of a white umbrella and gridded ceiling above", + "class": "p5", + "module": "Lights, Camera", + "submodule": "Material" + }, + { + "file": "src/webgl/material.js", + "line": 438, + "description": "

Sets the global texture wrapping mode. This controls how textures behave\nwhen their uv's go outside of the 0 - 1 range. There are three options:\nCLAMP, REPEAT, and MIRROR.

\n

CLAMP causes the pixels at the edge of the texture to extend to the bounds\nREPEAT causes the texture to tile repeatedly until reaching the bounds\nMIRROR works similarly to REPEAT but it flips the texture with every new tile

\n

REPEAT & MIRROR are only available if the texture\nis a power of two size (128, 256, 512, 1024, etc.).

\n

This method will affect all textures in your sketch until a subsequent\ntextureWrap call is made.

\n

If only one argument is provided, it will be applied to both the\nhorizontal and vertical axes.

\n", + "itemtype": "method", + "name": "textureWrap", + "params": [ + { + "name": "wrapX", + "description": "

either CLAMP, REPEAT, or MIRROR

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

either CLAMP, REPEAT, or MIRROR

\n", + "type": "Constant", + "optional": true + } + ], + "example": [ + "\n
\n\nlet img;\nfunction preload() {\n img = loadImage('assets/rockies128.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n textureWrap(MIRROR);\n}\n\nfunction draw() {\n background(0);\n\n let dX = mouseX;\n let dY = mouseY;\n\n let u = lerp(1.0, 2.0, dX);\n let v = lerp(1.0, 2.0, dY);\n\n scale(width / 2);\n\n texture(img);\n\n beginShape(TRIANGLES);\n vertex(-1, -1, 0, 0, 0);\n vertex(1, -1, 0, u, 0);\n vertex(1, 1, 0, u, v);\n\n vertex(1, 1, 0, u, v);\n vertex(-1, 1, 0, 0, v);\n vertex(-1, -1, 0, 0, 0);\n endShape();\n}\n\n
" + ], + "alt": "an image of the rocky mountains repeated in mirrored tiles", + "class": "p5", + "module": "Lights, Camera", + "submodule": "Material" + }, + { + "file": "src/webgl/material.js", + "line": 513, "description": "

Ambient material for geometry with a given color. You can view all\npossible materials in this\nexample.

\n", "itemtype": "method", "name": "ambientMaterial", "chainable": 1, "example": [ - "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n ambientLight(100);\n pointLight(250, 250, 250, 100, 100, 0);\n ambientMaterial(250);\n sphere(50);\n}\n\n
" + "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n noStroke();\n ambientLight(200);\n ambientMaterial(70, 130, 230);\n sphere(40);\n}\n\n
" ], "alt": "radiating light source from top right of canvas", "class": "p5", @@ -17819,7 +18146,7 @@ module.exports={ "submodule": "Material", "overloads": [ { - "line": 301, + "line": 513, "params": [ { "name": "v1", @@ -17848,7 +18175,7 @@ module.exports={ "chainable": 1 }, { - "line": 332, + "line": 544, "params": [ { "name": "color", @@ -17862,13 +18189,13 @@ module.exports={ }, { "file": "src/webgl/material.js", - "line": 350, + "line": 563, "description": "

Specular material for geometry with a given color. You can view all\npossible materials in this\nexample.

\n", "itemtype": "method", "name": "specularMaterial", "chainable": 1, "example": [ - "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n ambientLight(100);\n pointLight(250, 250, 250, 100, 100, 0);\n specularMaterial(250);\n sphere(50);\n}\n\n
" + "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n noStroke();\n ambientLight(50);\n pointLight(250, 250, 250, 100, 100, 30);\n specularMaterial(250);\n sphere(40);\n}\n\n
" ], "alt": "diffused radiating light source from top right of canvas", "class": "p5", @@ -17876,7 +18203,7 @@ module.exports={ "submodule": "Material", "overloads": [ { - "line": 350, + "line": 563, "params": [ { "name": "v1", @@ -17905,7 +18232,7 @@ module.exports={ "chainable": 1 }, { - "line": 381, + "line": 595, "params": [ { "name": "color", @@ -17917,6 +18244,28 @@ module.exports={ } ] }, + { + "file": "src/webgl/material.js", + "line": 614, + "description": "

Sets the amount of gloss in the surface of shapes.\nUsed in combination with specularMaterial() in setting\nthe material properties of shapes. The default and minimum value is 1.

\n", + "itemtype": "method", + "name": "shininess", + "params": [ + { + "name": "shine", + "description": "

Degree of Shininess.\n Defaults to 1.

\n", + "type": "Number" + } + ], + "chainable": 1, + "example": [ + "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n noStroke();\n let locX = mouseX - width / 2;\n let locY = mouseY - height / 2;\n ambientLight(60, 60, 60);\n pointLight(255, 255, 255, locX, locY, 50);\n specularMaterial(250);\n translate(-25, 0, 0);\n shininess(1);\n sphere(20);\n translate(50, 0, 0);\n shininess(20);\n sphere(20);\n}\n\n
" + ], + "alt": "Shininess on Camera changes position with mouse", + "class": "p5", + "module": "Lights, Camera", + "submodule": "Material" + }, { "file": "src/webgl/p5.Camera.js", "line": 15, @@ -18108,7 +18457,7 @@ module.exports={ }, { "file": "src/webgl/p5.Camera.js", - "line": 380, + "line": 379, "description": "

Sets an orthographic projection for a p5.Camera object and sets parameters\nfor that projection according to ortho() syntax.

\n", "itemtype": "method", "name": "ortho", @@ -18118,7 +18467,7 @@ module.exports={ }, { "file": "src/webgl/p5.Camera.js", - "line": 487, + "line": 486, "description": "

Panning rotates the camera view to the left and right.

\n", "itemtype": "method", "name": "pan", @@ -18130,7 +18479,7 @@ module.exports={ } ], "example": [ - "\n
\n\nvar cam;\nvar delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n // set initial pan angle\n cam.pan(-0.8);\n}\n\nfunction draw() {\n background(200);\n\n // pan camera according to angle 'delta'\n cam.pan(delta);\n\n // every 160 frames, switch direction\n if (frameCount % 160 === 0) {\n delta *= -1;\n }\n\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n\n
" + "\n
\n\nlet cam;\nlet delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n // set initial pan angle\n cam.pan(-0.8);\n}\n\nfunction draw() {\n background(200);\n\n // pan camera according to angle 'delta'\n cam.pan(delta);\n\n // every 160 frames, switch direction\n if (frameCount % 160 === 0) {\n delta *= -1;\n }\n\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n\n
" ], "alt": "camera view pans left and right across a series of rotating 3D boxes.", "class": "p5.Camera", @@ -18139,7 +18488,7 @@ module.exports={ }, { "file": "src/webgl/p5.Camera.js", - "line": 546, + "line": 545, "description": "

Tilting rotates the camera view up and down.

\n", "itemtype": "method", "name": "tilt", @@ -18151,7 +18500,7 @@ module.exports={ } ], "example": [ - "\n
\n\nvar cam;\nvar delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n // set initial tilt\n cam.tilt(-0.8);\n}\n\nfunction draw() {\n background(200);\n\n // pan camera according to angle 'delta'\n cam.tilt(delta);\n\n // every 160 frames, switch direction\n if (frameCount % 160 === 0) {\n delta *= -1;\n }\n\n rotateY(frameCount * 0.01);\n translate(0, -100, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n}\n\n
" + "\n
\n\nlet cam;\nlet delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n // set initial tilt\n cam.tilt(-0.8);\n}\n\nfunction draw() {\n background(200);\n\n // pan camera according to angle 'delta'\n cam.tilt(delta);\n\n // every 160 frames, switch direction\n if (frameCount % 160 === 0) {\n delta *= -1;\n }\n\n rotateY(frameCount * 0.01);\n translate(0, -100, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n}\n\n
" ], "alt": "camera view tilts up and down across a series of rotating 3D boxes.", "class": "p5.Camera", @@ -18160,7 +18509,7 @@ module.exports={ }, { "file": "src/webgl/p5.Camera.js", - "line": 604, + "line": 603, "description": "

Reorients the camera to look at a position in world space.

\n", "itemtype": "method", "name": "lookAt", @@ -18182,7 +18531,7 @@ module.exports={ } ], "example": [ - "\n
\n\nvar cam;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // look at a new random point every 60 frames\n if (frameCount % 60 === 0) {\n cam.lookAt(random(-100, 100), random(-50, 50), 0);\n }\n\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n\n
" + "\n
\n\nlet cam;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // look at a new random point every 60 frames\n if (frameCount % 60 === 0) {\n cam.lookAt(random(-100, 100), random(-50, 50), 0);\n }\n\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n\n
" ], "alt": "camera view of rotating 3D cubes changes to look at a new random\npoint every second .", "class": "p5.Camera", @@ -18191,7 +18540,7 @@ module.exports={ }, { "file": "src/webgl/p5.Camera.js", - "line": 671, + "line": 670, "description": "

Sets a camera's position and orientation. This is equivalent to calling\ncamera() on a p5.Camera object.

\n", "itemtype": "method", "name": "camera", @@ -18201,7 +18550,7 @@ module.exports={ }, { "file": "src/webgl/p5.Camera.js", - "line": 752, + "line": 751, "description": "

Move camera along its local axes while maintaining current camera orientation.

\n", "itemtype": "method", "name": "move", @@ -18223,7 +18572,7 @@ module.exports={ } ], "example": [ - "\n
\n\n// see the camera move along its own axes while maintaining its orientation\nvar cam;\nvar delta = 0.5;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // move the camera along its local axes\n cam.move(delta, delta, 0);\n\n // every 100 frames, switch direction\n if (frameCount % 150 === 0) {\n delta *= -1;\n }\n\n translate(-10, -10, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n}\n\n
" + "\n
\n\n// see the camera move along its own axes while maintaining its orientation\nlet cam;\nlet delta = 0.5;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // move the camera along its local axes\n cam.move(delta, delta, 0);\n\n // every 100 frames, switch direction\n if (frameCount % 150 === 0) {\n delta *= -1;\n }\n\n translate(-10, -10, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n}\n\n
" ], "alt": "camera view moves along a series of 3D boxes, maintaining the same\norientation throughout the move", "class": "p5.Camera", @@ -18232,7 +18581,7 @@ module.exports={ }, { "file": "src/webgl/p5.Camera.js", - "line": 824, + "line": 823, "description": "

Set camera position in world-space while maintaining current camera\norientation.

\n", "itemtype": "method", "name": "setPosition", @@ -18254,7 +18603,7 @@ module.exports={ } ], "example": [ - "\n
\n\n// press '1' '2' or '3' keys to set camera position\n\nvar cam;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // '1' key\n if (keyIsDown(49)) {\n cam.setPosition(30, 0, 80);\n }\n // '2' key\n if (keyIsDown(50)) {\n cam.setPosition(0, 0, 80);\n }\n // '3' key\n if (keyIsDown(51)) {\n cam.setPosition(-30, 0, 80);\n }\n\n box(20);\n}\n\n
" + "\n
\n\n// press '1' '2' or '3' keys to set camera position\n\nlet cam;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // '1' key\n if (keyIsDown(49)) {\n cam.setPosition(30, 0, 80);\n }\n // '2' key\n if (keyIsDown(50)) {\n cam.setPosition(0, 0, 80);\n }\n // '3' key\n if (keyIsDown(51)) {\n cam.setPosition(-30, 0, 80);\n }\n\n box(20);\n}\n\n
" ], "alt": "camera position changes as the user presses keys, altering view of a 3D box", "class": "p5.Camera", @@ -18263,7 +18612,7 @@ module.exports={ }, { "file": "src/webgl/p5.Camera.js", - "line": 1089, + "line": 1088, "description": "

Sets rendererGL's current camera to a p5.Camera object. Allows switching\nbetween multiple cameras.

\n", "itemtype": "method", "name": "setCamera", @@ -18275,7 +18624,7 @@ module.exports={ } ], "example": [ - "\n
\n\nvar cam1, cam2;\nvar currentCamera;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n\n cam1 = createCamera();\n cam2 = createCamera();\n cam2.setPosition(30, 0, 50);\n cam2.lookAt(0, 0, 0);\n cam2.ortho();\n\n // set variable for previously active camera:\n currentCamera = 1;\n}\n\nfunction draw() {\n background(200);\n\n // camera 1:\n cam1.lookAt(0, 0, 0);\n cam1.setPosition(sin(frameCount / 60) * 200, 0, 100);\n\n // every 100 frames, switch between the two cameras\n if (frameCount % 100 === 0) {\n if (currentCamera === 1) {\n setCamera(cam1);\n currentCamera = 0;\n } else {\n setCamera(cam2);\n currentCamera = 1;\n }\n }\n\n drawBoxes();\n}\n\nfunction drawBoxes() {\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n\n
" + "\n
\n\nlet cam1, cam2;\nlet currentCamera;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n\n cam1 = createCamera();\n cam2 = createCamera();\n cam2.setPosition(30, 0, 50);\n cam2.lookAt(0, 0, 0);\n cam2.ortho();\n\n // set variable for previously active camera:\n currentCamera = 1;\n}\n\nfunction draw() {\n background(200);\n\n // camera 1:\n cam1.lookAt(0, 0, 0);\n cam1.setPosition(sin(frameCount / 60) * 200, 0, 100);\n\n // every 100 frames, switch between the two cameras\n if (frameCount % 100 === 0) {\n if (currentCamera === 1) {\n setCamera(cam1);\n currentCamera = 0;\n } else {\n setCamera(cam2);\n currentCamera = 1;\n }\n }\n\n drawBoxes();\n}\n\nfunction drawBoxes() {\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n\n
" ], "alt": "Canvas switches between two camera views, each showing a series of spinning\n3D boxes.", "class": "p5", @@ -18333,12 +18682,12 @@ module.exports={ }, { "file": "src/webgl/p5.RendererGL.js", - "line": 215, - "description": "

Set attributes for the WebGL Drawing context.\nThis is a way of adjusting ways that the WebGL\nrenderer works to fine-tune the display and performance.\nThis should be put in setup().\nThe available attributes are:\n
\nalpha - indicates if the canvas contains an alpha buffer\ndefault is true\n

\ndepth - indicates whether the drawing buffer has a depth buffer\nof at least 16 bits - default is true\n

\nstencil - indicates whether the drawing buffer has a stencil buffer\nof at least 8 bits\n

\nantialias - indicates whether or not to perform anti-aliasing\ndefault is false\n

\npremultipliedAlpha - indicates that the page compositor will assume\nthe drawing buffer contains colors with pre-multiplied alpha\ndefault is false\n

\npreserveDrawingBuffer - if true the buffers will not be cleared and\nand will preserve their values until cleared or overwritten by author\n(note that p5 clears automatically on draw loop)\ndefault is true\n

\nperPixelLighting - if true, per-pixel lighting will be used in the\nlighting shader.\ndefault is false\n

\n", + "line": 228, + "description": "

Set attributes for the WebGL Drawing context.\nThis is a way of adjusting how the WebGL\nrenderer works to fine-tune the display and performance.\n

\nNote that this will reinitialize the drawing context\nif called after the WebGL canvas is made.\n

\nIf an object is passed as the parameter, all attributes\nnot declared in the object will be set to defaults.\n

\nThe available attributes are:\n
\nalpha - indicates if the canvas contains an alpha buffer\ndefault is false\n

\ndepth - indicates whether the drawing buffer has a depth buffer\nof at least 16 bits - default is true\n

\nstencil - indicates whether the drawing buffer has a stencil buffer\nof at least 8 bits\n

\nantialias - indicates whether or not to perform anti-aliasing\ndefault is false\n

\npremultipliedAlpha - indicates that the page compositor will assume\nthe drawing buffer contains colors with pre-multiplied alpha\ndefault is false\n

\npreserveDrawingBuffer - if true the buffers will not be cleared and\nand will preserve their values until cleared or overwritten by author\n(note that p5 clears automatically on draw loop)\ndefault is true\n

\nperPixelLighting - if true, per-pixel lighting will be used in the\nlighting shader.\ndefault is false\n

\n", "itemtype": "method", "name": "setAttributes", "example": [ - "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(255);\n push();\n rotateZ(frameCount * 0.02);\n rotateX(frameCount * 0.02);\n rotateY(frameCount * 0.02);\n fill(0, 0, 0);\n box(50);\n pop();\n}\n\n
\n
\nNow with the antialias attribute set to true.\n
\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n setAttributes('antialias', true);\n}\n\nfunction draw() {\n background(255);\n push();\n rotateZ(frameCount * 0.02);\n rotateX(frameCount * 0.02);\n rotateY(frameCount * 0.02);\n fill(0, 0, 0);\n box(50);\n pop();\n}\n\n
\n\n
\n\n// press the mouse button to enable perPixelLighting\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noStroke();\n fill(255);\n}\n\nvar lights = [\n { c: '#f00', t: 1.12, p: 1.91, r: 0.2 },\n { c: '#0f0', t: 1.21, p: 1.31, r: 0.2 },\n { c: '#00f', t: 1.37, p: 1.57, r: 0.2 },\n { c: '#ff0', t: 1.12, p: 1.91, r: 0.7 },\n { c: '#0ff', t: 1.21, p: 1.31, r: 0.7 },\n { c: '#f0f', t: 1.37, p: 1.57, r: 0.7 }\n];\n\nfunction draw() {\n var t = millis() / 1000 + 1000;\n background(0);\n directionalLight(color('#222'), 1, 1, 1);\n\n for (var i = 0; i < lights.length; i++) {\n var light = lights[i];\n pointLight(\n color(light.c),\n p5.Vector.fromAngles(t * light.t, t * light.p, width * light.r)\n );\n }\n\n specularMaterial(255);\n sphere(width * 0.1);\n\n rotateX(t * 0.77);\n rotateY(t * 0.83);\n rotateZ(t * 0.91);\n torus(width * 0.3, width * 0.07, 30, 10);\n}\n\nfunction mousePressed() {\n setAttributes('perPixelLighting', true);\n noStroke();\n fill(255);\n}\nfunction mouseReleased() {\n setAttributes('perPixelLighting', false);\n noStroke();\n fill(255);\n}\n\n
" + "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(255);\n push();\n rotateZ(frameCount * 0.02);\n rotateX(frameCount * 0.02);\n rotateY(frameCount * 0.02);\n fill(0, 0, 0);\n box(50);\n pop();\n}\n\n
\n
\nNow with the antialias attribute set to true.\n
\n
\n\nfunction setup() {\n setAttributes('antialias', true);\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(255);\n push();\n rotateZ(frameCount * 0.02);\n rotateX(frameCount * 0.02);\n rotateY(frameCount * 0.02);\n fill(0, 0, 0);\n box(50);\n pop();\n}\n\n
\n\n
\n\n// press the mouse button to enable perPixelLighting\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noStroke();\n fill(255);\n}\n\nvar lights = [\n { c: '#f00', t: 1.12, p: 1.91, r: 0.2 },\n { c: '#0f0', t: 1.21, p: 1.31, r: 0.2 },\n { c: '#00f', t: 1.37, p: 1.57, r: 0.2 },\n { c: '#ff0', t: 1.12, p: 1.91, r: 0.7 },\n { c: '#0ff', t: 1.21, p: 1.31, r: 0.7 },\n { c: '#f0f', t: 1.37, p: 1.57, r: 0.7 }\n];\n\nfunction draw() {\n var t = millis() / 1000 + 1000;\n background(0);\n directionalLight(color('#222'), 1, 1, 1);\n\n for (var i = 0; i < lights.length; i++) {\n var light = lights[i];\n pointLight(\n color(light.c),\n p5.Vector.fromAngles(t * light.t, t * light.p, width * light.r)\n );\n }\n\n specularMaterial(255);\n sphere(width * 0.1);\n\n rotateX(t * 0.77);\n rotateY(t * 0.83);\n rotateZ(t * 0.91);\n torus(width * 0.3, width * 0.07, 24, 10);\n}\n\nfunction mousePressed() {\n setAttributes('perPixelLighting', true);\n noStroke();\n fill(255);\n}\nfunction mouseReleased() {\n setAttributes('perPixelLighting', false);\n noStroke();\n fill(255);\n}\n\n
" ], "alt": "a rotating cube with smoother edges", "class": "p5", @@ -18346,7 +18695,7 @@ module.exports={ "submodule": "Rendering", "overloads": [ { - "line": 215, + "line": 228, "params": [ { "name": "key", @@ -18361,7 +18710,7 @@ module.exports={ ] }, { - "line": 348, + "line": 367, "params": [ { "name": "obj", @@ -18374,7 +18723,7 @@ module.exports={ }, { "file": "src/webgl/p5.Shader.js", - "line": 274, + "line": 268, "description": "

Wrapper around gl.uniform functions.\nAs we store uniform info in the shader we can use that\nto do type checking on the supplied data and call\nthe appropriate function.

\n", "itemtype": "method", "name": "setUniform", @@ -18487,6 +18836,50 @@ module.exports={ { "file": "lib/addons/p5.dom.js", "line": 245, + "description": "

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

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

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

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

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

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

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

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

Helpers for create methods.

\n", "class": "p5", "module": "p5.dom", @@ -18494,7 +18887,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 258, + "line": 361, "description": "

Creates a <div></div> element in the DOM with given inner HTML.\nAppends to the container node if one is specified, otherwise\nappends to body.

\n", "itemtype": "method", "name": "createDiv", @@ -18519,7 +18912,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 272, + "line": 375, "description": "

Creates a <p></p> element in the DOM with given inner HTML. Used\nfor paragraph length text.\nAppends to the container node if one is specified, otherwise\nappends to body.

\n", "itemtype": "method", "name": "createP", @@ -18544,7 +18937,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 287, + "line": 390, "description": "

Creates a <span></span> element in the DOM with given inner HTML.\nAppends to the container node if one is specified, otherwise\nappends to body.

\n", "itemtype": "method", "name": "createSpan", @@ -18569,7 +18962,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 310, + "line": 413, "description": "

Creates an <img> element in the DOM with given src and\nalternate text.\nAppends to the container node if one is specified, otherwise\nappends to body.

\n", "itemtype": "method", "name": "createImg", @@ -18585,7 +18978,7 @@ module.exports={ "submodule": "p5.dom", "overloads": [ { - "line": 310, + "line": 413, "params": [ { "name": "src", @@ -18611,7 +19004,7 @@ module.exports={ } }, { - "line": 326, + "line": 429, "params": [ { "name": "src", @@ -18633,7 +19026,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 359, + "line": 463, "description": "

Creates an <a></a> element in the DOM for including a hyperlink.\nAppends to the container node if one is specified, otherwise\nappends to body.

\n", "itemtype": "method", "name": "createA", @@ -18668,14 +19061,14 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 384, + "line": 488, "class": "p5", "module": "p5.dom", "submodule": "p5.dom" }, { "file": "lib/addons/p5.dom.js", - "line": 386, + "line": 490, "description": "

Creates a slider <input></input> element in the DOM.\nUse .size() to set the display length of the slider.\nAppends to the container node if one is specified, otherwise\nappends to body.

\n", "itemtype": "method", "name": "createSlider", @@ -18716,7 +19109,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 443, + "line": 547, "description": "

Creates a <button></button> element in the DOM.\nUse .size() to set the display size of the button.\nUse .mousePressed() to specify behavior on press.\nAppends to the container node if one is specified, otherwise\nappends to body.

\n", "itemtype": "method", "name": "createButton", @@ -18746,7 +19139,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 479, + "line": 583, "description": "

Creates a checkbox <input></input> element in the DOM.\nCalling .checked() on a checkbox returns if it is checked or not

\n", "itemtype": "method", "name": "createCheckbox", @@ -18777,7 +19170,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 547, + "line": 651, "description": "

Creates a dropdown menu <select></select> element in the DOM.\nIt also helps to assign select-box methods to p5.Element when selecting existing select box

\n", "itemtype": "method", "name": "createSelect", @@ -18786,14 +19179,14 @@ module.exports={ "type": "p5.Element" }, "example": [ - "\n
\nvar sel;\n\nfunction setup() {\n textAlign(CENTER);\n background(200);\n sel = createSelect();\n sel.position(10, 10);\n sel.option('pear');\n sel.option('kiwi');\n sel.option('grape');\n sel.changed(mySelectEvent);\n}\n\nfunction mySelectEvent() {\n var item = sel.value();\n background(200);\n text('it is a' + item + '!', 50, 50);\n}\n
" + "\n
\nvar sel;\n\nfunction setup() {\n textAlign(CENTER);\n background(200);\n sel = createSelect();\n sel.position(10, 10);\n sel.option('pear');\n sel.option('kiwi');\n sel.option('grape');\n sel.changed(mySelectEvent);\n}\n\nfunction mySelectEvent() {\n var item = sel.value();\n background(200);\n text('It is a ' + item + '!', 50, 50);\n}\n
" ], "class": "p5", "module": "p5.dom", "submodule": "p5.dom", "overloads": [ { - "line": 547, + "line": 651, "params": [ { "name": "multiple", @@ -18808,7 +19201,7 @@ module.exports={ } }, { - "line": 575, + "line": 679, "params": [ { "name": "existing", @@ -18825,7 +19218,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 651, + "line": 755, "description": "

Creates a radio button <input></input> element in the DOM.\nThe .option() method can be used to set options for the radio after it is\ncreated. The .value() method will return the currently selected option.

\n", "itemtype": "method", "name": "createRadio", @@ -18850,7 +19243,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 789, + "line": 893, "description": "

Creates a colorPicker element in the DOM for color input.\nThe .value() method will return a hex string (#rrggbb) of the color.\nThe .color() method will return a p5.Color object with the current chosen color.

\n", "itemtype": "method", "name": "createColorPicker", @@ -18875,7 +19268,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 863, + "line": 967, "description": "

Creates an <input></input> element in the DOM for text input.\nUse .size() to set the display length of the box.\nAppends to the container node if one is specified, otherwise\nappends to body.

\n", "itemtype": "method", "name": "createInput", @@ -18906,7 +19299,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 893, + "line": 997, "description": "

Creates an <input></input> element in the DOM of type 'file'.\nThis allows users to select local files for use in a sketch.

\n", "itemtype": "method", "name": "createFileInput", @@ -18929,7 +19322,7 @@ module.exports={ "type": "p5.Element" }, "example": [ - "\n
\nvar input;\nvar img;\n\nfunction setup() {\n input = createFileInput(handleFile);\n input.position(0, 0);\n}\n\nfunction draw() {\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\nfunction handleFile(file) {\n print(file);\n if (file.type === 'image') {\n img = createImg(file.data);\n img.hide();\n }\n}\n
" + "\n
\nlet input;\nlet img;\n\nfunction setup() {\n input = createFileInput(handleFile);\n input.position(0, 0);\n}\n\nfunction draw() {\n background(255);\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\nfunction handleFile(file) {\n print(file);\n if (file.type === 'image') {\n img = createImg(file.data);\n img.hide();\n } else {\n img = null;\n }\n}\n
" ], "class": "p5", "module": "p5.dom", @@ -18937,14 +19330,14 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 981, + "line": 1070, "class": "p5", "module": "p5.dom", "submodule": "p5.dom" }, { "file": "lib/addons/p5.dom.js", - "line": 1023, + "line": 1112, "description": "

Creates an HTML5 <video> element in the DOM for simple playback\nof audio/video. Shown by default, can be hidden with .hide()\nand drawn into canvas using video(). Appends to the container\nnode if one is specified, otherwise appends to body. The first parameter\ncan be either a single string path to a video file, or an array of string\npaths to different formats of the same video. This is useful for ensuring\nthat your video can play across different browsers, as each supports\ndifferent formats. See this\npage for further information about supported formats.

\n", "itemtype": "method", "name": "createVideo", @@ -18966,7 +19359,7 @@ module.exports={ "type": "p5.MediaElement" }, "example": [ - "\n
\nvar vid;\nfunction setup() {\n vid = createVideo(['small.mp4', 'small.ogv', 'small.webm'], vidLoad);\n}\n\n// This function is called when the video loads\nfunction vidLoad() {\n vid.play();\n}\n
" + "\n
\nvar vid;\nfunction setup() {\n noCanvas();\n\n vid = createVideo(\n ['assets/small.mp4', 'assets/small.ogv', 'assets/small.webm'],\n vidLoad\n );\n\n vid.size(100, 100);\n}\n\n// This function is called when the video loads\nfunction vidLoad() {\n vid.loop();\n vid.volume(0);\n}\n
" ], "class": "p5", "module": "p5.dom", @@ -18974,14 +19367,14 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1062, + "line": 1159, "class": "p5", "module": "p5.dom", "submodule": "p5.dom" }, { "file": "lib/addons/p5.dom.js", - "line": 1064, + "line": 1161, "description": "

Creates a hidden HTML5 <audio> element in the DOM for simple audio\nplayback. Appends to the container node if one is specified,\notherwise appends to body. The first parameter\ncan be either a single string path to a audio file, or an array of string\npaths to different formats of the same audio. This is useful for ensuring\nthat your audio can play across different browsers, as each supports\ndifferent formats. See this\npage for further information about supported formats.

\n", "itemtype": "method", "name": "createAudio", @@ -19012,14 +19405,14 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1102, + "line": 1199, "class": "p5", "module": "p5.dom", "submodule": "p5.dom" }, { "file": "lib/addons/p5.dom.js", - "line": 1104, + "line": 1201, "itemtype": "property", "name": "VIDEO", "type": "String", @@ -19033,7 +19426,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1110, + "line": 1207, "itemtype": "property", "name": "AUDIO", "type": "String", @@ -19047,7 +19440,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1147, + "line": 1244, "description": "

Creates a new HTML5 <video> element that contains the audio/video\nfeed from a webcam. The element is separate from the canvas and is\ndisplayed by default. The element can be hidden using .hide(). The feed\ncan be drawn onto the canvas using image(). The loadedmetadata property can\nbe used to detect when the element has fully loaded (see second example).

\n

More specific properties of the feed can be passing in a Constraints object.\nSee the\n W3C\nspec for possible properties. Note that not all of these are supported\nby all browsers.

\n

Security note: A new browser security specification requires that getUserMedia,\nwhich is behind createCapture(), only works when you're running the code locally,\nor on HTTPS. Learn more here\nand here.

", "itemtype": "method", "name": "createCapture", @@ -19069,7 +19462,7 @@ module.exports={ "type": "p5.Element" }, "example": [ - "\n
\nvar capture;\n\nfunction setup() {\n createCanvas(480, 480);\n capture = createCapture(VIDEO);\n capture.hide();\n}\n\nfunction draw() {\n image(capture, 0, 0, width, width * capture.height / capture.width);\n filter(INVERT);\n}\n
\n
\nfunction setup() {\n createCanvas(480, 120);\n var constraints = {\n video: {\n mandatory: {\n minWidth: 1280,\n minHeight: 720\n },\n optional: [{ maxFrameRate: 10 }]\n },\n audio: true\n };\n createCapture(constraints, function(stream) {\n console.log(stream);\n });\n}\n
\n
\nvar capture;\n\nfunction setup() {\n createCanvas(640, 480);\n capture = createCapture(VIDEO);\n}\nfunction draw() {\n background(0);\n if (capture.loadedmetadata) {\n var c = capture.get(0, 0, 100, 100);\n image(c, 0, 0);\n }\n}" + "\n
\nvar capture;\n\nfunction setup() {\n createCanvas(480, 480);\n capture = createCapture(VIDEO);\n capture.hide();\n}\n\nfunction draw() {\n image(capture, 0, 0, width, width * capture.height / capture.width);\n filter(INVERT);\n}\n
\n
\nfunction setup() {\n createCanvas(480, 120);\n var constraints = {\n video: {\n mandatory: {\n minWidth: 1280,\n minHeight: 720\n },\n optional: [{ maxFrameRate: 10 }]\n },\n audio: true\n };\n createCapture(constraints, function(stream) {\n console.log(stream);\n });\n}\n
\n
\nvar capture;\n\nfunction setup() {\n createCanvas(640, 480);\n capture = createCapture(VIDEO);\n}\nfunction draw() {\n background(0);\n if (capture.loadedmetadata) {\n var c = capture.get(0, 0, 100, 100);\n image(c, 0, 0);\n }\n}\n
" ], "class": "p5", "module": "p5.dom", @@ -19077,7 +19470,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1283, + "line": 1381, "description": "

Creates element with given tag in the DOM with given content.\nAppends to the container node if one is specified, otherwise\nappends to body.

\n", "itemtype": "method", "name": "createElement", @@ -19107,7 +19500,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1309, + "line": 1407, "description": "

Adds specified class to the element.

\n", "itemtype": "method", "name": "addClass", @@ -19128,7 +19521,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1336, + "line": 1432, "description": "

Removes specified class from the element.

\n", "itemtype": "method", "name": "removeClass", @@ -19149,7 +19542,52 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1368, + "line": 1463, + "description": "

Checks if specified class already set to element

\n", + "itemtype": "method", + "name": "hasClass", + "return": { + "description": "a boolean value if element has specified class", + "type": "Boolean" + }, + "params": [ + { + "name": "c", + "description": "

class name of class to check

\n", + "type": "String" + } + ], + "example": [ + "\n
\n var div;\nfunction setup() {\n div = createDiv('div');\n div.addClass('show');\n }\nfunction mousePressed() {\n if (div.hasClass('show')) {\n div.addClass('show');\n } else {\n div.removeClass('show');\n }\n }\n
" + ], + "class": "p5.Element", + "module": "p5.dom", + "submodule": "p5.dom" + }, + { + "file": "lib/addons/p5.dom.js", + "line": 1492, + "description": "

Toggles element class

\n", + "itemtype": "method", + "name": "toggleClass", + "params": [ + { + "name": "c", + "description": "

class name to toggle

\n", + "type": "String" + } + ], + "chainable": 1, + "example": [ + "\n
\n var div;\nfunction setup() {\n div = createDiv('div');\n div.addClass('show');\n }\nfunction mousePressed() {\n div.toggleClass('show');\n }\n
" + ], + "class": "p5.Element", + "module": "p5.dom", + "submodule": "p5.dom" + }, + { + "file": "lib/addons/p5.dom.js", + "line": 1525, "description": "

Attaches the element as a child to the parent specified.\n Accepts either a string ID, DOM node, or p5.Element.\n If no argument is specified, an array of children DOM nodes is returned.

\n", "itemtype": "method", "name": "child", @@ -19158,14 +19596,14 @@ module.exports={ "type": "Node[]" }, "example": [ - "\n
\n var div0 = createDiv('this is the parent');\n var div1 = createDiv('this is the child');\n div0.child(div1); // use p5.Element\n
\n
\n var div0 = createDiv('this is the parent');\n var div1 = createDiv('this is the child');\n div1.id('apples');\n div0.child('apples'); // use id\n
\n
\n var div0 = createDiv('this is the parent');\n var elt = document.getElementById('myChildDiv');\n div0.child(elt); // use element from page\n
" + "\n
\n var div0 = createDiv('this is the parent');\n var div1 = createDiv('this is the child');\n div0.child(div1); // use p5.Element\n
\n
\n var div0 = createDiv('this is the parent');\n var div1 = createDiv('this is the child');\n div1.id('apples');\n div0.child('apples'); // use id\n
\n
\n // this example assumes there is a div already on the page\n // with id \"myChildDiv\"\n var div0 = createDiv('this is the parent');\n var elt = document.getElementById('myChildDiv');\n div0.child(elt); // use element from page\n
" ], "class": "p5.Element", "module": "p5.dom", "submodule": "p5.dom", "overloads": [ { - "line": 1368, + "line": 1525, "params": [], "return": { "description": "an array of child nodes", @@ -19173,7 +19611,7 @@ module.exports={ } }, { - "line": 1394, + "line": 1553, "params": [ { "name": "child", @@ -19188,7 +19626,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1416, + "line": 1575, "description": "

Centers a p5 Element either vertically, horizontally,\nor both, relative to its parent or according to\nthe body if the Element has no parent. If no argument is passed\nthe Element is aligned both vertically and horizontally.

\n", "itemtype": "method", "name": "center", @@ -19210,7 +19648,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1470, + "line": 1629, "description": "

If an argument is given, sets the inner HTML of the element,\n replacing any existing html. If true is included as a second\n argument, html is appended instead of replacing existing html.\n If no arguments are given, returns\n the inner HTML of the element.

\n", "itemtype": "method", "name": "html", @@ -19226,7 +19664,7 @@ module.exports={ "submodule": "p5.dom", "overloads": [ { - "line": 1470, + "line": 1629, "params": [], "return": { "description": "the inner HTML of the element", @@ -19234,7 +19672,7 @@ module.exports={ } }, { - "line": 1491, + "line": 1650, "params": [ { "name": "html", @@ -19255,7 +19693,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1509, + "line": 1668, "description": "

Sets the position of the element relative to (0, 0) of the\n window. Essentially, sets position:absolute and left and top\n properties of style. If no arguments given returns the x and y position\n of the element in an object.

\n", "itemtype": "method", "name": "position", @@ -19271,7 +19709,7 @@ module.exports={ "submodule": "p5.dom", "overloads": [ { - "line": 1509, + "line": 1668, "params": [], "return": { "description": "the x and y position of the element in an object", @@ -19279,7 +19717,7 @@ module.exports={ } }, { - "line": 1528, + "line": 1687, "params": [ { "name": "x", @@ -19300,8 +19738,8 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1603, - "description": "

Sets the given style (css) property (1st arg) of the element with the\ngiven value (2nd arg). If a single argument is given, .style()\nreturns the value of the given property; however, if the single argument\nis given in css syntax ('text-align:center'), .style() sets the css\nappropriatly. .style() also handles 2d and 3d css transforms. If\nthe 1st arg is 'rotate', 'translate', or 'position', the following arguments\naccept Numbers as values. ('translate', 10, 100, 50);

\n", + "line": 1762, + "description": "

Sets the given style (css) property (1st arg) of the element with the\ngiven value (2nd arg). If a single argument is given, .style()\nreturns the value of the given property; however, if the single argument\nis given in css syntax ('text-align:center'), .style() sets the css\nappropriately.

\n", "itemtype": "method", "name": "style", "return": { @@ -19309,14 +19747,14 @@ module.exports={ "type": "String" }, "example": [ - "\n
\nvar myDiv = createDiv('I like pandas.');\nmyDiv.style('font-size', '18px');\nmyDiv.style('color', '#ff0000');\n
\n
\nvar col = color(25, 23, 200, 50);\nvar button = createButton('button');\nbutton.style('background-color', col);\nbutton.position(10, 10);\n
\n
\nvar myDiv = createDiv('I like lizards.');\nmyDiv.style('position', 20, 20);\nmyDiv.style('rotate', 45);\n
\n
\nvar myDiv;\nfunction setup() {\n background(200);\n myDiv = createDiv('I like gray.');\n myDiv.position(20, 20);\n}\n\nfunction draw() {\n myDiv.style('font-size', mouseX + 'px');\n}\n
" + "\n
\nvar myDiv = createDiv('I like pandas.');\nmyDiv.style('font-size', '18px');\nmyDiv.style('color', '#ff0000');\n
\n
\nvar col = color(25, 23, 200, 50);\nvar button = createButton('button');\nbutton.style('background-color', col);\nbutton.position(10, 10);\n
\n
\nvar myDiv;\nfunction setup() {\n background(200);\n myDiv = createDiv('I like gray.');\n myDiv.position(20, 20);\n}\n\nfunction draw() {\n myDiv.style('font-size', mouseX + 'px');\n}\n
" ], "class": "p5.Element", "module": "p5.dom", "submodule": "p5.dom", "overloads": [ { - "line": 1603, + "line": 1762, "params": [ { "name": "property", @@ -19330,7 +19768,7 @@ module.exports={ } }, { - "line": 1645, + "line": 1797, "params": [ { "name": "property", @@ -19339,29 +19777,21 @@ module.exports={ }, { "name": "value", - "description": "

value to assign to property (only String|Number for rotate/translate)

\n", + "description": "

value to assign to property

\n", "type": "String|Number|p5.Color" - }, - { - "name": "value2", - "description": "

position can take a 2nd value

\n", - "type": "String|Number|p5.Color", - "optional": true - }, - { - "name": "value3", - "description": "

translate can take a 2nd & 3rd value

\n", - "type": "String|Number|p5.Color", - "optional": true } ], - "chainable": 1 + "chainable": 1, + "return": { + "description": "current value of property, if no value is given as second argument", + "type": "String" + } } ] }, { "file": "lib/addons/p5.dom.js", - "line": 1704, + "line": 1851, "description": "

Adds a new attribute or changes the value of an existing attribute\n on the specified element. If no value is specified, returns the\n value of the given attribute, or null if attribute is not set.

\n", "itemtype": "method", "name": "attribute", @@ -19377,7 +19807,7 @@ module.exports={ "submodule": "p5.dom", "overloads": [ { - "line": 1704, + "line": 1851, "params": [], "return": { "description": "value of attribute", @@ -19385,7 +19815,7 @@ module.exports={ } }, { - "line": 1719, + "line": 1866, "params": [ { "name": "attr", @@ -19404,7 +19834,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1748, + "line": 1895, "description": "

Removes an attribute on the specified element.

\n", "itemtype": "method", "name": "removeAttribute", @@ -19425,7 +19855,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1793, + "line": 1940, "description": "

Either returns the value of the element if no arguments\ngiven, or sets the value of the element.

\n", "itemtype": "method", "name": "value", @@ -19441,7 +19871,7 @@ module.exports={ "submodule": "p5.dom", "overloads": [ { - "line": 1793, + "line": 1940, "params": [], "return": { "description": "value of the element", @@ -19449,7 +19879,7 @@ module.exports={ } }, { - "line": 1823, + "line": 1970, "params": [ { "name": "value", @@ -19463,7 +19893,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1839, + "line": 1986, "description": "

Shows the current element. Essentially, setting display:block for the style.

\n", "itemtype": "method", "name": "show", @@ -19477,7 +19907,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1857, + "line": 2004, "description": "

Hides the current element. Essentially, setting display:none for the style.

\n", "itemtype": "method", "name": "hide", @@ -19491,8 +19921,8 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1873, - "description": "

Sets the width and height of the element. AUTO can be used to\n only adjust one dimension. If no arguments given returns the width and height\n of the element in an object.

\n", + "line": 2020, + "description": "

Sets the width and height of the element. AUTO can be used to\n only adjust one dimension at a time. If no arguments are given, it\n returns the width and height of the element in an object. In case of\n elements which need to be loaded, such as images, it is recommended\n to call the function after the element has finished loading.

\n", "itemtype": "method", "name": "size", "return": { @@ -19500,14 +19930,14 @@ module.exports={ "type": "Object" }, "example": [ - "\n
\n var div = createDiv('this is a div');\n div.size(100, 100);\n
" + "\n
\n let div = createDiv('this is a div');\n div.size(100, 100);\n let img = createImg('assets/laDefense.jpg', () => {\n img.size(10, AUTO);\n });\n
" ], "class": "p5.Element", "module": "p5.dom", "submodule": "p5.dom", "overloads": [ { - "line": 1873, + "line": 2020, "params": [], "return": { "description": "the width and height of the element in an object", @@ -19515,7 +19945,7 @@ module.exports={ } }, { - "line": 1887, + "line": 2039, "params": [ { "name": "w", @@ -19535,7 +19965,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1951, + "line": 2099, "description": "

Removes the element and deregisters all listeners.

\n", "itemtype": "method", "name": "remove", @@ -19548,7 +19978,35 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 1999, + "line": 2119, + "description": "

Registers a callback that gets called every time a file that is\ndropped on the element has been loaded.\np5 will load every dropped file into memory and pass it as a p5.File object to the callback.\nMultiple files dropped at the same time will result in multiple calls to the callback.

\n

You can optionally pass a second callback which will be registered to the raw\ndrop event.\nThe callback will thus be provided the original\nDragEvent.\nDropping multiple files at the same time will trigger the second callback once per drop,\nwhereas the first callback will trigger for each loaded file.

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

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

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

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

\n", + "type": "Function", + "optional": true + } + ], + "chainable": 1, + "example": [ + "\n
\nfunction setup() {\n var c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('drop file', width / 2, height / 2);\n c.drop(gotFile);\n}\n\nfunction gotFile(file) {\n background(200);\n text('received file:', width / 2, height / 2);\n text(file.name, width / 2, height / 2 + 50);\n}\n
\n\n
\nvar img;\n\nfunction setup() {\n var c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('drop image', width / 2, height / 2);\n c.drop(gotFile);\n}\n\nfunction draw() {\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\nfunction gotFile(file) {\n img = createImg(file.data).hide();\n}\n
" + ], + "alt": "Canvas turns into whatever image is dragged/dropped onto it.", + "class": "p5.Element", + "module": "p5.dom", + "submodule": "p5.dom" + }, + { + "file": "lib/addons/p5.dom.js", + "line": 2253, "description": "

Path to the media element source.

\n", "itemtype": "property", "name": "src", @@ -19565,7 +20023,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 2065, + "line": 2319, "description": "

Play an HTML5 media element.

\n", "itemtype": "method", "name": "play", @@ -19579,7 +20037,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 2126, + "line": 2380, "description": "

Stops an HTML5 media element (sets current time to zero).

\n", "itemtype": "method", "name": "stop", @@ -19593,7 +20051,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 2190, + "line": 2444, "description": "

Pauses an HTML5 media element.

\n", "itemtype": "method", "name": "pause", @@ -19607,7 +20065,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 2252, + "line": 2506, "description": "

Set 'loop' to true for an HTML5 media element, and starts playing.

\n", "itemtype": "method", "name": "loop", @@ -19621,7 +20079,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 2308, + "line": 2562, "description": "

Set 'loop' to false for an HTML5 media element. Element will stop\nwhen it reaches the end.

\n", "itemtype": "method", "name": "noLoop", @@ -19635,7 +20093,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 2360, + "line": 2614, "description": "

Set HTML5 media element to autoplay or not.

\n", "itemtype": "method", "name": "autoplay", @@ -19653,7 +20111,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 2372, + "line": 2626, "description": "

Sets volume for this HTML5 media element. If no argument is given,\nreturns the current volume.

\n", "itemtype": "method", "name": "volume", @@ -19669,7 +20127,7 @@ module.exports={ "submodule": "p5.dom", "overloads": [ { - "line": 2372, + "line": 2626, "params": [], "return": { "description": "current volume", @@ -19677,7 +20135,7 @@ module.exports={ } }, { - "line": 2445, + "line": 2699, "params": [ { "name": "val", @@ -19691,7 +20149,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 2458, + "line": 2712, "description": "

If no arguments are given, returns the current playback speed of the\nelement. The speed parameter sets the speed where 2.0 will play the\nelement twice as fast, 0.5 will play at half the speed, and -1 will play\nthe element in normal speed in reverse.(Note that not all browsers support\nbackward playback and even if they do, playback might not be smooth.)

\n", "itemtype": "method", "name": "speed", @@ -19707,7 +20165,7 @@ module.exports={ "submodule": "p5.dom", "overloads": [ { - "line": 2458, + "line": 2712, "params": [], "return": { "description": "current playback speed of the element", @@ -19715,7 +20173,7 @@ module.exports={ } }, { - "line": 2529, + "line": 2783, "params": [ { "name": "speed", @@ -19729,7 +20187,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 2546, + "line": 2800, "description": "

If no arguments are given, returns the current time of the element.\nIf an argument is given the current time of the element is set to it.

\n", "itemtype": "method", "name": "time", @@ -19745,7 +20203,7 @@ module.exports={ "submodule": "p5.dom", "overloads": [ { - "line": 2546, + "line": 2800, "params": [], "return": { "description": "current time (in seconds)", @@ -19753,7 +20211,7 @@ module.exports={ } }, { - "line": 2591, + "line": 2845, "params": [ { "name": "time", @@ -19767,7 +20225,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 2605, + "line": 2859, "description": "

Returns the duration of the HTML5 media element.

\n", "itemtype": "method", "name": "duration", @@ -19784,7 +20242,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 2746, + "line": 2998, "description": "

Schedule an event to be called when the audio or video\nelement reaches the end. If the element is looping,\nthis will not be called. The element is passed in\nas the argument to the onended callback.

\n", "itemtype": "method", "name": "onended", @@ -19805,14 +20263,14 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 2777, + "line": 3029, "class": "p5.MediaElement", "module": "p5.dom", "submodule": "p5.dom" }, { "file": "lib/addons/p5.dom.js", - "line": 2779, + "line": 3031, "description": "

Send the audio output of this element to a specified audioNode or\np5.sound object. If no element is provided, connects to p5's master\noutput. That connection is established when this method is first called.\nAll connections are removed by the .disconnect() method.

\n

This method is meant to be used with the p5.sound.js addon library.

\n", "itemtype": "method", "name": "connect", @@ -19829,7 +20287,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 2828, + "line": 3080, "description": "

Disconnect all Web Audio routing, including to master output.\nThis is useful if you want to re-route the output through\naudio effects, for example.

\n", "itemtype": "method", "name": "disconnect", @@ -19839,14 +20297,14 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 2843, + "line": 3095, "class": "p5.MediaElement", "module": "p5.dom", "submodule": "p5.dom" }, { "file": "lib/addons/p5.dom.js", - "line": 2845, + "line": 3097, "description": "

Show the default MediaElement controls, as determined by the web browser.

\n", "itemtype": "method", "name": "showControls", @@ -19859,7 +20317,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 2876, + "line": 3128, "description": "

Hide the default mediaElement controls.

\n", "itemtype": "method", "name": "hideControls", @@ -19872,14 +20330,14 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 2905, + "line": 3157, "class": "p5.MediaElement", "module": "p5.dom", "submodule": "p5.dom" }, { "file": "lib/addons/p5.dom.js", - "line": 2916, + "line": 3168, "description": "

Schedule events to trigger every time a MediaElement\n(audio/video) reaches a playback cue point.

\n

Accepts a callback function, a time (in seconds) at which to trigger\nthe callback, and an optional parameter for the callback.

\n

Time will be passed as the first parameter to the callback function,\nand param will be the second parameter.

\n", "itemtype": "method", "name": "addCue", @@ -19914,7 +20372,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 2980, + "line": 3232, "description": "

Remove a callback based on its ID. The ID is returned by the\naddCue method.

\n", "itemtype": "method", "name": "removeCue", @@ -19934,7 +20392,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 3022, + "line": 3274, "description": "

Remove all of the callbacks that had originally been scheduled\nvia the addCue method.

\n", "itemtype": "method", "name": "clearCues", @@ -19954,7 +20412,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 3092, + "line": 3340, "description": "

Underlying File object. All normal File methods can be called on this.

\n", "itemtype": "property", "name": "file", @@ -19964,7 +20422,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 3104, + "line": 3352, "description": "

File type (image, text, etc.)

\n", "itemtype": "property", "name": "type", @@ -19974,7 +20432,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 3110, + "line": 3358, "description": "

File subtype (usually the file extension jpg, png, xml, etc.)

\n", "itemtype": "property", "name": "subtype", @@ -19984,7 +20442,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 3116, + "line": 3364, "description": "

File name

\n", "itemtype": "property", "name": "name", @@ -19994,7 +20452,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 3122, + "line": 3370, "description": "

File size

\n", "itemtype": "property", "name": "size", @@ -20004,7 +20462,7 @@ module.exports={ }, { "file": "lib/addons/p5.dom.js", - "line": 3129, + "line": 3377, "description": "

URL string containing image data.

\n", "itemtype": "property", "name": "data", @@ -20030,7 +20488,28 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 262, + "line": 363, + "class": "p5.sound", + "module": "p5.sound", + "submodule": "p5.sound" + }, + { + "file": "lib/addons/p5.sound.js", + "line": 740, + "class": "p5.sound", + "module": "p5.sound", + "submodule": "p5.sound" + }, + { + "file": "lib/addons/p5.sound.js", + "line": 810, + "class": "p5.sound", + "module": "p5.sound", + "submodule": "p5.sound" + }, + { + "file": "lib/addons/p5.sound.js", + "line": 1005, "description": "

Returns the Audio Context for this sketch. Useful for users\nwho would like to dig deeper into the Web Audio API\n.

\n\n

Some browsers require users to startAudioContext\nwith a user gesture, such as touchStarted in the example below.

", "itemtype": "method", "name": "getAudioContext", @@ -20047,7 +20526,38 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 328, + "line": 1042, + "description": "

It is a good practice to give users control over starting audio playback.\nThis practice is enforced by Google Chrome's autoplay policy as of r70\n(info), iOS Safari, and other browsers.\n

\n\n

\nuserStartAudio() starts the Audio Context on a user gesture. It utilizes\nthe StartAudioContext library by\nYotam Mann (MIT Licence, 2016). Read more at https://github.com/tambien/StartAudioContext.\n

\n\n

Starting the audio context on a user gesture can be as simple as userStartAudio().\nOptional parameters let you decide on a specific element that will start the audio context,\nand/or call a function once the audio context is started.

", + "params": [ + { + "name": "element(s)", + "description": "

This argument can be an Element,\n Selector String, NodeList, p5.Element,\n jQuery Element, or an Array of any of those.

\n", + "type": "Element|Array", + "optional": true + }, + { + "name": "callback", + "description": "

Callback to invoke when the AudioContext has started

\n", + "type": "Function", + "optional": true + } + ], + "return": { + "description": "Returns a Promise which is resolved when\n the AudioContext state is 'running'", + "type": "Promise" + }, + "itemtype": "method", + "name": "userStartAudio", + "example": [ + "\n
\nfunction setup() {\n var myDiv = createDiv('click to start audio');\n myDiv.position(0, 0);\n\n var mySynth = new p5.MonoSynth();\n\n // This won't play until the context has started\n mySynth.play('A6');\n\n // Start the audio context on a click/touch event\n userStartAudio().then(function() {\n myDiv.remove();\n });\n}\n
" + ], + "class": "p5.sound", + "module": "p5.sound", + "submodule": "p5.sound" + }, + { + "file": "lib/addons/p5.sound.js", + "line": 1099, "description": "

Master contains AudioContext and the master sound output.

\n", "class": "p5.sound", "module": "p5.sound", @@ -20055,7 +20565,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 361, + "line": 1132, "description": "

Returns a number representing the master amplitude (volume) for sound\nin this sketch.

\n", "itemtype": "method", "name": "getMasterVolume", @@ -20069,7 +20579,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 372, + "line": 1143, "description": "

Scale the output of all sound in this sketch

\nScaled between 0.0 (silence) and 1.0 (full volume).\n1.0 is the maximum amplitude of a digital sound, so multiplying\nby greater than 1.0 may cause digital distortion. To\nfade, provide a rampTime parameter. For more\ncomplex fades, see the Envelope class.\n\nAlternately, you can pass in a signal source such as an\noscillator to modulate the amplitude with an audio signal.\n\n

How This Works: When you load the p5.sound module, it\ncreates a single instance of p5sound. All sound objects in this\nmodule output to p5sound before reaching your computer's output.\nSo if you change the amplitude of p5sound, it impacts all of the\nsound in this module.

\n\n

If no value is provided, returns a Web Audio API Gain Node

", "itemtype": "method", "name": "masterVolume", @@ -20098,7 +20608,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 414, + "line": 1185, "description": "

p5.soundOut is the p5.sound master output. It sends output to\nthe destination of this window's web audio context. It contains\nWeb Audio API nodes including a dyanmicsCompressor (.limiter),\nand Gain Nodes for .input and .output.

\n", "itemtype": "property", "name": "soundOut", @@ -20109,14 +20619,14 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 439, + "line": 1210, "class": "p5", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 442, + "line": 1213, "description": "

Returns a number representing the sample rate, in samples per second,\nof all sound objects in this audio context. It is determined by the\nsampling rate of your operating system's sound card, and it is not\ncurrently possile to change.\nIt is often 44100, or twice the range of human hearing.

\n", "itemtype": "method", "name": "sampleRate", @@ -20130,7 +20640,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 455, + "line": 1226, "description": "

Returns the closest MIDI note value for\na given frequency.

\n", "itemtype": "method", "name": "freqToMidi", @@ -20151,7 +20661,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 469, + "line": 1240, "description": "

Returns the frequency value of a MIDI note value.\nGeneral MIDI treats notes as integers where middle C\nis 60, C# is 61, D is 62 etc. Useful for generating\nmusical frequencies with oscillators.

\n", "itemtype": "method", "name": "midiToFreq", @@ -20175,7 +20685,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 531, + "line": 1302, "description": "

List the SoundFile formats that you will include. LoadSound\nwill search your directory for these extensions, and will pick\na format that is compatable with the client's web browser.\nHere is a free online file\nconverter.

\n", "itemtype": "method", "name": "soundFormats", @@ -20197,7 +20707,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 644, + "line": 1415, "description": "

Used by Osc and Envelope to chain signal math

\n", "class": "p5", "module": "p5.sound", @@ -20205,7 +20715,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 923, + "line": 1763, "description": "

loadSound() returns a new p5.SoundFile from a specified\npath. If called during preload(), the p5.SoundFile will be ready\nto play in time for setup() and draw(). If called outside of\npreload, the p5.SoundFile will not be ready immediately, so\nloadSound accepts a callback as the second parameter. Using a\n\nlocal server is recommended when loading external files.

\n", "itemtype": "method", "name": "loadSound", @@ -20247,7 +20757,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1065, + "line": 1919, "description": "

Returns true if the sound file finished loading successfully.

\n", "itemtype": "method", "name": "isLoaded", @@ -20261,7 +20771,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1078, + "line": 1932, "description": "

Play the p5.SoundFile

\n", "itemtype": "method", "name": "play", @@ -20303,7 +20813,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1183, + "line": 2022, "description": "

p5.SoundFile has two play modes: restart and\nsustain. Play Mode determines what happens to a\np5.SoundFile if it is triggered while in the middle of playback.\nIn sustain mode, playback will continue simultaneous to the\nnew playback. In restart mode, play() will stop playback\nand start over. With untilDone, a sound will play only if it's\nnot already playing. Sustain is the default mode.

\n", "itemtype": "method", "name": "playMode", @@ -20323,7 +20833,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1227, + "line": 2066, "description": "

Pauses a file that is currently playing. If the file is not\nplaying, then nothing will happen.

\n

After pausing, .play() will resume from the paused\nposition.\nIf p5.SoundFile had been set to loop before it was paused,\nit will continue to loop after it is unpaused with .play().

\n", "itemtype": "method", "name": "pause", @@ -20344,7 +20854,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1283, + "line": 2122, "description": "

Loop the p5.SoundFile. Accepts optional parameters to set the\nplayback rate, playback volume, loopStart, loopEnd.

\n", "itemtype": "method", "name": "loop", @@ -20386,7 +20896,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1299, + "line": 2138, "description": "

Set a p5.SoundFile's looping flag to true or false. If the sound\nis currently playing, this change will take effect when it\nreaches the end of the current playback.

\n", "itemtype": "method", "name": "setLoop", @@ -20403,7 +20913,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1320, + "line": 2159, "description": "

Returns 'true' if a p5.SoundFile is currently looping and playing, 'false' if not.

\n", "itemtype": "method", "name": "isLooping", @@ -20417,7 +20927,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1335, + "line": 2174, "description": "

Returns true if a p5.SoundFile is playing, false if not (i.e.\npaused or stopped).

\n", "itemtype": "method", "name": "isPlaying", @@ -20431,7 +20941,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1345, + "line": 2184, "description": "

Returns true if a p5.SoundFile is paused, false if not (i.e.\nplaying or stopped).

\n", "itemtype": "method", "name": "isPaused", @@ -20445,7 +20955,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1355, + "line": 2194, "description": "

Stop soundfile playback.

\n", "itemtype": "method", "name": "stop", @@ -20463,7 +20973,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1401, + "line": 2239, "description": "

Multiply the output volume (amplitude) of a sound file\nbetween 0.0 (silence) and 1.0 (full volume).\n1.0 is the maximum amplitude of a digital sound, so multiplying\nby greater than 1.0 may cause digital distortion. To\nfade, provide a rampTime parameter. For more\ncomplex fades, see the Envelope class.

\n

Alternately, you can pass in a signal source such as an\noscillator to modulate the amplitude with an audio signal.

\n", "itemtype": "method", "name": "setVolume", @@ -20492,7 +21002,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1442, + "line": 2280, "description": "

Set the stereo panning of a p5.sound object to\na floating point number between -1.0 (left) and 1.0 (right).\nDefault is 0.0 (center).

\n", "itemtype": "method", "name": "pan", @@ -20519,7 +21029,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1481, + "line": 2319, "description": "

Returns the current stereo pan position (-1.0 to 1.0)

\n", "itemtype": "method", "name": "getPan", @@ -20533,7 +21043,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1492, + "line": 2330, "description": "

Set the playback rate of a sound file. Will change the speed and the pitch.\nValues less than zero will reverse the audio buffer.

\n", "itemtype": "method", "name": "rate", @@ -20554,7 +21064,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1565, + "line": 2403, "description": "

Returns the duration of a sound file in seconds.

\n", "itemtype": "method", "name": "duration", @@ -20568,7 +21078,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1579, + "line": 2417, "description": "

Return the current position of the p5.SoundFile playhead, in seconds.\nTime is relative to the normal buffer direction, so if reverseBuffer\nhas been called, currentTime will count backwards.

\n", "itemtype": "method", "name": "currentTime", @@ -20582,7 +21092,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1590, + "line": 2428, "description": "

Move the playhead of the song to a position, in seconds. Start timing\nand playback duration. If none are given, will reset the file to play\nentire duration from start to finish.

\n", "itemtype": "method", "name": "jump", @@ -20604,7 +21114,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1613, + "line": 2451, "description": "

Return the number of channels in a sound file.\nFor example, Mono = 1, Stereo = 2.

\n", "itemtype": "method", "name": "channels", @@ -20618,7 +21128,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1623, + "line": 2461, "description": "

Return the sample rate of the sound file.

\n", "itemtype": "method", "name": "sampleRate", @@ -20632,7 +21142,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1632, + "line": 2470, "description": "

Return the number of samples in a sound file.\nEqual to sampleRate * duration.

\n", "itemtype": "method", "name": "frames", @@ -20646,7 +21156,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1642, + "line": 2480, "description": "

Returns an array of amplitude peaks in a p5.SoundFile that can be\nused to draw a static waveform. Scans through the p5.SoundFile's\naudio buffer to find the greatest amplitudes. Accepts one\nparameter, 'length', which determines size of the array.\nLarger arrays result in more precise waveform visualizations.

\n

Inspired by Wavesurfer.js.

\n", "itemtype": "method", "name": "getPeaks", @@ -20668,7 +21178,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1694, + "line": 2532, "description": "

Reverses the p5.SoundFile's buffer source.\nPlayback must be handled separately (see example).

\n", "itemtype": "method", "name": "reverseBuffer", @@ -20681,7 +21191,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1734, + "line": 2572, "description": "

Schedule an event to be called when the soundfile\nreaches the end of a buffer. If the soundfile is\nplaying through once, this will be called when it\nends. If it is looping, it will be called when\nstop is called.

\n", "itemtype": "method", "name": "onended", @@ -20698,7 +21208,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1787, + "line": 2625, "description": "

Connects the output of a p5sound object to input of another\np5.sound object. For example, you may connect a p5.SoundFile to an\nFFT or an Effect. If no parameter is given, it will connect to\nthe master output. Most p5sound objects connect to the master\noutput when they are created.

\n", "itemtype": "method", "name": "connect", @@ -20716,7 +21226,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1808, + "line": 2646, "description": "

Disconnects the output of this p5sound object.

\n", "itemtype": "method", "name": "disconnect", @@ -20726,14 +21236,14 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1818, + "line": 2656, "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 1823, + "line": 2661, "description": "

Reset the source for this SoundFile to a\nnew path (URL).

\n", "itemtype": "method", "name": "setPath", @@ -20755,7 +21265,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1836, + "line": 2674, "description": "

Replace the current Audio Buffer with a new Buffer.

\n", "itemtype": "method", "name": "setBuffer", @@ -20772,7 +21282,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 1908, + "line": 2741, "description": "

processPeaks returns an array of timestamps where it thinks there is a beat.

\n

This is an asynchronous function that processes the soundfile in an offline audio context,\nand sends the results to your callback function.

\n

The process involves running the soundfile through a lowpass filter, and finding all of the\npeaks above the initial threshold. If the total number of peaks are below the minimum number of peaks,\nit decreases the threshold and re-runs the analysis until either minPeaks or minThreshold are reached.

\n", "itemtype": "method", "name": "processPeaks", @@ -20811,14 +21321,14 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 2099, + "line": 2934, "class": "p5.SoundFile", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 2108, + "line": 2943, "description": "

Schedule events to trigger every time a MediaElement\n(audio/video) reaches a playback cue point.

\n

Accepts a callback function, a time (in seconds) at which to trigger\nthe callback, and an optional parameter for the callback.

\n

Time will be passed as the first parameter to the callback function,\nand param will be the second parameter.

\n", "itemtype": "method", "name": "addCue", @@ -20853,7 +21363,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 2186, + "line": 3021, "description": "

Remove a callback based on its ID. The ID is returned by the\naddCue method.

\n", "itemtype": "method", "name": "removeCue", @@ -20870,7 +21380,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 2204, + "line": 3040, "description": "

Remove all of the callbacks that had originally been scheduled\nvia the addCue method.

\n", "itemtype": "method", "name": "clearCues", @@ -20880,7 +21390,45 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 2312, + "line": 3065, + "description": "

Save a p5.SoundFile as a .wav file. The browser will prompt the user\nto download the file to their device. To upload a file to a server, see\ngetBlob

\n", + "itemtype": "method", + "name": "save", + "params": [ + { + "name": "fileName", + "description": "

name of the resulting .wav file.

\n", + "type": "String", + "optional": true + } + ], + "example": [ + "\n
\n var inp, button, mySound;\n var fileName = 'cool';\n function preload() {\n mySound = loadSound('assets/doorbell.mp3');\n }\n function setup() {\n btn = createButton('click to save file');\n btn.position(0, 0);\n btn.mouseClicked(handleMouseClick);\n }\n\n function handleMouseClick() {\n mySound.save(fileName);\n }\n
" + ], + "class": "p5.SoundFile", + "module": "p5.sound", + "submodule": "p5.sound" + }, + { + "file": "lib/addons/p5.sound.js", + "line": 3094, + "description": "

This method is useful for sending a SoundFile to a server. It returns the\n.wav-encoded audio data as a "Blob".\nA Blob is a file-like data object that can be uploaded to a server\nwith an http request. We'll\nuse the httpDo options object to send a POST request with some\nspecific options: we encode the request as multipart/form-data,\nand attach the blob as one of the form values using FormData.

\n", + "itemtype": "method", + "name": "getBlob", + "return": { + "description": "A file-like data object", + "type": "Blob" + }, + "example": [ + "\n
\n\n function preload() {\n mySound = loadSound('assets/doorbell.mp3');\n }\n\n function setup() {\n noCanvas();\n var soundBlob = mySound.getBlob();\n\n // Now we can send the blob to a server...\n var serverUrl = 'https://jsonplaceholder.typicode.com/posts';\n var httpRequestOptions = {\n method: 'POST',\n body: new FormData().append('soundBlob', soundBlob),\n headers: new Headers({\n 'Content-Type': 'multipart/form-data'\n })\n };\n httpDo(serverUrl, httpRequestOptions);\n\n // We can also create an `ObjectURL` pointing to the Blob\n var blobUrl = URL.createObjectURL(soundBlob);\n\n // The `
" + ], + "class": "p5.SoundFile", + "module": "p5.sound", + "submodule": "p5.sound" + }, + { + "file": "lib/addons/p5.sound.js", + "line": 3257, "description": "

Connects to the p5sound instance (master output) by default.\nOptionally, you can pass in a specific source (i.e. a soundfile).

\n", "itemtype": "method", "name": "setInput", @@ -20907,7 +21455,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 2419, + "line": 3364, "description": "

Returns a single Amplitude reading at the moment it is called.\nFor continuous readings, run in the draw loop.

\n", "itemtype": "method", "name": "getLevel", @@ -20932,7 +21480,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 2460, + "line": 3405, "description": "

Determines whether the results of Amplitude.process() will be\nNormalized. To normalize, Amplitude finds the difference the\nloudest reading it has processed and the maximum amplitude of\n1.0. Amplitude adds this difference to all values to produce\nresults that will reliably map between 0.0 and 1.0. However,\nif a louder moment occurs, the amount that Normalize adds to\nall the values will change. Accepts an optional boolean parameter\n(true or false). Normalizing is off by default.

\n", "itemtype": "method", "name": "toggleNormalize", @@ -20950,7 +21498,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 2480, + "line": 3425, "description": "

Smooth Amplitude analysis by averaging with the last analysis\nframe. Off by default.

\n", "itemtype": "method", "name": "smooth", @@ -20967,7 +21515,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 2654, + "line": 3599, "description": "

Set the input source for the FFT analysis. If no source is\nprovided, FFT will analyze all sound in the sketch.

\n", "itemtype": "method", "name": "setInput", @@ -20985,7 +21533,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 2673, + "line": 3618, "description": "

Returns an array of amplitude values (between -1.0 and +1.0) that represent\na snapshot of amplitude readings in a single buffer. Length will be\nequal to bins (defaults to 1024). Can be used to draw the waveform\nof a sound.

\n", "itemtype": "method", "name": "waveform", @@ -21013,7 +21561,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 2716, + "line": 3661, "description": "

Returns an array of amplitude values (between 0 and 255)\nacross the frequency spectrum. Length is equal to FFT bins\n(1024 by default). The array indices correspond to frequencies\n(i.e. pitches), from the lowest to the highest that humans can\nhear. Each value represents amplitude at that slice of the\nfrequency spectrum. Must be called prior to using\ngetEnergy().

\n", "itemtype": "method", "name": "analyze", @@ -21044,7 +21592,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 2808, + "line": 3753, "description": "

Returns the amount of energy (volume) at a specific\n\nfrequency, or the average amount of energy between two\nfrequencies. Accepts Number(s) corresponding\nto frequency (in Hz), or a String corresponding to predefined\nfrequency ranges ("bass", "lowMid", "mid", "highMid", "treble").\nReturns a range between 0 (no energy/volume at that frequency) and\n255 (maximum energy).\nNOTE: analyze() must be called prior to getEnergy(). Analyze()\ntells the FFT to analyze frequency data, and getEnergy() uses\nthe results determine the value at a specific frequency or\nrange of frequencies.

\n", "itemtype": "method", "name": "getEnergy", @@ -21071,7 +21619,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 2890, + "line": 3835, "description": "

Returns the\n\nspectral centroid of the input signal.\nNOTE: analyze() must be called prior to getCentroid(). Analyze()\ntells the FFT to analyze frequency data, and getCentroid() uses\nthe results determine the spectral centroid.

\n", "itemtype": "method", "name": "getCentroid", @@ -21088,7 +21636,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 2970, + "line": 3915, "description": "

Smooth FFT analysis by averaging with the last analysis frame.

\n", "itemtype": "method", "name": "smooth", @@ -21105,7 +21653,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 2992, + "line": 3937, "description": "

Returns an array of average amplitude values for a given number\nof frequency bands split equally. N defaults to 16.\nNOTE: analyze() must be called prior to linAverages(). Analyze()\ntells the FFT to analyze frequency data, and linAverages() uses\nthe results to group them into a smaller set of averages.

\n", "itemtype": "method", "name": "linAverages", @@ -21126,7 +21674,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 3022, + "line": 3967, "description": "

Returns an array of average amplitude values of the spectrum, for a given\nset of \nOctave Bands\nNOTE: analyze() must be called prior to logAverages(). Analyze()\ntells the FFT to analyze frequency data, and logAverages() uses\nthe results to group them into a smaller set of averages.

\n", "itemtype": "method", "name": "logAverages", @@ -21147,7 +21695,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 3052, + "line": 3997, "description": "

Calculates and Returns the 1/N\nOctave Bands\nN defaults to 3 and minimum central frequency to 15.625Hz.\n(1/3 Octave Bands ~= 31 Frequency Bands)\nSetting fCtr0 to a central value of a higher octave will ignore the lower bands\nand produce less frequency groups.

\n", "itemtype": "method", "name": "getOctaveBands", @@ -21173,119 +21721,98 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 3110, - "class": "p5.FFT", - "module": "p5.sound", - "submodule": "p5.sound" - }, - { - "file": "lib/addons/p5.sound.js", - "line": 3487, - "class": "p5.FFT", - "module": "p5.sound", - "submodule": "p5.sound" - }, - { - "file": "lib/addons/p5.sound.js", - "line": 3508, - "class": "p5.FFT", - "module": "p5.sound", - "submodule": "p5.sound" - }, - { - "file": "lib/addons/p5.sound.js", - "line": 3567, + "line": 4055, "class": "p5.FFT", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 3885, + "line": 4076, "class": "p5.FFT", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 4057, + "line": 4135, "class": "p5.FFT", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 4215, + "line": 4453, "class": "p5.FFT", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 4256, + "line": 4625, "class": "p5.FFT", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 4326, + "line": 4783, "class": "p5.FFT", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 4514, + "line": 4824, "class": "p5.FFT", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 4571, + "line": 4881, "class": "p5.FFT", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 4739, + "line": 5049, "class": "p5.FFT", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 4787, + "line": 5097, "class": "p5.FFT", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 4818, + "line": 5128, "class": "p5.FFT", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 4839, + "line": 5149, "class": "p5.FFT", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 4859, + "line": 5169, "class": "p5.FFT", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 4961, + "line": 5268, "description": "

Fade to value, for smooth transitions

\n", "itemtype": "method", "name": "fade", @@ -21308,7 +21835,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 4972, + "line": 5279, "description": "

Connect a p5.sound object or Web Audio node to this\np5.Signal so that its amplitude values can be scaled.

\n", "itemtype": "method", "name": "setInput", @@ -21325,7 +21852,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 4986, + "line": 5293, "description": "

Add a constant value to this audio signal,\nand return the resulting audio signal. Does\nnot change the value of the original signal,\ninstead it returns a new p5.SignalAdd.

\n", "itemtype": "method", "name": "add", @@ -21346,7 +21873,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 5005, + "line": 5312, "description": "

Multiply this signal by a constant value,\nand return the resulting audio signal. Does\nnot change the value of the original signal,\ninstead it returns a new p5.SignalMult.

\n", "itemtype": "method", "name": "mult", @@ -21367,7 +21894,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 5024, + "line": 5331, "description": "

Scale this signal value to a given range,\nand return the result as an audio signal. Does\nnot change the value of the original signal,\ninstead it returns a new p5.SignalScale.

\n", "itemtype": "method", "name": "scale", @@ -21408,7 +21935,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 5158, + "line": 5465, "description": "

Start an oscillator. Accepts an optional parameter to\ndetermine how long (in seconds from now) until the\noscillator starts.

\n", "itemtype": "method", "name": "start", @@ -21432,7 +21959,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 5198, + "line": 5505, "description": "

Stop an oscillator. Accepts an optional parameter\nto determine how long (in seconds from now) until the\noscillator stops.

\n", "itemtype": "method", "name": "stop", @@ -21449,7 +21976,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 5214, + "line": 5521, "description": "

Set the amplitude between 0 and 1.0. Or, pass in an object\nsuch as an oscillator to modulate amplitude with an audio signal.

\n", "itemtype": "method", "name": "amp", @@ -21482,7 +22009,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 5249, + "line": 5556, "description": "

Set frequency of an oscillator to a value. Or, pass in an object\nsuch as an oscillator to modulate the frequency with an audio signal.

\n", "itemtype": "method", "name": "freq", @@ -21518,7 +22045,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 5308, + "line": 5615, "description": "

Set type to 'sine', 'triangle', 'sawtooth' or 'square'.

\n", "itemtype": "method", "name": "setType", @@ -21535,7 +22062,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 5320, + "line": 5627, "description": "

Connect to a p5.sound / Web Audio object.

\n", "itemtype": "method", "name": "connect", @@ -21552,7 +22079,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 5337, + "line": 5644, "description": "

Disconnect all outputs

\n", "itemtype": "method", "name": "disconnect", @@ -21562,7 +22089,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 5354, + "line": 5661, "description": "

Pan between Left (-1) and Right (1)

\n", "itemtype": "method", "name": "pan", @@ -21584,7 +22111,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 5386, + "line": 5693, "description": "

Set the phase of an oscillator between 0.0 and 1.0.\nIn this implementation, phase is a delay time\nbased on the oscillator's current frequency.

\n", "itemtype": "method", "name": "phase", @@ -21601,7 +22128,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 5440, + "line": 5747, "description": "

Add a value to the p5.Oscillator's output amplitude,\nand return the oscillator. Calling this method again\nwill override the initial add() with a new value.

\n", "itemtype": "method", "name": "add", @@ -21622,7 +22149,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 5457, + "line": 5764, "description": "

Multiply the p5.Oscillator's output amplitude\nby a fixed value (i.e. turn it up!). Calling this method\nagain will override the initial mult() with a new value.

\n", "itemtype": "method", "name": "mult", @@ -21643,7 +22170,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 5473, + "line": 5780, "description": "

Scale this oscillator's amplitude values to a given\nrange, and return the oscillator. Calling this method\nagain will override the initial scale() with new values.

\n", "itemtype": "method", "name": "scale", @@ -21679,21 +22206,21 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 5572, + "line": 5879, "class": "p5.SqrOsc", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 5775, + "line": 6082, "class": "p5.SqrOsc", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 6064, + "line": 6369, "description": "

Time until envelope reaches attackLevel

\n", "itemtype": "property", "name": "attackTime", @@ -21703,7 +22230,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 6069, + "line": 6374, "description": "

Level once attack is complete.

\n", "itemtype": "property", "name": "attackLevel", @@ -21713,7 +22240,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 6074, + "line": 6379, "description": "

Time until envelope reaches decayLevel.

\n", "itemtype": "property", "name": "decayTime", @@ -21723,7 +22250,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 6079, + "line": 6384, "description": "

Level after decay. The envelope will sustain here until it is released.

\n", "itemtype": "property", "name": "decayLevel", @@ -21733,7 +22260,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 6084, + "line": 6389, "description": "

Duration of the release portion of the envelope.

\n", "itemtype": "property", "name": "releaseTime", @@ -21743,7 +22270,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 6089, + "line": 6394, "description": "

Level at the end of the release.

\n", "itemtype": "property", "name": "releaseLevel", @@ -21753,7 +22280,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 6125, + "line": 6430, "description": "

Reset the envelope with a series of time/value pairs.

\n", "itemtype": "method", "name": "set", @@ -21798,7 +22325,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 6184, + "line": 6489, "description": "

Set values like a traditional\n\nADSR envelope\n.

\n", "itemtype": "method", "name": "setADSR", @@ -21828,7 +22355,7 @@ module.exports={ } ], "example": [ - "\n
\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv(){\n env.play();\n}\n
" + "\n
\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001;\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv() {\n env.play();\n}\n
" ], "class": "p5.Envelope", "module": "p5.sound", @@ -21836,7 +22363,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 6249, + "line": 6554, "description": "

Set max (attackLevel) and min (releaseLevel) of envelope.

\n", "itemtype": "method", "name": "setRange", @@ -21853,7 +22380,7 @@ module.exports={ } ], "example": [ - "\n
\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv(){\n env.play();\n}\n
" + "\n
\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001;\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv() {\n env.play();\n}\n
" ], "class": "p5.Envelope", "module": "p5.sound", @@ -21861,7 +22388,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 6328, + "line": 6633, "description": "

Assign a parameter to be controlled by this envelope.\nIf a p5.Sound object is given, then the p5.Envelope will control its\noutput gain. If multiple inputs are provided, the env will\ncontrol all of them.

\n", "itemtype": "method", "name": "setInput", @@ -21880,7 +22407,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 6343, + "line": 6648, "description": "

Set whether the envelope ramp is linear (default) or exponential.\nExponential ramps can be useful because we perceive amplitude\nand frequency logarithmically.

\n", "itemtype": "method", "name": "setExp", @@ -21897,7 +22424,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 6361, + "line": 6666, "description": "

Play tells the envelope to start acting on a given input.\nIf the input is a p5.sound object (i.e. AudioIn, Oscillator,\nSoundFile), then Envelope will control its output volume.\nEnvelopes can also be used to control any \nWeb Audio Audio Param.

\n", "itemtype": "method", "name": "play", @@ -21921,7 +22448,7 @@ module.exports={ } ], "example": [ - "\n
\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv(){\n // trigger env on triOsc, 0 seconds from now\n // After decay, sustain for 0.2 seconds before release\n env.play(triOsc, 0, 0.2);\n}\n
" + "\n
\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001;\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv() {\n // trigger env on triOsc, 0 seconds from now\n // After decay, sustain for 0.2 seconds before release\n env.play(triOsc, 0, 0.2);\n}\n
" ], "class": "p5.Envelope", "module": "p5.sound", @@ -21929,7 +22456,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 6422, + "line": 6727, "description": "

Trigger the Attack, and Decay portion of the Envelope.\nSimilar to holding down a key on a piano, but it will\nhold the sustain level until you let go. Input can be\nany p5.sound object, or a \nWeb Audio Param.

\n", "itemtype": "method", "name": "triggerAttack", @@ -21946,7 +22473,7 @@ module.exports={ } ], "example": [ - "\n
\n\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.3;\nvar susPercent = 0.4;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(envAttack);\n}\n\nfunction envAttack(){\n console.log('trigger attack');\n env.triggerAttack();\n\n background(0,255,0);\n text('attack!', width/2, height/2);\n}\n\nfunction mouseReleased() {\n env.triggerRelease();\n\n background(200);\n text('click to play', width/2, height/2);\n}\n
" + "\n
\n\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001;\nvar decayTime = 0.3;\nvar susPercent = 0.4;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(envAttack);\n}\n\nfunction envAttack() {\n console.log('trigger attack');\n env.triggerAttack();\n\n background(0,255,0);\n text('attack!', width/2, height/2);\n}\n\nfunction mouseReleased() {\n env.triggerRelease();\n\n background(200);\n text('click to play', width/2, height/2);\n}\n
" ], "class": "p5.Envelope", "module": "p5.sound", @@ -21954,7 +22481,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 6529, + "line": 6834, "description": "

Trigger the Release of the Envelope. This is similar to releasing\nthe key on a piano and letting the sound fade according to the\nrelease level and release time.

\n", "itemtype": "method", "name": "triggerRelease", @@ -21971,7 +22498,7 @@ module.exports={ } ], "example": [ - "\n
\n\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.3;\nvar susPercent = 0.4;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(envAttack);\n}\n\nfunction envAttack(){\n console.log('trigger attack');\n env.triggerAttack();\n\n background(0,255,0);\n text('attack!', width/2, height/2);\n}\n\nfunction mouseReleased() {\n env.triggerRelease();\n\n background(200);\n text('click to play', width/2, height/2);\n}\n
" + "\n
\n\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001;\nvar decayTime = 0.3;\nvar susPercent = 0.4;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(envAttack);\n}\n\nfunction envAttack() {\n console.log('trigger attack');\n env.triggerAttack();\n\n background(0,255,0);\n text('attack!', width/2, height/2);\n}\n\nfunction mouseReleased() {\n env.triggerRelease();\n\n background(200);\n text('click to play', width/2, height/2);\n}\n
" ], "class": "p5.Envelope", "module": "p5.sound", @@ -21979,7 +22506,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 6626, + "line": 6931, "description": "

Exponentially ramp to a value using the first two\nvalues from setADSR(attackTime, decayTime)\nas \ntime constants for simple exponential ramps.\nIf the value is higher than current value, it uses attackTime,\nwhile a decrease uses decayTime.

\n", "itemtype": "method", "name": "ramp", @@ -22015,7 +22542,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 6733, + "line": 7038, "description": "

Add a value to the p5.Oscillator's output amplitude,\nand return the oscillator. Calling this method\nagain will override the initial add() with new values.

\n", "itemtype": "method", "name": "add", @@ -22036,7 +22563,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 6749, + "line": 7054, "description": "

Multiply the p5.Envelope's output amplitude\nby a fixed value. Calling this method\nagain will override the initial mult() with new values.

\n", "itemtype": "method", "name": "mult", @@ -22057,7 +22584,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 6765, + "line": 7070, "description": "

Scale this envelope's amplitude values to a given\nrange, and return the envelope. Calling this method\nagain will override the initial scale() with new values.

\n", "itemtype": "method", "name": "scale", @@ -22093,7 +22620,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 6873, + "line": 7178, "description": "

Set the width of a Pulse object (an oscillator that implements\nPulse Width Modulation).

\n", "itemtype": "method", "name": "width", @@ -22111,7 +22638,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 7060, + "line": 7365, "description": "

Set type of noise to 'white', 'pink' or 'brown'.\nWhite is the default.

\n", "itemtype": "method", "name": "setType", @@ -22129,7 +22656,57 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 7178, + "line": 7478, + "itemtype": "property", + "name": "input", + "type": "GainNode", + "class": "p5.AudioIn", + "module": "p5.sound", + "submodule": "p5.sound" + }, + { + "file": "lib/addons/p5.sound.js", + "line": 7482, + "itemtype": "property", + "name": "output", + "type": "GainNode", + "class": "p5.AudioIn", + "module": "p5.sound", + "submodule": "p5.sound" + }, + { + "file": "lib/addons/p5.sound.js", + "line": 7486, + "itemtype": "property", + "name": "stream", + "type": "MediaStream|null", + "class": "p5.AudioIn", + "module": "p5.sound", + "submodule": "p5.sound" + }, + { + "file": "lib/addons/p5.sound.js", + "line": 7490, + "itemtype": "property", + "name": "mediaStream", + "type": "MediaStreamAudioSourceNode|null", + "class": "p5.AudioIn", + "module": "p5.sound", + "submodule": "p5.sound" + }, + { + "file": "lib/addons/p5.sound.js", + "line": 7494, + "itemtype": "property", + "name": "currentSource", + "type": "Number|null", + "class": "p5.AudioIn", + "module": "p5.sound", + "submodule": "p5.sound" + }, + { + "file": "lib/addons/p5.sound.js", + "line": 7498, "description": "

Client must allow browser to access their microphone / audioin source.\nDefault: false. Will become true when the client enables acces.

\n", "itemtype": "property", "name": "enabled", @@ -22140,7 +22717,18 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 7194, + "line": 7505, + "description": "

Input amplitude, connect to it by default but not to master out

\n", + "itemtype": "property", + "name": "amplitude", + "type": "p5.Amplitude", + "class": "p5.AudioIn", + "module": "p5.sound", + "submodule": "p5.sound" + }, + { + "file": "lib/addons/p5.sound.js", + "line": 7518, "description": "

Start processing audio input. This enables the use of other\nAudioIn methods like getLevel(). Note that by default, AudioIn\nis not connected to p5.sound's output. So you won't hear\nanything unless you use the connect() method.

\n

Certain browsers limit access to the user's microphone. For example,\nChrome only allows access from localhost and over https. For this reason,\nyou may want to include an errorCallback—a function that is called in case\nthe browser won't provide mic access.

\n", "itemtype": "method", "name": "start", @@ -22164,7 +22752,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 7247, + "line": 7571, "description": "

Turn the AudioIn off. If the AudioIn is stopped, it cannot getLevel().\nIf re-starting, the user may be prompted for permission access.

\n", "itemtype": "method", "name": "stop", @@ -22174,7 +22762,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 7263, + "line": 7587, "description": "

Connect to an audio unit. If no parameter is provided, will\nconnect to the master output (i.e. your speakers).

\n", "itemtype": "method", "name": "connect", @@ -22192,7 +22780,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 7284, + "line": 7608, "description": "

Disconnect the AudioIn from all audio units. For example, if\nconnect() had been called, disconnect() will stop sending\nsignal to your speakers.

\n", "itemtype": "method", "name": "disconnect", @@ -22202,7 +22790,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 7298, + "line": 7622, "description": "

Read the Amplitude (volume level) of an AudioIn. The AudioIn\nclass contains its own instance of the Amplitude class to help\nmake it easy to get a microphone's volume level. Accepts an\noptional smoothing value (0.0 < 1.0). NOTE: AudioIn must\n.start() before using .getLevel().

\n", "itemtype": "method", "name": "getLevel", @@ -22224,7 +22812,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 7316, + "line": 7640, "description": "

Set amplitude (volume) of a mic input between 0 and 1.0.

\n", "itemtype": "method", "name": "amp", @@ -22247,8 +22835,8 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 7335, - "description": "

Returns a list of available input sources. This is a wrapper\nfor <a title="MediaDevices.enumerateDevices() - Web APIs | MDN" target="_blank" href=\n "https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices"

\n
\n

and it returns a Promise.

\n
\n", + "line": 7659, + "description": "

Returns a list of available input sources. This is a wrapper\nfor <a title="MediaDevices.enumerateDevices() - Web APIs | MDN" target="_blank" href=\n "https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices"

\n
\n

and it returns a Promise.

\n
\n", "itemtype": "method", "name": "getSources", "params": [ @@ -22278,8 +22866,8 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 7386, - "description": "

Set the input source. Accepts a number representing a\nposition in the array returned by getSources().\nThis is only available in browsers that support\n<a title="MediaDevices.enumerateDevices() - Web APIs | MDN" target="_blank" href=\n"https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices"

\n
\n

navigator.mediaDevices.enumerateDevices().

\n
\n", + "line": 7710, + "description": "

Set the input source. Accepts a number representing a\nposition in the array returned by getSources().\nThis is only available in browsers that support\n<a title="MediaDevices.enumerateDevices() - Web APIs | MDN" target="_blank" href=\n"https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices"

\n
\n

navigator.mediaDevices.enumerateDevices().

\n
\n", "itemtype": "method", "name": "setSource", "params": [ @@ -22295,84 +22883,84 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 7426, + "line": 7750, "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 7442, + "line": 7766, "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 7466, + "line": 7790, "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 7492, + "line": 7816, "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 7514, + "line": 7838, "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 7536, + "line": 7860, "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 7582, + "line": 7906, "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 7613, + "line": 7937, "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 7631, + "line": 7955, "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 7968, + "line": 8292, "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 7990, + "line": 8314, "class": "p5.AudioIn", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 8066, + "line": 8390, "description": "

In classes that extend\np5.Effect, connect effect nodes\nto the wet parameter

\n", "class": "p5.Effect", "module": "p5.sound", @@ -22380,7 +22968,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8079, + "line": 8403, "description": "

Set the output volume of the filter.

\n", "itemtype": "method", "name": "amp", @@ -22410,7 +22998,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8096, + "line": 8420, "description": "

Link effects together in a chain
Example usage: filter.chain(reverb, delay, panner);\nMay be used with an open-ended number of arguments

\n", "itemtype": "method", "name": "chain", @@ -22428,7 +23016,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8113, + "line": 8437, "description": "

Adjust the dry/wet value.

\n", "itemtype": "method", "name": "drywet", @@ -22446,7 +23034,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8125, + "line": 8449, "description": "

Send output to a p5.js-sound, Web Audio Node, or use signal to\ncontrol an AudioParam

\n", "itemtype": "method", "name": "connect", @@ -22463,7 +23051,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8136, + "line": 8460, "description": "

Disconnect all output.

\n", "itemtype": "method", "name": "disconnect", @@ -22473,7 +23061,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8254, + "line": 8578, "description": "

The p5.Filter is built with a\n\nWeb Audio BiquadFilter Node.

\n", "itemtype": "property", "name": "biquadFilter", @@ -22484,7 +23072,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8272, + "line": 8596, "description": "

Filter an audio signal according to a set\nof filter parameters.

\n", "itemtype": "method", "name": "process", @@ -22513,7 +23101,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8286, + "line": 8610, "description": "

Set the frequency and the resonance of the filter.

\n", "itemtype": "method", "name": "set", @@ -22543,7 +23131,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8303, + "line": 8627, "description": "

Set the filter frequency, in Hz, from 10 to 22050 (the range of\nhuman hearing, although in reality most people hear in a narrower\nrange).

\n", "itemtype": "method", "name": "freq", @@ -22570,7 +23158,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8328, + "line": 8651, "description": "

Controls either width of a bandpass frequency,\nor the resonance of a low/highpass cutoff frequency.

\n", "itemtype": "method", "name": "res", @@ -22597,7 +23185,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8350, + "line": 8673, "description": "

Controls the gain attribute of a Biquad Filter.\nThis is distinctly different from .amp() which is inherited from p5.Effect\n.amp() controls the volume via the output gain node\np5.Filter.gain() controls the gain parameter of a Biquad Filter node.

\n", "itemtype": "method", "name": "gain", @@ -22618,7 +23206,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8371, + "line": 8694, "description": "

Toggle function. Switches between the specified type and allpass

\n", "itemtype": "method", "name": "toggle", @@ -22632,7 +23220,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8386, + "line": 8709, "description": "

Set the type of a p5.Filter. Possible types include:\n"lowpass" (default), "highpass", "bandpass",\n"lowshelf", "highshelf", "peaking", "notch",\n"allpass".

\n", "itemtype": "method", "name": "setType", @@ -22649,7 +23237,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8593, + "line": 8916, "description": "

The p5.EQ is built with abstracted p5.Filter objects.\nTo modify any bands, use methods of the \np5.Filter API, especially gain and freq.\nBands are stored in an array, with indices 0 - 3, or 0 - 7

\n", "itemtype": "property", "name": "bands", @@ -22660,7 +23248,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8628, + "line": 8951, "description": "

Process an input by connecting it to the EQ

\n", "itemtype": "method", "name": "process", @@ -22677,8 +23265,8 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8716, - "description": "

\nWeb Audio Spatial Panner Node

\n

Properties include

\n\n", + "line": 9039, + "description": "

\nWeb Audio Spatial Panner Node

\n

Properties include

\n\n", "itemtype": "property", "name": "panner", "type": "AudioNode", @@ -22688,7 +23276,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8739, + "line": 9062, "description": "

Connect an audio sorce

\n", "itemtype": "method", "name": "process", @@ -22705,7 +23293,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8748, + "line": 9071, "description": "

Set the X,Y,Z position of the Panner

\n", "itemtype": "method", "name": "set", @@ -22741,7 +23329,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8767, + "line": 9090, "description": "

Getter and setter methods for position coordinates

\n", "itemtype": "method", "name": "positionX", @@ -22755,7 +23343,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8772, + "line": 9095, "description": "

Getter and setter methods for position coordinates

\n", "itemtype": "method", "name": "positionY", @@ -22769,7 +23357,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8777, + "line": 9100, "description": "

Getter and setter methods for position coordinates

\n", "itemtype": "method", "name": "positionZ", @@ -22783,7 +23371,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8815, + "line": 9138, "description": "

Set the X,Y,Z position of the Panner

\n", "itemtype": "method", "name": "orient", @@ -22819,7 +23407,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8834, + "line": 9157, "description": "

Getter and setter methods for orient coordinates

\n", "itemtype": "method", "name": "orientX", @@ -22833,7 +23421,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8839, + "line": 9162, "description": "

Getter and setter methods for orient coordinates

\n", "itemtype": "method", "name": "orientY", @@ -22847,7 +23435,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8844, + "line": 9167, "description": "

Getter and setter methods for orient coordinates

\n", "itemtype": "method", "name": "orientZ", @@ -22861,7 +23449,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8882, + "line": 9205, "description": "

Set the rolloff factor and max distance

\n", "itemtype": "method", "name": "setFalloff", @@ -22885,7 +23473,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8892, + "line": 9215, "description": "

Maxium distance between the source and the listener

\n", "itemtype": "method", "name": "maxDist", @@ -22906,7 +23494,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 8904, + "line": 9227, "description": "

How quickly the volume is reduced as the source moves away from the listener

\n", "itemtype": "method", "name": "rollof", @@ -22927,7 +23515,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9209, + "line": 9532, "description": "

The p5.Delay is built with two\n\nWeb Audio Delay Nodes, one for each stereo channel.

\n", "itemtype": "property", "name": "leftDelay", @@ -22938,7 +23526,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9217, + "line": 9540, "description": "

The p5.Delay is built with two\n\nWeb Audio Delay Nodes, one for each stereo channel.

\n", "itemtype": "property", "name": "rightDelay", @@ -22949,7 +23537,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9249, + "line": 9572, "description": "

Add delay to an audio signal according to a set\nof delay parameters.

\n", "itemtype": "method", "name": "process", @@ -22984,7 +23572,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9284, + "line": 9607, "description": "

Set the delay (echo) time, in seconds. Usually this value will be\na floating point number between 0.0 and 1.0.

\n", "itemtype": "method", "name": "delayTime", @@ -23001,7 +23589,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9303, + "line": 9626, "description": "

Feedback occurs when Delay sends its signal back through its input\nin a loop. The feedback amount determines how much signal to send each\ntime through the loop. A feedback greater than 1.0 is not desirable because\nit will increase the overall output each time through the loop,\ncreating an infinite feedback loop. The default value is 0.5

\n", "itemtype": "method", "name": "feedback", @@ -23022,7 +23610,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9331, + "line": 9654, "description": "

Set a lowpass filter frequency for the delay. A lowpass filter\nwill cut off any frequencies higher than the filter frequency.

\n", "itemtype": "method", "name": "filter", @@ -23044,7 +23632,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9348, + "line": 9671, "description": "

Choose a preset type of delay. 'pingPong' bounces the signal\nfrom the left to the right channel to produce a stereo effect.\nAny other parameter will revert to the default delay setting.

\n", "itemtype": "method", "name": "setType", @@ -23061,7 +23649,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9381, + "line": 9704, "description": "

Set the output level of the delay effect.

\n", "itemtype": "method", "name": "amp", @@ -23090,7 +23678,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9390, + "line": 9713, "description": "

Send output to a p5.sound or web audio object

\n", "itemtype": "method", "name": "connect", @@ -23107,7 +23695,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9396, + "line": 9719, "description": "

Disconnect all output.

\n", "itemtype": "method", "name": "disconnect", @@ -23117,7 +23705,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9475, + "line": 9812, "description": "

Connect a source to the reverb, and assign reverb parameters.

\n", "itemtype": "method", "name": "process", @@ -23152,7 +23740,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9504, + "line": 9841, "description": "

Set the reverb settings. Similar to .process(), but without\nassigning a new input.

\n", "itemtype": "method", "name": "set", @@ -23182,7 +23770,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9532, + "line": 9869, "description": "

Set the output level of the reverb effect.

\n", "itemtype": "method", "name": "amp", @@ -23211,7 +23799,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9541, + "line": 9878, "description": "

Send output to a p5.sound or web audio object

\n", "itemtype": "method", "name": "connect", @@ -23228,7 +23816,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9547, + "line": 9884, "description": "

Disconnect all output.

\n", "itemtype": "method", "name": "disconnect", @@ -23238,10 +23826,10 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9641, + "line": 9975, "description": "

Internally, the p5.Convolver uses the a\n\nWeb Audio Convolver Node.

\n", "itemtype": "property", - "name": "convolverNod", + "name": "convolverNode", "type": "ConvolverNode", "class": "p5.Convolver", "module": "p5.sound", @@ -23249,7 +23837,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9666, + "line": 9998, "description": "

Create a p5.Convolver. Accepts a path to a soundfile\nthat will be used to generate an impulse response.

\n", "itemtype": "method", "name": "createConvolver", @@ -23285,7 +23873,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9790, + "line": 10122, "description": "

Connect a source to the reverb, and assign reverb parameters.

\n", "itemtype": "method", "name": "process", @@ -23305,7 +23893,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9822, + "line": 10154, "description": "

If you load multiple impulse files using the .addImpulse method,\nthey will be stored as Objects in this Array. Toggle between them\nwith the toggleImpulse(id) method.

\n", "itemtype": "property", "name": "impulses", @@ -23316,7 +23904,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9830, + "line": 10162, "description": "

Load and assign a new Impulse Response to the p5.Convolver.\nThe impulse is added to the .impulses array. Previous\nimpulses can be accessed with the .toggleImpulse(id)\nmethod.

\n", "itemtype": "method", "name": "addImpulse", @@ -23343,7 +23931,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9848, + "line": 10180, "description": "

Similar to .addImpulse, except that the .impulses\nArray is reset to save memory. A new .impulses\narray is created with this impulse as the only item.

\n", "itemtype": "method", "name": "resetImpulse", @@ -23370,7 +23958,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9866, + "line": 10198, "description": "

If you have used .addImpulse() to add multiple impulses\nto a p5.Convolver, then you can use this method to toggle between\nthe items in the .impulses Array. Accepts a parameter\nto identify which impulse you wish to use, identified either by its\noriginal filename (String) or by its position in the .impulses\n Array (Number).
\nYou can access the objects in the .impulses Array directly. Each\nObject has two attributes: an .audioBuffer (type:\nWeb Audio \nAudioBuffer) and a .name, a String that corresponds\nwith the original filename.

\n", "itemtype": "method", "name": "toggleImpulse", @@ -23387,21 +23975,21 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 9912, + "line": 10240, "class": "p5.Convolver", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 9937, + "line": 10265, "class": "p5.Convolver", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 10132, + "line": 10460, "description": "

Set the global tempo, in beats per minute, for all\np5.Parts. This method will impact all active p5.Parts.

\n", "itemtype": "method", "name": "setBPM", @@ -23423,7 +24011,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10222, + "line": 10550, "description": "

Array of values to pass into the callback\nat each step of the phrase. Depending on the callback\nfunction's requirements, these values may be numbers,\nstrings, or an object with multiple parameters.\nZero (0) indicates a rest.

\n", "itemtype": "property", "name": "sequence", @@ -23434,7 +24022,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10310, + "line": 10638, "description": "

Set the tempo of this part, in Beats Per Minute.

\n", "itemtype": "method", "name": "setBPM", @@ -23457,8 +24045,8 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10320, - "description": "

Returns the Beats Per Minute of this currently part.

\n", + "line": 10648, + "description": "

Returns the tempo, in Beats Per Minute, of this part.

\n", "itemtype": "method", "name": "getBPM", "return": { @@ -23471,7 +24059,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10329, + "line": 10657, "description": "

Start playback of this part. It will play\nthrough all of its phrases at a speed\ndetermined by setBPM.

\n", "itemtype": "method", "name": "start", @@ -23489,7 +24077,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10345, + "line": 10673, "description": "

Loop playback of this part. It will begin\nlooping through all of its phrases at a speed\ndetermined by setBPM.

\n", "itemtype": "method", "name": "loop", @@ -23507,7 +24095,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10362, + "line": 10690, "description": "

Tell the part to stop looping.

\n", "itemtype": "method", "name": "noLoop", @@ -23517,8 +24105,8 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10374, - "description": "

Stop the part and cue it to step 0.

\n", + "line": 10702, + "description": "

Stop the part and cue it to step 0. Playback will resume from the begining of the Part when it is played again.

\n", "itemtype": "method", "name": "stop", "params": [ @@ -23535,7 +24123,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10384, + "line": 10712, "description": "

Pause the part. Playback will resume\nfrom the current step.

\n", "itemtype": "method", "name": "pause", @@ -23552,7 +24140,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10396, + "line": 10724, "description": "

Add a p5.Phrase to this Part.

\n", "itemtype": "method", "name": "addPhrase", @@ -23569,7 +24157,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10417, + "line": 10745, "description": "

Remove a phrase from this part, based on the name it was\ngiven when it was created.

\n", "itemtype": "method", "name": "removePhrase", @@ -23586,7 +24174,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10431, + "line": 10759, "description": "

Get a phrase from this part, based on the name it was\ngiven when it was created. Now you can modify its array.

\n", "itemtype": "method", "name": "getPhrase", @@ -23603,8 +24191,8 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10445, - "description": "

Get a phrase from this part, based on the name it was\ngiven when it was created. Now you can modify its array.

\n", + "line": 10773, + "description": "

Find all sequences with the specified name, and replace their patterns with the specified array.

\n", "itemtype": "method", "name": "replaceSequence", "params": [ @@ -23625,8 +24213,8 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10473, - "description": "

Fire a callback function at every step.

\n", + "line": 10800, + "description": "

Set the function that will be called at every step. This will clear the previous function.

\n", "itemtype": "method", "name": "onStep", "params": [ @@ -23642,7 +24230,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10526, + "line": 10853, "description": "

Start playback of the score.

\n", "itemtype": "method", "name": "start", @@ -23652,7 +24240,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10535, + "line": 10862, "description": "

Stop playback of the score.

\n", "itemtype": "method", "name": "stop", @@ -23662,7 +24250,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10545, + "line": 10872, "description": "

Pause playback of the score.

\n", "itemtype": "method", "name": "pause", @@ -23672,7 +24260,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10553, + "line": 10880, "description": "

Loop playback of the score.

\n", "itemtype": "method", "name": "loop", @@ -23682,7 +24270,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10562, + "line": 10889, "description": "

Stop looping playback of the score. If it\nis currently playing, this will go into effect\nafter the current round of playback completes.

\n", "itemtype": "method", "name": "noLoop", @@ -23692,7 +24280,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10587, + "line": 10914, "description": "

Set the tempo for all parts in the score

\n", "itemtype": "method", "name": "setBPM", @@ -23714,7 +24302,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10655, + "line": 10982, "description": "

musicalTimeMode uses Tone.Time convention\ntrue if string, false if number

\n", "itemtype": "property", "name": "musicalTimeMode", @@ -23725,7 +24313,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10662, + "line": 10989, "description": "

musicalTimeMode variables\nmodify these only when the interval is specified in musicalTime format as a string

\n", "class": "p5.SoundLoop", "module": "p5.sound", @@ -23733,7 +24321,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10669, + "line": 10996, "description": "

Set a limit to the number of loops to play. defaults to Infinity

\n", "itemtype": "property", "name": "maxIterations", @@ -23744,7 +24332,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10678, + "line": 11005, "description": "

Do not initiate the callback if timeFromNow is < 0\nThis ususually occurs for a few milliseconds when the page\nis not fully loaded

\n

The callback should only be called until maxIterations is reached

\n", "class": "p5.SoundLoop", "module": "p5.sound", @@ -23752,7 +24340,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10692, + "line": 11019, "description": "

Start the loop

\n", "itemtype": "method", "name": "start", @@ -23770,7 +24358,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10705, + "line": 11032, "description": "

Stop the loop

\n", "itemtype": "method", "name": "stop", @@ -23788,7 +24376,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10718, + "line": 11045, "description": "

Pause the loop

\n", "itemtype": "method", "name": "pause", @@ -23806,7 +24394,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10731, + "line": 11058, "description": "

Synchronize loops. Use this method to start two more more loops in synchronization\nor to start a loop in synchronization with a loop that is already playing\nThis method will schedule the implicit loop in sync with the explicit master loop\ni.e. loopToStart.syncedStart(loopToSyncWith)

\n", "itemtype": "method", "name": "syncedStart", @@ -23829,7 +24417,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10812, + "line": 11139, "description": "

Getters and Setters, setting any paramter will result in a change in the clock's\nfrequency, that will be reflected after the next callback\nbeats per minute (defaults to 60)

\n", "itemtype": "property", "name": "bpm", @@ -23840,7 +24428,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10830, + "line": 11157, "description": "

number of quarter notes in a measure (defaults to 4)

\n", "itemtype": "property", "name": "timeSignature", @@ -23851,7 +24439,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10846, + "line": 11173, "description": "

length of the loops interval

\n", "itemtype": "property", "name": "interval", @@ -23862,7 +24450,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10860, + "line": 11187, "description": "

how many times the callback has been called so far

\n", "itemtype": "property", "name": "iterations", @@ -23874,7 +24462,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10901, + "line": 11228, "description": "

The p5.Compressor is built with a Web Audio Dynamics Compressor Node\n

\n", "itemtype": "property", "name": "compressor", @@ -23885,7 +24473,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10912, + "line": 11239, "description": "

Performs the same function as .connect, but also accepts\noptional parameters to set compressor's audioParams

\n", "itemtype": "method", "name": "process", @@ -23932,7 +24520,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10935, + "line": 11262, "description": "

Set the paramters of a compressor.

\n", "itemtype": "method", "name": "set", @@ -23969,7 +24557,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10967, + "line": 11294, "description": "

Get current attack or set value w/ time ramp

\n", "itemtype": "method", "name": "attack", @@ -23993,7 +24581,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 10987, + "line": 11314, "description": "

Get current knee or set value w/ time ramp

\n", "itemtype": "method", "name": "knee", @@ -24017,7 +24605,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11007, + "line": 11334, "description": "

Get current ratio or set value w/ time ramp

\n", "itemtype": "method", "name": "ratio", @@ -24041,7 +24629,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11026, + "line": 11353, "description": "

Get current threshold or set value w/ time ramp

\n", "itemtype": "method", "name": "threshold", @@ -24064,7 +24652,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11045, + "line": 11372, "description": "

Get current release or set value w/ time ramp

\n", "itemtype": "method", "name": "release", @@ -24087,7 +24675,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11065, + "line": 11392, "description": "

Return the current reduction value

\n", "itemtype": "method", "name": "reduction", @@ -24101,7 +24689,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11180, + "line": 11508, "description": "

Connect a specific device to the p5.SoundRecorder.\nIf no parameter is given, p5.SoundRecorer will record\nall audible p5.sound from your sketch.

\n", "itemtype": "method", "name": "setInput", @@ -24119,7 +24707,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11201, + "line": 11529, "description": "

Start recording. To access the recording, provide\na p5.SoundFile as the first parameter. The p5.SoundRecorder\nwill send its recording to that p5.SoundFile for playback once\nrecording is complete. Optional parameters include duration\n(in seconds) of the recording, and a callback function that\nwill be called once the complete recording has been\ntransfered to the p5.SoundFile.

\n", "itemtype": "method", "name": "record", @@ -24148,7 +24736,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11234, + "line": 11562, "description": "

Stop the recording. Once the recording is stopped,\nthe results will be sent to the p5.SoundFile that\nwas given on .record(), and if a callback function\nwas provided on record, that function will be called.

\n", "itemtype": "method", "name": "stop", @@ -24158,8 +24746,8 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11307, - "description": "

Save a p5.SoundFile as a .wav audio file.

\n", + "line": 11635, + "description": "

Save a p5.SoundFile as a .wav file. The browser will prompt the user\nto download the file to their device.\nFor uploading audio to a server, use\np5.SoundFile.saveBlob.

\n", "itemtype": "method", "name": "saveSound", "params": [ @@ -24169,18 +24757,18 @@ module.exports={ "type": "p5.SoundFile" }, { - "name": "name", + "name": "fileName", "description": "

name of the resulting .wav file.

\n", "type": "String" } ], - "class": "p5.SoundRecorder", + "class": "p5", "module": "p5.sound", "submodule": "p5.sound" }, { "file": "lib/addons/p5.sound.js", - "line": 11484, + "line": 11761, "description": "

isDetected is set to true when a peak is detected.

\n", "itemtype": "attribute", "name": "isDetected", @@ -24192,7 +24780,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11497, + "line": 11774, "description": "

The update method is run in the draw loop.

\n

Accepts an FFT object. You must call .analyze()\non the FFT object prior to updating the peakDetect\nbecause it relies on a completed FFT analysis.

\n", "itemtype": "method", "name": "update", @@ -24209,7 +24797,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11528, + "line": 11805, "description": "

onPeak accepts two arguments: a function to call when\na peak is detected. The value of the peak,\nbetween 0.0 and 1.0, is passed to the callback.

\n", "itemtype": "method", "name": "onPeak", @@ -24235,7 +24823,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11677, + "line": 11954, "description": "

Connect a source to the gain node.

\n", "itemtype": "method", "name": "setInput", @@ -24252,7 +24840,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11687, + "line": 11964, "description": "

Send output to a p5.sound or web audio object

\n", "itemtype": "method", "name": "connect", @@ -24269,7 +24857,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11697, + "line": 11974, "description": "

Disconnect all output.

\n", "itemtype": "method", "name": "disconnect", @@ -24279,7 +24867,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11707, + "line": 11984, "description": "

Set the output level of the gain node.

\n", "itemtype": "method", "name": "amp", @@ -24308,7 +24896,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11765, + "line": 12042, "description": "

Connect to p5 objects or Web Audio Nodes

\n", "itemtype": "method", "name": "connect", @@ -24325,7 +24913,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11774, + "line": 12051, "description": "

Disconnect from soundOut

\n", "itemtype": "method", "name": "disconnect", @@ -24335,7 +24923,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11860, + "line": 12131, "description": "

Play tells the MonoSynth to start playing a note. This method schedules\nthe calling of .triggerAttack and .triggerRelease.

\n", "itemtype": "method", "name": "play", @@ -24373,7 +24961,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11908, + "line": 12179, "description": "

Trigger the Attack, and Decay portion of the Envelope.\nSimilar to holding down a key on a piano, but it will\nhold the sustain level until you let go.

\n", "params": [ { @@ -24405,7 +24993,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11942, + "line": 12212, "description": "

Trigger the release of the Envelope. This is similar to releasing\nthe key on a piano and letting the sound fade according to the\nrelease level and release time.

\n", "params": [ { @@ -24425,7 +25013,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11967, + "line": 12236, "description": "

Set values like a traditional\n\nADSR envelope\n.

\n", "itemtype": "method", "name": "setADSR", @@ -24460,7 +25048,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11991, + "line": 12260, "description": "

Getters and Setters

\n", "itemtype": "property", "name": "attack", @@ -24471,7 +25059,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11995, + "line": 12264, "itemtype": "property", "name": "decay", "type": "Number", @@ -24481,7 +25069,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 11998, + "line": 12267, "itemtype": "property", "name": "sustain", "type": "Number", @@ -24491,7 +25079,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 12001, + "line": 12270, "itemtype": "property", "name": "release", "type": "Number", @@ -24501,7 +25089,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 12038, + "line": 12307, "description": "

MonoSynth amp

\n", "itemtype": "method", "name": "amp", @@ -24528,7 +25116,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 12052, + "line": 12321, "description": "

Connect to a p5.sound / Web Audio object.

\n", "itemtype": "method", "name": "connect", @@ -24545,7 +25133,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 12062, + "line": 12331, "description": "

Disconnect all outputs

\n", "itemtype": "method", "name": "disconnect", @@ -24555,7 +25143,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 12072, + "line": 12341, "description": "

Get rid of the MonoSynth and free up its resources / memory.

\n", "itemtype": "method", "name": "dispose", @@ -24565,7 +25153,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 12145, + "line": 12411, "description": "

An object that holds information about which notes have been played and\nwhich notes are currently being played. New notes are added as keys\non the fly. While a note has been attacked, but not released, the value of the\nkey is the audiovoice which is generating that note. When notes are released,\nthe value of the key becomes undefined.

\n", "itemtype": "property", "name": "notes", @@ -24575,7 +25163,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 12157, + "line": 12423, "description": "

A PolySynth must have at least 1 voice, defaults to 8

\n", "itemtype": "property", "name": "polyvalue", @@ -24585,7 +25173,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 12162, + "line": 12428, "description": "

Monosynth that generates the sound for each note that is triggered. The\np5.PolySynth defaults to using the p5.MonoSynth as its voice.

\n", "itemtype": "property", "name": "AudioVoice", @@ -24595,7 +25183,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 12193, + "line": 12459, "description": "

Play a note by triggering noteAttack and noteRelease with sustain time

\n", "itemtype": "method", "name": "play", @@ -24634,7 +25222,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 12239, + "line": 12505, "description": "

noteADSR sets the envelope for a specific note that has just been triggered.\nUsing this method modifies the envelope of whichever audiovoice is being used\nto play the desired note. The envelope should be reset before noteRelease is called\nin order to prevent the modified envelope from being used on other notes.

\n", "itemtype": "method", "name": "noteADSR", @@ -24676,7 +25264,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 12267, + "line": 12533, "description": "

Set the PolySynths global envelope. This method modifies the envelopes of each\nmonosynth so that all notes are played with this envelope.

\n", "itemtype": "method", "name": "setADSR", @@ -24712,7 +25300,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 12291, + "line": 12557, "description": "

Trigger the Attack, and Decay portion of a MonoSynth.\nSimilar to holding down a key on a piano, but it will\nhold the sustain level until you let go.

\n", "itemtype": "method", "name": "noteAttack", @@ -24745,7 +25333,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 12381, + "line": 12647, "description": "

Trigger the Release of an AudioVoice note. This is similar to releasing\nthe key on a piano and letting the sound fade according to the\nrelease level and release time.

\n", "itemtype": "method", "name": "noteRelease", @@ -24772,7 +25360,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 12446, + "line": 12712, "description": "

Connect to a p5.sound / Web Audio object.

\n", "itemtype": "method", "name": "connect", @@ -24789,7 +25377,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 12456, + "line": 12722, "description": "

Disconnect all outputs

\n", "itemtype": "method", "name": "disconnect", @@ -24799,7 +25387,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 12466, + "line": 12732, "description": "

Get rid of the MonoSynth and free up its resources / memory.

\n", "itemtype": "method", "name": "dispose", @@ -24809,7 +25397,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 12534, + "line": 12800, "description": "

The p5.Distortion is built with a\n\nWeb Audio WaveShaper Node.

\n", "itemtype": "property", "name": "WaveShaperNode", @@ -24820,7 +25408,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 12549, + "line": 12815, "description": "

Process a sound source, optionally specify amount and oversample values.

\n", "itemtype": "method", "name": "process", @@ -24846,7 +25434,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 12561, + "line": 12827, "description": "

Set the amount and oversample of the waveshaper distortion.

\n", "itemtype": "method", "name": "set", @@ -24872,7 +25460,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 12579, + "line": 12845, "description": "

Return the distortion amount, typically between 0-1.

\n", "itemtype": "method", "name": "getAmount", @@ -24886,7 +25474,7 @@ module.exports={ }, { "file": "lib/addons/p5.sound.js", - "line": 12589, + "line": 12855, "description": "

Return the oversampling.

\n", "itemtype": "method", "name": "getOversample", @@ -24914,31 +25502,31 @@ module.exports={ }, { "message": "unknown tag: alt", - "line": " src/color/creating_reading.js:121" + "line": " src/color/creating_reading.js:134" }, { "message": "unknown tag: alt", - "line": " src/color/creating_reading.js:319" + "line": " src/color/creating_reading.js:332" }, { "message": "unknown tag: alt", - "line": " src/color/creating_reading.js:350" + "line": " src/color/creating_reading.js:363" }, { "message": "unknown tag: alt", - "line": " src/color/creating_reading.js:387" + "line": " src/color/creating_reading.js:400" }, { "message": "unknown tag: alt", - "line": " src/color/creating_reading.js:484" + "line": " src/color/creating_reading.js:497" }, { "message": "unknown tag: alt", - "line": " src/color/creating_reading.js:514" + "line": " src/color/creating_reading.js:527" }, { "message": "unknown tag: alt", - "line": " src/color/creating_reading.js:554" + "line": " src/color/creating_reading.js:567" }, { "message": "unknown tag: alt", @@ -24946,23 +25534,23 @@ module.exports={ }, { "message": "unknown tag: alt", - "line": " src/color/p5.Color.js:248" + "line": " src/color/p5.Color.js:253" }, { "message": "unknown tag: alt", - "line": " src/color/p5.Color.js:275" + "line": " src/color/p5.Color.js:280" }, { "message": "unknown tag: alt", - "line": " src/color/p5.Color.js:302" + "line": " src/color/p5.Color.js:307" }, { "message": "unknown tag: alt", - "line": " src/color/p5.Color.js:329" + "line": " src/color/p5.Color.js:334" }, { "message": "unknown tag: alt", - "line": " src/color/p5.Color.js:763" + "line": " src/color/p5.Color.js:768" }, { "message": "unknown tag: alt", @@ -24970,55 +25558,63 @@ module.exports={ }, { "message": "unknown tag: alt", - "line": " src/color/setting.js:185" + "line": " src/color/setting.js:181" }, { "message": "unknown tag: alt", - "line": " src/color/setting.js:223" + "line": " src/color/setting.js:220" }, { "message": "unknown tag: alt", - "line": " src/color/setting.js:344" + "line": " src/color/setting.js:341" }, { "message": "unknown tag: alt", - "line": " src/color/setting.js:501" + "line": " src/color/setting.js:498" }, { "message": "unknown tag: alt", - "line": " src/color/setting.js:542" + "line": " src/color/setting.js:539" }, { "message": "unknown tag: alt", - "line": " src/color/setting.js:582" + "line": " src/color/setting.js:579" }, { "message": "unknown tag: alt", - "line": " src/core/shape/2d_primitives.js:16" + "line": " src/core/shape/2d_primitives.js:102" + }, + { + "message": "unknown tag: alt", + "line": " src/core/shape/2d_primitives.js:210" + }, + { + "message": "unknown tag: alt", + "line": " src/core/shape/2d_primitives.js:270" }, { "message": "unknown tag: alt", - "line": " src/core/shape/2d_primitives.js:149" + "line": " src/core/shape/2d_primitives.js:300" }, { "message": "unknown tag: alt", - "line": " src/core/shape/2d_primitives.js:208" + "line": " src/core/shape/2d_primitives.js:356" }, { "message": "unknown tag: alt", - "line": " src/core/shape/2d_primitives.js:264" + "line": " src/core/shape/2d_primitives.js:391" }, { "message": "unknown tag: alt", - "line": " src/core/shape/2d_primitives.js:299" + "line": " src/core/shape/2d_primitives.js:458" }, { "message": "unknown tag: alt", - "line": " src/core/shape/2d_primitives.js:353" + "line": " src/core/shape/2d_primitives.js:541" }, { "message": "unknown tag: alt", - "line": " src/core/shape/2d_primitives.js:436" + "line": " src/core/shape/2d_primitives.js:595" }, { "message": "unknown tag: alt", @@ -25030,23 +25626,23 @@ module.exports={ }, { "message": "unknown tag: alt", - "line": " src/core/shape/attributes.js:113" + "line": " src/core/shape/attributes.js:116" }, { "message": "unknown tag: alt", - "line": " src/core/shape/attributes.js:182" + "line": " src/core/shape/attributes.js:185" }, { "message": "unknown tag: alt", - "line": " src/core/shape/attributes.js:213" + "line": " src/core/shape/attributes.js:219" }, { "message": "unknown tag: alt", - "line": " src/core/shape/attributes.js:250" + "line": " src/core/shape/attributes.js:256" }, { "message": "unknown tag: alt", - "line": " src/core/shape/attributes.js:317" + "line": " src/core/shape/attributes.js:323" }, { "message": "unknown tag: alt", @@ -25094,47 +25690,51 @@ module.exports={ }, { "message": "unknown tag: alt", - "line": " src/core/shape/vertex.js:317" + "line": " src/core/shape/vertex.js:270" + }, + { + "message": "unknown tag: alt", + "line": " src/core/shape/vertex.js:270" }, { "message": "unknown tag: alt", - "line": " src/core/shape/vertex.js:390" + "line": " src/core/shape/vertex.js:398" }, { "message": "unknown tag: alt", - "line": " src/core/shape/vertex.js:435" + "line": " src/core/shape/vertex.js:443" }, { "message": "unknown tag: alt", - "line": " src/core/shape/vertex.js:500" + "line": " src/core/shape/vertex.js:508" }, { "message": "unknown tag: alt", - "line": " src/core/shape/vertex.js:560" + "line": " src/core/shape/vertex.js:568" }, { "message": "unknown tag: alt", - "line": " src/core/shape/vertex.js:646" + "line": " src/core/shape/vertex.js:654" }, { "message": "unknown tag: alt", - "line": " src/core/shape/vertex.js:709" + "line": " src/core/shape/vertex.js:720" }, { "message": "unknown tag: alt", - "line": " src/core/shape/vertex.js:800" + "line": " src/core/shape/vertex.js:813" }, { "message": "unknown tag: alt", - "line": " src/core/shape/vertex.js:800" + "line": " src/core/shape/vertex.js:813" }, { "message": "unknown tag: alt", - "line": " src/core/shape/vertex.js:800" + "line": " src/core/shape/vertex.js:813" }, { "message": "unknown tag: alt", - "line": " src/core/shape/vertex.js:800" + "line": " src/core/shape/vertex.js:813" }, { "message": "unknown tag: alt", @@ -25162,75 +25762,75 @@ module.exports={ }, { "message": "unknown tag: alt", - "line": " src/core/environment.js:49" + "line": " src/core/environment.js:53" }, { "message": "unknown tag: alt", - "line": " src/core/environment.js:76" + "line": " src/core/environment.js:80" }, { "message": "unknown tag: alt", - "line": " src/core/environment.js:108" + "line": " src/core/environment.js:112" }, { "message": "unknown tag: alt", - "line": " src/core/environment.js:167" + "line": " src/core/environment.js:181" }, { "message": "unknown tag: alt", - "line": " src/core/environment.js:268" + "line": " src/core/environment.js:281" }, { "message": "unknown tag: alt", - "line": " src/core/environment.js:293" + "line": " src/core/environment.js:306" }, { "message": "unknown tag: alt", - "line": " src/core/environment.js:312" + "line": " src/core/environment.js:325" }, { "message": "unknown tag: alt", - "line": " src/core/environment.js:331" + "line": " src/core/environment.js:344" }, { "message": "unknown tag: alt", - "line": " src/core/environment.js:347" + "line": " src/core/environment.js:360" }, { "message": "unknown tag: alt", - "line": " src/core/environment.js:363" + "line": " src/core/environment.js:376" }, { "message": "unknown tag: alt", - "line": " src/core/environment.js:441" + "line": " src/core/environment.js:454" }, { "message": "unknown tag: alt", - "line": " src/core/environment.js:492" + "line": " src/core/environment.js:505" }, { "message": "replacing incorrect tag: returns with return", - "line": " src/core/environment.js:527" + "line": " src/core/environment.js:540" }, { "message": "replacing incorrect tag: returns with return", - "line": " src/core/environment.js:547" + "line": " src/core/environment.js:560" }, { "message": "unknown tag: alt", - "line": " src/core/environment.js:547" + "line": " src/core/environment.js:560" }, { "message": "unknown tag: alt", - "line": " src/core/environment.js:604" + "line": " src/core/environment.js:617" }, { "message": "unknown tag: alt", - "line": " src/core/environment.js:635" + "line": " src/core/environment.js:648" }, { "message": "unknown tag: alt", - "line": " src/core/environment.js:658" + "line": " src/core/environment.js:671" }, { "message": "unknown tag: alt", @@ -25246,87 +25846,79 @@ module.exports={ }, { "message": "unknown tag: alt", - "line": " src/core/main.js:408" - }, - { - "message": "unknown tag: alt", - "line": " src/core/p5.Element.js:51" - }, - { - "message": "unknown tag: alt", - "line": " src/core/p5.Element.js:116" + "line": " src/core/main.js:401" }, { "message": "unknown tag: alt", - "line": " src/core/p5.Element.js:153" + "line": " src/core/p5.Element.js:52" }, { "message": "unknown tag: alt", - "line": " src/core/p5.Element.js:188" + "line": " src/core/p5.Element.js:122" }, { "message": "unknown tag: alt", - "line": " src/core/p5.Element.js:249" + "line": " src/core/p5.Element.js:162" }, { "message": "unknown tag: alt", - "line": " src/core/p5.Element.js:298" + "line": " src/core/p5.Element.js:197" }, { "message": "unknown tag: alt", - "line": " src/core/p5.Element.js:364" + "line": " src/core/p5.Element.js:258" }, { "message": "unknown tag: alt", - "line": " src/core/p5.Element.js:418" + "line": " src/core/p5.Element.js:307" }, { "message": "unknown tag: alt", - "line": " src/core/p5.Element.js:474" + "line": " src/core/p5.Element.js:373" }, { "message": "unknown tag: alt", - "line": " src/core/p5.Element.js:532" + "line": " src/core/p5.Element.js:427" }, { "message": "unknown tag: alt", - "line": " src/core/p5.Element.js:575" + "line": " src/core/p5.Element.js:483" }, { "message": "unknown tag: alt", - "line": " src/core/p5.Element.js:642" + "line": " src/core/p5.Element.js:541" }, { "message": "unknown tag: alt", - "line": " src/core/p5.Element.js:677" + "line": " src/core/p5.Element.js:584" }, { "message": "unknown tag: alt", - "line": " src/core/p5.Element.js:719" + "line": " src/core/p5.Element.js:626" }, { "message": "unknown tag: alt", - "line": " src/core/p5.Element.js:767" + "line": " src/core/p5.Element.js:674" }, { "message": "unknown tag: alt", - "line": " src/core/p5.Element.js:807" + "line": " src/core/p5.Element.js:714" }, { "message": "unknown tag: alt", - "line": " src/core/p5.Element.js:856" + "line": " src/core/p5.Element.js:763" }, { "message": "unknown tag: alt", - "line": " src/core/p5.Element.js:894" + "line": " src/core/p5.Element.js:801" }, { "message": "unknown tag: alt", - "line": " src/core/p5.Element.js:932" + "line": " src/core/p5.Graphics.js:65" }, { "message": "unknown tag: alt", - "line": " src/core/p5.Graphics.js:65" + "line": " src/core/p5.Graphics.js:117" }, { "message": "unknown tag: alt", @@ -25358,15 +25950,15 @@ module.exports={ }, { "message": "unknown tag: alt", - "line": " src/core/structure.js:116" + "line": " src/core/structure.js:122" }, { "message": "unknown tag: alt", - "line": " src/core/structure.js:181" + "line": " src/core/structure.js:191" }, { "message": "unknown tag: alt", - "line": " src/core/structure.js:247" + "line": " src/core/structure.js:261" }, { "message": "unknown tag: alt", @@ -25374,111 +25966,127 @@ module.exports={ }, { "message": "unknown tag: alt", - "line": " src/core/transform.js:135" + "line": " src/core/transform.js:150" }, { "message": "unknown tag: alt", - "line": " src/core/transform.js:161" + "line": " src/core/transform.js:176" }, { "message": "unknown tag: alt", - "line": " src/core/transform.js:201" + "line": " src/core/transform.js:216" }, { "message": "unknown tag: alt", - "line": " src/core/transform.js:231" + "line": " src/core/transform.js:246" }, { "message": "unknown tag: alt", - "line": " src/core/transform.js:261" + "line": " src/core/transform.js:276" }, { "message": "unknown tag: alt", - "line": " src/core/transform.js:291" + "line": " src/core/transform.js:306" }, { "message": "unknown tag: alt", - "line": " src/core/transform.js:366" + "line": " src/core/transform.js:381" }, { "message": "unknown tag: alt", - "line": " src/core/transform.js:405" + "line": " src/core/transform.js:421" }, { "message": "unknown tag: alt", - "line": " src/core/transform.js:444" + "line": " src/core/transform.js:461" }, { "message": "unknown tag: alt", - "line": " src/events/acceleration.js:91" + "line": " src/events/acceleration.js:23" }, { "message": "unknown tag: alt", - "line": " src/events/acceleration.js:125" + "line": " src/events/acceleration.js:46" }, { "message": "unknown tag: alt", - "line": " src/events/acceleration.js:158" + "line": " src/events/acceleration.js:69" }, { "message": "unknown tag: alt", - "line": " src/events/acceleration.js:194" + "line": " src/events/acceleration.js:135" }, { "message": "unknown tag: alt", - "line": " src/events/acceleration.js:239" + "line": " src/events/acceleration.js:166" }, { "message": "unknown tag: alt", - "line": " src/events/acceleration.js:283" + "line": " src/events/acceleration.js:197" }, { "message": "unknown tag: alt", - "line": " src/events/acceleration.js:350" + "line": " src/events/acceleration.js:233" }, { "message": "unknown tag: alt", - "line": " src/events/acceleration.js:393" + "line": " src/events/acceleration.js:278" }, { "message": "unknown tag: alt", - "line": " src/events/acceleration.js:437" + "line": " src/events/acceleration.js:322" }, { "message": "unknown tag: alt", - "line": " src/events/acceleration.js:468" + "line": " src/events/acceleration.js:380" }, { "message": "unknown tag: alt", - "line": " src/events/acceleration.js:527" + "line": " src/events/acceleration.js:419" }, { "message": "unknown tag: alt", - "line": " src/events/keyboard.js:18" + "line": " src/events/acceleration.js:462" }, { "message": "unknown tag: alt", - "line": " src/events/keyboard.js:45" + "line": " src/events/acceleration.js:506" }, { "message": "unknown tag: alt", - "line": " src/events/keyboard.js:74" + "line": " src/events/acceleration.js:538" }, { "message": "unknown tag: alt", - "line": " src/events/keyboard.js:107" + "line": " src/events/acceleration.js:597" }, { "message": "unknown tag: alt", - "line": " src/events/keyboard.js:194" + "line": " src/events/keyboard.js:12" }, { "message": "unknown tag: alt", - "line": " src/events/keyboard.js:246" + "line": " src/events/keyboard.js:39" }, { "message": "unknown tag: alt", - "line": " src/events/keyboard.js:310" + "line": " src/events/keyboard.js:68" + }, + { + "message": "unknown tag: alt", + "line": " src/events/keyboard.js:109" + }, + { + "message": "unknown tag: alt", + "line": " src/events/keyboard.js:196" + }, + { + "message": "unknown tag: alt", + "line": " src/events/keyboard.js:248" + }, + { + "message": "unknown tag: alt", + "line": " src/events/keyboard.js:312" }, { "message": "unknown tag: alt", @@ -25502,51 +26110,51 @@ module.exports={ }, { "message": "unknown tag: alt", - "line": " src/events/mouse.js:174" + "line": " src/events/mouse.js:176" }, { "message": "unknown tag: alt", - "line": " src/events/mouse.js:211" + "line": " src/events/mouse.js:215" }, { "message": "unknown tag: alt", - "line": " src/events/mouse.js:252" + "line": " src/events/mouse.js:256" }, { "message": "unknown tag: alt", - "line": " src/events/mouse.js:294" + "line": " src/events/mouse.js:298" }, { "message": "unknown tag: alt", - "line": " src/events/mouse.js:333" + "line": " src/events/mouse.js:337" }, { "message": "unknown tag: alt", - "line": " src/events/mouse.js:424" + "line": " src/events/mouse.js:428" }, { "message": "unknown tag: alt", - "line": " src/events/mouse.js:468" + "line": " src/events/mouse.js:483" }, { "message": "unknown tag: alt", - "line": " src/events/mouse.js:538" + "line": " src/events/mouse.js:564" }, { "message": "unknown tag: alt", - "line": " src/events/mouse.js:604" + "line": " src/events/mouse.js:641" }, { "message": "unknown tag: alt", - "line": " src/events/mouse.js:671" + "line": " src/events/mouse.js:719" }, { "message": "unknown tag: alt", - "line": " src/events/mouse.js:730" + "line": " src/events/mouse.js:789" }, { "message": "unknown tag: alt", - "line": " src/events/mouse.js:804" + "line": " src/events/mouse.js:874" }, { "message": "unknown tag: alt", @@ -25558,11 +26166,11 @@ module.exports={ }, { "message": "unknown tag: alt", - "line": " src/events/touch.js:138" + "line": " src/events/touch.js:149" }, { "message": "unknown tag: alt", - "line": " src/events/touch.js:200" + "line": " src/events/touch.js:222" }, { "message": "unknown tag: alt", @@ -25582,23 +26190,23 @@ module.exports={ }, { "message": "replacing incorrect tag: returns with return", - "line": " src/image/loading_displaying.js:108" + "line": " src/image/loading_displaying.js:110" }, { "message": "unknown tag: alt", - "line": " src/image/loading_displaying.js:125" + "line": " src/image/loading_displaying.js:127" }, { "message": "unknown tag: alt", - "line": " src/image/loading_displaying.js:296" + "line": " src/image/loading_displaying.js:298" }, { "message": "unknown tag: alt", - "line": " src/image/loading_displaying.js:396" + "line": " src/image/loading_displaying.js:398" }, { "message": "unknown tag: alt", - "line": " src/image/loading_displaying.js:462" + "line": " src/image/loading_displaying.js:464" }, { "message": "unknown tag: alt", @@ -25610,47 +26218,47 @@ module.exports={ }, { "message": "unknown tag: alt", - "line": " src/image/p5.Image.js:152" + "line": " src/image/p5.Image.js:153" }, { "message": "unknown tag: alt", - "line": " src/image/p5.Image.js:231" + "line": " src/image/p5.Image.js:232" }, { "message": "unknown tag: alt", - "line": " src/image/p5.Image.js:267" + "line": " src/image/p5.Image.js:268" }, { "message": "unknown tag: alt", - "line": " src/image/p5.Image.js:315" + "line": " src/image/p5.Image.js:316" }, { "message": "unknown tag: alt", - "line": " src/image/p5.Image.js:360" + "line": " src/image/p5.Image.js:371" }, { "message": "unknown tag: alt", - "line": " src/image/p5.Image.js:398" + "line": " src/image/p5.Image.js:409" }, { "message": "unknown tag: alt", - "line": " src/image/p5.Image.js:483" + "line": " src/image/p5.Image.js:494" }, { "message": "unknown tag: alt", - "line": " src/image/p5.Image.js:564" + "line": " src/image/p5.Image.js:575" }, { "message": "unknown tag: alt", - "line": " src/image/p5.Image.js:627" + "line": " src/image/p5.Image.js:638" }, { "message": "unknown tag: alt", - "line": " src/image/p5.Image.js:663" + "line": " src/image/p5.Image.js:674" }, { "message": "unknown tag: alt", - "line": " src/image/p5.Image.js:785" + "line": " src/image/p5.Image.js:796" }, { "message": "unknown tag: alt", @@ -25674,15 +26282,15 @@ module.exports={ }, { "message": "unknown tag: alt", - "line": " src/image/pixels.js:494" + "line": " src/image/pixels.js:506" }, { "message": "unknown tag: alt", - "line": " src/image/pixels.js:531" + "line": " src/image/pixels.js:543" }, { "message": "unknown tag: alt", - "line": " src/image/pixels.js:605" + "line": " src/image/pixels.js:617" }, { "message": "unknown tag: alt", @@ -25698,27 +26306,27 @@ module.exports={ }, { "message": "unknown tag: alt", - "line": " src/io/files.js:626" + "line": " src/io/files.js:603" }, { "message": "replacing incorrect tag: returns with return", - "line": " src/io/files.js:737" + "line": " src/io/files.js:714" }, { "message": "unknown tag: alt", - "line": " src/io/files.js:737" + "line": " src/io/files.js:714" }, { "message": "unknown tag: alt", - "line": " src/io/files.js:1530" + "line": " src/io/files.js:1519" }, { "message": "unknown tag: alt", - "line": " src/io/files.js:1582" + "line": " src/io/files.js:1577" }, { "message": "unknown tag: alt", - "line": " src/io/files.js:1644" + "line": " src/io/files.js:1645" }, { "message": "unknown tag: alt", @@ -25850,43 +26458,43 @@ module.exports={ }, { "message": "unknown tag: alt", - "line": " src/math/calculation.js:324" + "line": " src/math/calculation.js:327" }, { "message": "unknown tag: alt", - "line": " src/math/calculation.js:379" + "line": " src/math/calculation.js:383" }, { "message": "unknown tag: alt", - "line": " src/math/calculation.js:418" + "line": " src/math/calculation.js:422" }, { "message": "unknown tag: alt", - "line": " src/math/calculation.js:474" + "line": " src/math/calculation.js:478" }, { "message": "unknown tag: alt", - "line": " src/math/calculation.js:524" + "line": " src/math/calculation.js:528" }, { "message": "unknown tag: alt", - "line": " src/math/calculation.js:574" + "line": " src/math/calculation.js:578" }, { "message": "unknown tag: alt", - "line": " src/math/calculation.js:627" + "line": " src/math/calculation.js:631" }, { "message": "unknown tag: alt", - "line": " src/math/calculation.js:661" + "line": " src/math/calculation.js:665" }, { "message": "unknown tag: alt", - "line": " src/math/calculation.js:700" + "line": " src/math/calculation.js:704" }, { "message": "unknown tag: alt", - "line": " src/math/calculation.js:747" + "line": " src/math/calculation.js:751" }, { "message": "unknown tag: alt", @@ -25970,7 +26578,7 @@ module.exports={ }, { "message": "unknown tag: alt", - "line": " src/typography/attributes.js:189" + "line": " src/typography/attributes.js:191" }, { "message": "unknown tag: alt", @@ -25986,7 +26594,7 @@ module.exports={ }, { "message": "unknown tag: alt", - "line": " src/typography/p5.Font.js:43" + "line": " src/typography/p5.Font.js:32" }, { "message": "unknown tag: alt", @@ -26006,23 +26614,23 @@ module.exports={ }, { "message": "unknown tag: alt", - "line": " src/utilities/string_functions.js:237" + "line": " src/utilities/string_functions.js:243" }, { "message": "unknown tag: alt", - "line": " src/utilities/string_functions.js:313" + "line": " src/utilities/string_functions.js:319" }, { "message": "unknown tag: alt", - "line": " src/utilities/string_functions.js:375" + "line": " src/utilities/string_functions.js:381" }, { "message": "unknown tag: alt", - "line": " src/utilities/string_functions.js:437" + "line": " src/utilities/string_functions.js:459" }, { "message": "unknown tag: alt", - "line": " src/utilities/string_functions.js:526" + "line": " src/utilities/string_functions.js:548" }, { "message": "unknown tag: alt", @@ -26054,7 +26662,7 @@ module.exports={ }, { "message": "unknown tag: alt", - "line": " src/webgl/3d_primitives.js:15" + "line": " src/webgl/3d_primitives.js:14" }, { "message": "unknown tag: alt", @@ -26090,11 +26698,15 @@ module.exports={ }, { "message": "unknown tag: alt", - "line": " src/webgl/light.js:101" + "line": " src/webgl/light.js:87" + }, + { + "message": "unknown tag: alt", + "line": " src/webgl/light.js:185" }, { "message": "unknown tag: alt", - "line": " src/webgl/light.js:212" + "line": " src/webgl/light.js:287" }, { "message": "unknown tag: alt", @@ -26114,27 +26726,43 @@ module.exports={ }, { "message": "replacing incorrect tag: returns with return", - "line": " src/webgl/material.js:83" + "line": " src/webgl/material.js:113" }, { "message": "unknown tag: alt", - "line": " src/webgl/material.js:83" + "line": " src/webgl/material.js:113" }, { "message": "unknown tag: alt", - "line": " src/webgl/material.js:176" + "line": " src/webgl/material.js:225" }, { "message": "unknown tag: alt", - "line": " src/webgl/material.js:211" + "line": " src/webgl/material.js:262" }, { "message": "unknown tag: alt", - "line": " src/webgl/material.js:301" + "line": " src/webgl/material.js:359" }, { "message": "unknown tag: alt", - "line": " src/webgl/material.js:350" + "line": " src/webgl/material.js:359" + }, + { + "message": "unknown tag: alt", + "line": " src/webgl/material.js:438" + }, + { + "message": "unknown tag: alt", + "line": " src/webgl/material.js:513" + }, + { + "message": "unknown tag: alt", + "line": " src/webgl/material.js:563" + }, + { + "message": "unknown tag: alt", + "line": " src/webgl/material.js:614" }, { "message": "unknown tag: alt", @@ -26154,43 +26782,43 @@ module.exports={ }, { "message": "unknown tag: alt", - "line": " src/webgl/p5.Camera.js:487" + "line": " src/webgl/p5.Camera.js:486" }, { "message": "unknown tag: alt", - "line": " src/webgl/p5.Camera.js:546" + "line": " src/webgl/p5.Camera.js:545" }, { "message": "unknown tag: alt", - "line": " src/webgl/p5.Camera.js:604" + "line": " src/webgl/p5.Camera.js:603" }, { "message": "unknown tag: alt", - "line": " src/webgl/p5.Camera.js:752" + "line": " src/webgl/p5.Camera.js:751" }, { "message": "unknown tag: alt", - "line": " src/webgl/p5.Camera.js:824" + "line": " src/webgl/p5.Camera.js:823" }, { "message": "unknown tag: alt", - "line": " src/webgl/p5.Camera.js:1089" + "line": " src/webgl/p5.Camera.js:1088" }, { "message": "unknown tag: alt", - "line": " src/webgl/p5.RendererGL.js:215" + "line": " src/webgl/p5.RendererGL.js:228" }, { "message": "unknown tag: alt", - "line": " src/webgl/p5.RendererGL.js:427" + "line": " src/webgl/p5.RendererGL.js:474" }, { "message": "unknown tag: alt", - "line": " src/webgl/p5.RendererGL.js:474" + "line": " src/webgl/p5.RendererGL.js:516" }, { "message": "unknown tag: alt", - "line": " src/webgl/p5.RendererGL.js:515" + "line": " src/webgl/p5.RendererGL.js:586" }, { "message": "replacing incorrect tag: function with method", @@ -26236,37 +26864,57 @@ module.exports={ "message": "replacing incorrect tag: function with method", "line": " src/webgl/text.js:547" }, + { + "message": "unknown tag: alt", + "line": " lib/addons/p5.dom.js:245" + }, + { + "message": "unknown tag: alt", + "line": " lib/addons/p5.dom.js:313" + }, + { + "message": "replacing incorrect tag: returns with return", + "line": " lib/addons/p5.dom.js:1463" + }, { "message": "replacing incorrect tag: returns with return", - "line": " lib/addons/p5.dom.js:1368" + "line": " lib/addons/p5.dom.js:1525" }, { "message": "replacing incorrect tag: returns with return", - "line": " lib/addons/p5.dom.js:1470" + "line": " lib/addons/p5.dom.js:1629" }, { "message": "replacing incorrect tag: returns with return", - "line": " lib/addons/p5.dom.js:1509" + "line": " lib/addons/p5.dom.js:1668" }, { "message": "replacing incorrect tag: returns with return", - "line": " lib/addons/p5.dom.js:1603" + "line": " lib/addons/p5.dom.js:1762" + }, + { + "message": "unknown tag: alt", + "line": " lib/addons/p5.dom.js:2119" }, { "message": "replacing incorrect tag: params with param", - "line": " lib/addons/p5.sound.js:1642" + "line": " lib/addons/p5.sound.js:2480" }, { "message": "replacing incorrect tag: returns with return", - "line": " lib/addons/p5.sound.js:1642" + "line": " lib/addons/p5.sound.js:2480" }, { "message": "replacing incorrect tag: returns with return", - "line": " lib/addons/p5.sound.js:7335" + "line": " lib/addons/p5.sound.js:3094" }, { "message": "replacing incorrect tag: returns with return", - "line": " lib/addons/p5.sound.js:9303" + "line": " lib/addons/p5.sound.js:7659" + }, + { + "message": "replacing incorrect tag: returns with return", + "line": " lib/addons/p5.sound.js:9626" }, { "message": "Missing item type\nConversions adapted from .\n\nIn these functions, hue is always in the range [0, 1], just like all other\ncomponents are in the range [0, 1]. 'Brightness' and 'value' are used\ninterchangeably.", @@ -26298,55 +26946,55 @@ module.exports={ }, { "message": "Missing item type\nHue is the same in HSB and HSL, but the maximum value may be different.\nThis function will return the HSB-normalized saturation when supplied with\nan HSB color object, but will default to the HSL-normalized saturation\notherwise.", - "line": " src/color/p5.Color.js:410" + "line": " src/color/p5.Color.js:415" }, { "message": "Missing item type\nSaturation is scaled differently in HSB and HSL. This function will return\nthe HSB saturation when supplied with an HSB color object, but will default\nto the HSL saturation otherwise.", - "line": " src/color/p5.Color.js:441" + "line": " src/color/p5.Color.js:446" }, { "message": "Missing item type\nCSS named colors.", - "line": " src/color/p5.Color.js:460" + "line": " src/color/p5.Color.js:465" }, { "message": "Missing item type\nThese regular expressions are used to build up the patterns for matching\nviable CSS color strings: fragmenting the regexes in this way increases the\nlegibility and comprehensibility of the code.\n\nNote that RGB values of .9 are not parsed by IE, but are supported here for\ncolor string consistency.", - "line": " src/color/p5.Color.js:613" + "line": " src/color/p5.Color.js:618" }, { "message": "Missing item type\nFull color string patterns. The capture groups are necessary.", - "line": " src/color/p5.Color.js:626" + "line": " src/color/p5.Color.js:631" }, { "message": "Missing item type\nFor a number of different inputs, returns a color formatted as [r, g, b, a]\narrays, with each component normalized between 0 and 1.", - "line": " src/color/p5.Color.js:763" + "line": " src/color/p5.Color.js:768" }, { "message": "Missing item type\nFor HSB and HSL, interpret the gray level as a brightness/lightness\nvalue (they are equivalent when chroma is zero). For RGB, normalize the\ngray level according to the blue maximum.", - "line": " src/color/p5.Color.js:989" + "line": " src/color/p5.Color.js:994" + }, + { + "message": "Missing item type\nThis function does 3 things:\n\n 1. Bounds the desired start/stop angles for an arc (in radians) so that:\n\n 0 <= start < TWO_PI ; start <= stop < start + TWO_PI\n\n This means that the arc rendering functions don't have to be concerned\n with what happens if stop is smaller than start, or if the arc 'goes\n round more than once', etc.: they can just start at start and increase\n until stop and the correct arc will be drawn.\n\n 2. Optionally adjusts the angles within each quadrant to counter the naive\n scaling of the underlying ellipse up from the unit circle. Without\n this, the angles become arbitrary when width != height: 45 degrees\n might be drawn at 5 degrees on a 'wide' ellipse, or at 85 degrees on\n a 'tall' ellipse.\n\n 3. Flags up when start and stop correspond to the same place on the\n underlying ellipse. This is useful if you want to do something special\n there (like rendering a whole ellipse instead).", + "line": " src/core/shape/2d_primitives.js:16" }, { "message": "Missing item type\nReturns the current framerate.", - "line": " src/core/environment.js:242" + "line": " src/core/environment.js:255" }, { "message": "Missing item type\nSpecifies the number of frames to be displayed every second. For example,\nthe function call frameRate(30) will attempt to refresh 30 times a second.\nIf the processor is not fast enough to maintain the specified rate, the\nframe rate will not be achieved. Setting the frame rate within setup() is\nrecommended. The default rate is 60 frames per second.\n\nCalling frameRate() with no arguments returns the current framerate.", - "line": " src/core/environment.js:252" + "line": " src/core/environment.js:265" }, { "message": "Missing item type", "line": " src/core/error_helpers.js:1" }, - { - "message": "Missing item type\nPrints out a fancy, colorful message to the console log", - "line": " src/core/error_helpers.js:65" - }, { "message": "Missing item type\nValidates parameters\nparam {String} func the name of the function\nparam {Array} args user input arguments\n\nexample:\n var a;\n ellipse(10,10,a,5);\nconsole ouput:\n \"It looks like ellipse received an empty variable in spot #2.\"\n\nexample:\n ellipse(10,\"foo\",5,5);\nconsole output:\n \"ellipse was expecting a number for parameter #1,\n received \"foo\" instead.\"", - "line": " src/core/error_helpers.js:563" + "line": " src/core/error_helpers.js:584" }, { "message": "Missing item type\nPrints out all the colors in the color pallete with white text.\nFor color blindness testing.", - "line": " src/core/error_helpers.js:624" + "line": " src/core/error_helpers.js:645" }, { "message": "Missing item type", @@ -26362,19 +27010,19 @@ module.exports={ }, { "message": "Missing item type\nHelper fxn for sharing pixel methods", - "line": " src/core/p5.Element.js:1088" + "line": " src/core/p5.Element.js:865" }, { "message": "Missing item type\nResize our canvas element.", - "line": " src/core/p5.Renderer.js:96" + "line": " src/core/p5.Renderer.js:97" }, { "message": "Missing item type\nHelper fxn to check font type (system or otf)", - "line": " src/core/p5.Renderer.js:300" + "line": " src/core/p5.Renderer.js:335" }, { "message": "Missing item type\nHelper fxn to measure ascent and descent.\nAdapted from http://stackoverflow.com/a/25355178", - "line": " src/core/p5.Renderer.js:353" + "line": " src/core/p5.Renderer.js:388" }, { "message": "Missing item type\np5.Renderer2D\nThe 2D graphics canvas renderer class.\nextends p5.Renderer", @@ -26382,7 +27030,7 @@ module.exports={ }, { "message": "Missing item type\nGenerate a cubic Bezier representing an arc on the unit circle of total\nangle `size` radians, beginning `start` radians above the x-axis. Up to\nfour of these curves are combined to make a full arc.\n\nSee www.joecridge.me/bezier.pdf for an explanation of the method.", - "line": " src/core/p5.Renderer2D.js:414" + "line": " src/core/p5.Renderer2D.js:405" }, { "message": "Missing item type\nshim for Uint8ClampedArray.slice\n(allows arrayCopy to work with pixels[])\nwith thanks to http://halfpapstudios.com/blog/tag/html5-canvas/\nEnumerable set to false to protect for...in from\nUint8ClampedArray.prototype pollution.", @@ -26398,35 +27046,31 @@ module.exports={ }, { "message": "Missing item type\nprivate helper function to ensure that the user passed in valid\nvalues for the Dictionary type", - "line": " src/data/p5.TypedDict.js:382" + "line": " src/data/p5.TypedDict.js:394" }, { "message": "Missing item type\nprivate helper function to ensure that the user passed in valid\nvalues for the Dictionary type", - "line": " src/data/p5.TypedDict.js:425" + "line": " src/data/p5.TypedDict.js:437" }, { "message": "Missing item type\nprivate helper function for finding lowest or highest value\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than'", - "line": " src/data/p5.TypedDict.js:542" + "line": " src/data/p5.TypedDict.js:554" }, { "message": "Missing item type\nprivate helper function for finding lowest or highest key\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than'", - "line": " src/data/p5.TypedDict.js:609" + "line": " src/data/p5.TypedDict.js:621" }, { "message": "Missing item type\n_updatePAccelerations updates the pAcceleration values", - "line": " src/events/acceleration.js:80" - }, - { - "message": "Missing item type\nHolds the key codes of currently pressed keys.", - "line": " src/events/keyboard.js:12" + "line": " src/events/acceleration.js:124" }, { "message": "Missing item type\nThe onblur function is called when the user is no longer focused\non the p5 element. Because the keyup events will not fire if the user is\nnot focused on the element we must assume all keys currently down have\nbeen released.", - "line": " src/events/keyboard.js:300" + "line": " src/events/keyboard.js:302" }, { - "message": "Missing item type\nThe checkDownKeys function returns a boolean true if any keys pressed\nand a false if no keys are currently pressed.\n\nHelps avoid instances where a multiple keys are pressed simultaneously and\nreleasing a single key will then switch the\nkeyIsPressed property to true.", - "line": " src/events/keyboard.js:387" + "message": "Missing item type\nThe _areDownKeys function returns a boolean true if any keys pressed\nand a false if no keys are currently pressed.\n\nHelps avoid instances where multiple keys are pressed simultaneously and\nreleasing a single key will then switch the\nkeyIsPressed property to true.", + "line": " src/events/keyboard.js:389" }, { "message": "Missing item type\nThis module defines the filters for use with image buffers.\n\nThis module is basically a collection of functions stored in an object\nas opposed to modules. The functions are destructive, modifying\nthe passed in canvas rather than creating a copy.\n\nGenerally speaking users of this module will use the Filters.apply method\non a canvas to create an effect.\n\nA number of functions are borrowed/adapted from\nhttp://www.html5rocks.com/en/tutorials/canvas/imagefilters/\nor the java processing implementation.", @@ -26458,31 +27102,31 @@ module.exports={ }, { "message": "Missing item type\nConverts the image to black and white pixels depending if they are above or\nbelow the threshold defined by the level parameter. The parameter must be\nbetween 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used.\n\nBorrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/", - "line": " src/image/filters.js:159" + "line": " src/image/filters.js:175" }, { "message": "Missing item type\nConverts any colors in the image to grayscale equivalents.\nNo parameter is used.\n\nBorrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/", - "line": " src/image/filters.js:193" + "line": " src/image/filters.js:209" }, { "message": "Missing item type\nSets the alpha channel to entirely opaque. No parameter is used.", - "line": " src/image/filters.js:216" + "line": " src/image/filters.js:232" }, { "message": "Missing item type\nSets each pixel to its inverse value. No parameter is used.", - "line": " src/image/filters.js:232" + "line": " src/image/filters.js:248" }, { "message": "Missing item type\nLimits each channel of the image to the number of colors specified as\nthe parameter. The parameter can be set to values between 2 and 255, but\nresults are most noticeable in the lower ranges.\n\nAdapted from java based processing implementation", - "line": " src/image/filters.js:247" + "line": " src/image/filters.js:263" }, { "message": "Missing item type\nreduces the bright areas in an image", - "line": " src/image/filters.js:279" + "line": " src/image/filters.js:295" }, { "message": "Missing item type\nincreases the bright areas in an image", - "line": " src/image/filters.js:367" + "line": " src/image/filters.js:383" }, { "message": "Missing item type\nThis module defines the p5 methods for the p5.Image class\nfor drawing images to the main display canvas.", @@ -26490,11 +27134,11 @@ module.exports={ }, { "message": "Missing item type\nValidates clipping params. Per drawImage spec sWidth and sHight cannot be\nnegative or greater than image intrinsic width and height", - "line": " src/image/loading_displaying.js:108" + "line": " src/image/loading_displaying.js:110" }, { "message": "Missing item type\nApply the current tint color to the input image, return the resulting\ncanvas.", - "line": " src/image/loading_displaying.js:425" + "line": " src/image/loading_displaying.js:427" }, { "message": "Missing item type\nThis module defines the p5.Image class and P5 methods for\ndrawing images to the main display canvas.", @@ -26502,36 +27146,28 @@ module.exports={ }, { "message": "Missing item type\nHelper fxn for sharing pixel methods", - "line": " src/image/p5.Image.js:222" + "line": " src/image/p5.Image.js:223" }, { "message": "Missing item type\nGenerate a blob of file data as a url to prepare for download.\nAccepts an array of data, a filename, and an extension (optional).\nThis is a private function because it does not do any formatting,\nbut it is used by saveStrings, saveJSON, saveTable etc.", - "line": " src/io/files.js:1770" + "line": " src/io/files.js:1771" }, { "message": "Missing item type\nReturns a file extension, or another string\nif the provided parameter has no extension.", - "line": " src/io/files.js:1839" + "line": " src/io/files.js:1840" }, { "message": "Missing item type\nReturns true if the browser is Safari, false if not.\nSafari makes trouble for downloading files.", - "line": " src/io/files.js:1872" + "line": " src/io/files.js:1873" }, { "message": "Missing item type\nHelper function, a callback for download that deletes\nan invisible anchor element from the DOM once the file\nhas been automatically downloaded.", - "line": " src/io/files.js:1884" + "line": " src/io/files.js:1885" }, { "message": "Missing item type\nTable Options\n

Generic class for handling tabular data, typically from a\nCSV, TSV, or other sort of spreadsheet file.

\n

CSV files are\n\ncomma separated values, often with the data in quotes. TSV\nfiles use tabs as separators, and usually don't bother with the\nquotes.

\n

File names should end with .csv if they're comma separated.

\n

A rough \"spec\" for CSV can be found\nhere.

\n

To load files, use the loadTable method.

\n

To save tables to your computer, use the save method\n or the saveTable method.

\n\nPossible options include:\n
    \n
  • csv - parse the table as comma-separated values\n
  • tsv - parse the table as tab-separated values\n
  • header - this table has a header (title) row\n
", "line": " src/io/p5.Table.js:11" }, - { - "message": "Missing item type\nThis method is called while the parsing of XML (when loadXML() is\ncalled). The difference between this method and the setContent()\nmethod defined later is that this one is used to set the content\nwhen the node in question has more nodes under it and so on and\nnot directly text content. While in the other one is used when\nthe node in question directly has text inside it.", - "line": " src/io/p5.XML.js:801" - }, - { - "message": "Missing item type\nThis method is called while the parsing of XML (when loadXML() is\ncalled). The XML node is passed and its attributes are stored in the\np5.XML's attribute Object.", - "line": " src/io/p5.XML.js:818" - }, { "message": "Missing item type\nMultiplies a vector by a scalar and returns a new vector.", "line": " src/math/p5.Vector.js:1611" @@ -26558,27 +27194,27 @@ module.exports={ }, { "message": "Missing item type\nHelper function to measure ascent and descent.", - "line": " src/typography/attributes.js:282" + "line": " src/typography/attributes.js:284" }, { "message": "Missing item type\nReturns the set of opentype glyphs for the supplied string.\n\nNote that there is not a strict one-to-one mapping between characters\nand glyphs, so the list of returned glyphs can be larger or smaller\n than the length of the given string.", - "line": " src/typography/p5.Font.js:256" + "line": " src/typography/p5.Font.js:255" }, { "message": "Missing item type\nReturns an opentype path for the supplied string and position.", - "line": " src/typography/p5.Font.js:271" + "line": " src/typography/p5.Font.js:270" }, { "message": "Missing item type", - "line": " src/webgl/3d_primitives.js:259" + "line": " src/webgl/3d_primitives.js:260" }, { "message": "Missing item type\nDraws a point, a coordinate in space at the dimension of one pixel,\ngiven x, y and z coordinates. The color of the point is determined\nby the current stroke, while the point size is determined by current\nstroke weight.", - "line": " src/webgl/3d_primitives.js:745" + "line": " src/webgl/3d_primitives.js:732" }, { "message": "Missing item type\nDraw a line given two points", - "line": " src/webgl/3d_primitives.js:1162" + "line": " src/webgl/3d_primitives.js:1155" }, { "message": "Missing item type\nParse OBJ lines into model. For reference, this is what a simple model of a\nsquare might look like:\n\nv -0.5 -0.5 0.5\nv -0.5 -0.5 -0.5\nv -0.5 0.5 -0.5\nv -0.5 0.5 0.5\n\nf 4 3 2 1", @@ -26586,7 +27222,11 @@ module.exports={ }, { "message": "Missing item type", - "line": " src/webgl/material.js:399" + "line": " src/webgl/material.js:659" + }, + { + "message": "Missing item type", + "line": " src/webgl/material.js:681" }, { "message": "Missing item type\nCreate a 2D array for establishing stroke connections", @@ -26602,7 +27242,7 @@ module.exports={ }, { "message": "Missing item type\nPRIVATE", - "line": " src/webgl/p5.Matrix.js:673" + "line": " src/webgl/p5.Matrix.js:730" }, { "message": "Missing item type\nWelcome to RendererGL Immediate Mode.\nImmediate mode is used for drawing custom shapes\nfrom a set of vertices. Immediate Mode is activated\nwhen you call beginShape() & de-activated when you call endShape().\nImmediate mode is a style of programming borrowed\nfrom OpenGL's (now-deprecated) immediate mode.\nIt differs from p5.js' default, Retained Mode, which caches\ngeometries and buffers on the CPU to reduce the number of webgl\ndraw calls. Retained mode is more efficient & performative,\nhowever, Immediate Mode is useful for sketching quick\ngeometric ideas.", @@ -26610,7 +27250,7 @@ module.exports={ }, { "message": "Missing item type\nEnd shape drawing and render vertices to screen.", - "line": " src/webgl/p5.RendererGL.Immediate.js:118" + "line": " src/webgl/p5.RendererGL.Immediate.js:133" }, { "message": "Missing item type\ninitializes buffer defaults. runs each time a new geometry is\nregistered", @@ -26622,43 +27262,43 @@ module.exports={ }, { "message": "Missing item type\nDraws buffers given a geometry key ID", - "line": " src/webgl/p5.RendererGL.Retained.js:191" + "line": " src/webgl/p5.RendererGL.Retained.js:196" }, { "message": "Missing item type\nmodel view, projection, & normal\nmatrices", - "line": " src/webgl/p5.RendererGL.js:83" + "line": " src/webgl/p5.RendererGL.js:80" }, { "message": "Missing item type\n[background description]", - "line": " src/webgl/p5.RendererGL.js:405" + "line": " src/webgl/p5.RendererGL.js:456" }, { "message": "Missing item type\n[resize description]", - "line": " src/webgl/p5.RendererGL.js:644" + "line": " src/webgl/p5.RendererGL.js:707" }, { "message": "Missing item type\nclears color and depth buffers\nwith r,g,b,a", - "line": " src/webgl/p5.RendererGL.js:670" + "line": " src/webgl/p5.RendererGL.js:738" }, { "message": "Missing item type\n[translate description]", - "line": " src/webgl/p5.RendererGL.js:688" + "line": " src/webgl/p5.RendererGL.js:771" }, { "message": "Missing item type\nScales the Model View Matrix by a vector", - "line": " src/webgl/p5.RendererGL.js:707" + "line": " src/webgl/p5.RendererGL.js:790" }, { "message": "Missing item type\nturn a two dimensional array into one dimensional array", - "line": " src/webgl/p5.RendererGL.js:1028" + "line": " src/webgl/p5.RendererGL.js:1139" }, { "message": "Missing item type\nturn a p5.Vector Array into a one dimensional number array", - "line": " src/webgl/p5.RendererGL.js:1065" + "line": " src/webgl/p5.RendererGL.js:1176" }, { "message": "Missing item type\nensures that p5 is using a 3d renderer. throws an error if not.", - "line": " src/webgl/p5.RendererGL.js:1081" + "line": " src/webgl/p5.RendererGL.js:1192" }, { "message": "Missing item type\nHelper function for select and selectAll", @@ -26670,35 +27310,35 @@ module.exports={ }, { "message": "Missing item type\nHelpers for create methods.", - "line": " lib/addons/p5.dom.js:245" + "line": " lib/addons/p5.dom.js:348" }, { "message": "Missing item type", - "line": " lib/addons/p5.dom.js:384" + "line": " lib/addons/p5.dom.js:488" }, { "message": "Missing item type", - "line": " lib/addons/p5.dom.js:981" + "line": " lib/addons/p5.dom.js:1070" }, { "message": "Missing item type", - "line": " lib/addons/p5.dom.js:1062" + "line": " lib/addons/p5.dom.js:1159" }, { "message": "Missing item type", - "line": " lib/addons/p5.dom.js:1102" + "line": " lib/addons/p5.dom.js:1199" }, { "message": "Missing item type", - "line": " lib/addons/p5.dom.js:2777" + "line": " lib/addons/p5.dom.js:3029" }, { "message": "Missing item type", - "line": " lib/addons/p5.dom.js:2843" + "line": " lib/addons/p5.dom.js:3095" }, { "message": "Missing item type", - "line": " lib/addons/p5.dom.js:2905" + "line": " lib/addons/p5.dom.js:3157" }, { "message": "Missing item type\np5.sound \nhttps://p5js.org/reference/#/libraries/p5.sound\n\nFrom the Processing Foundation and contributors\nhttps://github.com/processing/p5.js-sound/graphs/contributors\n\nMIT License (MIT)\nhttps://github.com/processing/p5.js-sound/blob/master/LICENSE\n\nSome of the many audio libraries & resources that inspire p5.sound:\n - TONE.js (c) Yotam Mann. Licensed under The MIT License (MIT). https://github.com/TONEnoTONE/Tone.js\n - buzz.js (c) Jay Salvat. Licensed under The MIT License (MIT). http://buzz.jaysalvat.com/\n - Boris Smus Web Audio API book, 2013. Licensed under the Apache License http://www.apache.org/licenses/LICENSE-2.0\n - wavesurfer.js https://github.com/katspaugh/wavesurfer.js\n - Web Audio Components by Jordan Santell https://github.com/web-audio-components\n - Wilm Thoben's Sound library for Processing https://github.com/processing/processing/tree/master/java/libraries/sound\n\n Web Audio API: http://w3.org/TR/webaudio/", @@ -26709,200 +27349,200 @@ module.exports={ "line": " lib/addons/p5.sound.js:214" }, { - "message": "Missing item type\nMaster contains AudioContext and the master sound output.", - "line": " lib/addons/p5.sound.js:328" + "message": "Missing item type", + "line": " lib/addons/p5.sound.js:363" }, { - "message": "Missing item type\na silent connection to the DesinationNode\nwhich will ensure that anything connected to it\nwill not be garbage collected", - "line": " lib/addons/p5.sound.js:423" + "message": "Missing item type", + "line": " lib/addons/p5.sound.js:740" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:439" + "line": " lib/addons/p5.sound.js:810" }, { - "message": "Missing item type\nUsed by Osc and Envelope to chain signal math", - "line": " lib/addons/p5.sound.js:644" + "message": "Missing item type\nMaster contains AudioContext and the master sound output.", + "line": " lib/addons/p5.sound.js:1099" }, { - "message": "Missing item type\nThis is a helper function that the p5.SoundFile calls to load\nitself. Accepts a callback (the name of another function)\nas an optional parameter.", - "line": " lib/addons/p5.sound.js:973" + "message": "Missing item type\na silent connection to the DesinationNode\nwhich will ensure that anything connected to it\nwill not be garbage collected", + "line": " lib/addons/p5.sound.js:1194" }, { - "message": "Missing item type\nStop playback on all of this soundfile's sources.", - "line": " lib/addons/p5.sound.js:1379" + "message": "Missing item type", + "line": " lib/addons/p5.sound.js:1210" }, { - "message": "Missing item type", - "line": " lib/addons/p5.sound.js:1818" + "message": "Missing item type\nUsed by Osc and Envelope to chain signal math", + "line": " lib/addons/p5.sound.js:1415" }, { - "message": "Missing item type", - "line": " lib/addons/p5.sound.js:2099" + "message": "Missing item type\nThis is a helper function that the p5.SoundFile calls to load\nitself. Accepts a callback (the name of another function)\nas an optional parameter.", + "line": " lib/addons/p5.sound.js:1813" }, { - "message": "Missing item type", - "line": " lib/addons/p5.sound.js:3110" + "message": "Missing item type\nStop playback on all of this soundfile's sources.", + "line": " lib/addons/p5.sound.js:2218" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:3487" + "line": " lib/addons/p5.sound.js:2656" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:3508" + "line": " lib/addons/p5.sound.js:2934" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:3567" + "line": " lib/addons/p5.sound.js:4055" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:3885" + "line": " lib/addons/p5.sound.js:4076" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:4057" + "line": " lib/addons/p5.sound.js:4135" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:4215" + "line": " lib/addons/p5.sound.js:4453" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:4256" + "line": " lib/addons/p5.sound.js:4625" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:4326" + "line": " lib/addons/p5.sound.js:4783" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:4514" + "line": " lib/addons/p5.sound.js:4824" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:4571" + "line": " lib/addons/p5.sound.js:4881" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:4739" + "line": " lib/addons/p5.sound.js:5049" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:4787" + "line": " lib/addons/p5.sound.js:5097" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:4818" + "line": " lib/addons/p5.sound.js:5128" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:4839" + "line": " lib/addons/p5.sound.js:5149" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:4859" + "line": " lib/addons/p5.sound.js:5169" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:5572" + "line": " lib/addons/p5.sound.js:5879" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:5775" + "line": " lib/addons/p5.sound.js:6082" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:7426" + "line": " lib/addons/p5.sound.js:7750" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:7442" + "line": " lib/addons/p5.sound.js:7766" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:7466" + "line": " lib/addons/p5.sound.js:7790" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:7492" + "line": " lib/addons/p5.sound.js:7816" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:7514" + "line": " lib/addons/p5.sound.js:7838" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:7536" + "line": " lib/addons/p5.sound.js:7860" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:7582" + "line": " lib/addons/p5.sound.js:7906" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:7613" + "line": " lib/addons/p5.sound.js:7937" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:7631" + "line": " lib/addons/p5.sound.js:7955" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:7968" + "line": " lib/addons/p5.sound.js:8292" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:7990" + "line": " lib/addons/p5.sound.js:8314" }, { "message": "Missing item type\nThe p5.Effect class is built\n \tusing Tone.js CrossFade", - "line": " lib/addons/p5.sound.js:8060" + "line": " lib/addons/p5.sound.js:8384" }, { "message": "Missing item type\nIn classes that extend\np5.Effect, connect effect nodes\nto the wet parameter", - "line": " lib/addons/p5.sound.js:8066" + "line": " lib/addons/p5.sound.js:8390" }, { "message": "Missing item type\nEQFilter extends p5.Filter with constraints\nnecessary for the p5.EQ", - "line": " lib/addons/p5.sound.js:8456" + "line": " lib/addons/p5.sound.js:8779" }, { "message": "Missing item type\nInspired by Simple Reverb by Jordan Santell\nhttps://github.com/web-audio-components/simple-reverb/blob/master/index.js\n\nUtility function for building an impulse response\nbased on the module parameters.", - "line": " lib/addons/p5.sound.js:9552" + "line": " lib/addons/p5.sound.js:9889" }, { "message": "Missing item type\nPrivate method to load a buffer as an Impulse Response,\nassign it to the convolverNode, and add to the Array of .impulses.", - "line": " lib/addons/p5.sound.js:9724" + "line": " lib/addons/p5.sound.js:10056" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:9912" + "line": " lib/addons/p5.sound.js:10240" }, { "message": "Missing item type", - "line": " lib/addons/p5.sound.js:9937" + "line": " lib/addons/p5.sound.js:10265" }, { "message": "Missing item type\nmusicalTimeMode variables\nmodify these only when the interval is specified in musicalTime format as a string", - "line": " lib/addons/p5.sound.js:10662" + "line": " lib/addons/p5.sound.js:10989" }, { "message": "Missing item type\nDo not initiate the callback if timeFromNow is < 0\nThis ususually occurs for a few milliseconds when the page\nis not fully loaded\n\nThe callback should only be called until maxIterations is reached", - "line": " lib/addons/p5.sound.js:10678" + "line": " lib/addons/p5.sound.js:11005" }, { "message": "Missing item type\ncallback invoked when the recording is over", - "line": " lib/addons/p5.sound.js:11167" + "line": " lib/addons/p5.sound.js:11495" }, { "message": "Missing item type\ninternal method called on audio process", - "line": " lib/addons/p5.sound.js:11253" + "line": " lib/addons/p5.sound.js:11581" }, { "message": "Missing item type\nPrivate method to ensure accurate values of this._voicesInUse\nAny time a new value is scheduled, it is necessary to increment all subsequent\nscheduledValues after attack, and decrement all subsequent\nscheduledValues after release", - "line": " lib/addons/p5.sound.js:12361" + "line": " lib/addons/p5.sound.js:12627" }, { "message": "Missing item type\np5.sound \nhttps://p5js.org/reference/#/libraries/p5.sound\n\nFrom the Processing Foundation and contributors\nhttps://github.com/processing/p5.js-sound/graphs/contributors\n\nMIT License (MIT)\nhttps://github.com/processing/p5.js-sound/blob/master/LICENSE\n\nSome of the many audio libraries & resources that inspire p5.sound:\n - TONE.js (c) Yotam Mann. Licensed under The MIT License (MIT). https://github.com/TONEnoTONE/Tone.js\n - buzz.js (c) Jay Salvat. Licensed under The MIT License (MIT). http://buzz.jaysalvat.com/\n - Boris Smus Web Audio API book, 2013. Licensed under the Apache License http://www.apache.org/licenses/LICENSE-2.0\n - wavesurfer.js https://github.com/katspaugh/wavesurfer.js\n - Web Audio Components by Jordan Santell https://github.com/web-audio-components\n - Wilm Thoben's Sound library for Processing https://github.com/processing/processing/tree/master/java/libraries/sound\n\n Web Audio API: http://w3.org/TR/webaudio/", @@ -27003,9 +27643,6 @@ module.exports={ "TEXT": [ "p5.cursor" ], - "WAIT": [ - "p5.cursor" - ], "P2D": [ "p5.createCanvas", "p5.createGraphics" @@ -27084,11 +27721,8 @@ module.exports={ "p5.Image.blend", "p5.blend" ], - "NORMAL": [ - "p5.blendMode", - "p5.Image.blend", - "p5.blend", - "p5.textStyle" + "SUBTRACT": [ + "p5.blendMode" ], "THRESHOLD": [ "p5.Image.filter", @@ -27122,6 +27756,12 @@ module.exports={ "p5.Image.filter", "p5.filter" ], + "NORMAL": [ + "p5.Image.blend", + "p5.blend", + "p5.textStyle", + "p5.textureMode" + ], "RADIANS": [ "p5.angleMode" ], @@ -27149,6 +27789,21 @@ module.exports={ "BOLD": [ "p5.textStyle" ], + "BOLDITALIC": [ + "p5.textStyle" + ], + "IMAGE": [ + "p5.textureMode" + ], + "CLAMP": [ + "p5.textureWrap" + ], + "REPEAT": [ + "p5.textureWrap" + ], + "MIRROR": [ + "p5.textureWrap" + ], "VIDEO": [ "p5.createCapture" ], @@ -27158,139 +27813,165 @@ module.exports={ } } },{}],2:[function(_dereq_,module,exports){ -var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - -;(function (exports) { - 'use strict'; - - var Arr = (typeof Uint8Array !== 'undefined') - ? Uint8Array - : Array - - var PLUS = '+'.charCodeAt(0) - var SLASH = '/'.charCodeAt(0) - var NUMBER = '0'.charCodeAt(0) - var LOWER = 'a'.charCodeAt(0) - var UPPER = 'A'.charCodeAt(0) - var PLUS_URL_SAFE = '-'.charCodeAt(0) - var SLASH_URL_SAFE = '_'.charCodeAt(0) - - function decode (elt) { - var code = elt.charCodeAt(0) - if (code === PLUS || - code === PLUS_URL_SAFE) - return 62 // '+' - if (code === SLASH || - code === SLASH_URL_SAFE) - return 63 // '/' - if (code < NUMBER) - return -1 //no match - if (code < NUMBER + 10) - return code - NUMBER + 26 + 26 - if (code < UPPER + 26) - return code - UPPER - if (code < LOWER + 26) - return code - LOWER + 26 - } +'use strict' - function b64ToByteArray (b64) { - var i, j, l, tmp, placeHolders, arr +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray - if (b64.length % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - var len = b64.length - placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} - // base64 is 4/3 + up to two characters of the original data - arr = new Arr(b64.length * 3 / 4 - placeHolders) +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? b64.length - 4 : b64.length +function getLens (b64) { + var len = b64.length - var L = 0 + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } - function push (v) { - arr[L++] = v - } + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) - push((tmp & 0xFF0000) >> 16) - push((tmp & 0xFF00) >> 8) - push(tmp & 0xFF) - } + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) - if (placeHolders === 2) { - tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) - push(tmp & 0xFF) - } else if (placeHolders === 1) { - tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) - push((tmp >> 8) & 0xFF) - push(tmp & 0xFF) - } + return [validLen, placeHoldersLen] +} - return arr - } +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} - function uint8ToBase64 (uint8) { - var i, - extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes - output = "", - temp, length +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} - function encode (num) { - return lookup.charAt(num) - } +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] - function tripletToBase64 (num) { - return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) - } + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - // go through the array every three bytes, we'll deal with trailing stuff later - for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { - temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) - output += tripletToBase64(temp) - } + var curByte = 0 - // pad the end with zeros, but make sure to not forget the extra bytes - switch (extraBytes) { - case 1: - temp = uint8[uint8.length - 1] - output += encode(temp >> 2) - output += encode((temp << 4) & 0x3F) - output += '==' - break - case 2: - temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) - output += encode(temp >> 10) - output += encode((temp >> 4) & 0x3F) - output += encode((temp << 2) & 0x3F) - output += '=' - break - } + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen - return output - } + for (var i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } - exports.toByteArray = b64ToByteArray - exports.fromByteArray = uint8ToBase64 -}(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk( + uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) + )) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} },{}],3:[function(_dereq_,module,exports){ },{}],4:[function(_dereq_,module,exports){ -(function (global){ /*! * The buffer module from node.js, for the browser. * - * @author Feross Aboukhadijeh + * @author Feross Aboukhadijeh * @license MIT */ /* eslint-disable no-proto */ @@ -27299,268 +27980,336 @@ var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var base64 = _dereq_('base64-js') var ieee754 = _dereq_('ieee754') -var isArray = _dereq_('isarray') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 -Buffer.poolSize = 8192 // not used by this implementation -var rootParent = {} +var K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property - * on objects. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. */ -Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : typedArraySupport() +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} function typedArraySupport () { - function Bar () {} + // Can typed array instances can be augmented? try { var arr = new Uint8Array(1) - arr.foo = function () { return 42 } - arr.constructor = Bar - return arr.foo() === 42 && // typed array instances can be augmented - arr.constructor === Bar && // constructor can be set - typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } + return arr.foo() === 42 } catch (e) { return false } } -function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + buf.__proto__ = Buffer.prototype + return buf } /** - * Class: Buffer - * ============= + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. * - * The Buffer constructor returns instances of `Uint8Array` that are augmented - * with function properties for all the node `Buffer` API functions. We use - * `Uint8Array` so that square bracket notation works as expected -- it returns - * a single octet. - * - * By augmenting the instances, we can avoid modifying the `Uint8Array` - * prototype. + * The `Uint8Array` prototype remains unmodified. */ -function Buffer (arg) { - if (!(this instanceof Buffer)) { - // Avoid going through an ArgumentsAdaptorTrampoline in the common case. - if (arguments.length > 1) return new Buffer(arg, arguments[1]) - return new Buffer(arg) + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) } + return from(arg, encodingOrOffset, length) +} + +// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 +if (typeof Symbol !== 'undefined' && Symbol.species != null && + Buffer[Symbol.species] === Buffer) { + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true, + enumerable: false, + writable: false + }) +} + +Buffer.poolSize = 8192 // not used by this implementation - if (!Buffer.TYPED_ARRAY_SUPPORT) { - this.length = 0 - this.parent = undefined +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) } - // Common case. - if (typeof arg === 'number') { - return fromNumber(this, arg) + if (ArrayBuffer.isView(value)) { + return fromArrayLike(value) } - // Slightly less common case. - if (typeof arg === 'string') { - return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') + if (value == null) { + throw TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) } - // Unusual. - return fromObject(this, arg) -} + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } -function fromNumber (that, length) { - that = allocate(that, length < 0 ? 0 : checked(length) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < length; i++) { - that[i] = 0 - } + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) } - return that -} -function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8' + var valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } - // Assumption: byteLength() return value is always < kMaxLength. - var length = byteLength(string, encoding) | 0 - that = allocate(that, length) + var b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from( + value[Symbol.toPrimitive]('string'), encodingOrOffset, length + ) + } - that.write(string, encoding) - return that + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) } -function fromObject (that, object) { - if (Buffer.isBuffer(object)) return fromBuffer(that, object) +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} - if (isArray(object)) return fromArray(that, object) +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Buffer.prototype.__proto__ = Uint8Array.prototype +Buffer.__proto__ = Uint8Array - if (object == null) { - throw new TypeError('must start with number, buffer, array or string') +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') } +} - if (typeof ArrayBuffer !== 'undefined') { - if (object.buffer instanceof ArrayBuffer) { - return fromTypedArray(that, object) - } - if (object instanceof ArrayBuffer) { - return fromArrayBuffer(that, object) - } +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} - if (object.length) return fromArrayLike(that, object) +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} - return fromJsonObject(that, object) +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) } -function fromBuffer (that, buffer) { - var length = checked(buffer.length) | 0 - that = allocate(that, length) - buffer.copy(that, 0, 0, length) - return that +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) } -function fromArray (that, array) { - var length = checked(array.length) | 0 - that = allocate(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' } - return that -} -// Duplicate of fromArray() to keep fromArray() monomorphic. -function fromTypedArray (that, array) { - var length = checked(array.length) | 0 - that = allocate(that, length) - // Truncating the elements is probably not what people expect from typed - // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior - // of the old Buffer constructor. - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) } - return that -} -function fromArrayBuffer (that, array) { - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - array.byteLength - that = Buffer._augment(new Uint8Array(array)) - } else { - // Fallback: Return an object instance of the Buffer class - that = fromTypedArray(that, new Uint8Array(array)) + var length = byteLength(string, encoding) | 0 + var buf = createBuffer(length) + + var actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) } - return that + + return buf } -function fromArrayLike (that, array) { - var length = checked(array.length) | 0 - that = allocate(that, length) +function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + var buf = createBuffer(length) for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 + buf[i] = array[i] & 255 } - return that + return buf } -// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object. -// Returns a zero-length buffer for inputs that don't conform to the spec. -function fromJsonObject (that, object) { - var array - var length = 0 +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } - if (object.type === 'Buffer' && isArray(object.data)) { - array = object.data - length = checked(array.length) | 0 + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') } - that = allocate(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 + var buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) } - return that -} -if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array -} else { - // pre-set for values that may exist in the future - Buffer.prototype.length = undefined - Buffer.prototype.parent = undefined + // Return an augmented `Uint8Array` instance + buf.__proto__ = Buffer.prototype + return buf } -function allocate (that, length) { - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = Buffer._augment(new Uint8Array(length)) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that.length = length - that._isBuffer = true +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf } - var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1 - if (fromPool) that.parent = rootParent + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } - return that + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } } function checked (length) { - // Note: cannot use `length < kMaxLength` here because that fails when + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { + if (length >= K_MAX_LENGTH) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') } return length | 0 } -function SlowBuffer (subject, encoding) { - if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding) - - var buf = new Buffer(subject, encoding) - delete buf.parent - return buf +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false } Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) } if (a === b) return 0 @@ -27568,17 +28317,12 @@ Buffer.compare = function compare (a, b) { var x = a.length var y = b.length - var i = 0 - var len = Math.min(x, y) - while (i < len) { - if (a[i] !== b[i]) break - - ++i - } - - if (i !== len) { - x = a[i] - y = b[i] + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } } if (x < y) return -1 @@ -27592,9 +28336,9 @@ Buffer.isEncoding = function isEncoding (encoding) { case 'utf8': case 'utf-8': case 'ascii': + case 'latin1': case 'binary': case 'base64': - case 'raw': case 'ucs2': case 'ucs-2': case 'utf16le': @@ -27606,45 +28350,63 @@ Buffer.isEncoding = function isEncoding (encoding) { } Buffer.concat = function concat (list, length) { - if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } if (list.length === 0) { - return new Buffer(0) + return Buffer.alloc(0) } var i if (length === undefined) { length = 0 - for (i = 0; i < list.length; i++) { + for (i = 0; i < list.length; ++i) { length += list[i].length } } - var buf = new Buffer(length) + var buffer = Buffer.allocUnsafe(length) var pos = 0 - for (i = 0; i < list.length; i++) { - var item = list[i] - item.copy(buf, pos) - pos += item.length + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (isInstance(buf, Uint8Array)) { + buf = Buffer.from(buf) + } + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length } - return buf + return buffer } function byteLength (string, encoding) { - if (typeof string !== 'string') string = '' + string + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } var len = string.length - if (len === 0) return 0 + var mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': + case 'latin1': case 'binary': - // Deprecated - case 'raw': - case 'raws': return len case 'utf8': case 'utf-8': @@ -27659,7 +28421,9 @@ function byteLength (string, encoding) { case 'base64': return base64ToBytes(string).length default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } encoding = ('' + encoding).toLowerCase() loweredCase = true } @@ -27670,13 +28434,39 @@ Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false - start = start | 0 - end = end === undefined || end === Infinity ? this.length : end | 0 + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } if (!encoding) encoding = 'utf8' - if (start < 0) start = 0 - if (end > this.length) end = this.length - if (end <= start) return '' while (true) { switch (encoding) { @@ -27690,8 +28480,9 @@ function slowToString (encoding, start, end) { case 'ascii': return asciiSlice(this, start, end) + case 'latin1': case 'binary': - return binarySlice(this, start, end) + return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) @@ -27710,13 +28501,66 @@ function slowToString (encoding, start, end) { } } +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + Buffer.prototype.toString = function toString () { - var length = this.length | 0 + var length = this.length if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } +Buffer.prototype.toLocaleString = Buffer.prototype.toString + Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true @@ -27726,70 +28570,207 @@ Buffer.prototype.equals = function equals (b) { Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' - } + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' return '' } -Buffer.prototype.compare = function compare (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return 0 - return Buffer.compare(this, b) -} +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } -Buffer.prototype.indexOf = function indexOf (val, byteOffset) { - if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff - else if (byteOffset < -0x80000000) byteOffset = -0x80000000 - byteOffset >>= 0 + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } - if (this.length === 0) return -1 - if (byteOffset >= this.length) return -1 + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } - // Negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) + if (x < y) return -1 + if (y < x) return 1 + return 0 +} +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val if (typeof val === 'string') { - if (val.length === 0) return -1 // special case: looking for empty string always fails - return String.prototype.indexOf.call(this, val, byteOffset) + val = Buffer.from(val, encoding) } + + // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { - return arrayIndexOf(this, val, byteOffset) + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } - if (typeof val === 'number') { - if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { - return Uint8Array.prototype.indexOf.call(this, val, byteOffset) + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 } - return arrayIndexOf(this, [ val ], byteOffset) } - function arrayIndexOf (arr, val, byteOffset) { + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { var foundIndex = -1 - for (var i = 0; byteOffset + i < arr.length; i++) { - if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) { + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { + if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } - return -1 + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } } - throw new TypeError('val must be string, number or Buffer') + return -1 } -// `get` is deprecated -Buffer.prototype.get = function get (offset) { - console.log('.get() is deprecated. Access using array indexes instead.') - return this.readUInt8(offset) +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 } -// `set` is deprecated -Buffer.prototype.set = function set (v, offset) { - console.log('.set() is deprecated. Access using array indexes instead.') - return this.writeUInt8(v, offset) +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } function hexWrite (buf, string, offset, length) { @@ -27804,16 +28785,14 @@ function hexWrite (buf, string, offset, length) { } } - // must be an even number of digits var strLen = string.length - if (strLen % 2 !== 0) throw new Error('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) throw new Error('Invalid hex string') + if (numberIsNaN(parsed)) return i buf[offset + i] = parsed } return i @@ -27827,7 +28806,7 @@ function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } -function binaryWrite (buf, string, offset, length) { +function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } @@ -27852,27 +28831,25 @@ Buffer.prototype.write = function write (string, offset, length, encoding) { offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { - offset = offset | 0 + offset = offset >>> 0 if (isFinite(length)) { - length = length | 0 + length = length >>> 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } - // legacy write(string, encoding, offset, length) - remove in v0.13 } else { - var swap = encoding - encoding = offset - offset = length | 0 - length = swap + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('attempt to write outside buffer bounds') + throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' @@ -27890,8 +28867,9 @@ Buffer.prototype.write = function write (string, offset, length, encoding) { case 'ascii': return asciiWrite(this, string, offset, length) + case 'latin1': case 'binary': - return binaryWrite(this, string, offset, length) + return latin1Write(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write @@ -27936,8 +28914,8 @@ function utf8Slice (buf, start, end) { var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 + : (firstByte > 0xBF) ? 2 + : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint @@ -28026,17 +29004,17 @@ function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) - for (var i = start; i < end; i++) { + for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } -function binarySlice (buf, start, end) { +function latin1Slice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) - for (var i = start; i < end; i++) { + for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]) } return ret @@ -28049,7 +29027,7 @@ function hexSlice (buf, start, end) { if (!end || end < 0 || end > len) end = len var out = '' - for (var i = start; i < end; i++) { + for (var i = start; i < end; ++i) { out += toHex(buf[i]) } return out @@ -28059,7 +29037,7 @@ function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) } return res } @@ -28085,19 +29063,9 @@ Buffer.prototype.slice = function slice (start, end) { if (end < start) end = start - var newBuf - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = Buffer._augment(this.subarray(start, end)) - } else { - var sliceLen = end - start - newBuf = new Buffer(sliceLen, undefined) - for (var i = 0; i < sliceLen; i++) { - newBuf[i] = this[i + start] - } - } - - if (newBuf.length) newBuf.parent = this.parent || this - + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + newBuf.__proto__ = Buffer.prototype return newBuf } @@ -28110,8 +29078,8 @@ function checkOffset (offset, ext, length) { } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 + offset = offset >>> 0 + byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] @@ -28125,8 +29093,8 @@ Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 + offset = offset >>> 0 + byteLength = byteLength >>> 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } @@ -28141,21 +29109,25 @@ Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | @@ -28165,6 +29137,7 @@ Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + @@ -28174,8 +29147,8 @@ Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 + offset = offset >>> 0 + byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] @@ -28192,8 +29165,8 @@ Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 + offset = offset >>> 0 + byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength @@ -28210,24 +29183,28 @@ Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | @@ -28237,6 +29214,7 @@ Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | @@ -28246,36 +29224,43 @@ Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') - if (value > max || value < min) throw new RangeError('value is out of bounds') - if (offset + ext > buf.length) throw new RangeError('index out of range') + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } var mul = 1 var i = 0 @@ -28289,9 +29274,12 @@ Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } var i = byteLength - 1 var mul = 1 @@ -28305,98 +29293,69 @@ Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) this[offset] = (value & 0xff) return offset + 1 } -function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 - } -} - Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) return offset + 2 } -function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff - } -} - Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, true) - } + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) + var limit = Math.pow(2, (8 * byteLength) - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 - var sub = value < 0 ? 1 : 0 + var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } @@ -28405,18 +29364,21 @@ Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, no Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) + var limit = Math.pow(2, (8 * byteLength) - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 - var sub = value < 0 ? 1 : 0 + var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } @@ -28425,9 +29387,8 @@ Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, no Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 @@ -28435,68 +29396,53 @@ Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - } else { - objectWriteUInt32(this, value, offset, true) - } + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { - if (value > max || value < min) throw new RangeError('value is out of bounds') - if (offset + ext > buf.length) throw new RangeError('index out of range') - if (offset < 0) throw new RangeError('index out of range') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } @@ -28513,6 +29459,8 @@ Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } @@ -28530,6 +29478,7 @@ Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length @@ -28544,7 +29493,7 @@ Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart 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? @@ -28554,152 +29503,105 @@ Buffer.prototype.copy = function copy (target, targetStart, start, end) { } var len = end - start - var i - if (this === target && start < targetStart && targetStart < end) { + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else if (this === target && start < targetStart && targetStart < end) { // descending copy from end - for (i = len - 1; i >= 0; i--) { - target[i + targetStart] = this[i + start] - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; i++) { + for (var i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } } else { - target._set(this.subarray(start, start + len), targetStart) + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) } return len } -// fill(value, start=0, end=buffer.length) -Buffer.prototype.fill = function fill (value, start, end) { - if (!value) value = 0 - if (!start) start = 0 - if (!end) end = this.length +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } - if (end < start) throw new RangeError('end < start') + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } - // Fill 0 bytes; we're done - if (end === start) return - if (this.length === 0) return + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 - if (start < 0 || start >= this.length) throw new RangeError('start out of bounds') - if (end < 0 || end > this.length) throw new RangeError('end out of bounds') + if (!val) val = 0 var i - if (typeof value === 'number') { - for (i = start; i < end; i++) { - this[i] = value + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val } } else { - var bytes = utf8ToBytes(value.toString()) + var bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) var len = bytes.length - for (i = start; i < end; i++) { - this[i] = bytes[i % len] + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] } } return this } -/** - * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. - * Added in Node 0.12. Only available in browsers that support ArrayBuffer. - */ -Buffer.prototype.toArrayBuffer = function toArrayBuffer () { - if (typeof Uint8Array !== 'undefined') { - if (Buffer.TYPED_ARRAY_SUPPORT) { - return (new Buffer(this)).buffer - } else { - var buf = new Uint8Array(this.length) - for (var i = 0, len = buf.length; i < len; i += 1) { - buf[i] = this[i] - } - return buf.buffer - } - } else { - throw new TypeError('Buffer.toArrayBuffer not supported in this browser') - } -} - // HELPER FUNCTIONS // ================ -var BP = Buffer.prototype - -/** - * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods - */ -Buffer._augment = function _augment (arr) { - arr.constructor = Buffer - arr._isBuffer = true - - // save reference to original Uint8Array set method before overwriting - arr._set = arr.set - - // deprecated - arr.get = BP.get - arr.set = BP.set - - arr.write = BP.write - arr.toString = BP.toString - arr.toLocaleString = BP.toString - arr.toJSON = BP.toJSON - arr.equals = BP.equals - arr.compare = BP.compare - arr.indexOf = BP.indexOf - arr.copy = BP.copy - arr.slice = BP.slice - arr.readUIntLE = BP.readUIntLE - arr.readUIntBE = BP.readUIntBE - arr.readUInt8 = BP.readUInt8 - arr.readUInt16LE = BP.readUInt16LE - arr.readUInt16BE = BP.readUInt16BE - arr.readUInt32LE = BP.readUInt32LE - arr.readUInt32BE = BP.readUInt32BE - arr.readIntLE = BP.readIntLE - arr.readIntBE = BP.readIntBE - arr.readInt8 = BP.readInt8 - arr.readInt16LE = BP.readInt16LE - arr.readInt16BE = BP.readInt16BE - arr.readInt32LE = BP.readInt32LE - arr.readInt32BE = BP.readInt32BE - arr.readFloatLE = BP.readFloatLE - arr.readFloatBE = BP.readFloatBE - arr.readDoubleLE = BP.readDoubleLE - arr.readDoubleBE = BP.readDoubleBE - arr.writeUInt8 = BP.writeUInt8 - arr.writeUIntLE = BP.writeUIntLE - arr.writeUIntBE = BP.writeUIntBE - arr.writeUInt16LE = BP.writeUInt16LE - arr.writeUInt16BE = BP.writeUInt16BE - arr.writeUInt32LE = BP.writeUInt32LE - arr.writeUInt32BE = BP.writeUInt32BE - arr.writeIntLE = BP.writeIntLE - arr.writeIntBE = BP.writeIntBE - arr.writeInt8 = BP.writeInt8 - arr.writeInt16LE = BP.writeInt16LE - arr.writeInt16BE = BP.writeInt16BE - arr.writeInt32LE = BP.writeInt32LE - arr.writeInt32BE = BP.writeInt32BE - arr.writeFloatLE = BP.writeFloatLE - arr.writeFloatBE = BP.writeFloatBE - arr.writeDoubleLE = BP.writeDoubleLE - arr.writeDoubleBE = BP.writeDoubleBE - arr.fill = BP.fill - arr.inspect = BP.inspect - arr.toArrayBuffer = BP.toArrayBuffer - - return arr -} - -var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g +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 = stringtrim(str).replace(INVALID_BASE64_RE, '') + 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 @@ -28709,11 +29611,6 @@ function base64clean (str) { return str } -function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') -} - function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) @@ -28726,7 +29623,7 @@ function utf8ToBytes (string, units) { var leadSurrogate = null var bytes = [] - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i) // is surrogate component @@ -28801,7 +29698,7 @@ function utf8ToBytes (string, units) { function asciiToBytes (str) { var byteArray = [] - for (var i = 0; i < str.length; i++) { + for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } @@ -28811,7 +29708,7 @@ function asciiToBytes (str) { function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] - for (var i = 0; i < str.length; i++) { + for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i) @@ -28829,22 +29726,34 @@ function base64ToBytes (str) { } function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"base64-js":2,"ieee754":8,"isarray":9}],5:[function(_dereq_,module,exports){ +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +},{"base64-js":2,"ieee754":8}],5:[function(_dereq_,module,exports){ (function (process,global){ /*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE - * @version 4.1.1 + * @version v4.2.6+9869a4bc */ (function (global, factory) { @@ -28862,7 +29771,9 @@ function isFunction(x) { return typeof x === 'function'; } -var _isArray = undefined; + + +var _isArray = void 0; if (Array.isArray) { _isArray = Array.isArray; } else { @@ -28874,8 +29785,8 @@ if (Array.isArray) { var isArray = _isArray; var len = 0; -var vertxNext = undefined; -var customSchedulerFn = undefined; +var vertxNext = void 0; +var customSchedulerFn = void 0; var asap = function asap(callback, arg) { queue[len] = callback; @@ -28904,7 +29815,7 @@ function setAsap(asapFn) { var browserWindow = typeof window !== 'undefined' ? window : undefined; var browserGlobal = browserWindow || {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; -var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]'; +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'; @@ -28975,8 +29886,7 @@ function flush() { function attemptVertx() { try { - var r = _dereq_; - var vertx = r('vertx'); + var vertx = Function('return this')().require('vertx'); vertxNext = vertx.runOnLoop || vertx.runOnContext; return useVertxTimer(); } catch (e) { @@ -28984,7 +29894,7 @@ function attemptVertx() { } } -var scheduleFlush = undefined; +var scheduleFlush = void 0; // Decide what async method to use to triggering processing of queued callbacks: if (isNode) { scheduleFlush = useNextTick(); @@ -28999,8 +29909,6 @@ if (isNode) { } function then(onFulfillment, onRejection) { - var _arguments = arguments; - var parent = this; var child = new this.constructor(noop); @@ -29011,13 +29919,12 @@ function then(onFulfillment, onRejection) { var _state = parent._state; + if (_state) { - (function () { - var callback = _arguments[_state - 1]; - asap(function () { - return invokeCallback(_state, child, callback, parent._result); - }); - })(); + var callback = arguments[_state - 1]; + asap(function () { + return invokeCallback(_state, child, callback, parent._result); + }); } else { subscribe(parent, child, onFulfillment, onRejection); } @@ -29069,7 +29976,7 @@ function resolve$1(object) { return promise; } -var PROMISE_ID = Math.random().toString(36).substring(16); +var PROMISE_ID = Math.random().toString(36).substring(2); function noop() {} @@ -29077,7 +29984,7 @@ var PENDING = void 0; var FULFILLED = 1; var REJECTED = 2; -var GET_THEN_ERROR = new ErrorObject(); +var TRY_CATCH_ERROR = { error: null }; function selfFulfillment() { return new TypeError("You cannot resolve a promise with itself"); @@ -29091,8 +29998,8 @@ function getThen(promise) { try { return promise.then; } catch (error) { - GET_THEN_ERROR.error = error; - return GET_THEN_ERROR; + TRY_CATCH_ERROR.error = error; + return TRY_CATCH_ERROR; } } @@ -29151,9 +30058,9 @@ function handleMaybeThenable(promise, maybeThenable, then$$1) { if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) { handleOwnThenable(promise, maybeThenable); } else { - if (then$$1 === GET_THEN_ERROR) { - reject(promise, GET_THEN_ERROR.error); - GET_THEN_ERROR.error = null; + if (then$$1 === TRY_CATCH_ERROR) { + reject(promise, TRY_CATCH_ERROR.error); + TRY_CATCH_ERROR.error = null; } else if (then$$1 === undefined) { fulfill(promise, maybeThenable); } else if (isFunction(then$$1)) { @@ -29209,6 +30116,7 @@ function subscribe(parent, child, onFulfillment, onRejection) { var _subscribers = parent._subscribers; var length = _subscribers.length; + parent._onerror = null; _subscribers[length] = child; @@ -29228,8 +30136,8 @@ function publish(promise) { return; } - var child = undefined, - callback = undefined, + var child = void 0, + callback = void 0, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { @@ -29246,12 +30154,6 @@ function publish(promise) { promise._subscribers.length = 0; } -function ErrorObject() { - this.error = null; -} - -var TRY_CATCH_ERROR = new ErrorObject(); - function tryCatch(callback, detail) { try { return callback(detail); @@ -29263,10 +30165,10 @@ function tryCatch(callback, detail) { function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), - value = undefined, - error = undefined, - succeeded = undefined, - failed = undefined; + value = void 0, + error = void 0, + succeeded = void 0, + failed = void 0; if (hasCallback) { value = tryCatch(callback, detail); @@ -29291,14 +30193,14 @@ function invokeCallback(settled, promise, callback, detail) { if (promise._state !== PENDING) { // noop } else if (hasCallback && succeeded) { - resolve(promise, value); - } else if (failed) { - reject(promise, error); - } else if (settled === FULFILLED) { - fulfill(promise, value); - } else if (settled === REJECTED) { - reject(promise, value); - } + resolve(promise, value); + } else if (failed) { + reject(promise, error); + } else if (settled === FULFILLED) { + fulfill(promise, value); + } else if (settled === REJECTED) { + reject(promise, value); + } } function initializePromise(promise, resolver) { @@ -29325,97 +30227,103 @@ function makePromise(promise) { promise._subscribers = []; } -function Enumerator$1(Constructor, input) { - this._instanceConstructor = Constructor; - this.promise = new Constructor(noop); +function validationError() { + return new Error('Array Methods must be provided an Array'); +} - if (!this.promise[PROMISE_ID]) { - makePromise(this.promise); - } +var Enumerator = function () { + function Enumerator(Constructor, input) { + this._instanceConstructor = Constructor; + this.promise = new Constructor(noop); - if (isArray(input)) { - this.length = input.length; - this._remaining = input.length; + if (!this.promise[PROMISE_ID]) { + makePromise(this.promise); + } - this._result = new Array(this.length); + if (isArray(input)) { + this.length = input.length; + this._remaining = input.length; - if (this.length === 0) { - fulfill(this.promise, this._result); - } else { - this.length = this.length || 0; - this._enumerate(input); - if (this._remaining === 0) { + this._result = new Array(this.length); + + if (this.length === 0) { fulfill(this.promise, this._result); + } else { + this.length = this.length || 0; + this._enumerate(input); + if (this._remaining === 0) { + fulfill(this.promise, this._result); + } } + } else { + reject(this.promise, validationError()); } - } else { - reject(this.promise, validationError()); } -} -function validationError() { - return new Error('Array Methods must be provided an Array'); -} + Enumerator.prototype._enumerate = function _enumerate(input) { + for (var i = 0; this._state === PENDING && i < input.length; i++) { + this._eachEntry(input[i], i); + } + }; -Enumerator$1.prototype._enumerate = function (input) { - for (var i = 0; this._state === PENDING && i < input.length; i++) { - this._eachEntry(input[i], i); - } -}; + Enumerator.prototype._eachEntry = function _eachEntry(entry, i) { + var c = this._instanceConstructor; + var resolve$$1 = c.resolve; -Enumerator$1.prototype._eachEntry = function (entry, i) { - var c = this._instanceConstructor; - var resolve$$1 = c.resolve; - if (resolve$$1 === resolve$1) { - var _then = getThen(entry); + if (resolve$$1 === resolve$1) { + var _then = getThen(entry); - if (_then === then && entry._state !== PENDING) { - this._settledAt(entry._state, i, entry._result); - } else if (typeof _then !== 'function') { - this._remaining--; - this._result[i] = entry; - } else if (c === Promise$2) { - var promise = new c(noop); - handleMaybeThenable(promise, entry, _then); - this._willSettleAt(promise, i); + if (_then === then && entry._state !== PENDING) { + this._settledAt(entry._state, i, entry._result); + } else if (typeof _then !== 'function') { + this._remaining--; + this._result[i] = entry; + } else if (c === Promise$1) { + var promise = new c(noop); + handleMaybeThenable(promise, entry, _then); + this._willSettleAt(promise, i); + } else { + this._willSettleAt(new c(function (resolve$$1) { + return resolve$$1(entry); + }), i); + } } else { - this._willSettleAt(new c(function (resolve$$1) { - return resolve$$1(entry); - }), i); + this._willSettleAt(resolve$$1(entry), i); } - } else { - this._willSettleAt(resolve$$1(entry), i); - } -}; + }; -Enumerator$1.prototype._settledAt = function (state, i, value) { - var promise = this.promise; + Enumerator.prototype._settledAt = function _settledAt(state, i, value) { + var promise = this.promise; - if (promise._state === PENDING) { - this._remaining--; - if (state === REJECTED) { - reject(promise, value); - } else { - this._result[i] = value; + if (promise._state === PENDING) { + this._remaining--; + + if (state === REJECTED) { + reject(promise, value); + } else { + this._result[i] = value; + } } - } - if (this._remaining === 0) { - fulfill(promise, this._result); - } -}; + if (this._remaining === 0) { + fulfill(promise, this._result); + } + }; -Enumerator$1.prototype._willSettleAt = function (promise, i) { - var enumerator = this; + Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) { + var enumerator = this; - subscribe(promise, undefined, function (value) { - return enumerator._settledAt(FULFILLED, i, value); - }, function (reason) { - return enumerator._settledAt(REJECTED, i, reason); - }); -}; + subscribe(promise, undefined, function (value) { + return enumerator._settledAt(FULFILLED, i, value); + }, function (reason) { + return enumerator._settledAt(REJECTED, i, reason); + }); + }; + + return Enumerator; +}(); /** `Promise.all` accepts an array of promises, and returns a new promise which @@ -29464,8 +30372,8 @@ Enumerator$1.prototype._willSettleAt = function (promise, i) { fulfilled, or rejected if any of them become rejected. @static */ -function all$1(entries) { - return new Enumerator$1(this, entries).promise; +function all(entries) { + return new Enumerator(this, entries).promise; } /** @@ -29533,7 +30441,7 @@ function all$1(entries) { @return {Promise} a promise which settles in the same way as the first passed promise to settle. */ -function race$1(entries) { +function race(entries) { /*jshint validthis:true */ var Constructor = this; @@ -29700,305 +30608,332 @@ function needsNew() { ``` @class Promise - @param {function} resolver + @param {Function} resolver Useful for tooling. @constructor */ -function Promise$2(resolver) { - this[PROMISE_ID] = nextId(); - this._result = this._state = undefined; - this._subscribers = []; - - if (noop !== resolver) { - typeof resolver !== 'function' && needsResolver(); - this instanceof Promise$2 ? initializePromise(this, resolver) : needsNew(); - } -} -Promise$2.all = all$1; -Promise$2.race = race$1; -Promise$2.resolve = resolve$1; -Promise$2.reject = reject$1; -Promise$2._setScheduler = setScheduler; -Promise$2._setAsap = setAsap; -Promise$2._asap = asap; +var Promise$1 = function () { + function Promise(resolver) { + this[PROMISE_ID] = nextId(); + this._result = this._state = undefined; + this._subscribers = []; -Promise$2.prototype = { - constructor: Promise$2, + if (noop !== resolver) { + typeof resolver !== 'function' && needsResolver(); + this instanceof Promise ? initializePromise(this, resolver) : needsNew(); + } + } /** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. - - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` - - Chaining - -------- - - The return value of `then` is itself a promise. This second, 'downstream' - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. - - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return 'default name'; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `'default name'` - }); - - findUser().then(function (user) { - throw new Error('Found user, but still unhappy'); - }, function (reason) { - throw new Error('`findUser` rejected and we're unhappy'); - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. - // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. - - ```js - findUser().then(function (user) { - throw new PedagogicalException('Upstream error'); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` - - Assimilation - ------------ - - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` - - If the assimliated promise rejects, then the downstream promise will also reject. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` - - Simple Example - -------------- - - Synchronous Example - - ```javascript - let result; - - try { - result = findResult(); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - findResult(function(result, err){ - if (err) { - // failure - } else { - // success - } - }); - ``` - - Promise Example; - - ```javascript - findResult().then(function(result){ - // success - }, function(reason){ + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + Chaining + -------- + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + Assimilation + ------------ + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + If the assimliated promise rejects, then the downstream promise will also reject. + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + Simple Example + -------------- + Synchronous Example + ```javascript + let result; + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + Errback Example + ```js + findResult(function(result, err){ + if (err) { // failure - }); - ``` - - Advanced Example - -------------- - - Synchronous Example - - ```javascript - let author, books; - - try { - author = findAuthor(); - books = findBooksByAuthor(author); + } else { // success - } catch(reason) { - // failure } - ``` - - Errback Example - - ```js - - function foundBooks(books) { - - } - - function failure(reason) { - - } - - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure - } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } + }); + ``` + Promise Example; + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + Advanced Example + -------------- + Synchronous Example + ```javascript + let author, books; + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + Errback Example + ```js + function foundBooks(books) { + } + function failure(reason) { + } + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); } - }); - } catch(error) { - failure(err); - } - // success + } + }); + } catch(error) { + failure(err); } - }); - ``` - - Promise Example; - - ```javascript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong - }); - ``` - - @method then - @param {Function} onFulfilled - @param {Function} onRejected - Useful for tooling. - @return {Promise} + // success + } + }); + ``` + Promise Example; + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} */ - then: then, + + + Promise.prototype.catch = function _catch(onRejection) { + return this.then(null, onRejection); + }; /** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. + `finally` will be invoked regardless of the promise's fate just as native + try/catch/finally behaves + + Synchronous example: ```js - function findAuthor(){ - throw new Error('couldn't find that author'); + findAuthor() { + if (Math.random() > 0.5) { + throw new Error(); + } + return new Author(); } - // synchronous try { - findAuthor(); - } catch(reason) { - // something went wrong + return findAuthor(); // succeed or fail + } catch(error) { + return findOtherAuther(); + } finally { + // always runs + // doesn't affect the return value } + ``` + + Asynchronous example: - // async with promises + ```js findAuthor().catch(function(reason){ - // something went wrong + return findOtherAuther(); + }).finally(function(){ + // author was either found, or not }); ``` - @method catch - @param {Function} onRejection - Useful for tooling. + @method finally + @param {Function} callback @return {Promise} */ - 'catch': function _catch(onRejection) { - return this.then(null, onRejection); - } -}; + + + Promise.prototype.finally = function _finally(callback) { + var promise = this; + var constructor = promise.constructor; + + if (isFunction(callback)) { + return promise.then(function (value) { + return constructor.resolve(callback()).then(function () { + return value; + }); + }, function (reason) { + return constructor.resolve(callback()).then(function () { + throw reason; + }); + }); + } + + return promise.then(callback, callback); + }; + + return Promise; +}(); + +Promise$1.prototype.then = then; +Promise$1.all = all; +Promise$1.race = race; +Promise$1.resolve = resolve$1; +Promise$1.reject = reject$1; +Promise$1._setScheduler = setScheduler; +Promise$1._setAsap = setAsap; +Promise$1._asap = asap; /*global self*/ -function polyfill$1() { - var local = undefined; +function polyfill() { + var local = void 0; - if (typeof global !== 'undefined') { - local = global; - } else if (typeof self !== 'undefined') { - local = self; - } else { - try { - local = Function('return this')(); - } catch (e) { - throw new Error('polyfill failed because global object is unavailable in this environment'); - } + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); } + } - var P = local.Promise; + var P = local.Promise; - if (P) { - var promiseToString = null; - try { - promiseToString = Object.prototype.toString.call(P.resolve()); - } catch (e) { - // silently ignored - } + if (P) { + var promiseToString = null; + try { + promiseToString = Object.prototype.toString.call(P.resolve()); + } catch (e) { + // silently ignored + } - if (promiseToString === '[object Promise]' && !P.cast) { - return; - } + if (promiseToString === '[object Promise]' && !P.cast) { + return; } + } - local.Promise = Promise$2; + local.Promise = Promise$1; } // Strange compat.. -Promise$2.polyfill = polyfill$1; -Promise$2.Promise = Promise$2; +Promise$1.polyfill = polyfill; +Promise$1.Promise = Promise$1; -return Promise$2; +return Promise$1; }))); + + }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":12}],6:[function(_dereq_,module,exports){ +},{"_process":11}],6:[function(_dereq_,module,exports){ (function (global, factory) { if (typeof define === 'function' && define.amd) { define(['exports', 'module'], factory); @@ -30315,7 +31250,7 @@ if (typeof module !== "undefined" && module.exports) { },{}],8:[function(_dereq_,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m - var eLen = nBytes * 8 - mLen - 1 + var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 @@ -30328,12 +31263,12 @@ exports.read = function (buffer, offset, isLE, mLen, nBytes) { e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias @@ -30348,7 +31283,7 @@ exports.read = function (buffer, offset, isLE, mLen, nBytes) { exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c - var eLen = nBytes * 8 - mLen - 1 + var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) @@ -30381,7 +31316,7 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { m = 0 e = eMax } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen) + m = ((value * c) - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) @@ -30399,13 +31334,6 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { } },{}],9:[function(_dereq_,module,exports){ -var toString = {}.toString; - -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; - -},{}],10:[function(_dereq_,module,exports){ /* Copyright 2000, Silicon Graphics, Inc. All Rights Reserved. @@ -30465,7 +31393,7 @@ function W(a,b){for(var c=a.d,d=a.e,e=a.c,f=b,g=c[f];;){var h=f<<1;h= 200 && this.status < 300 this.statusText = 'statusText' in options ? options.statusText : 'OK' this.headers = new Headers(options.headers) @@ -43581,6 +44512,8 @@ process.umask = function() { return 0; }; if (request.credentials === 'include') { xhr.withCredentials = true + } else if (request.credentials === 'omit') { + xhr.withCredentials = false } if ('responseType' in xhr && support.blob) { @@ -43597,7 +44530,7 @@ process.umask = function() { return 0; }; self.fetch.polyfill = true })(typeof self !== 'undefined' ? self : this); -},{}],14:[function(_dereq_,module,exports){ +},{}],13:[function(_dereq_,module,exports){ 'use strict'; // core @@ -43687,7 +44620,7 @@ _dereq_('./core/init'); module.exports = p5; -},{"./color/color_conversion":15,"./color/creating_reading":16,"./color/p5.Color":17,"./color/setting":18,"./core/constants":19,"./core/environment":20,"./core/error_helpers":21,"./core/helpers":22,"./core/init":23,"./core/legacy":24,"./core/main":25,"./core/p5.Element":26,"./core/p5.Graphics":27,"./core/p5.Renderer":28,"./core/p5.Renderer2D":29,"./core/rendering":30,"./core/shape/2d_primitives":31,"./core/shape/attributes":32,"./core/shape/curves":33,"./core/shape/vertex":34,"./core/shim":35,"./core/structure":36,"./core/transform":37,"./data/p5.TypedDict":38,"./events/acceleration":39,"./events/keyboard":40,"./events/mouse":41,"./events/touch":42,"./image/filters":43,"./image/image":44,"./image/loading_displaying":45,"./image/p5.Image":46,"./image/pixels":47,"./io/files":48,"./io/p5.Table":49,"./io/p5.TableRow":50,"./io/p5.XML":51,"./math/calculation":52,"./math/math":53,"./math/noise":54,"./math/p5.Vector":55,"./math/random":56,"./math/trigonometry":57,"./typography/attributes":58,"./typography/loading_displaying":59,"./typography/p5.Font":60,"./utilities/array_functions":61,"./utilities/conversion":62,"./utilities/string_functions":63,"./utilities/time_date":64,"./webgl/3d_primitives":65,"./webgl/interaction":66,"./webgl/light":67,"./webgl/loading":68,"./webgl/material":69,"./webgl/p5.Camera":70,"./webgl/p5.Geometry":71,"./webgl/p5.Matrix":72,"./webgl/p5.RendererGL":75,"./webgl/p5.RendererGL.Immediate":73,"./webgl/p5.RendererGL.Retained":74,"./webgl/p5.Shader":76,"./webgl/p5.Texture":77,"./webgl/text":78}],15:[function(_dereq_,module,exports){ +},{"./color/color_conversion":14,"./color/creating_reading":15,"./color/p5.Color":16,"./color/setting":17,"./core/constants":18,"./core/environment":19,"./core/error_helpers":20,"./core/helpers":21,"./core/init":22,"./core/legacy":23,"./core/main":24,"./core/p5.Element":25,"./core/p5.Graphics":26,"./core/p5.Renderer":27,"./core/p5.Renderer2D":28,"./core/rendering":29,"./core/shape/2d_primitives":30,"./core/shape/attributes":31,"./core/shape/curves":32,"./core/shape/vertex":33,"./core/shim":34,"./core/structure":35,"./core/transform":36,"./data/p5.TypedDict":37,"./events/acceleration":38,"./events/keyboard":39,"./events/mouse":40,"./events/touch":41,"./image/filters":42,"./image/image":43,"./image/loading_displaying":44,"./image/p5.Image":45,"./image/pixels":46,"./io/files":47,"./io/p5.Table":48,"./io/p5.TableRow":49,"./io/p5.XML":50,"./math/calculation":51,"./math/math":52,"./math/noise":53,"./math/p5.Vector":54,"./math/random":55,"./math/trigonometry":56,"./typography/attributes":57,"./typography/loading_displaying":58,"./typography/p5.Font":59,"./utilities/array_functions":60,"./utilities/conversion":61,"./utilities/string_functions":62,"./utilities/time_date":63,"./webgl/3d_primitives":64,"./webgl/interaction":65,"./webgl/light":66,"./webgl/loading":67,"./webgl/material":68,"./webgl/p5.Camera":69,"./webgl/p5.Geometry":70,"./webgl/p5.Matrix":71,"./webgl/p5.RendererGL":74,"./webgl/p5.RendererGL.Immediate":72,"./webgl/p5.RendererGL.Retained":73,"./webgl/p5.Shader":75,"./webgl/p5.Texture":76,"./webgl/text":77}],14:[function(_dereq_,module,exports){ /** * @module Color * @submodule Color Conversion @@ -43962,7 +44895,7 @@ p5.ColorConversion._rgbaToHSLA = function(rgba) { module.exports = p5.ColorConversion; -},{"../core/main":25}],16:[function(_dereq_,module,exports){ +},{"../core/main":24}],15:[function(_dereq_,module,exports){ /** * @module Color * @submodule Creating & Reading @@ -43989,10 +44922,10 @@ _dereq_('../core/error_helpers'); *
* * noStroke(); - * var c = color(0, 126, 255, 102); + * let c = color(0, 126, 255, 102); * fill(c); * rect(15, 15, 35, 70); - * var value = alpha(c); // Sets 'value' to 102 + * let value = alpha(c); // Sets 'value' to 102 * fill(value); * rect(50, 15, 35, 70); * @@ -44004,7 +44937,7 @@ _dereq_('../core/error_helpers'); * Left half of canvas salmon pink and the right half white. * Yellow rect in middle right of canvas, with 55 pixel width and height. * Yellow ellipse in top left canvas, black ellipse in bottom right,both 80x80. - * Bright fuschia rect in middle of canvas, 60 pixel width and height. + * Bright fuchsia rect in middle of canvas, 60 pixel width and height. * Two bright green rects on opposite sides of the canvas, both 45x80. * Four blue rects in each corner of the canvas, each are 35x35. * Bright sea green rect on left and darker rect on right of canvas, both 45x80. @@ -44033,11 +44966,11 @@ p5.prototype.alpha = function(c) { * @example *
* - * var c = color(175, 100, 220); // Define color 'c' + * let c = color(175, 100, 220); // Define color 'c' * fill(c); // Use color variable 'c' as fill color * rect(15, 20, 35, 60); // Draw left rectangle * - * var blueValue = blue(c); // Get blue in 'c' + * let blueValue = blue(c); // Get blue in 'c' * print(blueValue); // Prints "220.0" * fill(0, 0, blueValue); // Use 'blueValue' in new fill * rect(50, 20, 35, 60); // Draw right rectangle @@ -44065,10 +44998,22 @@ p5.prototype.blue = function(c) { * * noStroke(); * colorMode(HSB, 255); - * var c = color(0, 126, 255); + * let c = color(0, 126, 255); + * fill(c); + * rect(15, 20, 35, 60); + * let value = brightness(c); // Sets 'value' to 255 + * fill(value); + * rect(50, 20, 35, 60); + * + *
+ *
+ * + * noStroke(); + * colorMode(HSB, 255); + * let c = color('hsb(60, 100%, 50%)'); * fill(c); * rect(15, 20, 35, 60); - * var value = brightness(c); // Sets 'value' to 255 + * let value = brightness(c); // A 'value' of 50% is 127.5 * fill(value); * rect(50, 20, 35, 60); * @@ -44076,6 +45021,7 @@ p5.prototype.blue = function(c) { * * @alt * Left half of canvas salmon pink and the right half white. + * Left half of canvas yellow at half brightness and the right gray . * */ p5.prototype.brightness = function(c) { @@ -44111,7 +45057,7 @@ p5.prototype.brightness = function(c) { * @example *
* - * var c = color(255, 204, 0); // Define color 'c' + * let c = color(255, 204, 0); // Define color 'c' * fill(c); // Use color variable 'c' as fill color * noStroke(); // Don't draw a stroke around shapes * rect(30, 20, 55, 55); // Draw rectangle @@ -44120,7 +45066,7 @@ p5.prototype.brightness = function(c) { * *
* - * var c = color(255, 204, 0); // Define color 'c' + * let c = color(255, 204, 0); // Define color 'c' * fill(c); // Use color variable 'c' as fill color * noStroke(); // Don't draw a stroke around shapes * ellipse(25, 25, 80, 80); // Draw left circle @@ -44136,7 +45082,7 @@ p5.prototype.brightness = function(c) { *
* * // Named SVG & CSS colors may be used, - * var c = color('magenta'); + * let c = color('magenta'); * fill(c); // Use 'c' as fill color * noStroke(); // Don't draw a stroke around shapes * rect(20, 20, 60, 60); // Draw rectangle @@ -44147,7 +45093,7 @@ p5.prototype.brightness = function(c) { * * // as can hex color codes: * noStroke(); // Don't draw a stroke around shapes - * var c = color('#0f0'); + * let c = color('#0f0'); * fill(c); // Use 'c' as fill color * rect(0, 10, 45, 80); // Draw rectangle * @@ -44161,7 +45107,7 @@ p5.prototype.brightness = function(c) { * * // RGB and RGBA color strings are also supported: * // these all set to the same color (solid blue) - * var c; + * let c; * noStroke(); // Don't draw a stroke around shapes * c = color('rgb(0,0,255)'); * fill(c); // Use 'c' as fill color @@ -44185,7 +45131,7 @@ p5.prototype.brightness = function(c) { * * // HSL color is also supported and can be specified * // by value - * var c; + * let c; * noStroke(); // Don't draw a stroke around shapes * c = color('hsl(160, 100%, 50%)'); * fill(c); // Use 'c' as fill color @@ -44201,7 +45147,7 @@ p5.prototype.brightness = function(c) { * * // HSB color is also supported and can be specified * // by value - * var c; + * let c; * noStroke(); // Don't draw a stroke around shapes * c = color('hsb(160, 100%, 50%)'); * fill(c); // Use 'c' as fill color @@ -44215,7 +45161,7 @@ p5.prototype.brightness = function(c) { * *
* - * var c; // Declare color 'c' + * let c; // Declare color 'c' * noStroke(); // Don't draw a stroke around shapes * * // If no colorMode is specified, then the @@ -44234,7 +45180,7 @@ p5.prototype.brightness = function(c) { * @alt * Yellow rect in middle right of canvas, with 55 pixel width and height. * Yellow ellipse in top left of canvas, black ellipse in bottom right,both 80x80. - * Bright fuschia rect in middle of canvas, 60 pixel width and height. + * Bright fuchsia rect in middle of canvas, 60 pixel width and height. * Two bright green rects on opposite sides of the canvas, both 45x80. * Four blue rects in each corner of the canvas, each are 35x35. * Bright sea green rect on left and darker rect on right of canvas, both 45x80. @@ -44291,11 +45237,11 @@ p5.prototype.color = function() { * @example *
* - * var c = color(20, 75, 200); // Define color 'c' + * 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 * - * var greenValue = green(c); // Get green in 'c' + * 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 @@ -44330,10 +45276,10 @@ p5.prototype.green = function(c) { * * noStroke(); * colorMode(HSB, 255); - * var c = color(0, 126, 255); + * let c = color(0, 126, 255); * fill(c); * rect(15, 20, 35, 60); - * var value = hue(c); // Sets 'value' to "0" + * let value = hue(c); // Sets 'value' to "0" * fill(value); * rect(50, 20, 35, 60); * @@ -44371,11 +45317,11 @@ p5.prototype.hue = function(c) { * colorMode(RGB); * stroke(255); * background(51); - * var from = color(218, 165, 32); - * var to = color(72, 61, 139); + * let from = color(218, 165, 32); + * let to = color(72, 61, 139); * colorMode(RGB); // Try changing to HSB. - * var interA = lerpColor(from, to, 0.33); - * var interB = lerpColor(from, to, 0.66); + * let interA = lerpColor(from, to, 0.33); + * let interB = lerpColor(from, to, 0.66); * fill(from); * rect(10, 20, 20, 60); * fill(interA); @@ -44458,10 +45404,10 @@ p5.prototype.lerpColor = function(c1, c2, amt) { * * noStroke(); * colorMode(HSL); - * var c = color(156, 100, 50, 1); + * let c = color(156, 100, 50, 1); * fill(c); * rect(15, 20, 35, 60); - * var value = lightness(c); // Sets 'value' to 50 + * let value = lightness(c); // Sets 'value' to 50 * fill(value); * rect(50, 20, 35, 60); * @@ -44486,24 +45432,24 @@ p5.prototype.lightness = function(c) { * @example *
* - * var c = color(255, 204, 0); // Define color 'c' + * 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 * - * var redValue = red(c); // Get red in 'c' + * let redValue = red(c); // Get red in 'c' * print(redValue); // Print "255.0" * fill(redValue, 0, 0); // Use 'redValue' in new fill * rect(50, 20, 35, 60); // Draw right rectangle * *
* - *
+ *
* - * colorMode(RGB, 255); - * var c = color(127, 255, 0); - * colorMode(RGB, 1); - * var myColor = red(c); - * print(myColor); + * 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 * *
* @@ -44533,10 +45479,10 @@ p5.prototype.red = function(c) { * * noStroke(); * colorMode(HSB, 255); - * var c = color(0, 126, 255); + * let c = color(0, 126, 255); * fill(c); * rect(15, 20, 35, 60); - * var value = saturation(c); // Sets 'value' to 126 + * let value = saturation(c); // Sets 'value' to 126 * fill(value); * rect(50, 20, 35, 60); * @@ -44554,7 +45500,7 @@ p5.prototype.saturation = function(c) { module.exports = p5; -},{"../core/constants":19,"../core/error_helpers":21,"../core/main":25,"./p5.Color":17}],17:[function(_dereq_,module,exports){ +},{"../core/constants":18,"../core/error_helpers":20,"../core/main":24,"./p5.Color":16}],16:[function(_dereq_,module,exports){ /** * @module Color * @submodule Creating & Reading @@ -44620,7 +45566,7 @@ p5.Color = function(pInst, vals) { * @example *
* - * var myColor; + * let myColor; * function setup() { * createCanvas(200, 200); * stroke(255); @@ -44641,9 +45587,6 @@ p5.Color = function(pInst, vals) { * canvas with text representation of color */ p5.Color.prototype.toString = function(format) { - if (!this.hsba) this.hsba = color_conversion._rgbaToHSBA(this._array); - if (!this.hsla) this.hsla = color_conversion._rgbaToHSLA(this._array); - var a = this.levels; var f = this._array; var alpha = f[3]; // String representation uses normalized alpha @@ -44706,6 +45649,7 @@ p5.Color.prototype.toString = function(format) { case 'hsb': case 'hsv': + if (!this.hsba) this.hsba = color_conversion._rgbaToHSBA(this._array); return 'hsb('.concat( this.hsba[0] * this.maxes[constants.HSB][0], ', ', @@ -44717,6 +45661,7 @@ p5.Color.prototype.toString = function(format) { case 'hsb%': case 'hsv%': + if (!this.hsba) this.hsba = color_conversion._rgbaToHSBA(this._array); return 'hsb('.concat( (100 * this.hsba[0]).toPrecision(3), '%, ', @@ -44728,6 +45673,7 @@ p5.Color.prototype.toString = function(format) { case 'hsba': case 'hsva': + if (!this.hsba) this.hsba = color_conversion._rgbaToHSBA(this._array); return 'hsba('.concat( this.hsba[0] * this.maxes[constants.HSB][0], ', ', @@ -44741,6 +45687,7 @@ p5.Color.prototype.toString = function(format) { case 'hsba%': case 'hsva%': + if (!this.hsba) this.hsba = color_conversion._rgbaToHSBA(this._array); return 'hsba('.concat( (100 * this.hsba[0]).toPrecision(3), '%, ', @@ -44753,6 +45700,7 @@ p5.Color.prototype.toString = function(format) { ); case 'hsl': + if (!this.hsla) this.hsla = color_conversion._rgbaToHSLA(this._array); return 'hsl('.concat( this.hsla[0] * this.maxes[constants.HSL][0], ', ', @@ -44763,6 +45711,7 @@ p5.Color.prototype.toString = function(format) { ); case 'hsl%': + if (!this.hsla) this.hsla = color_conversion._rgbaToHSLA(this._array); return 'hsl('.concat( (100 * this.hsla[0]).toPrecision(3), '%, ', @@ -44773,6 +45722,7 @@ p5.Color.prototype.toString = function(format) { ); case 'hsla': + if (!this.hsla) this.hsla = color_conversion._rgbaToHSLA(this._array); return 'hsla('.concat( this.hsla[0] * this.maxes[constants.HSL][0], ', ', @@ -44785,6 +45735,7 @@ p5.Color.prototype.toString = function(format) { ); case 'hsla%': + if (!this.hsla) this.hsla = color_conversion._rgbaToHSLA(this._array); return 'hsl('.concat( (100 * this.hsla[0]).toPrecision(3), '%, ', @@ -44798,7 +45749,7 @@ p5.Color.prototype.toString = function(format) { case 'rgba': default: - return 'rgba(' + a[0] + ',' + a[1] + ',' + a[2] + ',' + alpha + ')'; + return 'rgba('.concat(a[0], ',', a[1], ',', a[2], ',', alpha, ')'); } }; @@ -44808,7 +45759,7 @@ p5.Color.prototype.toString = function(format) { * @example *
* - * var backgroundColor; + * let backgroundColor; * * function setup() { * backgroundColor = color(100, 50, 150); @@ -44835,7 +45786,7 @@ p5.Color.prototype.setRed = function(new_red) { * @example *
* - * var backgroundColor; + * let backgroundColor; * * function setup() { * backgroundColor = color(100, 50, 150); @@ -44862,7 +45813,7 @@ p5.Color.prototype.setGreen = function(new_green) { * @example *
* - * var backgroundColor; + * let backgroundColor; * * function setup() { * backgroundColor = color(100, 50, 150); @@ -44889,7 +45840,7 @@ p5.Color.prototype.setBlue = function(new_blue) { * @example *
* - * var squareColor; + * let squareColor; * * function setup() { * ellipseMode(CORNERS); @@ -45572,7 +46523,7 @@ p5.Color._parseInputs = function(r, g, b, a) { module.exports = p5.Color; -},{"../core/constants":19,"../core/main":25,"./color_conversion":15}],18:[function(_dereq_,module,exports){ +},{"../core/constants":18,"../core/main":24,"./color_conversion":14}],17:[function(_dereq_,module,exports){ /** * @module Color * @submodule Setting @@ -45589,7 +46540,7 @@ _dereq_('./p5.Color'); /** * The background() function sets the color used for the background of the - * p5.js canvas. The default background is light gray. This function is + * 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. @@ -45734,7 +46685,7 @@ _dereq_('./p5.Color'); /** * @method background - * @param {Number[]} values an array containing the red,green,blue & + * @param {Number[]} values an array containing the red, green, blue * and alpha components of the color * @chainable */ @@ -45749,19 +46700,16 @@ _dereq_('./p5.Color'); */ p5.prototype.background = function() { - if (arguments[0] instanceof p5.Image) { - this.image(arguments[0], 0, 0, this.width, this.height); - } else { - this._renderer.background.apply(this._renderer, arguments); - } + this._renderer.background.apply(this._renderer, arguments); return this; }; /** - * Clears the pixels within a buffer. This function only works on p5.Canvas - * objects created with the createCanvas() function; it won't work with the - * main display window. Unlike the main graphics context, pixels in - * additional graphics areas created with createGraphics() can be entirely + * 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. * @@ -45819,8 +46767,8 @@ p5.prototype.clear = function() { * * noStroke(); * colorMode(RGB, 100); - * for (var i = 0; i < 100; i++) { - * for (var j = 0; j < 100; j++) { + * for (let i = 0; i < 100; i++) { + * for (let j = 0; j < 100; j++) { * stroke(i, j, 0); * point(i, j); * } @@ -45832,8 +46780,8 @@ p5.prototype.clear = function() { * * noStroke(); * colorMode(HSB, 100); - * for (var i = 0; i < 100; i++) { - * for (var j = 0; j < 100; j++) { + * for (let i = 0; i < 100; i++) { + * for (let j = 0; j < 100; j++) { * stroke(i, j, 100); * point(i, j); * } @@ -45844,10 +46792,10 @@ p5.prototype.clear = function() { *
* * colorMode(RGB, 255); - * var c = color(127, 255, 0); + * let c = color(127, 255, 0); * * colorMode(RGB, 1); - * var myColor = c._getRed(); + * let myColor = c._getRed(); * text(myColor, 10, 10, 80, 80); * *
@@ -45869,7 +46817,7 @@ p5.prototype.clear = function() { *Green to red gradient from bottom L to top R. shading originates from top left. *Rainbow gradient from left to right. Brightness increasing to white at top. *unknown image. - *50x50 ellipse at middle L & 40x40 ellipse at center. Transluscent pink outlines. + *50x50 ellipse at middle L & 40x40 ellipse at center. Translucent pink outlines. * */ /** @@ -45879,7 +46827,7 @@ p5.prototype.clear = function() { * current color mode * @param {Number} max2 range for the green or saturation depending * on the current color mode - * @param {Number} max3 range for the blue or brightness/lighntess + * @param {Number} max3 range for the blue or brightness/lightness * depending on the current color mode * @param {Number} [maxA] range for the alpha * @chainable @@ -46037,7 +46985,7 @@ p5.prototype.colorMode = function(mode, max1, max2, max3, maxA) { * 60x60 light green rect with black outline in center of canvas. * 60x60 soft green rect with black outline in center of canvas. * 60x60 red rect with black outline in center of canvas. - * 60x60 dark fushcia rect with black outline in center of canvas. + * 60x60 dark fuchsia rect with black outline in center of canvas. * 60x60 blue rect with black outline in center of canvas. */ @@ -46289,7 +47237,7 @@ p5.prototype.noStroke = function() { * 60x60 white rect at center. Bright green outline. * 60x60 white rect at center. Soft green outline. * 60x60 white rect at center. Red outline. - * 60x60 white rect at center. Dark fushcia outline. + * 60x60 white rect at center. Dark fuchsia outline. * 60x60 white rect at center. Blue outline. */ @@ -46328,7 +47276,7 @@ p5.prototype.stroke = function() { module.exports = p5; -},{"../core/constants":19,"../core/main":25,"./p5.Color":17}],19:[function(_dereq_,module,exports){ +},{"../core/constants":18,"../core/main":24,"./p5.Color":16}],18:[function(_dereq_,module,exports){ /** * @module Constants * @submodule Constants @@ -46679,6 +47627,10 @@ module.exports = { // DOM EXTENSION /** + * AUTO allows us to automatically set the width or height of an element (but not both), + * based on the current height and width of the element. Only one parameter can + * be passed to the size function as AUTO, at a time. + * * @property {String} AUTO * @final */ @@ -46731,6 +47683,11 @@ module.exports = { * @final */ DIFFERENCE: 'difference', + /** + * @property {String} SUBTRACT + * @final + */ + SUBTRACT: 'subtract', /** * @property {String} EXCLUSION * @final @@ -46838,6 +47795,11 @@ module.exports = { * @final */ BOLD: 'bold', + /** + * @property {String} BOLDITALIC + * @final + */ + BOLDITALIC: 'bold italic', // TYPOGRAPHY-INTERNAL _DEFAULT_TEXT_FILL: '#000000', @@ -46856,7 +47818,15 @@ module.exports = { TEXTURE: 'texture', IMMEDIATE: 'immediate', - //WEBGL TEXTURE WRAP AND FILTERING + // WEBGL TEXTURE MODE + // NORMAL already exists for typography + /** + * @property {String} IMAGE + * @final + */ + IMAGE: 'image', + + // WEBGL TEXTURE WRAP AND FILTERING // LINEAR already exists above NEAREST: 'nearest', REPEAT: 'repeat', @@ -46892,7 +47862,7 @@ module.exports = { AXES: 'axes' }; -},{}],20:[function(_dereq_,module,exports){ +},{}],19:[function(_dereq_,module,exports){ /** * @module Environment * @submodule Environment @@ -46921,12 +47891,16 @@ var _windowPrint = window.print; * the function. Individual elements can be * separated with quotes ("") and joined with the addition operator (+). * + * Note that calling print() without any arguments invokes the window.print() + * function which opens the browser's print dialog. To print a blank line + * to console you can write print('\n'). + * * @method print * @param {Any} contents any combination of Number, String, Object, Boolean, * Array to print * @example *
- * var x = 10; + * let x = 10; * print('The value of x is ' + x); * // prints "The value of x is 10" *
@@ -47007,26 +47981,36 @@ p5.prototype.focused = document.hasFocus(); * must be less than the dimensions of the image. * * @method cursor - * @param {String|Constant} type either ARROW, CROSS, HAND, MOVE, TEXT, or - * WAIT, or path for image - * @param {Number} [x] the horizontal active spot of the cursor - * @param {Number} [y] the vertical active spot of the cursor + * @param {String|Constant} type Built-In: either ARROW, CROSS, HAND, MOVE, TEXT and WAIT + * Native CSS properties: 'grab', 'progress', 'cell' etc. + * External: path for cursor's images + * (Allowed File extensions: .cur, .gif, .jpg, .jpeg, .png) + * For more information on Native CSS cursors and url visit: + * https://developer.mozilla.org/en-US/docs/Web/CSS/cursor + * @param {Number} [x] the horizontal active spot of the cursor (must be less than 32) + * @param {Number} [y] the vertical active spot of the cursor (must be less than 32) * @example *
- * // Move the mouse left and right across the image - * // to see the cursor change from a cross to a hand + * // Move the mouse across the quadrants + * // to see the cursor change * function draw() { * line(width / 2, 0, width / 2, height); - * if (mouseX < 50) { + * line(0, height / 2, width, height / 2); + * if (mouseX < 50 && mouseY < 50) { * cursor(CROSS); + * } else if (mouseX > 50 && mouseY < 50) { + * cursor('progress'); + * } else if (mouseX > 50 && mouseY > 50) { + * cursor('https://s3.amazonaws.com/mupublicdata/cursor.cur'); * } else { - * cursor(HAND); + * cursor('grab'); * } * } *
* * @alt - * horizontal line divides canvas. cursor on left is a cross, right is hand. + * 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. * */ p5.prototype.cursor = function(type, x, y) { @@ -47084,9 +48068,9 @@ p5.prototype.cursor = function(type, x, y) { * @example * *
- * var rectX = 0; - * var fr = 30; //starting FPS - * var clr; + * let rectX = 0; + * let fr = 30; //starting FPS + * let clr; * * function setup() { * background(200); @@ -47130,7 +48114,6 @@ p5.prototype.frameRate = function(fps) { return this._frameRate; } else { this._setProperty('_targetFrameRate', fps); - this._runFrames(); return this; } }; @@ -47353,7 +48336,7 @@ p5.prototype.height = 0; * } * function mousePressed() { * if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { - * var fs = fullscreen(); + * let fs = fullscreen(); * fullscreen(!fs); * } * } @@ -47448,7 +48431,7 @@ p5.prototype.pixelDensity = function(val) { *
* * function setup() { - * var density = displayDensity(); + * let density = displayDensity(); * pixelDensity(density); * createCanvas(100, 100); * background(200); @@ -47503,8 +48486,8 @@ function exitFullscreen() { * @example *
* - * var url; - * var x = 100; + * let url; + * let x = 100; * * function setup() { * fill(0); @@ -47534,8 +48517,8 @@ p5.prototype.getURL = function() { * @example *
* function setup() { - * var urlPath = getURLPath(); - * for (var i = 0; i < urlPath.length; i++) { + * let urlPath = getURLPath(); + * for (let i = 0; i < urlPath.length; i++) { * text(urlPath[i], 10, i * 20 + 20); * } * } @@ -47560,7 +48543,7 @@ p5.prototype.getURLPath = function() { * // Example: http://p5js.org?year=2014&month=May&day=15 * * function setup() { - * var params = getURLParams(); + * let params = getURLParams(); * text(params.day, 10, 20); * text(params.month, 10, 40); * text(params.year, 10, 60); @@ -47586,7 +48569,7 @@ p5.prototype.getURLParams = function() { module.exports = p5; -},{"./constants":19,"./main":25}],21:[function(_dereq_,module,exports){ +},{"./constants":18,"./main":24}],20:[function(_dereq_,module,exports){ /** * @for p5 * @requires core @@ -47597,8 +48580,12 @@ module.exports = p5; var p5 = _dereq_('./main'); var constants = _dereq_('./constants'); +// p5.js blue, p5.js orange, auto dark green; fallback p5.js darkened magenta +// See testColors below for all the color codes and names +var typeColors = ['#2D7BB6', '#EE9900', '#4DB200', '#C83C00']; + if (typeof IS_MINIFIED !== 'undefined') { - p5._validateParameters = p5._friendlyFileLoadError = function() {}; + p5._validateParameters = p5._friendlyFileLoadError = p5._friendlyError = function() {}; } else { var doFriendlyWelcome = false; // TEMP until we get it all working LM // for parameter validation @@ -47654,6 +48641,7 @@ if (typeof IS_MINIFIED !== 'undefined') { /** * Prints out a fancy, colorful message to the console log * + * @method report * @private * @param {String} message the words to be said * @param {String} func the name of the function to link @@ -47661,12 +48649,6 @@ if (typeof IS_MINIFIED !== 'undefined') { * * @return console logs */ - // Wrong number of params, undefined param, wrong type - var FILE_LOAD = 3; - var ERR_PARAMS = 3; - // p5.js blue, p5.js orange, auto dark green; fallback p5.js darkened magenta - // See testColors below for all the color codes and names - var typeColors = ['#2D7BB6', '#EE9900', '#4DB200', '#C83C00']; var report = function(message, func, color) { if (doFriendlyWelcome) { friendlyWelcome(); @@ -47735,6 +48717,15 @@ if (typeof IS_MINIFIED !== 'undefined') { 'we recommend splitting the file into smaller segments and fetching those.' } }; + + /** + * This is called internally if there is a error during file loading. + * + * @method _friendlyFileLoadError + * @private + * @param {Number} errorType + * @param {String} filePath + */ p5._friendlyFileLoadError = function(errorType, filePath) { var errorInfo = errorCases[errorType]; var message; @@ -47752,7 +48743,20 @@ if (typeof IS_MINIFIED !== 'undefined') { (errorInfo.message || '') + ' or running a local server.'; } - report(message, errorInfo.method, FILE_LOAD); + report(message, errorInfo.method, 3); + }; + + /** + * This is a generic method that can be called from anywhere in the p5 + * library to alert users to a common error. + * + * @method _friendlyError + * @private + * @param {Number} message message to be printed + * @param {String} method name of method + */ + p5._friendlyError = function(message, method) { + report(message, method); }; var docCache = {}; @@ -48145,7 +49149,7 @@ if (typeof IS_MINIFIED !== 'undefined') { } } catch (err) {} - report(message + '.', func, ERR_PARAMS); + report(message + '.', func, 3); } }; @@ -48362,7 +49366,7 @@ if (document.readyState !== 'complete') { module.exports = p5; -},{"../../docs/reference/data.json":1,"./constants":19,"./main":25}],22:[function(_dereq_,module,exports){ +},{"../../docs/reference/data.json":1,"./constants":18,"./main":24}],21:[function(_dereq_,module,exports){ /** * @requires constants */ @@ -48385,7 +49389,7 @@ module.exports = { } }; -},{"./constants":19}],23:[function(_dereq_,module,exports){ +},{"./constants":18}],22:[function(_dereq_,module,exports){ 'use strict'; var p5 = _dereq_('../core/main'); @@ -48427,7 +49431,7 @@ if (document.readyState === 'complete') { window.addEventListener('load', _globalInit, false); } -},{"../core/main":25}],24:[function(_dereq_,module,exports){ +},{"../core/main":24}],23:[function(_dereq_,module,exports){ /** * @for p5 * @requires core @@ -48442,10 +49446,6 @@ if (document.readyState === 'complete') { var p5 = _dereq_('./main'); -p5.prototype.exit = function() { - throw new Error('exit() not implemented, see remove()'); -}; - p5.prototype.pushStyle = function() { throw new Error('pushStyle() not used, see push()'); }; @@ -48454,15 +49454,25 @@ p5.prototype.popStyle = function() { throw new Error('popStyle() not used, see pop()'); }; -p5.prototype.size = function() { - var s = 'size() is not a valid p5 function, to set the size of the '; - s += 'drawing canvas, please use createCanvas() instead'; - throw new Error(s); +p5.prototype.popMatrix = function() { + throw new Error('popMatrix() not used, see pop()'); +}; + +p5.prototype.printMatrix = function() { + throw new Error( + 'printMatrix() is not implemented in p5.js, ' + + 'refer to [https://simonsarris.com/a-transformation-class-for-canvas-to-keep-track-of-the-transformation-matrix/] ' + + 'to add your own implementation.' + ); +}; + +p5.prototype.pushMatrix = function() { + throw new Error('pushMatrix() not used, see push()'); }; module.exports = p5; -},{"./main":25}],25:[function(_dereq_,module,exports){ +},{"./main":24}],24:[function(_dereq_,module,exports){ /** * @module Structure * @submodule Structure @@ -48527,15 +49537,15 @@ var p5 = function(sketch, node, sync) { * @method preload * @example *
- * var img; - * var c; + * let img; + * let c; * function preload() { - // preload() runs once + * // preload() runs once * img = loadImage('assets/laDefense.jpg'); * } * * function setup() { - // setup() waits until preload() is done + * // setup() waits until preload() is done * img.loadPixels(); * // get color of middle pixel * c = img.get(img.width / 2, img.height / 2); @@ -48565,7 +49575,7 @@ var p5 = function(sketch, node, sync) { * @method setup * @example *
- * var a = 0; + * let a = 0; * * function setup() { * background(0); @@ -48613,13 +49623,13 @@ var p5 = function(sketch, node, sync) { * @method draw * @example *
- * var yPos = 0; + * let yPos = 0; * function setup() { - // setup() runs once + * // setup() runs once * frameRate(30); * } * function draw() { - // draw() loops forever, until stopped + * // draw() loops forever, until stopped * background(204); * yPos = yPos - 1; * if (yPos < 0) { @@ -48644,6 +49654,7 @@ var p5 = function(sketch, node, sync) { this._userNode = node; this._curElement = null; this._elements = []; + this._glAttributes = null; this._requestAnimId = 0; this._preloadCount = 0; this._isGlobal = false; @@ -48738,7 +49749,6 @@ var p5 = function(sketch, node, sync) { this._runIfPreloadsAreDone(); } else { this._setup(); - this._runFrames(); this._draw(); } }.bind(this); @@ -48751,7 +49761,6 @@ var p5 = function(sketch, node, sync) { loadingScreen.parentNode.removeChild(loadingScreen); } context._setup(); - context._runFrames(); context._draw(); } }; @@ -48857,12 +49866,6 @@ var p5 = function(sketch, node, sync) { } }.bind(this); - this._runFrames = function() { - if (this._updateInterval) { - clearInterval(this._updateInterval); - } - }.bind(this); - this._setProperty = function(prop, value) { this[prop] = value; if (this._isGlobal) { @@ -49047,14 +50050,30 @@ p5.prototype._initializeInstanceVariables = function() { }; this._pixelsDirty = true; + + this._downKeys = {}; //Holds the key codes of currently pressed keys }; // This is a pointer to our global mode p5 instance, if we're in // global mode. p5.instance = null; -// Allows for the friendly error system to be turned off when creating a sketch, -// which can give a significant boost to performance when needed. +/** + * Allows for the friendly error system (FES) to be turned off when creating a sketch, + * which can give a significant boost to performance when needed. + * See + * disabling the friendly error system. + * + * @property {Boolean} disableFriendlyErrors + * @example + *
+ * p5.disableFriendlyErrors = true; + * + * function setup() { + * createCanvas(100, 50); + * } + *
+ */ p5.disableFriendlyErrors = false; // attach constants to p5 prototype @@ -49180,7 +50199,7 @@ p5.prototype._createFriendlyGlobalFunctionBinder = function(options) { module.exports = p5; -},{"./constants":19,"./shim":35}],26:[function(_dereq_,module,exports){ +},{"./constants":18,"./shim":34}],25:[function(_dereq_,module,exports){ /** * @module DOM * @submodule DOM @@ -49211,13 +50230,14 @@ p5.Element = function(elt, pInst) { * @example *
* - * createCanvas(300, 500); - * background(0, 0, 0, 0); - * var input = createInput(); - * input.position(20, 225); - * var inputElem = new p5.Element(input.elt); - * inputElem.style('width:450px;'); - * inputElem.value('some string'); + * function setup() { + * let c = createCanvas(50, 50); + * c.elt.style.border = '5px solid red'; + * } + * + * function draw() { + * background(220); + * } * *
* @@ -49225,7 +50245,7 @@ p5.Element = function(elt, pInst) { * @readOnly */ this.elt = elt; - this._pInst = pInst; + this._pInst = this._pixelsState = pInst; this._events = {}; this.width = this.elt.offsetWidth; this.height = this.elt.offsetHeight; @@ -49240,6 +50260,11 @@ p5.Element = function(elt, pInst) { * * positioning the canvas wiki page. * + * All above examples except for the first one require the inclusion of + * the p5.dom library in your index.html. See the + * using a library + * section for information on how to include this library. + * * @method parent * @param {String|p5.Element|Object} parent the ID, DOM node, or p5.Element * of desired parent element @@ -49251,23 +50276,23 @@ p5.Element = function(elt, pInst) { * // <div id="myContainer"></div> * * // in the js file: - * var cnv = createCanvas(100, 100); + * let cnv = createCanvas(100, 100); * cnv.parent('myContainer'); *
*
- * var div0 = createDiv('this is the parent'); - * var div1 = createDiv('this is the child'); + * let div0 = createDiv('this is the parent'); + * let div1 = createDiv('this is the child'); * div1.parent(div0); // use p5.Element *
*
- * var div0 = createDiv('this is the parent'); + * let div0 = createDiv('this is the parent'); * div0.id('apples'); - * var div1 = createDiv('this is the child'); + * let div1 = createDiv('this is the child'); * div1.parent('apples'); // use id *
*
- * var elt = document.getElementById('myParentDiv'); - * var div1 = createDiv('this is the child'); + * let elt = document.getElementById('myParentDiv'); + * let div1 = createDiv('this is the child'); * div1.parent(elt); // use element from page *
* @@ -49300,6 +50325,9 @@ p5.Element.prototype.parent = function(p) { * * Sets the ID of the element. If no ID argument is passed in, it instead * returns the current ID of the element. + * Note that only one element can have a particular id in a page. + * The .class() function can be used + * to identify multiple elements with the same class name. * * @method id * @param {String} id ID of the element @@ -49308,7 +50336,7 @@ p5.Element.prototype.parent = function(p) { * @example *
* function setup() { - * var cnv = createCanvas(100, 100); + * let cnv = createCanvas(100, 100); * // Assigns a CSS selector ID to * // the canvas element. * cnv.id('mycanvas'); @@ -49345,7 +50373,7 @@ p5.Element.prototype.id = function(id) { * @example *
* function setup() { - * var cnv = createCanvas(100, 100); + * let cnv = createCanvas(100, 100); * // Assigns a CSS selector class 'small' * // to the canvas element. * cnv.class('small'); @@ -49383,9 +50411,9 @@ p5.Element.prototype.class = function(c) { * @chainable * @example *
- * var cnv; - * var d; - * var g; + * let cnv; + * let d; + * let g; * function setup() { * cnv = createCanvas(100, 100); * cnv.mousePressed(changeGray); // attach listener for @@ -49422,10 +50450,10 @@ p5.Element.prototype.mousePressed = function(fxn) { this._pInst._setProperty('mouseIsPressed', true); this._pInst._setMouseButton(event); // Pass along the return-value of the callback: - return fxn(); + return fxn.call(this); }; // Pass along the event-prepended form of the callback. - adjustListener('mousedown', eventPrependedFxn, this); + p5.Element._adjustListener('mousedown', eventPrependedFxn, this); return this; }; @@ -49442,9 +50470,9 @@ p5.Element.prototype.mousePressed = function(fxn) { * @return {p5.Element} * @example *
- * var cnv; - * var d; - * var g; + * let cnv; + * let d; + * let g; * function setup() { * cnv = createCanvas(100, 100); * cnv.doubleClicked(changeGray); // attach listener for @@ -49474,7 +50502,7 @@ p5.Element.prototype.mousePressed = function(fxn) { * */ p5.Element.prototype.doubleClicked = function(fxn) { - adjustListener('dblclick', fxn, this); + p5.Element._adjustListener('dblclick', fxn, this); return this; }; @@ -49501,9 +50529,9 @@ p5.Element.prototype.doubleClicked = function(fxn) { * @chainable * @example *
- * var cnv; - * var d; - * var g; + * let cnv; + * let d; + * let g; * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseWheel(changeSize); // attach listener for @@ -49540,7 +50568,7 @@ p5.Element.prototype.doubleClicked = function(fxn) { * */ p5.Element.prototype.mouseWheel = function(fxn) { - adjustListener('wheel', fxn, this); + p5.Element._adjustListener('wheel', fxn, this); return this; }; @@ -49559,9 +50587,9 @@ p5.Element.prototype.mouseWheel = function(fxn) { * @chainable * @example *
- * var cnv; - * var d; - * var g; + * let cnv; + * let d; + * let g; * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseReleased(changeGray); // attach listener for @@ -49594,7 +50622,7 @@ p5.Element.prototype.mouseWheel = function(fxn) { * */ p5.Element.prototype.mouseReleased = function(fxn) { - adjustListener('mouseup', fxn, this); + p5.Element._adjustListener('mouseup', fxn, this); return this; }; @@ -49614,9 +50642,9 @@ p5.Element.prototype.mouseReleased = function(fxn) { * @example *
* - * var cnv; - * var d; - * var g; + * let cnv; + * let d; + * let g; * * function setup() { * cnv = createCanvas(100, 100); @@ -49650,7 +50678,7 @@ p5.Element.prototype.mouseReleased = function(fxn) { * */ p5.Element.prototype.mouseClicked = function(fxn) { - adjustListener('click', fxn, this); + p5.Element._adjustListener('click', fxn, this); return this; }; @@ -49667,9 +50695,9 @@ p5.Element.prototype.mouseClicked = function(fxn) { * @chainable * @example *
- * var cnv; - * var d = 30; - * var g; + * let cnv; + * let d = 30; + * let g; * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseMoved(changeSize); // attach listener for @@ -49708,7 +50736,7 @@ p5.Element.prototype.mouseClicked = function(fxn) { * */ p5.Element.prototype.mouseMoved = function(fxn) { - adjustListener('mousemove', fxn, this); + p5.Element._adjustListener('mousemove', fxn, this); return this; }; @@ -49725,8 +50753,8 @@ p5.Element.prototype.mouseMoved = function(fxn) { * @chainable * @example *
- * var cnv; - * var d; + * let cnv; + * let d; * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseOver(changeGray); @@ -49751,109 +50779,7 @@ p5.Element.prototype.mouseMoved = function(fxn) { * */ p5.Element.prototype.mouseOver = function(fxn) { - adjustListener('mouseover', fxn, this); - return this; -}; - -/** - * The .changed() function is called when the value of an - * element changes. - * This can be used to attach an element specific event listener. - * - * @method changed - * @param {Function|Boolean} fxn function to be fired when the value of - * an element changes. - * if `false` is passed instead, the previously - * firing function will no longer fire. - * @chainable - * @example - *
- * var 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() { - * var item = sel.value(); - * background(200); - * text("it's a " + item + '!', 50, 50); - * } - *
- *
- * var checkbox; - * var cnv; - * - * function setup() { - * checkbox = createCheckbox(' fill'); - * checkbox.changed(changeFill); - * cnv = createCanvas(100, 100); - * cnv.position(0, 30); - * noFill(); - * } - * - * function draw() { - * background(200); - * ellipse(50, 50, 50, 50); - * } - * - * function changeFill() { - * if (checkbox.checked()) { - * fill(0); - * } else { - * noFill(); - * } - * } - *
- * - * @alt - * dropdown: pear, kiwi, grape. When selected text "its a" + selection shown. - * - */ -p5.Element.prototype.changed = function(fxn) { - adjustListener('change', fxn, this); - return this; -}; - -/** - * The .input() function is called when any user input is - * detected with an element. The input event is often used - * to detect keystrokes in a input element, or changes on a - * slider element. This can be used to attach an element specific - * event listener. - * - * @method input - * @param {Function|Boolean} fxn function to be fired when any user input is - * detected within the element. - * if `false` is passed instead, the previously - * firing function will no longer fire. - * @chainable - * @example - *
- * // Open your console to see the output - * function setup() { - * var inp = createInput(''); - * inp.input(myInputEvent); - * } - * - * function myInputEvent() { - * console.log('you are typing: ', this.value()); - * } - *
- * - * @alt - * no display. - * - */ -p5.Element.prototype.input = function(fxn) { - adjustListener('input', fxn, this); + p5.Element._adjustListener('mouseover', fxn, this); return this; }; @@ -49870,8 +50796,8 @@ p5.Element.prototype.input = function(fxn) { * @chainable * @example *
- * var cnv; - * var d; + * let cnv; + * let d; * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseOut(changeGray); @@ -49895,7 +50821,7 @@ p5.Element.prototype.input = function(fxn) { * */ p5.Element.prototype.mouseOut = function(fxn) { - adjustListener('mouseout', fxn, this); + p5.Element._adjustListener('mouseout', fxn, this); return this; }; @@ -49911,9 +50837,9 @@ p5.Element.prototype.mouseOut = function(fxn) { * @chainable * @example *
- * var cnv; - * var d; - * var g; + * let cnv; + * let d; + * let g; * function setup() { * cnv = createCanvas(100, 100); * cnv.touchStarted(changeGray); // attach listener for @@ -49943,7 +50869,7 @@ p5.Element.prototype.mouseOut = function(fxn) { * */ p5.Element.prototype.touchStarted = function(fxn) { - adjustListener('touchstart', fxn, this); + p5.Element._adjustListener('touchstart', fxn, this); return this; }; @@ -49959,8 +50885,8 @@ p5.Element.prototype.touchStarted = function(fxn) { * @chainable * @example *
- * var cnv; - * var g; + * let cnv; + * let g; * function setup() { * cnv = createCanvas(100, 100); * cnv.touchMoved(changeGray); // attach listener for @@ -49983,7 +50909,7 @@ p5.Element.prototype.touchStarted = function(fxn) { * */ p5.Element.prototype.touchMoved = function(fxn) { - adjustListener('touchmove', fxn, this); + p5.Element._adjustListener('touchmove', fxn, this); return this; }; @@ -49999,9 +50925,9 @@ p5.Element.prototype.touchMoved = function(fxn) { * @chainable * @example *
- * var cnv; - * var d; - * var g; + * let cnv; + * let d; + * let g; * function setup() { * cnv = createCanvas(100, 100); * cnv.touchEnded(changeGray); // attach listener for @@ -50032,7 +50958,7 @@ p5.Element.prototype.touchMoved = function(fxn) { * */ p5.Element.prototype.touchEnded = function(fxn) { - adjustListener('touchend', fxn, this); + p5.Element._adjustListener('touchend', fxn, this); return this; }; @@ -50052,7 +50978,7 @@ p5.Element.prototype.touchEnded = function(fxn) { * // To test this sketch, simply drag a * // file over the canvas * function setup() { - * var c = createCanvas(100, 100); + * let c = createCanvas(100, 100); * background(200); * textAlign(CENTER); * text('Drag file', width / 2, height / 2); @@ -50070,7 +50996,7 @@ p5.Element.prototype.touchEnded = function(fxn) { * nothing displayed */ p5.Element.prototype.dragOver = function(fxn) { - adjustListener('dragover', fxn, this); + p5.Element._adjustListener('dragover', fxn, this); return this; }; @@ -50090,7 +51016,7 @@ p5.Element.prototype.dragOver = function(fxn) { * // To test this sketch, simply drag a file * // over and then out of the canvas area * function setup() { - * var c = createCanvas(100, 100); + * let c = createCanvas(100, 100); * background(200); * textAlign(CENTER); * text('Drag file', width / 2, height / 2); @@ -50108,165 +51034,35 @@ p5.Element.prototype.dragOver = function(fxn) { * nothing displayed */ p5.Element.prototype.dragLeave = function(fxn) { - adjustListener('dragleave', fxn, this); - return this; -}; - -/** - * The .drop() function is called for each file dropped on the element. - * It requires a callback that is passed a p5.File object. You can - * optionally pass two callbacks, the first one (required) is triggered - * for each file dropped when the file is loaded. The second (optional) - * is triggered just once when a file (or files) are dropped. - * - * @method drop - * @param {Function} callback callback triggered when files are dropped. - * @param {Function} [fxn] callback to receive loaded file. - * @chainable - * @example - *
- * function setup() { - * var 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); - * } - *
- * - *
- * var img; - * - * function setup() { - * var c = createCanvas(100, 100); - * background(200); - * textAlign(CENTER); - * text('drop image', width / 2, height / 2); - * c.drop(gotFile); - * } - * - * function draw() { - * if (img) { - * image(img, 0, 0, width, height); - * } - * } - * - * function gotFile(file) { - * img = createImg(file.data).hide(); - * } - *
- * - * @alt - * Canvas turns into whatever image is dragged/dropped onto it. - */ -p5.Element.prototype.drop = function(callback, fxn) { - // Make a file loader callback and trigger user's callback - function makeLoader(theFile) { - // Making a p5.File object - var p5file = new p5.File(theFile); - return function(e) { - p5file.data = e.target.result; - callback(p5file); - }; - } - - // Is the file stuff supported? - if (window.File && window.FileReader && window.FileList && window.Blob) { - // If you want to be able to drop you've got to turn off - // a lot of default behavior - attachListener( - 'dragover', - function(evt) { - evt.stopPropagation(); - evt.preventDefault(); - }, - this - ); - - // If this is a drag area we need to turn off the default behavior - attachListener( - 'dragleave', - function(evt) { - evt.stopPropagation(); - evt.preventDefault(); - }, - this - ); - - // If just one argument it's the callback for the files - if (typeof fxn !== 'undefined') { - attachListener('drop', fxn, this); - } - - // Deal with the files - attachListener( - 'drop', - function(evt) { - evt.stopPropagation(); - evt.preventDefault(); - - // 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]; - var reader = new FileReader(); - reader.onload = makeLoader(f); - - // Text or data? - // This should likely be improved - if (f.type.indexOf('text') > -1) { - reader.readAsText(f); - } else { - reader.readAsDataURL(f); - } - } - }, - this - ); - } else { - console.log('The File APIs are not fully supported in this browser.'); - } - + p5.Element._adjustListener('dragleave', fxn, this); return this; }; // General handler for event attaching and detaching -function adjustListener(ev, fxn, ctx) { +p5.Element._adjustListener = function(ev, fxn, ctx) { if (fxn === false) { - detachListener(ev, ctx); + p5.Element._detachListener(ev, ctx); } else { - attachListener(ev, fxn, ctx); + p5.Element._attachListener(ev, fxn, ctx); } return this; -} - -function attachListener(ev, fxn, ctx) { - // LM removing, not sure why we had this? - // var _this = ctx; - // var f = function (e) { fxn(e, _this); }; +}; +p5.Element._attachListener = function(ev, fxn, ctx) { // detach the old listener if there was one if (ctx._events[ev]) { - detachListener(ev, ctx); + p5.Element._detachListener(ev, ctx); } var f = fxn.bind(ctx); ctx.elt.addEventListener(ev, f, false); ctx._events[ev] = f; -} +}; -function detachListener(ev, ctx) { +p5.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 @@ -50278,7 +51074,7 @@ p5.Element.prototype._setProperty = function(prop, value) { module.exports = p5.Element; -},{"./main":25}],27:[function(_dereq_,module,exports){ +},{"./main":24}],26:[function(_dereq_,module,exports){ /** * @module Rendering * @submodule Rendering @@ -50311,7 +51107,7 @@ p5.Graphics = function(w, h, renderer, pInst) { var node = pInst._userNode || document.body; node.appendChild(this.canvas); - p5.Element.call(this, this.canvas, pInst, false); + p5.Element.call(this, this.canvas, pInst); // bind methods and props of p5 to the new object for (var p in p5.prototype) { @@ -50343,6 +51139,58 @@ p5.Graphics = function(w, h, renderer, pInst) { p5.Graphics.prototype = Object.create(p5.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. + * + */ +p5.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. @@ -50351,7 +51199,7 @@ p5.Graphics.prototype = Object.create(p5.Element.prototype); * * @example *
- * var bg; + * let bg; * function setup() { * bg = createCanvas(100, 100); * bg.background(0); @@ -50361,7 +51209,7 @@ p5.Graphics.prototype = Object.create(p5.Element.prototype); *
* *
- * var bg; + * let bg; * function setup() { * pixelDensity(1); * createCanvas(100, 100); @@ -50374,14 +51222,14 @@ p5.Graphics.prototype = Object.create(p5.Element.prototype); * bg.ellipse(50, 50, 80, 80); * } * function draw() { - * var t = millis() / 1000; + * let t = millis() / 1000; * // draw the background * if (bg) { * image(bg, frameCount % 100, 0); * image(bg, frameCount % 100 - 100, 0); * } * // draw the foreground - * var p = p5.Vector.fromAngle(t, 35).add(50, 50); + * let p = p5.Vector.fromAngle(t, 35).add(50, 50); * ellipse(p.x, p.y, 30); * } * function mouseClicked() { @@ -50413,7 +51261,7 @@ p5.Graphics.prototype.remove = function() { module.exports = p5.Graphics; -},{"./constants":19,"./main":25}],28:[function(_dereq_,module,exports){ +},{"./constants":18,"./main":24}],27:[function(_dereq_,module,exports){ /** * @module Rendering * @submodule Rendering @@ -50440,6 +51288,7 @@ var constants = _dereq_('../core/constants'); p5.Renderer = function(elt, pInst, isMainCanvas) { p5.Element.call(this, elt, pInst); this.canvas = elt; + this._pixelsState = pInst; if (isMainCanvas) { this._isMainCanvas = true; // for pixel method sharing with pimage @@ -50525,6 +51374,39 @@ p5.Renderer.prototype.resize = function(w, h) { } }; +p5.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 p5.Image(w, h); + region.canvas + .getContext('2d') + .drawImage(canvas, x, y, w * pd, h * pd, 0, 0, w, h); + + return region; +}; + p5.Renderer.prototype.textLeading = function(l) { if (typeof l === 'number') { this._setProperty('_textLeading', l); @@ -50549,7 +51431,8 @@ p5.Renderer.prototype.textStyle = function(s) { if ( s === constants.NORMAL || s === constants.ITALIC || - s === constants.BOLD + s === constants.BOLD || + s === constants.BOLDITALIC ) { this._setProperty('_textStyle', s); } @@ -50787,7 +51670,7 @@ function calculateOffset(object) { module.exports = p5.Renderer; -},{"../core/constants":19,"./main":25}],29:[function(_dereq_,module,exports){ +},{"../core/constants":18,"./main":24}],28:[function(_dereq_,module,exports){ 'use strict'; var p5 = _dereq_('./main'); @@ -50851,7 +51734,7 @@ p5.Renderer2D.prototype.background = function() { } this.drawingContext.restore(); - this._pInst._pixelsDirty = true; + this._pixelsState._pixelsDirty = true; }; p5.Renderer2D.prototype.clear = function() { @@ -50860,7 +51743,7 @@ p5.Renderer2D.prototype.clear = function() { this.drawingContext.clearRect(0, 0, this.width, this.height); this.drawingContext.restore(); - this._pInst._pixelsDirty = true; + this._pixelsState._pixelsDirty = true; }; p5.Renderer2D.prototype.fill = function() { @@ -50922,7 +51805,7 @@ p5.Renderer2D.prototype.image = function( } } - this._pInst._pixelsDirty = true; + this._pixelsState._pixelsDirty = true; }; p5.Renderer2D.prototype._getTintedImageCanvas = function(img) { @@ -50955,8 +51838,30 @@ p5.Renderer2D.prototype._getTintedImageCanvas = function(img) { ////////////////////////////////////////////// p5.Renderer2D.prototype.blendMode = function(mode) { - this.drawingContext.globalCompositeOperation = mode; + if (mode === constants.SUBTRACT) { + console.warn('blendMode(SUBTRACT) only works in WEBGL mode.'); + } else if ( + mode === constants.BLEND || + 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.drawingContext.globalCompositeOperation = mode; + } else { + throw new Error('Mode ' + mode + ' not recognized.'); + } }; + p5.Renderer2D.prototype.blend = function() { var currBlend = this.drawingContext.globalCompositeOperation; var blendMode = arguments[arguments.length - 1]; @@ -50999,7 +51904,7 @@ p5.Renderer2D.prototype.copy = function() { } p5.Renderer2D._copyHelper(this, srcImage, sx, sy, sw, sh, dx, dy, dw, dh); - this._pInst._pixelsDirty = true; + this._pixelsState._pixelsDirty = true; }; p5.Renderer2D._copyHelper = function( @@ -51029,93 +51934,58 @@ p5.Renderer2D._copyHelper = function( ); }; -p5.Renderer2D.prototype.get = function(x, y, w, h) { - if (typeof w === 'undefined' && typeof h === 'undefined') { - if (typeof x === 'undefined' && typeof y === 'undefined') { - x = y = 0; - w = this.width; - h = this.height; - } else { - w = h = 1; - } - } - - // if the section does not overlap the canvas - if (x + w < 0 || y + h < 0 || x >= this.width || y >= this.height) { - // TODO: is this valid for w,h > 1 ? - return [0, 0, 0, 255]; - } - - var ctx = this._pInst || this; - var pd = ctx._pixelDensity; +// p5.Renderer2D.prototype.get = p5.Renderer.prototype.get; +// .get() is not overridden - // round down to get integer numbers - x = Math.floor(x); - y = Math.floor(y); - w = Math.floor(w); - h = Math.floor(h); - - var sx = x * pd; - var sy = y * pd; - if (w === 1 && h === 1 && !(this instanceof p5.RendererGL)) { - var imageData, index; - if (ctx._pixelsDirty) { - imageData = this.drawingContext.getImageData(sx, sy, 1, 1).data; - index = 0; - } else { - imageData = ctx.pixels; - index = (sx + sy * this.width * pd) * 4; - } - return [ - imageData[index + 0], - imageData[index + 1], - imageData[index + 2], - imageData[index + 3] - ]; +// x,y are canvas-relative (pre-scaled by _pixelDensity) +p5.Renderer2D.prototype._getPixel = function(x, y) { + var pixelsState = this._pixelsState; + var imageData, index; + if (pixelsState._pixelsDirty) { + imageData = this.drawingContext.getImageData(x, y, 1, 1).data; + index = 0; } else { - //auto constrain the width and height to - //dimensions of the source image - var dw = Math.min(w, ctx.width); - var dh = Math.min(h, ctx.height); - var sw = dw * pd; - var sh = dh * pd; - - var region = new p5.Image(dw, dh); - region.canvas - .getContext('2d') - .drawImage(this.canvas, sx, sy, sw, sh, 0, 0, dw, dh); - - return region; + imageData = pixelsState.pixels; + index = (Math.floor(x) + Math.floor(y) * this.canvas.width) * 4; } + return [ + imageData[index + 0], + imageData[index + 1], + imageData[index + 2], + imageData[index + 3] + ]; }; p5.Renderer2D.prototype.loadPixels = function() { - var ctx = this._pInst || this; // if called by p5.Image - if (!ctx._pixelsDirty) return; - ctx._pixelsDirty = false; + var pixelsState = this._pixelsState; // if called by p5.Image + if (!pixelsState._pixelsDirty) return; + pixelsState._pixelsDirty = false; - var pd = ctx._pixelDensity; + 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. - ctx._setProperty('imageData', imageData); - ctx._setProperty('pixels', imageData.data); + pixelsState._setProperty('imageData', imageData); + pixelsState._setProperty('pixels', imageData.data); }; p5.Renderer2D.prototype.set = function(x, y, imgOrCol) { // round down to get integer numbers x = Math.floor(x); y = Math.floor(y); - var ctx = this._pInst || this; + var pixelsState = this._pixelsState; if (imgOrCol instanceof p5.Image) { this.drawingContext.save(); this.drawingContext.setTransform(1, 0, 0, 1, 0, 0); - this.drawingContext.scale(ctx._pixelDensity, ctx._pixelDensity); + this.drawingContext.scale( + pixelsState._pixelDensity, + pixelsState._pixelDensity + ); this.drawingContext.drawImage(imgOrCol.canvas, x, y); this.drawingContext.restore(); - ctx._pixelsDirty = true; + pixelsState._pixelsDirty = true; } else { var r = 0, g = 0, @@ -51123,13 +51993,15 @@ p5.Renderer2D.prototype.set = function(x, y, imgOrCol) { a = 0; var idx = 4 * - (y * ctx._pixelDensity * (this.width * ctx._pixelDensity) + - x * ctx._pixelDensity); - if (!ctx.imageData || ctx._pixelsDirty) { - ctx.loadPixels.call(ctx); + (y * + pixelsState._pixelDensity * + (this.width * pixelsState._pixelDensity) + + x * pixelsState._pixelDensity); + if (!pixelsState.imageData || pixelsState._pixelsDirty) { + pixelsState.loadPixels.call(pixelsState); } if (typeof imgOrCol === 'number') { - if (idx < ctx.pixels.length) { + if (idx < pixelsState.pixels.length) { r = imgOrCol; g = imgOrCol; b = imgOrCol; @@ -51140,7 +52012,7 @@ p5.Renderer2D.prototype.set = function(x, y, imgOrCol) { if (imgOrCol.length < 4) { throw new Error('pixel array must be of the form [R, G, B, A]'); } - if (idx < ctx.pixels.length) { + if (idx < pixelsState.pixels.length) { r = imgOrCol[0]; g = imgOrCol[1]; b = imgOrCol[2]; @@ -51148,7 +52020,7 @@ p5.Renderer2D.prototype.set = function(x, y, imgOrCol) { //this.updatePixels.call(this); } } else if (imgOrCol instanceof p5.Color) { - if (idx < ctx.pixels.length) { + if (idx < pixelsState.pixels.length) { r = imgOrCol.levels[0]; g = imgOrCol.levels[1]; b = imgOrCol.levels[2]; @@ -51157,25 +52029,27 @@ p5.Renderer2D.prototype.set = function(x, y, imgOrCol) { } } // loop over pixelDensity * pixelDensity - for (var i = 0; i < ctx._pixelDensity; i++) { - for (var j = 0; j < ctx._pixelDensity; j++) { + for (var i = 0; i < pixelsState._pixelDensity; i++) { + for (var j = 0; j < pixelsState._pixelDensity; j++) { // loop over idx = 4 * - ((y * ctx._pixelDensity + j) * this.width * ctx._pixelDensity + - (x * ctx._pixelDensity + i)); - ctx.pixels[idx] = r; - ctx.pixels[idx + 1] = g; - ctx.pixels[idx + 2] = b; - ctx.pixels[idx + 3] = a; + ((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; } } } }; p5.Renderer2D.prototype.updatePixels = function(x, y, w, h) { - var ctx = this._pInst || this; - var pd = ctx._pixelDensity; + var pixelsState = this._pixelsState; + var pd = pixelsState._pixelDensity; if ( x === undefined && y === undefined && @@ -51190,10 +52064,10 @@ p5.Renderer2D.prototype.updatePixels = function(x, y, w, h) { w *= pd; h *= pd; - this.drawingContext.putImageData(ctx.imageData, x, y, 0, 0, w, h); + this.drawingContext.putImageData(pixelsState.imageData, x, y, 0, 0, w, h); if (x !== 0 || y !== 0 || w !== this.width || h !== this.height) { - ctx._pixelsDirty = true; + pixelsState._pixelsDirty = true; } }; @@ -51212,7 +52086,7 @@ p5.Renderer2D.prototype._acuteArcToBezier = function _acuteArcToBezier( start, size ) { - // Evauate constants. + // Evaluate constants. var alpha = size / 2.0, cos_alpha = Math.cos(alpha), sin_alpha = Math.sin(alpha), @@ -51225,17 +52099,24 @@ p5.Renderer2D.prototype._acuteArcToBezier = function _acuteArcToBezier( // Return rotated waypoints. return { - ax: Math.cos(start), - ay: Math.sin(start), - bx: lambda * cos_phi + mu * sin_phi, - by: lambda * sin_phi - mu * cos_phi, - cx: lambda * cos_phi - mu * sin_phi, - cy: lambda * sin_phi + mu * cos_phi, - dx: Math.cos(start + size), - dy: Math.sin(start + size) + 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 + */ p5.Renderer2D.prototype.arc = function(x, y, w, h, start, stop, mode) { var ctx = this.drawingContext; var rx = w / 2.0; @@ -51248,7 +52129,7 @@ p5.Renderer2D.prototype.arc = function(x, y, w, h, start, stop, mode) { y += ry; // Create curves - while (stop - start > epsilon) { + while (stop - start >= epsilon) { arcToDraw = Math.min(stop - start, constants.HALF_PI); curves.push(this._acuteArcToBezier(start, arcToDraw)); start += arcToDraw; @@ -51271,6 +52152,7 @@ p5.Renderer2D.prototype.arc = function(x, y, w, h, start, stop, mode) { } ctx.closePath(); ctx.fill(); + this._pixelsState._pixelsDirty = true; } // Stroke curves @@ -51292,6 +52174,7 @@ p5.Renderer2D.prototype.arc = function(x, y, w, h, start, stop, mode) { ctx.closePath(); } ctx.stroke(); + this._pixelsState._pixelsDirty = true; } return this; }; @@ -51329,9 +52212,11 @@ p5.Renderer2D.prototype.ellipse = function(args) { ctx.closePath(); if (doFill) { ctx.fill(); + this._pixelsState._pixelsDirty = true; } if (doStroke) { ctx.stroke(); + this._pixelsState._pixelsDirty = true; } }; @@ -51342,17 +52227,11 @@ p5.Renderer2D.prototype.line = function(x1, y1, x2, y2) { } else if (this._getStroke() === styleEmpty) { return this; } - // Translate the line by (0.5, 0.5) to draw it crisp - if (ctx.lineWidth % 2 === 1) { - ctx.translate(0.5, 0.5); - } ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke(); - if (ctx.lineWidth % 2 === 1) { - ctx.translate(-0.5, -0.5); - } + this._pixelsState._pixelsDirty = true; return this; }; @@ -51377,6 +52256,7 @@ p5.Renderer2D.prototype.point = function(x, y) { ctx.fillRect(x, y, 1, 1); } this._setFill(f); + this._pixelsState._pixelsDirty = true; }; p5.Renderer2D.prototype.quad = function(x1, y1, x2, y2, x3, y3, x4, y4) { @@ -51404,6 +52284,7 @@ p5.Renderer2D.prototype.quad = function(x1, y1, x2, y2, x3, y3, x4, y4) { if (doStroke) { ctx.stroke(); } + this._pixelsState._pixelsDirty = true; return this; }; @@ -51428,10 +52309,6 @@ p5.Renderer2D.prototype.rect = function(args) { return this; } } - // Translate the line by (0.5, 0.5) to draw a crisp rectangle border - if (this._doStroke && ctx.lineWidth % 2 === 1) { - ctx.translate(0.5, 0.5); - } ctx.beginPath(); if (typeof tl === 'undefined') { @@ -51494,9 +52371,7 @@ p5.Renderer2D.prototype.rect = function(args) { if (this._doStroke) { ctx.stroke(); } - if (this._doStroke && ctx.lineWidth % 2 === 1) { - ctx.translate(-0.5, -0.5); - } + this._pixelsState._pixelsDirty = true; return this; }; @@ -51526,9 +52401,11 @@ p5.Renderer2D.prototype.triangle = function(args) { ctx.closePath(); if (doFill) { ctx.fill(); + this._pixelsState._pixelsDirty = true; } if (doStroke) { ctx.stroke(); + this._pixelsState._pixelsDirty = true; } }; @@ -51585,7 +52462,7 @@ p5.Renderer2D.prototype.endShape = function( if (closeShape) { this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]); } - this._doFillStrokeClose(); + this._doFillStrokeClose(closeShape); } } else if ( isBezier && @@ -51610,7 +52487,7 @@ p5.Renderer2D.prototype.endShape = function( ); } } - this._doFillStrokeClose(); + this._doFillStrokeClose(closeShape); } else if ( isQuadratic && (shapeKind === constants.POLYGON || shapeKind === null) @@ -51619,7 +52496,7 @@ p5.Renderer2D.prototype.endShape = function( for (i = 0; i < numVerts; i++) { if (vertices[i].isVert) { if (vertices[i].moveTo) { - this.drawingContext.moveTo([0], vertices[i][1]); + this.drawingContext.moveTo(vertices[i][0], vertices[i][1]); } else { this.drawingContext.lineTo(vertices[i][0], vertices[i][1]); } @@ -51632,7 +52509,7 @@ p5.Renderer2D.prototype.endShape = function( ); } } - this._doFillStrokeClose(); + this._doFillStrokeClose(closeShape); } else { if (shapeKind === constants.POINTS) { for (i = 0; i < numVerts; i++) { @@ -51688,7 +52565,7 @@ p5.Renderer2D.prototype.endShape = function( this._pInst.fill(vertices[i + 2][5]); } } - this._doFillStrokeClose(); + this._doFillStrokeClose(closeShape); } } else if (shapeKind === constants.TRIANGLE_FAN) { if (numVerts > 2) { @@ -51722,7 +52599,7 @@ p5.Renderer2D.prototype.endShape = function( } } } - this._doFillStrokeClose(); + this._doFillStrokeClose(closeShape); } } else if (shapeKind === constants.QUADS) { for (i = 0; i + 3 < numVerts; i += 4) { @@ -51739,7 +52616,7 @@ p5.Renderer2D.prototype.endShape = function( if (this._doStroke) { this._pInst.stroke(vertices[i + 3][6]); } - this._doFillStrokeClose(); + this._doFillStrokeClose(closeShape); } } else if (shapeKind === constants.QUAD_STRIP) { if (numVerts > 3) { @@ -51761,7 +52638,7 @@ p5.Renderer2D.prototype.endShape = function( this.drawingContext.moveTo(v[0], v[1]); this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]); } - this._doFillStrokeClose(); + this._doFillStrokeClose(closeShape); } } } else { @@ -51777,7 +52654,7 @@ p5.Renderer2D.prototype.endShape = function( } } } - this._doFillStrokeClose(); + this._doFillStrokeClose(closeShape); } } isCurve = false; @@ -51788,27 +52665,13 @@ p5.Renderer2D.prototype.endShape = function( vertices.pop(); } - this._pInst._pixelsDirty = true; + this._pixelsState._pixelsDirty = true; return this; }; ////////////////////////////////////////////// // SHAPE | Attributes ////////////////////////////////////////////// -p5.Renderer2D.prototype.noSmooth = function() { - if ('imageSmoothingEnabled' in this.drawingContext) { - this.drawingContext.imageSmoothingEnabled = false; - } - return this; -}; - -p5.Renderer2D.prototype.smooth = function() { - if ('imageSmoothingEnabled' in this.drawingContext) { - this.drawingContext.imageSmoothingEnabled = true; - } - return this; -}; - p5.Renderer2D.prototype.strokeCap = function(cap) { if ( cap === constants.ROUND || @@ -51894,16 +52757,18 @@ p5.Renderer2D.prototype.curve = function(x1, y1, x2, y2, x3, y3, x4, y4) { // SHAPE | Vertex ////////////////////////////////////////////// -p5.Renderer2D.prototype._doFillStrokeClose = function() { +p5.Renderer2D.prototype._doFillStrokeClose = function(closeShape) { + if (closeShape) { + this.drawingContext.closePath(); + } if (this._doFill) { this.drawingContext.fill(); } if (this._doStroke) { this.drawingContext.stroke(); } - this.drawingContext.closePath(); - this._pInst._pixelsDirty = true; + this._pixelsState._pixelsDirty = true; }; ////////////////////////////////////////////// @@ -51932,16 +52797,6 @@ p5.Renderer2D.prototype.scale = function(x, y) { return this; }; -p5.Renderer2D.prototype.shearX = function(rad) { - this.drawingContext.transform(1, 0, Math.tan(rad), 1, 0, 0); - return this; -}; - -p5.Renderer2D.prototype.shearY = function(rad) { - this.drawingContext.transform(1, Math.tan(rad), 0, 1, 0, 0); - return this; -}; - p5.Renderer2D.prototype.translate = function(x, y) { // support passing a vector as the 1st parameter if (x instanceof p5.Vector) { @@ -52011,7 +52866,7 @@ p5.Renderer2D.prototype._renderText = function(p, line, x, y, maxY) { p.pop(); - this._pInst._pixelsDirty = true; + this._pixelsState._pixelsDirty = true; return p; }; @@ -52086,7 +52941,7 @@ p5.Renderer2D.prototype.pop = function(style) { module.exports = p5.Renderer2D; -},{"../image/filters":43,"./constants":19,"./main":25,"./p5.Renderer":28}],30:[function(_dereq_,module,exports){ +},{"../image/filters":42,"./constants":18,"./main":24,"./p5.Renderer":27}],29:[function(_dereq_,module,exports){ /** * @module Rendering * @submodule Rendering @@ -52297,7 +53152,7 @@ p5.prototype.noCanvas = function() { * @example *
* - * var pg; + * let pg; * function setup() { * createCanvas(100, 100); * pg = createGraphics(100, 100); @@ -52328,7 +53183,7 @@ p5.prototype.createGraphics = function(w, h, renderer) { * with the ones of pixels already in the display window (B): *
    *
  • BLEND - linear interpolation of colours: C = - * A\*factor + B. This is the default blending mode.
  • + * A\*factor + B. This is the default blending mode. *
  • ADD - sum of A and B
  • *
  • DARKEST - only the darkest colour succeeds: C = * min(A\*factor, B).
  • @@ -52344,23 +53199,28 @@ p5.prototype.createGraphics = function(w, h, renderer) { *
  • REPLACE - the pixels entirely replace the others and * don't utilize alpha (transparency) values.
  • *
  • OVERLAY - mix of MULTIPLY and SCREEN - * . Multiplies dark values, and screens light values.
  • + *
    . Multiplies dark values, and screens light values. (2D) *
  • HARD_LIGHT - SCREEN when greater than 50% - * gray, MULTIPLY when lower.
  • + * gray, MULTIPLY when lower. (2D) *
  • SOFT_LIGHT - mix of DARKEST and - * LIGHTEST. Works like OVERLAY, but not as harsh. + * LIGHTEST. Works like OVERLAY, but not as harsh. (2D) *
  • *
  • DODGE - lightens light tones and increases contrast, - * ignores darks.
  • + * ignores darks. (2D) *
  • BURN - darker areas are applied, increasing contrast, - * ignores lights.
  • + * ignores lights. (2D) + *
  • SUBTRACT - remainder of A and B (3D)
  • *
+ *

+ * (2D) indicates that this blend mode only works in the 2D renderer.
+ * (3D) indicates that this blend mode only works in the WEBGL renderer. + * * * @method blendMode * @param {Constant} mode blend mode to set for canvas. * either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY, * EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT, - * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL + * SOFT_LIGHT, DODGE, BURN, ADD, or SUBTRACT * @example *
* @@ -52389,32 +53249,19 @@ p5.prototype.createGraphics = function(w, h, renderer) { */ p5.prototype.blendMode = function(mode) { p5._validateParameters('blendMode', arguments); - if ( - mode === constants.BLEND || - 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 || - mode === constants.NORMAL - ) { - this._renderer.blendMode(mode); - } else { - throw new Error('Mode ' + mode + ' not recognized.'); + if (mode === constants.NORMAL) { + // Warning added 3/26/19, can be deleted in future (1.0 release?) + console.warn( + 'NORMAL has been deprecated for use in blendMode. defaulting to BLEND instead.' + ); + mode = constants.BLEND; } + this._renderer.blendMode(mode); }; module.exports = p5; -},{"../webgl/p5.RendererGL":75,"./constants":19,"./main":25,"./p5.Graphics":27,"./p5.Renderer2D":29}],31:[function(_dereq_,module,exports){ +},{"../webgl/p5.RendererGL":74,"./constants":18,"./main":24,"./p5.Graphics":26,"./p5.Renderer2D":28}],30:[function(_dereq_,module,exports){ /** * @module Shape * @submodule 2D Primitives @@ -52430,16 +53277,100 @@ var constants = _dereq_('../constants'); var canvas = _dereq_('../helpers'); _dereq_('../error_helpers'); +/** + * This function does 3 things: + * + * 1. Bounds the desired start/stop angles for an arc (in radians) so that: + * + * 0 <= start < TWO_PI ; start <= stop < start + TWO_PI + * + * This means that the arc rendering functions don't have to be concerned + * with what happens if stop is smaller than start, or if the arc 'goes + * round more than once', etc.: they can just start at start and increase + * until stop and the correct arc will be drawn. + * + * 2. Optionally adjusts the angles within each quadrant to counter the naive + * scaling of the underlying ellipse up from the unit circle. Without + * this, the angles become arbitrary when width != height: 45 degrees + * might be drawn at 5 degrees on a 'wide' ellipse, or at 85 degrees on + * a 'tall' ellipse. + * + * 3. Flags up when start and stop correspond to the same place on the + * underlying ellipse. This is useful if you want to do something special + * there (like rendering a whole ellipse instead). + */ +p5.prototype._normalizeArcAngles = function( + start, + stop, + width, + height, + correctForScaling +) { + var epsilon = 0.00001; // Smallest visible angle on displays up to 4K. + var separation; + + // The order of the steps is important here: each one builds upon the + // adjustments made in the steps that precede it. + + // Constrain both start and stop to [0,TWO_PI). + start = start - constants.TWO_PI * Math.floor(start / constants.TWO_PI); + stop = stop - constants.TWO_PI * Math.floor(stop / constants.TWO_PI); + + // Get the angular separation between the requested start and stop points. + // + // Technically this separation only matches what gets drawn if + // correctForScaling is enabled. We could add a more complicated calculation + // for when the scaling is uncorrected (in which case the drawn points could + // end up pushed together or pulled apart quite dramatically relative to what + // was requested), but it would make things more opaque for little practical + // benefit. + // + // (If you do disable correctForScaling and find that correspondToSamePoint + // is set too aggressively, the easiest thing to do is probably to just make + // epsilon smaller...) + separation = Math.min( + Math.abs(start - stop), + constants.TWO_PI - Math.abs(start - stop) + ); + + // Optionally adjust the angles to counter linear scaling. + if (correctForScaling) { + if (start <= constants.HALF_PI) { + start = Math.atan(width / height * Math.tan(start)); + } else if (start > constants.HALF_PI && start <= 3 * constants.HALF_PI) { + start = Math.atan(width / height * Math.tan(start)) + constants.PI; + } else { + start = Math.atan(width / height * Math.tan(start)) + constants.TWO_PI; + } + if (stop <= constants.HALF_PI) { + stop = Math.atan(width / height * Math.tan(stop)); + } else if (stop > constants.HALF_PI && stop <= 3 * constants.HALF_PI) { + stop = Math.atan(width / height * Math.tan(stop)) + constants.PI; + } else { + stop = Math.atan(width / height * Math.tan(stop)) + constants.TWO_PI; + } + } + + // Ensure that start <= stop < start + TWO_PI. + if (start > stop) { + stop += constants.TWO_PI; + } + + return { + start: start, + stop: stop, + correspondToSamePoint: separation < epsilon + }; +}; + /** * Draw an arc to the screen. If called with only x, y, w, h, start, and * stop, the arc will be drawn and filled as an open pie segment. If a mode parameter is provided, the arc * will be filled like an open semi-circle (OPEN) , a closed semi-circle (CHORD), or as a closed pie segment (PIE). The * origin may be changed with the ellipseMode() function.

- * Note that drawing a full circle (ex: 0 to TWO_PI) will appear blank - * because 0 and TWO_PI are the same position on the unit circle. The - * best way to handle this is by using the ellipse() function instead - * to create a closed ellipse, and to use the arc() function - * only to draw parts of an ellipse. + * 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. * * @method arc * @param {Number} x x-coordinate of the arc's ellipse @@ -52510,55 +53441,32 @@ p5.prototype.arc = function(x, y, w, h, start, stop, mode, detail) { start = this._toRadians(start); stop = this._toRadians(stop); - // Make all angles positive... - while (start < 0) { - start += constants.TWO_PI; - } - while (stop < 0) { - stop += constants.TWO_PI; - } - - if (typeof start !== 'undefined' && typeof stop !== 'undefined') { - // don't display anything if the angles are same or they have a difference of 0 - TWO_PI - if ( - stop.toFixed(10) === start.toFixed(10) || - Math.abs(stop - start) === constants.TWO_PI - ) { - start %= constants.TWO_PI; - stop %= constants.TWO_PI; - start += constants.TWO_PI; - } else if (Math.abs(stop - start) > constants.TWO_PI) { - // display a full circle if the difference between them is greater than 0 - TWO_PI - start %= constants.TWO_PI; - stop %= constants.TWO_PI; - stop += constants.TWO_PI; - } - } - - //Adjust angles to counter linear scaling. - if (start <= constants.HALF_PI) { - start = Math.atan(w / h * Math.tan(start)); - } else if (start > constants.HALF_PI && start <= 3 * constants.HALF_PI) { - start = Math.atan(w / h * Math.tan(start)) + constants.PI; - } - if (stop <= constants.HALF_PI) { - stop = Math.atan(w / h * Math.tan(stop)); - } else if (stop > constants.HALF_PI && stop <= 3 * constants.HALF_PI) { - stop = Math.atan(w / h * Math.tan(stop)) + constants.PI; - } - - // Exceed the interval if necessary in order to preserve the size and - // orientation of the arc. - if (start > stop) { - stop += constants.TWO_PI; - } - // p5 supports negative width and heights for ellipses w = Math.abs(w); h = Math.abs(h); var vals = canvas.modeAdjust(x, y, w, h, this._renderer._ellipseMode); - this._renderer.arc(vals.x, vals.y, vals.w, vals.h, start, stop, mode, detail); + var angles = this._normalizeArcAngles(start, stop, vals.w, vals.h, true); + + if (angles.correspondToSamePoint) { + // If the arc starts and ends at (near enough) the same place, we choose to + // draw an ellipse instead. This is preferable to faking an ellipse (by + // making stop ever-so-slightly less than start + TWO_PI) because the ends + // join up to each other rather than at a vertex at the centre (leaving + // an unwanted spike in the stroke/fill). + this._renderer.ellipse([vals.x, vals.y, vals.w, vals.h, detail]); + } else { + this._renderer.arc( + vals.x, + vals.y, + vals.w, + vals.h, + angles.start, // [0, TWO_PI) + angles.stop, // [start, start + TWO_PI) + mode, + detail + ); + } return this; }; @@ -52594,7 +53502,7 @@ p5.prototype.arc = function(x, y, w, h, start, stop, mode, detail) { * @param {Number} y * @param {Number} w * @param {Number} h - * @param {Integer} detail number of radial sectors to draw + * @param {Integer} detail number of radial sectors to draw (for WebGL mode) */ p5.prototype.ellipse = function(x, y, w, h, detailX) { p5._validateParameters('ellipse', arguments); @@ -52622,6 +53530,37 @@ p5.prototype.ellipse = function(x, y, w, h, detailX) { return this; }; + +/** + * Draws a circle to the screen. A circle is a simple closed shape. + * It is the set of all points in a plane that are at a given distance from a given point, the centre. + * This function is a special case of the ellipse() function, where the width and height of the ellipse are the same. + * Height and width of the ellipse correspond to the diameter of the circle. + * By default, the first two parameters set the location of the centre of the circle, the third sets the diameter of the circle. + * + * @method circle + * @param {Number} x x-coordinate of the centre of the circle. + * @param {Number} y y-coordinate of the centre of the circle. + * @param {Number} d diameter of the circle. + * @chainable + * @example + *
+ * + * // Draw a circle at location (30, 30) with a diameter of 20. + * circle(30, 30, 20); + * + *
+ * + * @alt + * white circle with black outline in mid of canvas that is 55x55. + */ +p5.prototype.circle = function() { + var args = Array.prototype.slice.call(arguments, 0, 2); + args.push(arguments[2]); + args.push(arguments[2]); + return this.ellipse.apply(this, args); +}; + /** * Draws a line (a direct path between two points) to the screen. The version * of line() with four parameters draws the line in 2D. To color a line, use @@ -52687,7 +53626,7 @@ p5.prototype.line = function() { * @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} [z] the z-coordinate (for WebGL mode) * @chainable * @example *
@@ -52719,6 +53658,8 @@ p5.prototype.point = function() { * constrained to ninety degrees. The first pair of parameters (x1,y1) * sets the first vertex and the subsequent pairs should proceed * clockwise or counter-clockwise around the defined shape. + * z-arguments only work when quad() is used in WEBGL mode. + * * * @method quad * @param {Number} x1 the x-coordinate of the first point @@ -52761,7 +53702,18 @@ p5.prototype.quad = function() { p5._validateParameters('quad', arguments); if (this._renderer._doStroke || this._renderer._doFill) { - this._renderer.quad.apply(this._renderer, arguments); + if (this._renderer.isP3D && arguments.length !== 12) { + // if 3D and we weren't passed 12 args, assume Z is 0 + // prettier-ignore + this._renderer.quad.call( + this._renderer, + arguments[0], arguments[1], 0, + arguments[2], arguments[3], 0, + arguments[4], arguments[5], 0, + arguments[6], arguments[7], 0); + } else { + this._renderer.quad.apply(this._renderer, arguments); + } } return this; @@ -52823,8 +53775,8 @@ p5.prototype.quad = function() { * @param {Number} y * @param {Number} w * @param {Number} h - * @param {Integer} [detailX] number of segments in the x-direction - * @param {Integer} [detailY] number of segments in the y-direction + * @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 */ p5.prototype.rect = function() { @@ -52850,6 +53802,60 @@ p5.prototype.rect = function() { return this; }; +/** + * 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, however, + * may be changed with the rectMode() function. + *

+ * The fourth, fifth, sixth and seventh parameters, if specified, + * determine corner radius for the top-left, top-right, lower-right and + * lower-left corners, respectively. An omitted corner radius parameter is set + * to the value of the previously specified radius value in the parameter list. + * + * @method square + * @param {Number} x x-coordinate of the square. + * @param {Number} y y-coordinate of the square. + * @param {Number} s side size of the square. + * @param {Number} [tl] optional radius of top-left corner. + * @param {Number} [tr] optional radius of top-right corner. + * @param {Number} [br] optional radius of bottom-right corner. + * @param {Number} [bl] optional radius of bottom-left corner. + * @chainable + * @example + *
+ * + * // Draw a square at location (30, 20) with a side size of 55. + * square(30, 20, 55); + * + *
+ * + *
+ * + * // Draw a square with rounded corners, each having a radius of 20. + * square(30, 20, 55, 20); + * + *
+ * + *
+ * + * // Draw a square with rounded corners having the following radii: + * // top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5. + * square(30, 20, 55, 20, 15, 10, 5); + * + *
+ * + * @alt + * 55x55 white square with black outline in mid-right of canvas. + * 55x55 white square with black outline and rounded edges in mid-right of canvas. + * 55x55 white square with black outline and rounded edges of different radii. + */ +p5.prototype.square = function(x, y, s, tl, tr, br, bl) { + return this.rect(x, y, s, s, tl, tr, br, bl); +}; + /** * A triangle is a plane created by connecting three points. The first two * arguments specify the first point, the middle two arguments specify the @@ -52886,7 +53892,7 @@ p5.prototype.triangle = function() { module.exports = p5; -},{"../constants":19,"../error_helpers":21,"../helpers":22,"../main":25}],32:[function(_dereq_,module,exports){ +},{"../constants":18,"../error_helpers":20,"../helpers":21,"../main":24}],31:[function(_dereq_,module,exports){ /** * @module Shape * @submodule Attributes @@ -52995,7 +54001,10 @@ p5.prototype.ellipseMode = function(m) { * */ p5.prototype.noSmooth = function() { - this._renderer.noSmooth(); + this.setAttributes('antialias', false); + if ('imageSmoothingEnabled' in this.drawingContext) { + this.drawingContext.imageSmoothingEnabled = false; + } return this; }; @@ -53095,7 +54104,10 @@ p5.prototype.rectMode = function(m) { * */ p5.prototype.smooth = function() { - this._renderer.smooth(); + this.setAttributes('antialias', true); + if ('imageSmoothingEnabled' in this.drawingContext) { + this.drawingContext.imageSmoothingEnabled = true; + } return this; }; @@ -53234,7 +54246,7 @@ p5.prototype.strokeWeight = function(w) { module.exports = p5; -},{"../constants":19,"../main":25}],33:[function(_dereq_,module,exports){ +},{"../constants":18,"../main":24}],32:[function(_dereq_,module,exports){ /** * @module Shape * @submodule Curves @@ -53392,21 +54404,21 @@ p5.prototype.bezierDetail = function(d) { *
* * noFill(); - * var x1 = 85, + * let x1 = 85, x2 = 10, x3 = 90, x4 = 15; - * var y1 = 20, + * let y1 = 20, y2 = 10, y3 = 90, y4 = 80; * bezier(x1, y1, x2, y2, x3, y3, x4, y4); * fill(255); - * var steps = 10; - * for (var i = 0; i <= steps; i++) { - * var t = i / steps; - * var x = bezierPoint(x1, x2, x3, x4, t); - * var y = bezierPoint(y1, y2, y3, y4, t); + * let steps = 10; + * for (let i = 0; i <= steps; i++) { + * let t = i / steps; + * let x = bezierPoint(x1, x2, x3, x4, t); + * let y = bezierPoint(y1, y2, y3, y4, t); * ellipse(x, y, 5, 5); * } * @@ -53446,18 +54458,18 @@ p5.prototype.bezierPoint = function(a, b, c, d, t) { * * noFill(); * bezier(85, 20, 10, 10, 90, 90, 15, 80); - * var steps = 6; + * let steps = 6; * fill(255); - * for (var i = 0; i <= steps; i++) { - * var t = i / steps; + * for (let i = 0; i <= steps; i++) { + * let t = i / steps; * // Get the location of the point - * var x = bezierPoint(85, 10, 90, 15, t); - * var y = bezierPoint(20, 10, 90, 80, t); + * let x = bezierPoint(85, 10, 90, 15, t); + * let y = bezierPoint(20, 10, 90, 80, t); * // Get the tangent points - * var tx = bezierTangent(85, 10, 90, 15, t); - * var ty = bezierTangent(20, 10, 90, 80, t); + * let tx = bezierTangent(85, 10, 90, 15, t); + * let ty = bezierTangent(20, 10, 90, 80, t); * // Calculate an angle from the tangent points - * var a = atan2(ty, tx); + * let a = atan2(ty, tx); * a += PI; * stroke(255, 102, 0); * line(x, y, cos(a) * 30 + x, sin(a) * 30 + y); @@ -53475,14 +54487,14 @@ p5.prototype.bezierPoint = function(a, b, c, d, t) { * noFill(); * bezier(85, 20, 10, 10, 90, 90, 15, 80); * stroke(255, 102, 0); - * var steps = 16; - * for (var i = 0; i <= steps; i++) { - * var t = i / steps; - * var x = bezierPoint(85, 10, 90, 15, t); - * var y = bezierPoint(20, 10, 90, 80, t); - * var tx = bezierTangent(85, 10, 90, 15, t); - * var ty = bezierTangent(20, 10, 90, 80, t); - * var a = atan2(ty, tx); + * let steps = 16; + * for (let i = 0; i <= steps; i++) { + * let t = i / steps; + * let x = bezierPoint(85, 10, 90, 15, t); + * let y = bezierPoint(20, 10, 90, 80, t); + * let tx = bezierTangent(85, 10, 90, 15, t); + * let ty = bezierTangent(20, 10, 90, 80, t); + * let a = atan2(ty, tx); * a -= HALF_PI; * line(x, y, cos(a) * 8 + x, sin(a) * 8 + y); * } @@ -53542,9 +54554,9 @@ p5.prototype.bezierTangent = function(a, b, c, d, t) { *
* * // Define the curve points as JavaScript objects - * var p1 = { x: 5, y: 26 }, + * let p1 = { x: 5, y: 26 }, p2 = { x: 73, y: 24 }; - * var p3 = { x: 73, y: 61 }, + * let p3 = { x: 73, y: 61 }, p4 = { x: 15, y: 65 }; * noFill(); * stroke(255, 102, 0); @@ -53608,7 +54620,7 @@ p5.prototype.curve = function() { * information. * * @method curveDetail - * @param {Number} resolution of the curves + * @param {Number} resolution resolution of the curves * @chainable * @example *
@@ -53650,7 +54662,7 @@ p5.prototype.curveDetail = function(d) { * increase in magnitude, they will continue to deform. * * @method curveTightness - * @param {Number} amount of deformation from the original vertices + * @param {Number} amount amount of deformation from the original vertices * @chainable * @example *
@@ -53664,7 +54676,7 @@ p5.prototype.curveDetail = function(d) { * * function draw() { * background(204); - * var t = map(mouseX, 0, width, -5, 5); + * let t = map(mouseX, 0, width, -5, 5); * curveTightness(t); * beginShape(); * curveVertex(10, 26); @@ -53709,11 +54721,11 @@ p5.prototype.curveTightness = function(t) { * curve(5, 26, 73, 24, 73, 61, 15, 65); * fill(255); * ellipseMode(CENTER); - * var steps = 6; - * for (var i = 0; i <= steps; i++) { - * var t = i / steps; - * var x = curvePoint(5, 5, 73, 73, t); - * var y = curvePoint(26, 26, 24, 61, t); + * let steps = 6; + * for (let i = 0; i <= steps; i++) { + * let t = i / steps; + * let x = curvePoint(5, 5, 73, 73, t); + * let y = curvePoint(26, 26, 24, 61, t); * ellipse(x, y, 5, 5); * x = curvePoint(5, 73, 73, 15, t); * y = curvePoint(26, 24, 61, 65, t); @@ -53753,15 +54765,15 @@ p5.prototype.curvePoint = function(a, b, c, d, t) { * * noFill(); * curve(5, 26, 73, 24, 73, 61, 15, 65); - * var steps = 6; - * for (var i = 0; i <= steps; i++) { - * var t = i / steps; - * var x = curvePoint(5, 73, 73, 15, t); - * var y = curvePoint(26, 24, 61, 65, t); + * let steps = 6; + * for (let i = 0; i <= steps; i++) { + * let t = i / steps; + * let x = curvePoint(5, 73, 73, 15, t); + * let y = curvePoint(26, 24, 61, 65, t); * //ellipse(x, y, 5, 5); - * var tx = curveTangent(5, 73, 73, 15, t); - * var ty = curveTangent(26, 24, 61, 65, t); - * var a = atan2(ty, tx); + * let tx = curveTangent(5, 73, 73, 15, t); + * let ty = curveTangent(26, 24, 61, 65, t); + * let a = atan2(ty, tx); * a -= PI / 2.0; * line(x, y, cos(a) * 8 + x, sin(a) * 8 + y); * } @@ -53784,7 +54796,7 @@ p5.prototype.curveTangent = function(a, b, c, d, t) { module.exports = p5; -},{"../error_helpers":21,"../main":25}],34:[function(_dereq_,module,exports){ +},{"../error_helpers":20,"../main":24}],33:[function(_dereq_,module,exports){ /** * @module Shape * @submodule Vertex @@ -54076,6 +55088,7 @@ p5.prototype.beginShape = function(kind) { * @param {Number} x4 x-coordinate for the anchor point * @param {Number} y4 y-coordinate for the anchor point * @chainable + * * @example *
* @@ -54087,6 +55100,10 @@ p5.prototype.beginShape = function(kind) { * *
* + * @alt + * crescent-shaped line in middle of canvas. Points facing left. + * + * @example *
* * beginShape(); @@ -54098,21 +55115,8 @@ p5.prototype.beginShape = function(kind) { *
* * @alt - * crescent-shaped line in middle of canvas. Points facing left. * white crescent shape in middle of canvas. Points facing left. - */ -/** - * @method bezierVertex - * @param {Number} x2 - * @param {Number} y2 - * @param {Number} [z2] z-coordinate for the first control point (for WebGL mode) - * @param {Number} x3 - * @param {Number} y3 - * @param {Number} [z3] z-coordinate for the second control point (for WebGL mode) - * @param {Number} x4 - * @param {Number} y4 - * @param {Number} [z4] z-coordinate for the anchor point (for WebGL mode) - * @chainable + * * @example *
* @@ -54150,13 +55154,29 @@ p5.prototype.beginShape = function(kind) { * crescent shape in middle of canvas with another crescent shape on positive z-axis. */ +/** + * @method bezierVertex + * @param {Number} x2 + * @param {Number} y2 + * @param {Number} z2 z-coordinate for the first control point (for WebGL mode) + * @param {Number} x3 + * @param {Number} y3 + * @param {Number} z3 z-coordinate for the second control point (for WebGL mode) + * @param {Number} x4 + * @param {Number} y4 + * @param {Number} z4 z-coordinate for the anchor point (for WebGL mode) + * @chainable + */ p5.prototype.bezierVertex = function() { p5._validateParameters('bezierVertex', arguments); if (this._renderer.isP3D) { this._renderer.bezierVertex.apply(this._renderer, arguments); } else { if (vertices.length === 0) { - throw 'vertex() must be used once before calling bezierVertex()'; + p5._friendlyError( + 'vertex() must be used once before calling bezierVertex()', + 'bezierVertex' + ); } else { isBezier = true; var vert = []; @@ -54450,6 +55470,7 @@ p5.prototype.endShape = function(mode) { * @param {Number} x3 x-coordinate for the anchor point * @param {Number} y3 y-coordinate for the anchor point * @chainable + * * @example *
* @@ -54492,16 +55513,19 @@ p5.prototype.endShape = function(mode) { * @alt * arched-shaped black line with 4 pixel thick stroke weight. * backwards s-shaped black line with 4 pixel thick stroke weight. + * */ + /** * @method quadraticVertex * @param {Number} cx * @param {Number} cy - * @param {Number} [cz] z-coordinate for the control point (for WebGL mode) + * @param {Number} cz z-coordinate for the control point (for WebGL mode) * @param {Number} x3 * @param {Number} y3 - * @param {Number} [z3] z-coordinate for the anchor point (for WebGL mode) + * @param {Number} z3 z-coordinate for the anchor point (for WebGL mode) * @chainable + * * @example *
* @@ -54576,8 +55600,9 @@ p5.prototype.quadraticVertex = function() { vertices.push(vert); } } else { - throw new Error( - 'vertex() must be used once before calling quadraticVertex()' + p5._friendlyError( + 'vertex() must be used once before calling quadraticVertex()', + 'quadraticVertex' ); } } @@ -54711,7 +55736,7 @@ p5.prototype.vertex = function(x, y, moveTo, u, v) { module.exports = p5; -},{"../constants":19,"../main":25}],35:[function(_dereq_,module,exports){ +},{"../constants":18,"../main":24}],34:[function(_dereq_,module,exports){ 'use strict'; // requestAnim shim layer by Paul Irish @@ -54813,7 +55838,7 @@ window.requestAnimationFrame = (function() { } })(); -},{}],36:[function(_dereq_,module,exports){ +},{}],35:[function(_dereq_,module,exports){ /** * @module Structure * @submodule Structure @@ -54856,7 +55881,7 @@ var p5 = _dereq_('./main'); *
* *
- * var x = 0; + * let x = 0; * function setup() { * createCanvas(100, 100); * } @@ -54892,10 +55917,12 @@ p5.prototype.noLoop = function() { * within it. However, the draw() loop may be stopped by calling noLoop(). * In that case, the draw() loop can be resumed with loop(). * + * Avoid calling loop() from inside setup(). + * * @method loop * @example *
- * var x = 0; + * let x = 0; * function setup() { * createCanvas(100, 100); * noLoop(); @@ -54925,8 +55952,12 @@ p5.prototype.noLoop = function() { */ p5.prototype.loop = function() { - this._loop = true; - this._draw(); + if (!this._loop) { + this._loop = true; + if (this._setupDone) { + this._draw(); + } + } }; /** @@ -54942,7 +55973,11 @@ p5.prototype.loop = function() { * and style settings controlled by the following functions: fill(), * stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(), * imageMode(), rectMode(), ellipseMode(), colorMode(), textAlign(), - * textFont(), textMode(), textSize(), textLeading(). + * textFont(), textSize(), textLeading(). + *

+ * In WEBGL mode additional style settings are stored. These are controlled by the following functions: setCamera(), ambientLight(), directionalLight(), + * pointLight(), texture(), specularMaterial(), shininess(), normalMaterial() + * and shader(). * * @method push * @example @@ -55007,7 +56042,11 @@ p5.prototype.push = function() { * and style settings controlled by the following functions: fill(), * stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(), * imageMode(), rectMode(), ellipseMode(), colorMode(), textAlign(), - * textFont(), textMode(), textSize(), textLeading(). + * textFont(), textSize(), textLeading(). + *

+ * In WEBGL mode additional style settings are stored. These are controlled by the following functions: setCamera(), ambientLight(), directionalLight(), + * pointLight(), texture(), specularMaterial(), shininess(), normalMaterial() + * and shader(). * * @method pop * @example @@ -55081,7 +56120,7 @@ p5.prototype.pop = function() { * @param {Integer} [n] Redraw for n-times. The default value is 1. * @example *
- * var x = 0; + * let x = 0; * * function setup() { * createCanvas(100, 100); @@ -55100,7 +56139,7 @@ p5.prototype.pop = function() { *
* *
- * var x = 0; + * let x = 0; * * function setup() { * createCanvas(100, 100); @@ -55124,6 +56163,10 @@ p5.prototype.pop = function() { * */ p5.prototype.redraw = function(n) { + if (this._inUserDraw || !this._setupDone) { + return; + } + var numberOfRedraws = parseInt(n); if (isNaN(numberOfRedraws) || numberOfRedraws < 1) { numberOfRedraws = 1; @@ -55146,7 +56189,12 @@ p5.prototype.redraw = function(n) { } context._setProperty('frameCount', context.frameCount + 1); context._registeredMethods.pre.forEach(callMethod); - userDraw(); + this._inUserDraw = true; + try { + userDraw(); + } finally { + this._inUserDraw = false; + } context._registeredMethods.post.forEach(callMethod); } } @@ -55154,7 +56202,7 @@ p5.prototype.redraw = function(n) { module.exports = p5; -},{"./main":25}],37:[function(_dereq_,module,exports){ +},{"./main":24}],36:[function(_dereq_,module,exports){ /** * @module Transform * @submodule Transform @@ -55264,6 +56312,33 @@ var p5 = _dereq_('./main'); * } * *
+ *
+ * + * function setup() { + * createCanvas(100, 100, WEBGL); + * noFill(); + * } + * + * function draw() { + * background(200); + * rotateY(PI / 6); + * stroke(153); + * box(35); + * var rad = millis() / 1000; + * // Set rotation angles + * var ct = cos(rad); + * var st = sin(rad); + * // Matrix for rotation around the Y axis + * // prettier-ignore + * applyMatrix( ct, 0.0, st, 0.0, + * 0.0, 1.0, 0.0, 0.0, + * -st, 0.0, ct, 0.0, + * 0.0, 0.0, 0.0, 1.0); + * stroke(255); + * box(50); + * } + * + *
* * @alt * A rectangle translating to the right @@ -55273,22 +56348,10 @@ var p5 = _dereq_('./main'); * */ p5.prototype.applyMatrix = function(a, b, c, d, e, f) { - this._renderer.applyMatrix(a, b, c, d, e, f); + this._renderer.applyMatrix.apply(this._renderer, arguments); return this; }; -p5.prototype.popMatrix = function() { - throw new Error('popMatrix() not used, see pop()'); -}; - -p5.prototype.printMatrix = function() { - throw new Error('printMatrix() not implemented'); -}; - -p5.prototype.pushMatrix = function() { - throw new Error('pushMatrix() not used, see push()'); -}; - /** * Replaces the current matrix with the identity matrix. * @@ -55555,7 +56618,8 @@ p5.prototype.scale = function(x, y, z) { */ p5.prototype.shearX = function(angle) { p5._validateParameters('shearX', arguments); - this._renderer.shearX(this._toRadians(angle)); + var rad = this._toRadians(angle); + this._renderer.applyMatrix(1, 0, Math.tan(rad), 1, 0, 0); return this; }; @@ -55594,7 +56658,8 @@ p5.prototype.shearX = function(angle) { */ p5.prototype.shearY = function(angle) { p5._validateParameters('shearY', arguments); - this._renderer.shearY(this._toRadians(angle)); + var rad = this._toRadians(angle); + this._renderer.applyMatrix(1, Math.tan(rad), 0, 1, 0, 0); return this; }; @@ -55669,7 +56734,7 @@ p5.prototype.translate = function(x, y, z) { module.exports = p5; -},{"./main":25}],38:[function(_dereq_,module,exports){ +},{"./main":24}],37:[function(_dereq_,module,exports){ /** * @module Data * @submodule Dictionary @@ -55700,10 +56765,10 @@ var p5 = _dereq_('../core/main'); *
* * function setup() { - * var myDictionary = createStringDict('p5', 'js'); + * let myDictionary = createStringDict('p5', 'js'); * print(myDictionary.hasKey('p5')); // logs true to console * - * var anotherDictionary = createStringDict({ happy: 'coding' }); + * let anotherDictionary = createStringDict({ happy: 'coding' }); * print(anotherDictionary.hasKey('happy')); // logs true to console * } *
@@ -55734,10 +56799,10 @@ p5.prototype.createStringDict = function(key, value) { *
* * function setup() { - * var myDictionary = createNumberDict(100, 42); + * let myDictionary = createNumberDict(100, 42); * print(myDictionary.hasKey(100)); // logs true to console * - * var anotherDictionary = createNumberDict({ 200: 84 }); + * let anotherDictionary = createNumberDict({ 200: 84 }); * print(anotherDictionary.hasKey(200)); // logs true to console * } *
@@ -55782,7 +56847,7 @@ p5.TypedDict = function(key, value) { *
* * function setup() { - * var myDictionary = createNumberDict(1, 10); + * let myDictionary = createNumberDict(1, 10); * myDictionary.create(2, 20); * myDictionary.create(3, 30); * print(myDictionary.size()); // logs 3 to the console @@ -55806,7 +56871,7 @@ p5.TypedDict.prototype.size = function() { *
* * function setup() { - * var myDictionary = createStringDict('p5', 'js'); + * let myDictionary = createStringDict('p5', 'js'); * print(myDictionary.hasKey('p5')); // logs true to console * } *
@@ -55828,8 +56893,8 @@ p5.TypedDict.prototype.hasKey = function(key) { *
* * function setup() { - * var myDictionary = createStringDict('p5', 'js'); - * var myValue = myDictionary.get('p5'); + * let myDictionary = createStringDict('p5', 'js'); + * let myValue = myDictionary.get('p5'); * print(myValue === 'js'); // logs true to console * } *
@@ -55856,7 +56921,7 @@ p5.TypedDict.prototype.get = function(key) { *
* * function setup() { - * var myDictionary = createStringDict('p5', 'js'); + * let myDictionary = createStringDict('p5', 'js'); * myDictionary.set('p5', 'JS'); * myDictionary.print(); // logs "key: p5 - value: JS" to console * } @@ -55894,7 +56959,7 @@ p5.TypedDict.prototype._addObj = function(obj) { *
* * function setup() { - * var myDictionary = createStringDict('p5', 'js'); + * let myDictionary = createStringDict('p5', 'js'); * myDictionary.create('happy', 'coding'); * myDictionary.print(); * // above logs "key: p5 - value: js, key: happy - value: coding" to console @@ -55927,7 +56992,7 @@ p5.TypedDict.prototype.create = function(key, value) { *
* * function setup() { - * var myDictionary = createStringDict('p5', 'js'); + * let myDictionary = createStringDict('p5', 'js'); * print(myDictionary.hasKey('p5')); // prints 'true' * myDictionary.clear(); * print(myDictionary.hasKey('p5')); // prints 'false' @@ -55950,7 +57015,7 @@ p5.TypedDict.prototype.clear = function() { *
* * function setup() { - * var myDictionary = createStringDict('p5', 'js'); + * let myDictionary = createStringDict('p5', 'js'); * myDictionary.create('happy', 'coding'); * myDictionary.print(); * // above logs "key: p5 - value: js, key: happy - value: coding" to console @@ -55979,7 +57044,7 @@ p5.TypedDict.prototype.remove = function(key) { *
* * function setup() { - * var myDictionary = createStringDict('p5', 'js'); + * let myDictionary = createStringDict('p5', 'js'); * myDictionary.create('happy', 'coding'); * myDictionary.print(); * // above logs "key: p5 - value: js, key: happy - value: coding" to console @@ -56001,16 +57066,22 @@ p5.TypedDict.prototype.print = function() { * @example *
* - * createButton('save') - * .position(10, 10) - * .mousePressed(function() { + * 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'); - * }); + * } + * } * *
*/ @@ -56033,16 +57104,22 @@ p5.TypedDict.prototype.saveTable = function(filename) { * @example *
* - * createButton('save') - * .position(10, 10) - * .mousePressed(function() { + * 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'); - * }); + * } + * } * *
*/ @@ -56114,7 +57191,7 @@ p5.NumberDict.prototype._validate = function(value) { *
* * function setup() { - * var myDictionary = createNumberDict(2, 5); + * let myDictionary = createNumberDict(2, 5); * myDictionary.add(2, 2); * print(myDictionary.get(2)); // logs 7 to console. * } @@ -56142,7 +57219,7 @@ p5.NumberDict.prototype.add = function(key, amount) { *
* * function setup() { - * var myDictionary = createNumberDict(2, 5); + * let myDictionary = createNumberDict(2, 5); * myDictionary.sub(2, 2); * print(myDictionary.get(2)); // logs 3 to console. * } @@ -56166,7 +57243,7 @@ p5.NumberDict.prototype.sub = function(key, amount) { *
* * function setup() { - * var myDictionary = createNumberDict(2, 4); + * let myDictionary = createNumberDict(2, 4); * myDictionary.mult(2, 2); * print(myDictionary.get(2)); // logs 8 to console. * } @@ -56194,7 +57271,7 @@ p5.NumberDict.prototype.mult = function(key, amount) { *
* * function setup() { - * var myDictionary = createNumberDict(2, 8); + * let myDictionary = createNumberDict(2, 8); * myDictionary.div(2, 2); * print(myDictionary.get(2)); // logs 4 to console. * } @@ -56245,8 +57322,8 @@ p5.NumberDict.prototype._valueTest = function(flip) { *
* * function setup() { - * var myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 }); - * var lowestValue = myDictionary.minValue(); // value is -10 + * let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 }); + * let lowestValue = myDictionary.minValue(); // value is -10 * print(lowestValue); * } *
@@ -56266,8 +57343,8 @@ p5.NumberDict.prototype.minValue = function() { *
* * function setup() { - * var myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 }); - * var highestValue = myDictionary.maxValue(); // value is 3 + * let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 }); + * let highestValue = myDictionary.maxValue(); // value is 3 * print(highestValue); * } *
@@ -56310,8 +57387,8 @@ p5.NumberDict.prototype._keyTest = function(flip) { *
* * function setup() { - * var myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 }); - * var lowestKey = myDictionary.minKey(); // value is 1.2 + * let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 }); + * let lowestKey = myDictionary.minKey(); // value is 1.2 * print(lowestKey); * } *
@@ -56331,8 +57408,8 @@ p5.NumberDict.prototype.minKey = function() { *
* * function setup() { - * var myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 }); - * var highestKey = myDictionary.maxKey(); // value is 4 + * let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 }); + * let highestKey = myDictionary.maxKey(); // value is 4 * print(highestKey); * } *
@@ -56345,7 +57422,7 @@ p5.NumberDict.prototype.maxKey = function() { module.exports = p5.TypedDict; -},{"../core/main":25}],39:[function(_dereq_,module,exports){ +},{"../core/main":24}],38:[function(_dereq_,module,exports){ /** * @module Events * @submodule Acceleration @@ -56374,6 +57451,20 @@ p5.prototype.deviceOrientation = undefined; * * @property {Number} accelerationX * @readOnly + * @example + *
+ * + * // Move a touchscreen device to register + * // acceleration changes. + * function draw() { + * background(220, 50); + * fill('magenta'); + * ellipse(width / 2, height / 2, accelerationX); + * } + * + *
+ * @alt + * Magnitude of device acceleration is displayed as ellipse size */ p5.prototype.accelerationX = 0; @@ -56383,6 +57474,20 @@ p5.prototype.accelerationX = 0; * * @property {Number} accelerationY * @readOnly + * @example + *
+ * + * // Move a touchscreen device to register + * // acceleration changes. + * function draw() { + * background(220, 50); + * fill('magenta'); + * ellipse(width / 2, height / 2, accelerationY); + * } + * + *
+ * @alt + * Magnitude of device acceleration is displayed as ellipse size */ p5.prototype.accelerationY = 0; @@ -56392,6 +57497,22 @@ p5.prototype.accelerationY = 0; * * @property {Number} accelerationZ * @readOnly + * + * @example + *
+ * + * // Move a touchscreen device to register + * // acceleration changes. + * function draw() { + * background(220, 50); + * fill('magenta'); + * ellipse(width / 2, height / 2, accelerationZ); + * } + * + *
+ * + * @alt + * Magnitude of device acceleration is displayed as ellipse size */ p5.prototype.accelerationZ = 0; @@ -56444,6 +57565,8 @@ p5.prototype._updatePAccelerations = function() { * together, it must be called in the order Z-X-Y or there might be * unexpected behaviour. * + * @property {Number} rotationX + * @readOnly * @example *
* @@ -56460,13 +57583,8 @@ p5.prototype._updatePAccelerations = function() { * } * *
- * - * @property {Number} rotationX - * @readOnly - * * @alt * red horizontal line right, green vertical line bottom. black background. - * */ p5.prototype.rotationX = 0; @@ -56478,6 +57596,8 @@ p5.prototype.rotationX = 0; * together, it must be called in the order Z-X-Y or there might be * unexpected behaviour. * + * @property {Number} rotationY + * @readOnly * @example *
* @@ -56494,10 +57614,6 @@ p5.prototype.rotationX = 0; * } * *
- * - * @property {Number} rotationY - * @readOnly - * * @alt * red horizontal line right, green vertical line bottom. black background. */ @@ -56556,14 +57672,14 @@ p5.prototype.rotationZ = 0; * * // Some extra logic is needed to account for cases where * // the angles wrap around. - * var rotateDirection = 'clockwise'; + * let rotateDirection = 'clockwise'; * * // Simple range conversion to make things simpler. * // This is not absolutely necessary but the logic * // will be different in that case. * - * var rX = rotationX + 180; - * var pRX = pRotationX + 180; + * let rX = rotationX + 180; + * let pRX = pRotationX + 180; * * if ((rX - pRX > 0 && rX - pRX < 270) || rX - pRX < -270) { * rotateDirection = 'clockwise'; @@ -56601,14 +57717,14 @@ p5.prototype.pRotationX = 0; * * // Some extra logic is needed to account for cases where * // the angles wrap around. - * var rotateDirection = 'clockwise'; + * let rotateDirection = 'clockwise'; * * // Simple range conversion to make things simpler. * // This is not absolutely necessary but the logic * // will be different in that case. * - * var rY = rotationY + 180; - * var pRY = pRotationY + 180; + * let rY = rotationY + 180; + * let pRY = pRotationY + 180; * * if ((rY - pRY > 0 && rY - pRY < 270) || rY - pRY < -270) { * rotateDirection = 'clockwise'; @@ -56645,7 +57761,7 @@ p5.prototype.pRotationY = 0; * * // Some extra logic is needed to account for cases where * // the angles wrap around. - * var rotateDirection = 'clockwise'; + * let rotateDirection = 'clockwise'; * * if ( * (rotationZ - pRotationZ > 0 && rotationZ - pRotationZ < 270) || @@ -56687,8 +57803,38 @@ p5.prototype._updatePRotations = function() { }; /** + * When a device is rotated, the axis that triggers the deviceTurned() + * method is stored in the turnAxis variable. The turnAxis variable is only defined within + * the scope of deviceTurned(). * @property {String} turnAxis * @readOnly + * @example + *
+ * + * // Run this example on a mobile device + * // Rotate the device by 90 degrees in the + * // X-axis to change the value. + * + * var value = 0; + * function draw() { + * fill(value); + * rect(25, 25, 50, 50); + * } + * function deviceTurned() { + * if (turnAxis === 'X') { + * if (value === 0) { + * value = 255; + * } else if (value === 255) { + * value = 0; + * } + * } + * } + * + *
+ * + * @alt + * 50x50 black rect in center of canvas. turns white on mobile when device turns + * 50x50 black rect in center of canvas. turns white on mobile when x-axis turns */ p5.prototype.turnAxis = undefined; @@ -56708,8 +57854,8 @@ var shake_threshold = 30; * // You will need to move the device incrementally further * // the closer the square's color gets to white in order to change the value. * - * var value = 0; - * var threshold = 0.5; + * let value = 0; + * let threshold = 0.5; * function setup() { * setMoveThreshold(threshold); * } @@ -56751,8 +57897,8 @@ p5.prototype.setMoveThreshold = function(val) { * // You will need to shake the device more firmly * // the closer the box's fill gets to white in order to change the value. * - * var value = 0; - * var threshold = 30; + * let value = 0; + * let threshold = 30; * function setup() { * setShakeThreshold(threshold); * } @@ -56784,8 +57930,9 @@ p5.prototype.setShakeThreshold = function(val) { /** * The deviceMoved() function is called when the device is moved by more than - * the threshold value along X, Y or Z axis. The default threshold is set to - * 0.5. + * the threshold value along X, Y or Z axis. The default threshold is set to 0.5. + * The threshold value can be changed using setMoveThreshold(). + * * @method deviceMoved * @example *
@@ -56794,7 +57941,7 @@ p5.prototype.setShakeThreshold = function(val) { * // Move the device around * // to change the value. * - * var value = 0; + * let value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); @@ -56829,7 +57976,7 @@ p5.prototype.setShakeThreshold = function(val) { * // Rotate the device by 90 degrees * // to change the value. * - * var value = 0; + * let value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); @@ -56849,7 +57996,7 @@ p5.prototype.setShakeThreshold = function(val) { * // Rotate the device by 90 degrees in the * // X-axis to change the value. * - * var value = 0; + * let value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); @@ -56876,6 +58023,8 @@ p5.prototype.setShakeThreshold = function(val) { * The deviceShaken() function is called when the device total acceleration * changes of accelerationX and accelerationY values is more than * the threshold value. The default threshold is set to 30. + * The threshold value can be changed using setShakeThreshold(). + * * @method deviceShaken * @example *
@@ -56883,7 +58032,7 @@ p5.prototype.setShakeThreshold = function(val) { * // Run this example on a mobile device * // Shake the device to change the value. * - * var value = 0; + * let value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); @@ -57024,7 +58173,7 @@ p5.prototype._handleMotion = function() { module.exports = p5; -},{"../core/main":25}],40:[function(_dereq_,module,exports){ +},{"../core/main":24}],39:[function(_dereq_,module,exports){ /** * @module Events * @submodule Keyboard @@ -57036,12 +58185,6 @@ module.exports = p5; var p5 = _dereq_('../core/main'); -/** - * Holds the key codes of currently pressed keys. - * @private - */ -var downKeys = {}; - /** * The boolean system variable keyIsPressed is true if any key is pressed * and false if no keys are pressed. @@ -57109,7 +58252,7 @@ p5.prototype.key = ''; * @readOnly * @example *
- * var fillVal = 126; + * let fillVal = 126; * function draw() { * fill(fillVal); * rect(25, 25, 50, 50); @@ -57124,10 +58267,18 @@ p5.prototype.key = ''; * return false; // prevent default * } *
- * + *
+ * function draw() {} + * function keyPressed() { + * background('yellow'); + * text(`${key} ${keyCode}`, 10, 40); + * print(key, ' ', keyCode); + * return false; // prevent default + * } + *
* @alt * Grey rect center. turns white when up arrow pressed and black when down - * + * Display key pressed and its keyCode in a yellow box */ p5.prototype.keyCode = 0; @@ -57139,7 +58290,7 @@ p5.prototype.keyCode = 0; * equals BACKSPACE, DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL, * OPTION, ALT, UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW. *

- * For ASCII keys that was pressed is stored in the key variable. However, it + * For ASCII keys, the key that was pressed is stored in the key variable. However, it * does not distinguish between uppercase and lowercase. For this reason, it * is recommended to use keyTyped() to read the key variable, in which the * case of the variable will be distinguished. @@ -57156,7 +58307,7 @@ p5.prototype.keyCode = 0; * @example *
* - * var value = 0; + * let value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); @@ -57172,7 +58323,7 @@ p5.prototype.keyCode = 0; *
*
* - * var value = 0; + * let value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); @@ -57201,14 +58352,14 @@ p5.prototype.keyCode = 0; * */ p5.prototype._onkeydown = function(e) { - if (downKeys[e.which]) { + if (this._downKeys[e.which]) { // prevent multiple firings return; } this._setProperty('isKeyPressed', true); this._setProperty('keyIsPressed', true); this._setProperty('keyCode', e.which); - downKeys[e.which] = true; + this._downKeys[e.which] = true; this._setProperty('key', e.key || String.fromCharCode(e.which) || e.which); var keyPressed = this.keyPressed || window.keyPressed; if (typeof keyPressed === 'function' && !e.charCode) { @@ -57229,7 +58380,7 @@ p5.prototype._onkeydown = function(e) { * @example *
* - * var value = 0; + * let value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); @@ -57251,9 +58402,9 @@ p5.prototype._onkeydown = function(e) { */ p5.prototype._onkeyup = function(e) { var keyReleased = this.keyReleased || window.keyReleased; - downKeys[e.which] = false; + this._downKeys[e.which] = false; - if (!areDownKeys()) { + if (!this._areDownKeys()) { this._setProperty('isKeyPressed', false); this._setProperty('keyIsPressed', false); } @@ -57287,7 +58438,7 @@ p5.prototype._onkeyup = function(e) { * @example *
* - * var value = 0; + * let value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); @@ -57331,7 +58482,7 @@ p5.prototype._onkeypress = function(e) { * been released. */ p5.prototype._onblur = function(e) { - downKeys = {}; + this._downKeys = {}; }; /** @@ -57347,11 +58498,12 @@ p5.prototype._onblur = function(e) { * @return {Boolean} whether key is down or not * @example *
- * var x = 100; - * var y = 100; + * let x = 100; + * let y = 100; * * function setup() { * createCanvas(512, 512); + * fill(255, 0, 0); * } * * function draw() { @@ -57372,13 +58524,12 @@ p5.prototype._onblur = function(e) { * } * * clear(); - * fill(255, 0, 0); * ellipse(x, y, 50, 50); * } *
* *
- * var diameter = 50; + * let diameter = 50; * * function setup() { * createCanvas(512, 512); @@ -57408,30 +58559,30 @@ p5.prototype._onblur = function(e) { */ p5.prototype.keyIsDown = function(code) { p5._validateParameters('keyIsDown', arguments); - return downKeys[code]; + return this._downKeys[code]; }; /** - * The checkDownKeys function returns a boolean true if any keys pressed + * The _areDownKeys function returns a boolean true if any keys pressed * and a false if no keys are currently pressed. - * Helps avoid instances where a multiple keys are pressed simultaneously and + * Helps avoid instances where multiple keys are pressed simultaneously and * releasing a single key will then switch the * keyIsPressed property to true. * @private **/ -function areDownKeys() { - for (var key in downKeys) { - if (downKeys.hasOwnProperty(key) && downKeys[key] === true) { +p5.prototype._areDownKeys = function() { + for (var key in this._downKeys) { + if (this._downKeys.hasOwnProperty(key) && this._downKeys[key] === true) { return true; } } return false; -} +}; module.exports = p5; -},{"../core/main":25}],41:[function(_dereq_,module,exports){ +},{"../core/main":24}],40:[function(_dereq_,module,exports){ /** * @module Events * @submodule Mouse @@ -57563,7 +58714,7 @@ p5.prototype.pmouseX = 0; *
* * @alt - * 60x60 black rect center, fuschia background. rect flickers on mouse movement + * 60x60 black rect center, fuchsia background. rect flickers on mouse movement * */ p5.prototype.pmouseY = 0; @@ -57578,11 +58729,13 @@ p5.prototype.pmouseY = 0; * @example *
* - * var myCanvas; + * let myCanvas; * * function setup() { * //use a variable to store a pointer to the canvas * myCanvas = createCanvas(100, 100); + * const body = document.getElementsByTagName('body')[0]; + * myCanvas.parent(body); * } * * function draw() { @@ -57590,7 +58743,7 @@ p5.prototype.pmouseY = 0; * fill(0); * * //move the canvas to the horizontal mouse position - * //rela tive to the window + * //relative to the window * myCanvas.position(winMouseX + 1, windowHeight / 2); * * //the y of the square is relative to the canvas @@ -57600,7 +58753,7 @@ p5.prototype.pmouseY = 0; *
* * @alt - * 60x60 black rect y moves with mouse y and fuschia canvas moves with mouse x + * 60x60 black rect y moves with mouse y and fuchsia canvas moves with mouse x * */ p5.prototype.winMouseX = 0; @@ -57615,11 +58768,13 @@ p5.prototype.winMouseX = 0; * @example *
* - * var myCanvas; + * let myCanvas; * * function setup() { * //use a variable to store a pointer to the canvas * myCanvas = createCanvas(100, 100); + * const body = document.getElementsByTagName('body')[0]; + * myCanvas.parent(body); * } * * function draw() { @@ -57627,7 +58782,7 @@ p5.prototype.winMouseX = 0; * fill(0); * * //move the canvas to the vertical mouse position - * //rel ative to the window + * //relative to the window * myCanvas.position(windowWidth / 2, winMouseY + 1); * * //the x of the square is relative to the canvas @@ -57637,7 +58792,7 @@ p5.prototype.winMouseX = 0; *
* * @alt - * 60x60 black rect x moves with mouse x and fuschia canvas y moves with mouse y + * 60x60 black rect x moves with mouse x and fuchsia canvas y moves with mouse y * */ p5.prototype.winMouseY = 0; @@ -57654,7 +58809,7 @@ p5.prototype.winMouseY = 0; * @example *
* - * var myCanvas; + * let myCanvas; * * function setup() { * //use a variable to store a pointer to the canvas @@ -57667,7 +58822,7 @@ p5.prototype.winMouseY = 0; * clear(); * //the difference between previous and * //current x position is the horizontal mouse speed - * var speed = abs(winMouseX - pwinMouseX); + * let speed = abs(winMouseX - pwinMouseX); * //change the size of the circle * //according to the horizontal speed * ellipse(50, 50, 10 + speed * 5, 10 + speed * 5); @@ -57678,7 +58833,7 @@ p5.prototype.winMouseY = 0; *
* * @alt - * fuschia ellipse moves with mouse x and y. Grows and shrinks with mouse speed + * fuchsia ellipse moves with mouse x and y. Grows and shrinks with mouse speed * */ p5.prototype.pwinMouseX = 0; @@ -57696,7 +58851,7 @@ p5.prototype.pwinMouseX = 0; * @example *
* - * var myCanvas; + * let myCanvas; * * function setup() { * //use a variable to store a pointer to the canvas @@ -57709,7 +58864,7 @@ p5.prototype.pwinMouseX = 0; * clear(); * //the difference between previous and * //current y position is the vertical mouse speed - * var speed = abs(winMouseY - pwinMouseY); + * let speed = abs(winMouseY - pwinMouseY); * //change the size of the circle * //according to the vertical speed * ellipse(50, 50, 10 + speed * 5, 10 + speed * 5); @@ -57720,7 +58875,7 @@ p5.prototype.pwinMouseX = 0; *
* * @alt - * fuschia ellipse moves with mouse x and y. Grows and shrinks with mouse speed + * fuchsia ellipse moves with mouse x and y. Grows and shrinks with mouse speed * */ p5.prototype.pwinMouseY = 0; @@ -57759,7 +58914,7 @@ p5.prototype.pwinMouseY = 0; *
* * @alt - * 50x50 black ellipse appears on center of fuschia canvas on mouse click/press. + * 50x50 black ellipse appears on center of fuchsia canvas on mouse click/press. * */ p5.prototype.mouseButton = 0; @@ -57790,7 +58945,7 @@ p5.prototype.mouseButton = 0; *
* * @alt - * black 50x50 rect becomes ellipse with mouse click/press. fuschia background. + * black 50x50 rect becomes ellipse with mouse click/press. fuchsia background. * */ p5.prototype.mouseIsPressed = false; @@ -57863,13 +59018,14 @@ p5.prototype._setMouseButton = function(e) { * behavior for this event, add "return false" to the end of the method. * * @method mouseMoved + * @param {Object} [event] optional MouseEvent callback argument. * @example *
* * // Move the mouse across the page * // to change its value * - * var value = 0; + * let value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); @@ -57893,6 +59049,16 @@ p5.prototype._setMouseButton = function(e) { * *
* + *
+ * + * // returns a MouseEvent object + * // as a callback argument + * function mouseMoved(event) { + * console.log(event); + * } + * + *
+ * * @alt * black 50x50 rect becomes lighter with mouse movements until white then resets * no image displayed @@ -57908,13 +59074,14 @@ p5.prototype._setMouseButton = function(e) { * behavior for this event, add "return false" to the end of the method. * * @method mouseDragged + * @param {Object} [event] optional MouseEvent callback argument. * @example *
* * // Drag the mouse across the page * // to change its value * - * var value = 0; + * let value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); @@ -57938,6 +59105,16 @@ p5.prototype._setMouseButton = function(e) { * *
* + *
+ * + * // returns a MouseEvent object + * // as a callback argument + * function mouseDragged(event) { + * console.log(event); + * } + * + *
+ * * @alt * black 50x50 rect turns lighter with mouse click and drag until white, resets * no image displayed @@ -57980,13 +59157,14 @@ p5.prototype._onmousemove = function(e) { * behavior for this event, add "return false" to the end of the method. * * @method mousePressed + * @param {Object} [event] optional MouseEvent callback argument. * @example *
* * // Click within the image to change * // the value of the rectangle * - * var value = 0; + * let value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); @@ -58011,6 +59189,16 @@ p5.prototype._onmousemove = function(e) { * *
* + *
+ * + * // returns a MouseEvent object + * // as a callback argument + * function mousePressed(event) { + * console.log(event); + * } + * + *
+ * * @alt * black 50x50 rect turns white with mouse click/press. * no image displayed @@ -58045,6 +59233,7 @@ p5.prototype._onmousedown = function(e) { * * * @method mouseReleased + * @param {Object} [event] optional MouseEvent callback argument. * @example *
* @@ -58052,7 +59241,7 @@ p5.prototype._onmousedown = function(e) { * // the value of the rectangle * // after the mouse has been clicked * - * var value = 0; + * let value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); @@ -58077,6 +59266,16 @@ p5.prototype._onmousedown = function(e) { * *
* + *
+ * + * // returns a MouseEvent object + * // as a callback argument + * function mouseReleased(event) { + * console.log(event); + * } + * + *
+ * * @alt * black 50x50 rect turns white with mouse click/press. * no image displayed @@ -58113,6 +59312,7 @@ p5.prototype._ondragover = p5.prototype._onmousemove; * behavior for this event, add "return false" to the end of the method. * * @method mouseClicked + * @param {Object} [event] optional MouseEvent callback argument. * @example *
* @@ -58120,7 +59320,7 @@ p5.prototype._ondragover = p5.prototype._onmousemove; * // the value of the rectangle * // after the mouse has been clicked * - * var value = 0; + * let value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); @@ -58146,6 +59346,16 @@ p5.prototype._ondragover = p5.prototype._onmousemove; * *
* + *
+ * + * // returns a MouseEvent object + * // as a callback argument + * function mouseClicked(event) { + * console.log(event); + * } + * + *
+ * * @alt * black 50x50 rect turns white with mouse click/press. * no image displayed @@ -58171,6 +59381,7 @@ p5.prototype._onclick = function(e) { * https://developer.mozilla.org/en-US/docs/Web/Events/dblclick * * @method doubleClicked + * @param {Object} [event] optional MouseEvent callback argument. * @example *
* @@ -58178,7 +59389,7 @@ p5.prototype._onclick = function(e) { * // the value of the rectangle * // after the mouse has been double clicked * - * var value = 0; + * let value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); @@ -58204,6 +59415,16 @@ p5.prototype._onclick = function(e) { * *
* + *
+ * + * // returns a MouseEvent object + * // as a callback argument + * function doubleClicked(event) { + * console.log(event); + * } + * + *
+ * * @alt * black 50x50 rect turns white with mouse doubleClick/press. * no image displayed @@ -58250,11 +59471,12 @@ p5.prototype._pmouseWheelDeltaY = 0; * may only work as expected if "return false" is included while using Safari. * * @method mouseWheel + * @param {Object} [event] optional WheelEvent callback argument. * * @example *
* - * var pos = 25; + * let pos = 25; * * function draw() { * background(237, 34, 93); @@ -58273,7 +59495,7 @@ p5.prototype._pmouseWheelDeltaY = 0; *
* * @alt - * black 50x50 rect moves up and down with vertical scroll. fuschia background + * black 50x50 rect moves up and down with vertical scroll. fuchsia background * */ p5.prototype._onwheel = function(e) { @@ -58290,7 +59512,7 @@ p5.prototype._onwheel = function(e) { module.exports = p5; -},{"../core/constants":19,"../core/main":25}],42:[function(_dereq_,module,exports){ +},{"../core/constants":18,"../core/main":24}],41:[function(_dereq_,module,exports){ /** * @module Events * @submodule Touch @@ -58322,7 +59544,7 @@ var p5 = _dereq_('../core/main'); * // at the same time * function draw() { * clear(); - * var display = touches.length + ' touches'; + * let display = touches.length + ' touches'; * text(display, 5, 10); * } * @@ -58373,13 +59595,14 @@ function getTouchInfo(canvas, w, h, e, i) { * to the end of the method. * * @method touchStarted + * @param {Object} [event] optional TouchEvent callback argument. * @example *
* * // Touch within the image to change * // the value of the rectangle * - * var value = 0; + * let value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); @@ -58404,6 +59627,16 @@ function getTouchInfo(canvas, w, h, e, i) { * *
* + *
+ * + * // returns a TouchEvent object + * // as a callback argument + * function touchStarted(event) { + * console.log(event); + * } + * + *
+ * * @alt * 50x50 black rect turns white with touch event. * no image displayed @@ -58437,13 +59670,14 @@ p5.prototype._ontouchstart = function(e) { * to the end of the method. * * @method touchMoved + * @param {Object} [event] optional TouchEvent callback argument. * @example *
* * // Move your finger across the page * // to change its value * - * var value = 0; + * let value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); @@ -58467,6 +59701,16 @@ p5.prototype._ontouchstart = function(e) { * *
* + *
+ * + * // returns a TouchEvent object + * // as a callback argument + * function touchMoved(event) { + * console.log(event); + * } + * + *
+ * * @alt * 50x50 black rect turns lighter with touch until white. resets * no image displayed @@ -58499,13 +59743,14 @@ p5.prototype._ontouchmove = function(e) { * to the end of the method. * * @method touchEnded + * @param {Object} [event] optional TouchEvent callback argument. * @example *
* * // Release touch within the image to * // change the value of the rectangle * - * var value = 0; + * let value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); @@ -58530,6 +59775,16 @@ p5.prototype._ontouchmove = function(e) { * *
* + *
+ * + * // returns a TouchEvent object + * // as a callback argument + * function touchEnded(event) { + * console.log(event); + * } + * + *
+ * * @alt * 50x50 black rect turns white with touch. * no image displayed @@ -58556,7 +59811,7 @@ p5.prototype._ontouchend = function(e) { module.exports = p5; -},{"../core/main":25}],43:[function(_dereq_,module,exports){ +},{"../core/main":24}],42:[function(_dereq_,module,exports){ /*global ImageData:false */ /** @@ -58698,16 +59953,32 @@ Filters._createImageData = function(width, height) { * @param {Object} filterParam [description] */ Filters.apply = function(canvas, func, filterParam) { - var ctx = canvas.getContext('2d'); - var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); + 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) { - ctx.putImageData(newImageData, 0, 0, 0, 0, canvas.width, canvas.height); + pixelsState.putImageData( + newImageData, + 0, + 0, + 0, + 0, + canvas.width, + canvas.height + ); } else { - ctx.putImageData(imageData, 0, 0, 0, 0, canvas.width, canvas.height); + pixelsState.putImageData( + imageData, + 0, + 0, + 0, + 0, + canvas.width, + canvas.height + ); } }; @@ -59166,7 +60437,7 @@ Filters.blur = function(canvas, radius) { module.exports = Filters; -},{}],44:[function(_dereq_,module,exports){ +},{}],43:[function(_dereq_,module,exports){ /** * @module Image * @submodule Image @@ -59212,10 +60483,10 @@ var p5 = _dereq_('../core/main'); * @example *
* - * var img = createImage(66, 66); + * let img = createImage(66, 66); * img.loadPixels(); - * for (var i = 0; i < img.width; i++) { - * for (var j = 0; j < img.height; j++) { + * for (let i = 0; i < img.width; i++) { + * for (let j = 0; j < img.height; j++) { * img.set(i, j, color(0, 90, 102)); * } * } @@ -59226,10 +60497,10 @@ var p5 = _dereq_('../core/main'); * *
* - * var img = createImage(66, 66); + * let img = createImage(66, 66); * img.loadPixels(); - * for (var i = 0; i < img.width; i++) { - * for (var j = 0; j < img.height; j++) { + * 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)); * } * } @@ -59241,12 +60512,12 @@ var p5 = _dereq_('../core/main'); * *
* - * var pink = color(255, 102, 204); - * var img = createImage(66, 66); + * let pink = color(255, 102, 204); + * let img = createImage(66, 66); * img.loadPixels(); - * var d = pixelDensity(); - * var halfImage = 4 * (img.width * d) * (img.height / 2 * d); - * for (var i = 0; i < halfImage; i += 4) { + * let d = pixelDensity(); + * let halfImage = 4 * (img.width * d) * (img.height / 2 * d); + * for (let i = 0; i < halfImage; i += 4) { * img.pixels[i] = red(pink); * img.pixels[i + 1] = green(pink); * img.pixels[i + 2] = blue(pink); @@ -59281,7 +60552,7 @@ p5.prototype.createImage = function(width, height) { * @example *
* function setup() { - * var c = createCanvas(100, 100); + * let c = createCanvas(100, 100); * background(255, 0, 0); * saveCanvas(c, 'myCanvas', 'jpg'); * } @@ -59290,7 +60561,7 @@ p5.prototype.createImage = function(width, height) { * // note that this example has the same result as above * // if no canvas is specified, defaults to main canvas * function setup() { - * var c = createCanvas(100, 100); + * let c = createCanvas(100, 100); * background(255, 0, 0); * saveCanvas('myCanvas', 'jpg'); * @@ -59394,7 +60665,7 @@ p5.prototype.saveCanvas = function() { * } * * function mousePressed() { - * saveFrames('out', 'png', 1, 25, function(data) { + * saveFrames('out', 'png', 1, 25, data => { * print(data); * }); * } @@ -59474,7 +60745,7 @@ p5.prototype._makeFrame = function(filename, extension, _cnv) { module.exports = p5; -},{"../core/main":25}],45:[function(_dereq_,module,exports){ +},{"../core/main":24}],44:[function(_dereq_,module,exports){ /** * @module Image * @submodule Loading & Displaying @@ -59515,7 +60786,7 @@ _dereq_('../core/error_helpers'); * @example *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/laDefense.jpg'); * } @@ -59528,7 +60799,7 @@ _dereq_('../core/error_helpers'); * * function setup() { * // here we use a callback to display the image after loading - * loadImage('assets/laDefense.jpg', function(img) { + * loadImage('assets/laDefense.jpg', img => { * image(img, 0, 0); * }); * } @@ -59564,6 +60835,8 @@ p5.prototype.loadImage = function(path, successCallback, failureCallback) { p5._friendlyFileLoadError(0, img.src); if (typeof failureCallback === 'function') { failureCallback(e); + } else { + console.error(e); } }; @@ -59625,7 +60898,7 @@ function _sAssign(sVal, iVal) { * @example *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/laDefense.jpg'); * } @@ -59638,7 +60911,7 @@ function _sAssign(sVal, iVal) { *
*
* - * var img; + * let img; * function preload() { * img = loadImage('assets/laDefense.jpg'); * } @@ -59654,7 +60927,7 @@ function _sAssign(sVal, iVal) { * * function setup() { * // Here, we use a callback to display the image after loading - * loadImage('assets/laDefense.jpg', function(img) { + * loadImage('assets/laDefense.jpg', img => { * image(img, 0, 0); * }); * } @@ -59662,7 +60935,7 @@ function _sAssign(sVal, iVal) { *
*
* - * var img; + * let img; * function preload() { * img = loadImage('assets/gradient.png'); * } @@ -59796,7 +61069,7 @@ p5.prototype.image = function( * @example *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/laDefense.jpg'); * } @@ -59810,7 +61083,7 @@ p5.prototype.image = function( * *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/laDefense.jpg'); * } @@ -59824,7 +61097,7 @@ p5.prototype.image = function( * *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/laDefense.jpg'); * } @@ -59878,7 +61151,7 @@ p5.prototype.tint = function() { * @example *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } @@ -59958,7 +61231,7 @@ p5.prototype._getTintedImageCanvas = function(img) { * *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } @@ -59971,7 +61244,7 @@ p5.prototype._getTintedImageCanvas = function(img) { * *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } @@ -59984,7 +61257,7 @@ p5.prototype._getTintedImageCanvas = function(img) { * *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } @@ -60014,7 +61287,7 @@ p5.prototype.imageMode = function(m) { module.exports = p5; -},{"../core/constants":19,"../core/error_helpers":21,"../core/helpers":22,"../core/main":25,"./filters":43}],46:[function(_dereq_,module,exports){ +},{"../core/constants":18,"../core/error_helpers":20,"../core/helpers":21,"../core/main":24,"./filters":42}],45:[function(_dereq_,module,exports){ /** * @module Image * @submodule Image @@ -60055,28 +61328,28 @@ var Filters = _dereq_('./filters'); * @example *
* function setup() { - * var img = createImage(100, 100); // same as new p5.Image(100, 100); + * 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) { - * var index = (x + y * width) * 4; + * 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; * } * - * var x, y; + * let x, y; * // fill with random colors * for (y = 0; y < img.height; y++) { * for (x = 0; x < img.width; x++) { - * var red = random(255); - * var green = random(255); - * var blue = random(255); - * var alpha = 255; + * let red = random(255); + * let green = random(255); + * let blue = random(255); + * let alpha = 255; * writeColor(img, x, y, red, green, blue, alpha); * } * } @@ -60110,7 +61383,7 @@ p5.Image = function(width, height) { * @readOnly * @example *
- * var img; + * let img; * function preload() { * img = loadImage('assets/rockies.jpg'); * } @@ -60118,8 +61391,8 @@ p5.Image = function(width, height) { * function setup() { * createCanvas(100, 100); * image(img, 0, 0); - * for (var i = 0; i < img.width; i++) { - * var c = img.get(i, img.height / 2); + * for (let i = 0; i < img.width; i++) { + * let c = img.get(i, img.height / 2); * stroke(c); * line(i, height / 2, i, height); * } @@ -60137,7 +61410,7 @@ p5.Image = function(width, height) { * @readOnly * @example *
- * var img; + * let img; * function preload() { * img = loadImage('assets/rockies.jpg'); * } @@ -60145,8 +61418,8 @@ p5.Image = function(width, height) { * function setup() { * createCanvas(100, 100); * image(img, 0, 0); - * for (var i = 0; i < img.height; i++) { - * var c = img.get(img.width / 2, i); + * for (let i = 0; i < img.height; i++) { + * let c = img.get(img.width / 2, i); * stroke(c); * line(0, i, width / 2, i); * } @@ -60162,6 +61435,7 @@ p5.Image = function(width, height) { this.canvas.width = this.width; this.canvas.height = this.height; this.drawingContext = this.canvas.getContext('2d'); + this._pixelsState = this; this._pixelDensity = 1; //used for webgl texturing only this._modified = false; @@ -60181,15 +61455,15 @@ p5.Image = function(width, height) { * values of the pixel at (1, 0). More generally, to set values for a pixel * at (x, y): * ```javascript - * var d = pixelDensity(); - * for (var i = 0; i < d; i++) { - * for (var j = 0; j < d; j++) { + * let d = pixelDensity(); + * for (let i = 0; i < d; i++) { + * for (let j = 0; j < d; j++) { * // loop over - * idx = 4 * ((y * d + j) * width * d + (x * d + i)); - * pixels[idx] = r; - * pixels[idx+1] = g; - * pixels[idx+2] = b; - * pixels[idx+3] = a; + * 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; * } * } * ``` @@ -60201,10 +61475,10 @@ p5.Image = function(width, height) { * @example *
* - * var img = createImage(66, 66); + * let img = createImage(66, 66); * img.loadPixels(); - * for (var i = 0; i < img.width; i++) { - * for (var j = 0; j < img.height; j++) { + * for (let i = 0; i < img.width; i++) { + * for (let j = 0; j < img.height; j++) { * img.set(i, j, color(0, 90, 102)); * } * } @@ -60214,10 +61488,10 @@ p5.Image = function(width, height) { *
*
* - * var pink = color(255, 102, 204); - * var img = createImage(66, 66); + * let pink = color(255, 102, 204); + * let img = createImage(66, 66); * img.loadPixels(); - * for (var i = 0; i < 4 * (width * height / 2); i += 4) { + * 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); @@ -60251,8 +61525,8 @@ p5.Image.prototype._setProperty = function(prop, value) { * @method loadPixels * @example *
- * var myImage; - * var halfImage; + * let myImage; + * let halfImage; * * function preload() { * myImage = loadImage('assets/rockies.jpg'); @@ -60260,15 +61534,15 @@ p5.Image.prototype._setProperty = function(prop, value) { * * function setup() { * myImage.loadPixels(); - * halfImage = 4 * width * height / 2; - * for (var i = 0; i < halfImage; i++) { + * 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); + * image(myImage, 0, 0, width, height); * } *
* @@ -60296,8 +61570,8 @@ p5.Image.prototype.loadPixels = function() { * underlying canvas * @example *
- * var myImage; - * var halfImage; + * let myImage; + * let halfImage; * * function preload() { * myImage = loadImage('assets/rockies.jpg'); @@ -60305,15 +61579,15 @@ p5.Image.prototype.loadPixels = function() { * * function setup() { * myImage.loadPixels(); - * halfImage = 4 * width * height / 2; - * for (var i = 0; i < halfImage; i++) { + * 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); + * image(myImage, 0, 0, width, height); * } *
* @@ -60332,24 +61606,21 @@ p5.Image.prototype.updatePixels = function(x, y, w, h) { /** * Get a region of pixels from an image. * - * If no params are passed, those 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 + * 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. * - * Returns undefined if the region is outside the bounds of the image - * * @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 {Number[]|Color|p5.Image} color of pixel at x,y in array format - * [R, G, B, A] or p5.Image + * @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 *
- * var myImage; - * var c; + * let myImage; + * let c; * * function preload() { * myImage = loadImage('assets/rockies.jpg'); @@ -60370,10 +61641,23 @@ p5.Image.prototype.updatePixels = function(x, y, w, h) { * image of rocky mountains with 50x50 green rect in front * */ +/** + * @method get + * @return {p5.Image} the whole p5.Image + */ +/** + * @method get + * @param {Number} x + * @param {Number} y + * @return {Number[]} color of pixel at x,y in array format [R, G, B, A] + */ p5.Image.prototype.get = function(x, y, w, h) { - return p5.Renderer2D.prototype.get.call(this, x, y, w, h); + p5._validateParameters('p5.Image.get', arguments); + return p5.Renderer2D.prototype.get.apply(this, arguments); }; +p5.Image.prototype._getPixel = p5.Renderer2D.prototype._getPixel; + /** * Set the color of a single pixel or write an image into * this p5.Image. @@ -60390,10 +61674,10 @@ p5.Image.prototype.get = function(x, y, w, h) { * @example *
* - * var img = createImage(66, 66); + * let img = createImage(66, 66); * img.loadPixels(); - * for (var i = 0; i < img.width; i++) { - * for (var j = 0; j < img.height; j++) { + * 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)); * } * } @@ -60423,7 +61707,7 @@ p5.Image.prototype.set = function(x, y, imgOrCol) { * @param {Number} height the resized image height * @example *
- * var img; + * let img; * * function preload() { * img = loadImage('assets/rockies.jpg'); @@ -60516,10 +61800,10 @@ p5.Image.prototype.resize = function(width, height) { * @param {Integer} dh destination image height * @example *
- * var photo; - * var bricks; - * var x; - * var y; + * let photo; + * let bricks; + * let x; + * let y; * * function preload() { * photo = loadImage('assets/rockies.jpg'); @@ -60587,7 +61871,7 @@ p5.Image.prototype.copy = function() { * @param {p5.Image} srcImage source image * @example *
- * var photo, maskImage; + * let photo, maskImage; * function preload() { * photo = loadImage('assets/rockies.jpg'); * maskImage = loadImage('assets/mask2.png'); @@ -60653,8 +61937,8 @@ p5.Image.prototype.mask = function(p5Image) { * to each filter, see above * @example *
- * var photo1; - * var photo2; + * let photo1; + * let photo2; * * function preload() { * photo1 = loadImage('assets/rockies.jpg'); @@ -60662,7 +61946,7 @@ p5.Image.prototype.mask = function(p5Image) { * } * * function setup() { - * photo2.filter('gray'); + * photo2.filter(GRAY); * image(photo1, 0, 0); * image(photo2, width / 2, 0); * } @@ -60673,7 +61957,7 @@ p5.Image.prototype.mask = function(p5Image) { * */ p5.Image.prototype.filter = function(operation, value) { - Filters.apply(this.canvas, Filters[operation.toLowerCase()], value); + Filters.apply(this.canvas, Filters[operation], value); this.setModified(true); }; @@ -60705,8 +61989,8 @@ p5.Image.prototype.filter = function(operation, value) { * http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/ * @example *
- * var mountains; - * var bricks; + * let mountains; + * let bricks; * * function preload() { * mountains = loadImage('assets/rockies.jpg'); @@ -60720,8 +62004,8 @@ p5.Image.prototype.filter = function(operation, value) { * } *
*
- * var mountains; - * var bricks; + * let mountains; + * let bricks; * * function preload() { * mountains = loadImage('assets/rockies.jpg'); @@ -60735,8 +62019,8 @@ p5.Image.prototype.filter = function(operation, value) { * } *
*
- * var mountains; - * var bricks; + * let mountains; + * let bricks; * * function preload() { * mountains = loadImage('assets/rockies.jpg'); @@ -60809,7 +62093,7 @@ p5.Image.prototype.isModified = function() { * @param {String} extension 'png' or 'jpg' * @example *
- * var photo; + * let photo; * * function preload() { * photo = loadImage('assets/rockies.jpg'); @@ -60836,7 +62120,7 @@ p5.Image.prototype.save = function(filename, extension) { module.exports = p5.Image; -},{"../core/main":25,"./filters":43}],47:[function(_dereq_,module,exports){ +},{"../core/main":24,"./filters":42}],46:[function(_dereq_,module,exports){ /** * @module Image * @submodule Pixels @@ -60868,15 +62152,15 @@ _dereq_('../color/p5.Color'); * 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 - * var d = pixelDensity(); - * for (var i = 0; i < d; i++) { - * for (var j = 0; j < d; j++) { + * let d = pixelDensity(); + * for (let i = 0; i < d; i++) { + * for (let j = 0; j < d; j++) { * // loop over - * idx = 4 * ((y * d + j) * width * d + (x * d + i)); - * pixels[idx] = r; - * pixels[idx+1] = g; - * pixels[idx+2] = b; - * pixels[idx+3] = a; + * 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; * } * } * ``` @@ -60899,11 +62183,11 @@ _dereq_('../color/p5.Color'); * @example *
* - * var pink = color(255, 102, 204); + * let pink = color(255, 102, 204); * loadPixels(); - * var d = pixelDensity(); - * var halfImage = 4 * (width * d) * (height / 2 * d); - * for (var i = 0; i < halfImage; i += 4) { + * 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); @@ -60940,8 +62224,8 @@ p5.prototype.pixels = []; * * @example *
- * var img0; - * var img1; + * let img0; + * let img1; * * function preload() { * img0 = loadImage('assets/rockies.jpg'); @@ -60955,8 +62239,8 @@ p5.prototype.pixels = []; * } *
*
- * var img0; - * var img1; + * let img0; + * let img1; * * function preload() { * img0 = loadImage('assets/rockies.jpg'); @@ -60970,8 +62254,8 @@ p5.prototype.pixels = []; * } *
*
- * var img0; - * var img1; + * let img0; + * let img1; * * function preload() { * img0 = loadImage('assets/rockies.jpg'); @@ -61034,7 +62318,7 @@ p5.prototype.blend = function() { * * @example *
- * var img; + * let img; * * function preload() { * img = loadImage('assets/rockies.jpg'); @@ -61128,7 +62412,7 @@ p5.prototype.copy = function() { * @example *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } @@ -61141,7 +62425,7 @@ p5.prototype.copy = function() { * *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } @@ -61154,7 +62438,7 @@ p5.prototype.copy = function() { * *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } @@ -61167,7 +62451,7 @@ p5.prototype.copy = function() { * *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } @@ -61180,7 +62464,7 @@ p5.prototype.copy = function() { * *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } @@ -61193,7 +62477,7 @@ p5.prototype.copy = function() { * *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } @@ -61206,7 +62490,7 @@ p5.prototype.copy = function() { * *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } @@ -61219,7 +62503,7 @@ p5.prototype.copy = function() { * *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } @@ -61245,13 +62529,15 @@ p5.prototype.copy = function() { p5.prototype.filter = function(operation, value) { p5._validateParameters('filter', arguments); if (this.canvas !== undefined) { - Filters.apply(this.canvas, Filters[operation.toLowerCase()], value); + Filters.apply(this.canvas, Filters[operation], value); } else { - Filters.apply(this.elt, Filters[operation.toLowerCase()], value); + Filters.apply(this.elt, Filters[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 @@ -61259,47 +62545,46 @@ p5.prototype.filter = function(operation, value) { * getting an image, the x and y parameters define the coordinates for the * upper-left corner of the image, regardless of the current imageMode(). *

- * If the pixel requested is outside of the image window, [0,0,0,255] is - * returned. To get the numbers scaled according to the current color ranges + * To get the color components scaled according to the current color ranges * and taking into account colorMode, use getColor instead of get. *

* 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 - * - * var x, y, d; // set these to the coordinates - * var off = (y * width + x) * d * 4; - * var components = [ + * ```javascript + * let x, y, d; // set these to the coordinates + * let off = (y * width + x) * d * 4; + * let components = [ * pixels[off], * pixels[off + 1], * pixels[off + 2], * pixels[off + 3] * ]; * print(components); - * + * ``` *

+ * * See the reference for pixels[] for more information. * * If you want to extract an array of colors or a subimage from an p5.Image object, * take a look at p5.Image.get() * * @method get - * @param {Number} [x] x-coordinate of the pixel - * @param {Number} [y] y-coordinate of the pixel - * @param {Number} [w] width - * @param {Number} [h] height - * @return {Number[]|p5.Image} values of pixel at x,y in array format - * [R, G, B, A] or p5.Image + * @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 *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/rockies.jpg'); * } * function setup() { * image(img, 0, 0); - * var c = get(); + * let c = get(); * image(c, width / 2, 0); * } * @@ -61307,13 +62592,13 @@ p5.prototype.filter = function(operation, value) { * *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/rockies.jpg'); * } * function setup() { * image(img, 0, 0); - * var c = get(50, 90); + * let c = get(50, 90); * fill(c); * noStroke(); * rect(25, 25, 50, 50); @@ -61326,8 +62611,19 @@ p5.prototype.filter = function(operation, value) { * Image of the rocky mountains with 50x50 green rect in center of canvas * */ +/** + * @method get + * @return {p5.Image} the whole p5.Image + */ +/** + * @method get + * @param {Number} x + * @param {Number} y + * @return {Number[]} color of pixel at x,y in array format [R, G, B, A] + */ p5.prototype.get = function(x, y, w, h) { - return this._renderer.get(x, y, w, h); + p5._validateParameters('get', arguments); + return this._renderer.get.apply(this._renderer, arguments); }; /** @@ -61340,17 +62636,17 @@ p5.prototype.get = function(x, y, w, h) { * @example *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/rockies.jpg'); * } * * function setup() { - * image(img, 0, 0); - * var d = pixelDensity(); - * var halfImage = 4 * (img.width * d) * (img.height * d / 2); + * image(img, 0, 0, width, height); + * let d = pixelDensity(); + * let halfImage = 4 * (width * d) * (height * d / 2); * loadPixels(); - * for (var i = 0; i < halfImage; i++) { + * for (let i = 0; i < halfImage; i++) { * pixels[i + halfImage] = pixels[i]; * } * updatePixels(); @@ -61396,7 +62692,7 @@ p5.prototype.loadPixels = function() { * @example *
* - * var black = color(0); + * let black = color(0); * set(30, 20, black); * set(85, 20, black); * set(85, 75, black); @@ -61407,9 +62703,9 @@ p5.prototype.loadPixels = function() { * *
* - * for (var i = 30; i < width - 15; i++) { - * for (var j = 20; j < height - 25; j++) { - * var c = color(204 - j, 153 - i, 0); + * 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); * } * } @@ -61419,7 +62715,7 @@ p5.prototype.loadPixels = function() { * *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/rockies.jpg'); * } @@ -61459,17 +62755,17 @@ p5.prototype.set = function(x, y, imgOrCol) { * @example *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/rockies.jpg'); * } * * function setup() { - * image(img, 0, 0); - * var d = pixelDensity(); - * var halfImage = 4 * (img.width * d) * (img.height * d / 2); + * image(img, 0, 0, width, height); + * let d = pixelDensity(); + * let halfImage = 4 * (width * d) * (height * d / 2); * loadPixels(); - * for (var i = 0; i < halfImage; i++) { + * for (let i = 0; i < halfImage; i++) { * pixels[i + halfImage] = pixels[i]; * } * updatePixels(); @@ -61491,7 +62787,7 @@ p5.prototype.updatePixels = function(x, y, w, h) { module.exports = p5; -},{"../color/p5.Color":17,"../core/main":25,"./filters":43}],48:[function(_dereq_,module,exports){ +},{"../color/p5.Color":16,"../core/main":24,"./filters":42}],47:[function(_dereq_,module,exports){ /** * @module IO * @submodule Input @@ -61541,10 +62837,10 @@ _dereq_('../core/error_helpers'); *
* // Examples use USGS Earthquake API: * // https://earthquake.usgs.gov/fdsnws/event/1/#methods - * var earthquakes; + * let earthquakes; * function preload() { * // Get the most recent earthquake in the database - * var url = + * let url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' + * 'summary/all_day.geojson'; * earthquakes = loadJSON(url); @@ -61557,8 +62853,8 @@ _dereq_('../core/error_helpers'); * function draw() { * background(200); * // Get the magnitude and name of the earthquake out of the loaded JSON - * var earthquakeMag = earthquakes.features[0].properties.mag; - * var earthquakeName = earthquakes.features[0].properties.place; + * let earthquakeMag = earthquakes.features[0].properties.mag; + * let earthquakeName = earthquakes.features[0].properties.place; * ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10); * textAlign(CENTER); * text(earthquakeName, 0, height - 30, width, 30); @@ -61571,7 +62867,7 @@ _dereq_('../core/error_helpers'); *
* function setup() { * noLoop(); - * var url = + * let url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' + * 'summary/all_day.geojson'; * loadJSON(url, drawEarthquake); @@ -61583,8 +62879,8 @@ _dereq_('../core/error_helpers'); * * function drawEarthquake(earthquakes) { * // Get the magnitude and name of the earthquake out of the loaded JSON - * var earthquakeMag = earthquakes.features[0].properties.mag; - * var earthquakeName = earthquakes.features[0].properties.place; + * let earthquakeMag = earthquakes.features[0].properties.mag; + * let earthquakeName = earthquakes.features[0].properties.place; * ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10); * textAlign(CENTER); * text(earthquakeName, 0, height - 30, width, 30); @@ -61700,14 +62996,14 @@ p5.prototype.loadJSON = function() { * operation before setup() and draw() are called.

* *
- * var result; + * let result; * function preload() { * result = loadStrings('assets/test.txt'); * } * function setup() { * background(200); - * var ind = floor(random(result.length)); + * let ind = floor(random(result.length)); * text(result[ind], 10, 10, 80, 80); * } *
@@ -61722,7 +63018,7 @@ p5.prototype.loadJSON = function() { * * function pickString(result) { * background(200); - * var ind = floor(random(result.length)); + * let ind = floor(random(result.length)); * text(result[ind], 10, 10, 80, 80); * } *
@@ -61841,7 +63137,7 @@ p5.prototype.loadStrings = function() { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -61861,8 +63157,8 @@ p5.prototype.loadStrings = function() { * //["Goat", "Leopard", "Zebra"] * * //cycle through the table - * for (var r = 0; r < table.getRowCount(); r++) - * for (var c = 0; c < table.getColumnCount(); c++) { + * for (let r = 0; r < table.getRowCount(); r++) + * for (let c = 0; c < table.getColumnCount(); c++) { * print(table.getString(r, c)); * } * } @@ -62069,7 +63365,7 @@ p5.prototype.loadTable = function(path) { if (errorCallback) { errorCallback(err); } else { - throw err; + console.error(err); } } ); @@ -62094,29 +63390,6 @@ function makeObject(row, headers) { return ret; } -function parseXML(two) { - var one = new p5.XML(); - var children = two.childNodes; - if (children && children.length) { - for (var i = 0; i < children.length; i++) { - var node = parseXML(children[i]); - one.addChild(node); - } - one.setName(two.nodeName); - one._setCont(two.textContent); - one._setAttributes(two); - for (var j = 0; j < one.children.length; j++) { - one.children[j].parent = one; - } - return one; - } else { - one.setName(two.nodeName); - one._setCont(two.textContent); - one._setAttributes(two); - return one; - } -} - /** * 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, @@ -62156,19 +63429,19 @@ function parseXML(two) { * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * - * var xml; + * let xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { - * var children = xml.getChildren('animal'); + * let children = xml.getChildren('animal'); * - * for (var i = 0; i < children.length; i++) { - * var id = children[i].getNum('id'); - * var coloring = children[i].getString('species'); - * var name = children[i].getContent(); + * 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); * } * } @@ -62184,7 +63457,7 @@ function parseXML(two) { * */ p5.prototype.loadXML = function() { - var ret = {}; + var ret = new p5.XML(); var callback, errorCallback; for (var i = 1; i < arguments.length; i++) { @@ -62240,14 +63513,14 @@ p5.prototype.loadXML = function() { * * @example *
- * var data; + * let data; * * function preload() { * data = loadBytes('assets/mammals.xml'); * } * * function setup() { - * for (var i = 0; i < 5; i++) { + * for (let i = 0; i < 5; i++) { * console.log(data.bytes[i].toString(16)); * } * } @@ -62313,10 +63586,10 @@ p5.prototype.loadBytes = function(file, callback, errorCallback) { *
* // Examples use USGS Earthquake API: * // https://earthquake.usgs.gov/fdsnws/event/1/#methods - * var earthquakes; + * let earthquakes; * function preload() { * // Get the most recent earthquake in the database - * var url = + * let url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?' + * 'format=geojson&limit=1&orderby=time'; * httpGet(url, 'jsonp', false, function(response) { @@ -62333,8 +63606,8 @@ p5.prototype.loadBytes = function(file, callback, errorCallback) { * } * background(200); * // Get the magnitude and name of the earthquake out of the loaded JSON - * var earthquakeMag = earthquakes.features[0].properties.mag; - * var earthquakeName = earthquakes.features[0].properties.place; + * let earthquakeMag = earthquakes.features[0].properties.mag; + * let earthquakeName = earthquakes.features[0].properties.place; * ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10); * textAlign(CENTER); * text(earthquakeName, 0, height - 30, width, 30); @@ -62390,8 +63663,8 @@ p5.prototype.httpGet = function() { * * // Examples use jsonplaceholder.typicode.com for a Mock Data API * - * var url = 'https://jsonplaceholder.typicode.com/posts'; - * var postData = { userId: 1, title: 'p5 Clicked!', body: 'p5.js is way cool.' }; + * let url = 'https://jsonplaceholder.typicode.com/posts'; + * let postData = { userId: 1, title: 'p5 Clicked!', body: 'p5.js is way cool.' }; * * function setup() { * createCanvas(800, 800); @@ -62399,9 +63672,9 @@ p5.prototype.httpGet = function() { * * function mousePressed() { * // Pick new random color values - * var r = random(255); - * var g = random(255); - * var b = random(255); + * let r = random(255); + * let g = random(255); + * let b = random(255); * * httpPost(url, 'json', postData, function(result) { * strokeWeight(2); @@ -62416,8 +63689,8 @@ p5.prototype.httpGet = function() { * * *
- * var url = 'https://invalidURL'; // A bad URL that will cause errors - * var postData = { title: 'p5 Clicked!', body: 'p5.js is way cool.' }; + * let url = 'https://invalidURL'; // A bad URL that will cause errors + * let postData = { title: 'p5 Clicked!', body: 'p5.js is way cool.' }; * * function setup() { * createCanvas(800, 800); @@ -62425,9 +63698,9 @@ p5.prototype.httpGet = function() { * * function mousePressed() { * // Pick new random color values - * var r = random(255); - * var g = random(255); - * var b = random(255); + * let r = random(255); + * let g = random(255); + * let b = random(255); * * httpPost( * url, @@ -62501,11 +63774,11 @@ p5.prototype.httpPost = function() { * // https://earthquake.usgs.gov/fdsnws/event/1/#methods * * // displays an animation of all USGS earthquakes - * var earthquakes; - * var eqFeatureIndex = 0; + * let earthquakes; + * let eqFeatureIndex = 0; * * function preload() { - * var url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson'; + * let url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson'; * httpDo( * url, * { @@ -62526,9 +63799,9 @@ p5.prototype.httpPost = function() { * } * clear(); * - * var feature = earthquakes.features[eqFeatureIndex]; - * var mag = feature.properties.mag; - * var rad = mag / 11 * ((width + height) / 2); + * let feature = earthquakes.features[eqFeatureIndex]; + * let mag = feature.properties.mag; + * let rad = mag / 11 * ((width + height) / 2); * fill(255, 0, 0, 100); * ellipse(width / 2 + random(-2, 2), height / 2 + random(-2, 2), rad, rad); * @@ -62610,6 +63883,9 @@ p5.prototype.httpDo = function() { for (var attr in a) { jsonpOptions[attr] = a[attr]; } + } else if (a instanceof p5.XML) { + data = a.serialize(); + contentType = 'application/xml'; } else { data = JSON.stringify(a); contentType = 'application/json'; @@ -62655,7 +63931,10 @@ p5.prototype.httpDo = function() { err.ok = false; throw err; } else { - var fileSize = res.headers.get('content-length'); + var fileSize = 0; + if (type !== 'jsonp') { + fileSize = res.headers.get('content-length'); + } if (fileSize && fileSize > 64000000) { p5._friendlyFileLoadError(7, path); } @@ -62671,7 +63950,7 @@ p5.prototype.httpDo = function() { return res.text().then(function(text) { var parser = new DOMParser(); var xml = parser.parseFromString(text, 'text/xml'); - return parseXML(xml.documentElement); + return new p5.XML(xml.documentElement); }); default: return res.text(); @@ -62702,16 +63981,22 @@ p5.prototype._pWriters = []; * @example *
* - * createButton('save') - * .position(10, 10) - * .mousePressed(function() { + * 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) { * var writer = createWriter('squares.txt'); - * for (var i = 0; i < 10; i++) { + * for (let i = 0; i < 10; i++) { * writer.print(i * i); * } * writer.close(); * writer.clear(); - * }); + * } + * } * *
*/ @@ -62751,7 +64036,7 @@ p5.PrintWriter = function(filename, extension) { *
* * // creates a file called 'newFile.txt' - * var writer = createWriter('newFile.txt'); + * let writer = createWriter('newFile.txt'); * // write 'Hello world!'' to the file * writer.write(['Hello world!']); * // close the PrintWriter and save the file @@ -62761,7 +64046,7 @@ p5.PrintWriter = function(filename, extension) { *
* * // creates a file called 'newFile2.txt' - * var writer = createWriter('newFile2.txt'); + * let writer = createWriter('newFile2.txt'); * // write 'apples,bananas,123' to the file * writer.write(['apples', 'bananas', 123]); * // close the PrintWriter and save the file @@ -62771,7 +64056,7 @@ p5.PrintWriter = function(filename, extension) { *
* * // creates a file called 'newFile3.txt' - * var writer = createWriter('newFile3.txt'); + * let writer = createWriter('newFile3.txt'); * // write 'My name is: Teddy' to the file * writer.write('My name is:'); * writer.write(' Teddy'); @@ -62791,7 +64076,7 @@ p5.PrintWriter = function(filename, extension) { *
* * // creates a file called 'newFile.txt' - * var writer = createWriter('newFile.txt'); + * let writer = createWriter('newFile.txt'); * // creates a file containing * // My name is: * // Teddy @@ -62803,7 +64088,7 @@ p5.PrintWriter = function(filename, extension) { *
*
* - * var writer; + * let writer; * * function setup() { * createCanvas(400, 400); @@ -62832,7 +64117,7 @@ p5.PrintWriter = function(filename, extension) { * @example *
* // create writer object - * var writer = createWriter('newFile.txt'); + * let writer = createWriter('newFile.txt'); * writer.write(['clear me']); * // clear writer object here * writer.clear(); @@ -62851,7 +64136,7 @@ p5.PrintWriter = function(filename, extension) { *
* * // create a file called 'newFile.txt' - * var writer = createWriter('newFile.txt'); + * let writer = createWriter('newFile.txt'); * // close the PrintWriter and save the file * writer.close(); * @@ -62859,7 +64144,7 @@ p5.PrintWriter = function(filename, extension) { *
* * // create a file called 'newFile2.txt' - * var writer = createWriter('newFile2.txt'); + * let writer = createWriter('newFile2.txt'); * // write some data to the file * writer.write([100, 101, 102]); * // close the PrintWriter and save the file @@ -62912,25 +64197,25 @@ p5.PrintWriter = function(filename, extension) { * p5.SoundFile (requires p5.sound). The second parameter is a filename * (including extension). The third parameter is for options specific * to this type of object. This method will save a file that fits the - * given paramaters. For example:

+ * given parameters. For example:

* *

  * // Saves canvas as an image
  * save('myCanvas.jpg');
  *
  * // Saves pImage as a png image
- * var img = createImage(10, 10);
+ * let img = createImage(10, 10);
  * save(img, 'my.png');
  *
  * // Saves canvas as an image
- * var cnv = createCanvas(100, 100);
+ * let cnv = createCanvas(100, 100);
  * save(cnv, 'myCanvas.jpg');
  *
  * // Saves p5.Renderer object as an image
- * var gb = createGraphics(100, 100);
+ * let gb = createGraphics(100, 100);
  * save(gb, 'myGraphics.jpg');
  *
- * var myTable = new p5.Table();
+ * let myTable = new p5.Table();
  *
  * // Saves table as html file
  * save(myTable, 'myTable.html');
@@ -62941,7 +64226,7 @@ p5.PrintWriter = function(filename, extension) {
  * // Tab Separated Values
  * save(myTable, 'myTable.tsv');
  *
- * var myJSON = { a: 1, b: true };
+ * let myJSON = { a: 1, b: true };
  *
  * // Saves pretty JSON
  * save(myJSON, 'my.json');
@@ -62950,7 +64235,7 @@ p5.PrintWriter = function(filename, extension) {
  * save(myJSON, 'my.json', true);
  *
  * // Saves array of strings to a text file with line breaks after each item
- * var arrayOfStrings = ['a', 'b'];
+ * let arrayOfStrings = ['a', 'b'];
  * save(arrayOfStrings, 'my.txt');
  * 
* @@ -62981,7 +64266,7 @@ p5.prototype.save = function(object, _filename, _options) { // OPTION 1: saveCanvas... // if no arguments are provided, save canvas - var cnv = this._curElement.elt; + var cnv = this._curElement ? this._curElement.elt : this.elt; if (args.length === 0) { p5.prototype.saveCanvas(cnv); return; @@ -63035,17 +64320,23 @@ p5.prototype.save = function(object, _filename, _options) { * (but not readability). * @example *
- * var json = {}; // new JSON Object + * let json = {}; // new JSON Object * * json.id = 0; * json.species = 'Panthera leo'; * json.name = 'Lion'; * - * createButton('save') - * .position(10, 10) - * .mousePressed(function() { + * function setup() { + * createCanvas(100, 100); + * background(200); + * text('click here to save', 10, 10, 70, 80); + * } + * + * function mousePressed() { + * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { * saveJSON(json, 'lion.json'); - * }); + * } + * } * * // saves the following to a file called "lion.json": * // { @@ -63084,16 +64375,22 @@ p5.prototype.saveJSONArray = p5.prototype.saveJSON; * @param {String} [extension] the filename's extension * @example *
- * var words = 'apple bear cat dog'; + * let words = 'apple bear cat dog'; * * // .split() outputs an Array - * var list = split(words, ' '); + * let list = split(words, ' '); + * + * function setup() { + * createCanvas(100, 100); + * background(200); + * text('click here to save', 10, 10, 70, 80); + * } * - * createButton('save') - * .position(10, 10) - * .mousePressed(function() { + * function mousePressed() { + * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { * saveStrings(list, 'nouns.txt'); - * }); + * } + * } * * // Saves the following to a file called 'nouns.txt': * // @@ -63148,7 +64445,7 @@ function escapeHelper(content) { * @param {String} [options] can be one of "tsv", "csv", or "html" * @example *
- * var table; + * let table; * * function setup() { * table = new p5.Table(); @@ -63157,7 +64454,7 @@ function escapeHelper(content) { * table.addColumn('species'); * table.addColumn('name'); * - * var newRow = table.addRow(); + * let newRow = table.addRow(); * newRow.setNum('id', table.getRowCount() - 1); * newRow.setString('species', 'Panthera leo'); * newRow.setString('name', 'Lion'); @@ -63388,7 +64685,7 @@ function destroyClickedElement(event) { module.exports = p5; -},{"../core/error_helpers":21,"../core/main":25,"es6-promise":5,"fetch-jsonp":6,"file-saver":7,"whatwg-fetch":13}],49:[function(_dereq_,module,exports){ +},{"../core/error_helpers":20,"../core/main":24,"es6-promise":5,"fetch-jsonp":6,"file-saver":7,"whatwg-fetch":12}],48:[function(_dereq_,module,exports){ /** * @module IO * @submodule Table @@ -63468,7 +64765,7 @@ p5.Table = function(rows) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -63478,14 +64775,14 @@ p5.Table = function(rows) { * * function setup() { * //add a row - * var newRow = table.addRow(); + * let newRow = table.addRow(); * newRow.setString('id', table.getRowCount() - 1); * newRow.setString('species', 'Canis Lupus'); * newRow.setString('name', 'Wolf'); * * //print the results - * for (var r = 0; r < table.getRowCount(); r++) - * for (var c = 0; c < table.getColumnCount(); c++) + * for (let r = 0; r < table.getRowCount(); r++) + * for (let c = 0; c < table.getColumnCount(); c++) * print(table.getString(r, c)); * } * @@ -63525,7 +64822,7 @@ p5.Table.prototype.addRow = function(row) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -63538,8 +64835,8 @@ p5.Table.prototype.addRow = function(row) { * table.removeRow(0); * * //print the results - * for (var r = 0; r < table.getRowCount(); r++) - * for (var c = 0; c < table.getColumnCount(); c++) + * for (let r = 0; r < table.getRowCount(); r++) + * for (let c = 0; c < table.getColumnCount(); c++) * print(table.getString(r, c)); * } * @@ -63575,7 +64872,7 @@ p5.Table.prototype.removeRow = function(id) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -63584,10 +64881,10 @@ p5.Table.prototype.removeRow = function(id) { * } * * function setup() { - * var row = table.getRow(1); + * let row = table.getRow(1); * //print it column by column * //note: a row is an object, not an array - * for (var c = 0; c < table.getColumnCount(); c++) { + * for (let c = 0; c < table.getColumnCount(); c++) { * print(row.getString(c)); * } * } @@ -63619,7 +64916,7 @@ p5.Table.prototype.getRow = function(r) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -63628,16 +64925,16 @@ p5.Table.prototype.getRow = function(r) { * } * * function setup() { - * var rows = table.getRows(); + * let rows = table.getRows(); * * //warning: rows is an array of objects - * for (var r = 0; r < rows.length; r++) { + * for (let r = 0; r < rows.length; r++) { * rows[r].set('name', 'Unicorn'); * } * * //print the results - * for (r = 0; r < table.getRowCount(); r++) - * for (var c = 0; c < table.getColumnCount(); c++) + * for (let r = 0; r < table.getRowCount(); r++) + * for (let c = 0; c < table.getColumnCount(); c++) * print(table.getString(r, c)); * } * @@ -63675,7 +64972,7 @@ p5.Table.prototype.getRows = function() { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -63685,7 +64982,7 @@ p5.Table.prototype.getRows = function() { * * function setup() { * //find the animal named zebra - * var row = table.findRow('Zebra', 'name'); + * let row = table.findRow('Zebra', 'name'); * //find the corresponding species * print(row.getString('species')); * } @@ -63740,7 +65037,7 @@ p5.Table.prototype.findRow = function(value, column) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -63750,13 +65047,13 @@ p5.Table.prototype.findRow = function(value, column) { * * function setup() { * //add another goat - * var newRow = table.addRow(); + * 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 - * var rows = table.findRows('Goat', 'name'); + * let rows = table.findRows('Goat', 'name'); * print(rows.length + ' Goats found'); * } * @@ -63809,7 +65106,7 @@ p5.Table.prototype.findRows = function(value, column) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -63819,7 +65116,7 @@ p5.Table.prototype.findRows = function(value, column) { * * function setup() { * //Search using specified regex on a given column, return TableRow object - * var mammal = table.matchRow(new RegExp('ant'), 1); + * let mammal = table.matchRow(new RegExp('ant'), 1); * print(mammal.getString(1)); * //Output "Panthera pardus" * } @@ -63858,7 +65155,7 @@ p5.Table.prototype.matchRow = function(regexp, column) { * @example *
* - * var table; + * let table; * * function setup() { * table = new p5.Table(); @@ -63866,7 +65163,7 @@ p5.Table.prototype.matchRow = function(regexp, column) { * table.addColumn('name'); * table.addColumn('type'); * - * var newRow = table.addRow(); + * let newRow = table.addRow(); * newRow.setString('name', 'Lion'); * newRow.setString('type', 'Mammal'); * @@ -63882,8 +65179,8 @@ p5.Table.prototype.matchRow = function(regexp, column) { * newRow.setString('name', 'Lizard'); * newRow.setString('type', 'Reptile'); * - * var rows = table.matchRows('R.*', 'type'); - * for (var i = 0; i < rows.length; i++) { + * let rows = table.matchRows('R.*', 'type'); + * for (let i = 0; i < rows.length; i++) { * print(rows[i].getString('name') + ': ' + rows[i].getString('type')); * } * } @@ -63930,7 +65227,7 @@ p5.Table.prototype.matchRows = function(regexp, column) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -63981,7 +65278,7 @@ p5.Table.prototype.getColumn = function(value) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -64026,7 +65323,7 @@ p5.Table.prototype.clearRows = function() { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -64041,8 +65338,8 @@ p5.Table.prototype.clearRows = function() { * table.set(2, 'carnivore', 'no'); * * //print the results - * for (var r = 0; r < table.getRowCount(); r++) - * for (var c = 0; c < table.getColumnCount(); c++) + * for (let r = 0; r < table.getRowCount(); r++) + * for (let c = 0; c < table.getColumnCount(); c++) * print(table.getString(r, c)); * } * @@ -64070,7 +65367,7 @@ p5.Table.prototype.addColumn = function(title) { * // Blob1, Blobby, Sweet, Blob, Pink * // Blob2, Saddy, Savory, Blob, Blue * - * var table; + * let table; * * function preload() { * table = loadTable('assets/blobs.csv'); @@ -64083,7 +65380,7 @@ p5.Table.prototype.addColumn = function(title) { * } * * function draw() { - * var numOfColumn = table.getColumnCount(); + * let numOfColumn = table.getColumnCount(); * text('There are ' + numOfColumn + ' columns in the table.', 100, 50); * } * @@ -64107,7 +65404,7 @@ p5.Table.prototype.getColumnCount = function() { * // Blob1, Blobby, Sweet, Blob, Pink * // Blob2, Saddy, Savory, Blob, Blue * - * var table; + * let table; * * function preload() { * table = loadTable('assets/blobs.csv'); @@ -64144,12 +65441,12 @@ p5.Table.prototype.getRowCount = function() { * @example *
* function setup() { - * var table = new p5.Table(); + * let table = new p5.Table(); * * table.addColumn('name'); * table.addColumn('type'); * - * var newRow = table.addRow(); + * let newRow = table.addRow(); * newRow.setString('name', ' $Lion ,'); * newRow.setString('type', ',,,Mammal'); * @@ -64215,12 +65512,12 @@ p5.Table.prototype.removeTokens = function(chars, column) { * @example *
* function setup() { - * var table = new p5.Table(); + * let table = new p5.Table(); * * table.addColumn('name'); * table.addColumn('type'); * - * var newRow = table.addRow(); + * let newRow = table.addRow(); * newRow.setString('name', ' Lion ,'); * newRow.setString('type', ' Mammal '); * @@ -64288,7 +65585,7 @@ p5.Table.prototype.trim = function(column) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -64354,7 +65651,7 @@ p5.Table.prototype.removeColumn = function(c) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -64367,8 +65664,8 @@ p5.Table.prototype.removeColumn = function(c) { * table.set(0, 'name', 'Wolf'); * * //print the results - * for (var r = 0; r < table.getRowCount(); r++) - * for (var c = 0; c < table.getColumnCount(); c++) + * for (let r = 0; r < table.getRowCount(); r++) + * for (let c = 0; c < table.getColumnCount(); c++) * print(table.getString(r, c)); * } * @@ -64404,7 +65701,7 @@ p5.Table.prototype.set = function(row, column, value) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -64447,7 +65744,7 @@ p5.Table.prototype.setNum = function(row, column, value) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -64457,7 +65754,7 @@ p5.Table.prototype.setNum = function(row, column, value) { * * function setup() { * //add a row - * var newRow = table.addRow(); + * let newRow = table.addRow(); * newRow.setString('id', table.getRowCount() - 1); * newRow.setString('species', 'Canis Lupus'); * newRow.setString('name', 'Wolf'); @@ -64495,7 +65792,7 @@ p5.Table.prototype.setString = function(row, column, value) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -64542,7 +65839,7 @@ p5.Table.prototype.get = function(row, column) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -64587,7 +65884,7 @@ p5.Table.prototype.getNum = function(row, column) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * // table is comma separated value "CSV" @@ -64639,7 +65936,7 @@ p5.Table.prototype.getString = function(row, column) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -64648,7 +65945,7 @@ p5.Table.prototype.getString = function(row, column) { * } * * function setup() { - * var tableObject = table.getObject(); + * let tableObject = table.getObject(); * * print(tableObject); * //outputs an object @@ -64701,7 +65998,7 @@ p5.Table.prototype.getObject = function(headerColumn) { * // 1,Panthera pardus,Leoperd * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * // table is comma separated value "CSV" @@ -64710,8 +66007,8 @@ p5.Table.prototype.getObject = function(headerColumn) { * } * * function setup() { - * var tableArray = table.getArray(); - * for (var i = 0; i < tableArray.length; i++) { + * let tableArray = table.getArray(); + * for (let i = 0; i < tableArray.length; i++) { * print(tableArray[i]); * } * } @@ -64732,7 +66029,7 @@ p5.Table.prototype.getArray = function() { module.exports = p5; -},{"../core/main":25}],50:[function(_dereq_,module,exports){ +},{"../core/main":24}],49:[function(_dereq_,module,exports){ /** * @module IO * @submodule Table @@ -64792,7 +66089,7 @@ p5.TableRow = function(str, separator) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -64801,8 +66098,8 @@ p5.TableRow = function(str, separator) { * } * * function setup() { - * var rows = table.getRows(); - * for (var r = 0; r < rows.length; r++) { + * let rows = table.getRows(); + * for (let r = 0; r < rows.length; r++) { * rows[r].set('name', 'Unicorn'); * } * @@ -64856,7 +66153,7 @@ p5.TableRow.prototype.set = function(column, value) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -64865,8 +66162,8 @@ p5.TableRow.prototype.set = function(column, value) { * } * * function setup() { - * var rows = table.getRows(); - * for (var r = 0; r < rows.length; r++) { + * let rows = table.getRows(); + * for (let r = 0; r < rows.length; r++) { * rows[r].setNum('id', r + 10); * } * @@ -64900,7 +66197,7 @@ p5.TableRow.prototype.setNum = function(column, value) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -64909,9 +66206,9 @@ p5.TableRow.prototype.setNum = function(column, value) { * } * * function setup() { - * var rows = table.getRows(); - * for (var r = 0; r < rows.length; r++) { - * var name = rows[r].getString('name'); + * 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'); * } * @@ -64945,7 +66242,7 @@ p5.TableRow.prototype.setString = function(column, value) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -64954,9 +66251,9 @@ p5.TableRow.prototype.setString = function(column, value) { * } * * function setup() { - * var names = []; - * var rows = table.getRows(); - * for (var r = 0; r < rows.length; r++) { + * let names = []; + * let rows = table.getRows(); + * for (let r = 0; r < rows.length; r++) { * names.push(rows[r].get('name')); * } * @@ -64993,7 +66290,7 @@ p5.TableRow.prototype.get = function(column) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -65002,11 +66299,11 @@ p5.TableRow.prototype.get = function(column) { * } * * function setup() { - * var rows = table.getRows(); - * var minId = Infinity; - * var maxId = -Infinity; - * for (var r = 0; r < rows.length; r++) { - * var id = rows[r].getNum('id'); + * 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); * } @@ -65049,7 +66346,7 @@ p5.TableRow.prototype.getNum = function(column) { * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * - * var table; + * let table; * * function preload() { * //my table is comma separated value "csv" @@ -65058,10 +66355,10 @@ p5.TableRow.prototype.getNum = function(column) { * } * * function setup() { - * var rows = table.getRows(); - * var longest = ''; - * for (var r = 0; r < rows.length; r++) { - * var species = rows[r].getString('species'); + * 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; * } @@ -65084,7 +66381,7 @@ p5.TableRow.prototype.getString = function(column) { module.exports = p5; -},{"../core/main":25}],51:[function(_dereq_,module,exports){ +},{"../core/main":24}],50:[function(_dereq_,module,exports){ /** * @module IO * @submodule XML @@ -65113,19 +66410,19 @@ var p5 = _dereq_('../core/main'); * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * - * var xml; + * let xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { - * var children = xml.getChildren('animal'); + * let children = xml.getChildren('animal'); * - * for (var i = 0; i < children.length; i++) { - * var id = children[i].getNum('id'); - * var coloring = children[i].getString('species'); - * var name = children[i].getContent(); + * 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); * } * } @@ -65140,12 +66437,13 @@ var p5 = _dereq_('../core/main'); * no image displayed * */ -p5.XML = function() { - this.name = null; //done - this.attributes = {}; //done - this.children = []; - this.parent = null; - this.content = null; //done +p5.XML = function(DOM) { + if (!DOM) { + var xmlDoc = document.implementation.createDocument(null, 'doc'); + this.DOM = xmlDoc.createElement('root'); + } else { + this.DOM = DOM; + } }; /** @@ -65166,15 +66464,15 @@ p5.XML = function() { * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * - * var xml; + * let xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { - * var children = xml.getChildren('animal'); - * var parent = children[1].getParent(); + * let children = xml.getChildren('animal'); + * let parent = children[1].getParent(); * print(parent.getName()); * } * @@ -65183,7 +66481,7 @@ p5.XML = function() { *
*/ p5.XML.prototype.getParent = function() { - return this.parent; + return new p5.XML(this.DOM.parentElement); }; /** @@ -65203,7 +66501,7 @@ p5.XML.prototype.getParent = function() { * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * - * var xml; + * let xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); @@ -65218,7 +66516,7 @@ p5.XML.prototype.getParent = function() { *
*/ p5.XML.prototype.getName = function() { - return this.name; + return this.DOM.tagName; }; /** @@ -65238,7 +66536,7 @@ p5.XML.prototype.getName = function() { * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * - * var xml; + * let xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); @@ -65256,7 +66554,15 @@ p5.XML.prototype.getName = function() { *
*/ p5.XML.prototype.setName = function(name) { - this.name = 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; }; /** @@ -65277,7 +66583,7 @@ p5.XML.prototype.setName = function(name) { * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * - * var xml; + * let xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); @@ -65292,7 +66598,7 @@ p5.XML.prototype.setName = function(name) { *
*/ p5.XML.prototype.hasChildren = function() { - return this.children.length > 0; + return this.DOM.children.length > 0; }; /** @@ -65314,7 +66620,7 @@ p5.XML.prototype.hasChildren = function() { * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * - * var xml; + * let xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); @@ -65329,9 +66635,11 @@ p5.XML.prototype.hasChildren = function() { *
*/ p5.XML.prototype.listChildren = function() { - return this.children.map(function(c) { - return c.name; - }); + var arr = []; + for (var i = 0; i < this.DOM.childNodes.length; i++) { + arr.push(this.DOM.childNodes[i].nodeName); + } + return arr; }; /** @@ -65354,16 +66662,16 @@ p5.XML.prototype.listChildren = function() { * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * - * var xml; + * let xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { - * var animals = xml.getChildren('animal'); + * let animals = xml.getChildren('animal'); * - * for (var i = 0; i < animals.length; i++) { + * for (let i = 0; i < animals.length; i++) { * print(animals[i].getContent()); * } * } @@ -65376,14 +66684,20 @@ p5.XML.prototype.listChildren = function() { */ p5.XML.prototype.getChildren = function(param) { if (param) { - return this.children.filter(function(c) { - return c.name === param; - }); + return elementsToP5XML(this.DOM.getElementsByTagName(param)); } else { - return this.children; + return elementsToP5XML(this.DOM.children); } }; +function elementsToP5XML(elements) { + var arr = []; + for (var i = 0; i < elements.length; i++) { + arr.push(new p5.XML(elements[i])); + } + return arr; +} + /** * Returns the first of the element's children that matches the name parameter * or the child of the given index.It returns undefined if no matching @@ -65404,14 +66718,14 @@ p5.XML.prototype.getChildren = function(param) { * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * - * var xml; + * let xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { - * var firstChild = xml.getChild('animal'); + * let firstChild = xml.getChild('animal'); * print(firstChild.getContent()); * } * @@ -65419,14 +66733,14 @@ p5.XML.prototype.getChildren = function(param) { * // "Goat" *
*
- * var xml; + * let xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { - * var secondChild = xml.getChild(1); + * let secondChild = xml.getChild(1); * print(secondChild.getContent()); * } * @@ -65436,12 +66750,12 @@ p5.XML.prototype.getChildren = function(param) { */ p5.XML.prototype.getChild = function(param) { if (typeof param === 'string') { - for (var i = 0; i < this.children.length; i++) { - var child = this.children[i]; - if (child.name === param) return child; + for (var i = 0; i < this.DOM.children.length; i++) { + var child = this.DOM.children[i]; + if (child.tagName === param) return new p5.XML(child); } } else { - return this.children[param]; + return new p5.XML(this.DOM.children[param]); } }; @@ -65465,20 +66779,21 @@ p5.XML.prototype.getChild = function(param) { * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * - * var xml; + * let xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { - * var child = new p5.XML(); + * let child = new p5.XML(); + * child.setName('animal'); * child.setAttribute('id', '3'); * child.setAttribute('species', 'Ornithorhynchus anatinus'); * child.setContent('Platypus'); * xml.addChild(child); * - * var animals = xml.getChildren('animal'); + * let animals = xml.getChildren('animal'); * print(animals[animals.length - 1].getContent()); * } * @@ -65490,7 +66805,7 @@ p5.XML.prototype.getChild = function(param) { */ p5.XML.prototype.addChild = function(node) { if (node instanceof p5.XML) { - this.children.push(node); + this.DOM.appendChild(node.DOM); } else { // PEND } @@ -65513,7 +66828,7 @@ p5.XML.prototype.addChild = function(node) { * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * - * var xml; + * let xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); @@ -65521,8 +66836,8 @@ p5.XML.prototype.addChild = function(node) { * * function setup() { * xml.removeChild('animal'); - * var children = xml.getChildren(); - * for (var i = 0; i < children.length; i++) { + * let children = xml.getChildren(); + * for (let i = 0; i < children.length; i++) { * print(children[i].getContent()); * } * } @@ -65532,7 +66847,7 @@ p5.XML.prototype.addChild = function(node) { * // "Zebra" *
*
- * var xml; + * let xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); @@ -65540,8 +66855,8 @@ p5.XML.prototype.addChild = function(node) { * * function setup() { * xml.removeChild(1); - * var children = xml.getChildren(); - * for (var i = 0; i < children.length; i++) { + * let children = xml.getChildren(); + * for (let i = 0; i < children.length; i++) { * print(children[i].getContent()); * } * } @@ -65554,8 +66869,8 @@ p5.XML.prototype.addChild = function(node) { p5.XML.prototype.removeChild = function(param) { var ind = -1; if (typeof param === 'string') { - for (var i = 0; i < this.children.length; i++) { - if (this.children[i].name === param) { + for (var i = 0; i < this.DOM.children.length; i++) { + if (this.DOM.children[i].tagName === param) { ind = i; break; } @@ -65564,7 +66879,7 @@ p5.XML.prototype.removeChild = function(param) { ind = param; } if (ind !== -1) { - this.children.splice(ind, 1); + this.DOM.removeChild(this.DOM.children[ind]); } }; @@ -65585,14 +66900,14 @@ p5.XML.prototype.removeChild = function(param) { * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * - * var xml; + * let xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { - * var firstChild = xml.getChild('animal'); + * let firstChild = xml.getChild('animal'); * print(firstChild.getAttributeCount()); * } * @@ -65601,7 +66916,7 @@ p5.XML.prototype.removeChild = function(param) { *
*/ p5.XML.prototype.getAttributeCount = function() { - return Object.keys(this.attributes).length; + return this.DOM.attributes.length; }; /** @@ -65622,14 +66937,14 @@ p5.XML.prototype.getAttributeCount = function() { * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * - * var xml; + * let xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { - * var firstChild = xml.getChild('animal'); + * let firstChild = xml.getChild('animal'); * print(firstChild.listAttributes()); * } * @@ -65638,7 +66953,12 @@ p5.XML.prototype.getAttributeCount = function() { *
*/ p5.XML.prototype.listAttributes = function() { - return Object.keys(this.attributes); + var arr = []; + for (var i = 0; i < this.DOM.attributes.length; i++) { + var attribute = this.DOM.attributes[i]; + arr.push(attribute.nodeName); + } + return arr; }; /** @@ -65659,14 +66979,14 @@ p5.XML.prototype.listAttributes = function() { * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * - * var xml; + * let xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { - * var firstChild = xml.getChild('animal'); + * let firstChild = xml.getChild('animal'); * print(firstChild.hasAttribute('species')); * print(firstChild.hasAttribute('color')); * } @@ -65677,7 +66997,12 @@ p5.XML.prototype.listAttributes = function() { *
*/ p5.XML.prototype.hasAttribute = function(name) { - return this.attributes[name] ? true : false; + var obj = {}; + for (var i = 0; i < this.DOM.attributes.length; i++) { + var attribute = this.DOM.attributes[i]; + obj[attribute.nodeName] = attribute.nodeValue; + } + return obj[name] ? true : false; }; /** @@ -65702,14 +67027,14 @@ p5.XML.prototype.hasAttribute = function(name) { * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * - * var xml; + * let xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { - * var firstChild = xml.getChild('animal'); + * let firstChild = xml.getChild('animal'); * print(firstChild.getNum('id')); * } * @@ -65718,7 +67043,12 @@ p5.XML.prototype.hasAttribute = function(name) { *
*/ p5.XML.prototype.getNum = function(name, defaultValue) { - return Number(this.attributes[name]) || defaultValue || 0; + var obj = {}; + for (var i = 0; i < this.DOM.attributes.length; i++) { + var attribute = this.DOM.attributes[i]; + obj[attribute.nodeName] = attribute.nodeValue; + } + return Number(obj[name]) || defaultValue || 0; }; /** @@ -65743,14 +67073,14 @@ p5.XML.prototype.getNum = function(name, defaultValue) { * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * - * var xml; + * let xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { - * var firstChild = xml.getChild('animal'); + * let firstChild = xml.getChild('animal'); * print(firstChild.getString('species')); * } * @@ -65759,7 +67089,12 @@ p5.XML.prototype.getNum = function(name, defaultValue) { *
*/ p5.XML.prototype.getString = function(name, defaultValue) { - return String(this.attributes[name]) || defaultValue || null; + var obj = {}; + for (var i = 0; i < this.DOM.attributes.length; i++) { + var attribute = this.DOM.attributes[i]; + obj[attribute.nodeName] = attribute.nodeValue; + } + return obj[name] ? String(obj[name]) : defaultValue || null; }; /** @@ -65781,14 +67116,14 @@ p5.XML.prototype.getString = function(name, defaultValue) { * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * - * var xml; + * let xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { - * var firstChild = xml.getChild('animal'); + * let firstChild = xml.getChild('animal'); * print(firstChild.getString('species')); * firstChild.setAttribute('species', 'Jamides zebra'); * print(firstChild.getString('species')); @@ -65800,9 +67135,7 @@ p5.XML.prototype.getString = function(name, defaultValue) { *
*/ p5.XML.prototype.setAttribute = function(name, value) { - if (this.attributes[name]) { - this.attributes[name] = value; - } + this.DOM.setAttribute(name, value); }; /** @@ -65824,14 +67157,14 @@ p5.XML.prototype.setAttribute = function(name, value) { * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * - * var xml; + * let xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { - * var firstChild = xml.getChild('animal'); + * let firstChild = xml.getChild('animal'); * print(firstChild.getContent()); * } * @@ -65840,7 +67173,10 @@ p5.XML.prototype.setAttribute = function(name, value) { *
*/ p5.XML.prototype.getContent = function(defaultValue) { - return this.content || defaultValue || null; + var str; + str = this.DOM.textContent; + str = str.replace(/\s\s+/g, ','); + return str || defaultValue || null; }; /** @@ -65860,14 +67196,14 @@ p5.XML.prototype.getContent = function(defaultValue) { * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * - * var xml; + * let xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { - * var firstChild = xml.getChild('animal'); + * let firstChild = xml.getChild('animal'); * print(firstChild.getContent()); * firstChild.setContent('Mountain Goat'); * print(firstChild.getContent()); @@ -65879,50 +67215,45 @@ p5.XML.prototype.getContent = function(defaultValue) { *
*/ p5.XML.prototype.setContent = function(content) { - if (!this.children.length) { - this.content = content; + if (!this.DOM.children.length) { + this.DOM.textContent = content; } }; -/* HELPERS */ /** - * This method is called while the parsing of XML (when loadXML() is - * called). The difference between this method and the setContent() - * method defined later is that this one is used to set the content - * when the node in question has more nodes under it and so on and - * not directly text content. While in the other one is used when - * the node in question directly has text inside it. + * 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. * - */ -p5.XML.prototype._setCont = function(content) { - var str; - str = content; - str = str.replace(/\s\s+/g, ','); - //str = str.split(','); - this.content = str; -}; - -/** - * This method is called while the parsing of XML (when loadXML() is - * called). The XML node is passed and its attributes are stored in the - * p5.XML's attribute Object. + * @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 + * // + *
*/ -p5.XML.prototype._setAttributes = function(node) { - var att = {}; - var attributes = node.attributes; - if (attributes) { - for (var i = 0; i < attributes.length; i++) { - var attribute = attributes[i]; - att[attribute.nodeName] = attribute.nodeValue; - } - } - this.attributes = att; +p5.XML.prototype.serialize = function() { + var xmlSerializer = new XMLSerializer(); + return xmlSerializer.serializeToString(this.DOM); }; module.exports = p5; -},{"../core/main":25}],52:[function(_dereq_,module,exports){ +},{"../core/main":24}],51:[function(_dereq_,module,exports){ /** * @module Math * @submodule Calculation @@ -65944,8 +67275,8 @@ var p5 = _dereq_('../core/main'); * @example *
* function setup() { - * var x = -3; - * var y = abs(x); + * let x = -3; + * let y = abs(x); * * print(x); // -3 * print(y); // 3 @@ -65971,12 +67302,12 @@ p5.prototype.abs = Math.abs; * function draw() { * background(200); * // map, mouseX between 0 and 5. - * var ax = map(mouseX, 0, 100, 0, 5); - * var ay = 66; + * let ax = map(mouseX, 0, 100, 0, 5); + * let ay = 66; * * //Get the ceiling of the mapped number. - * var bx = ceil(map(mouseX, 0, 100, 0, 5)); - * var by = 33; + * let bx = ceil(map(mouseX, 0, 100, 0, 5)); + * let by = 33; * * // Multiply the mapped numbers by 20 to more easily * // see the changes. @@ -66011,14 +67342,14 @@ p5.prototype.ceil = Math.ceil; * function draw() { * background(200); * - * var leftWall = 25; - * var rightWall = 75; + * let leftWall = 25; + * let rightWall = 75; * * // xm is just the mouseX, while * // xc is the mouseX, but constrained * // between the leftWall and rightWall! - * var xm = mouseX; - * var xc = constrain(mouseX, leftWall, rightWall); + * let xm = mouseX; + * let xc = constrain(mouseX, leftWall, rightWall); * * // Draw the walls. * stroke(150); @@ -66061,10 +67392,10 @@ p5.prototype.constrain = function(n, low, high) { * background(200); * fill(0); * - * var x1 = 10; - * var y1 = 90; - * var x2 = mouseX; - * var y2 = mouseY; + * let x1 = 10; + * let y1 = 90; + * let x2 = mouseX; + * let y2 = mouseY; * * line(x1, y1, x2, y2); * ellipse(x1, y1, 7, 7); @@ -66072,7 +67403,7 @@ p5.prototype.constrain = function(n, low, high) { * * // d is the length of the line * // the distance from point 1 to point 2. - * var d = int(dist(x1, y1, x2, y2)); + * let d = int(dist(x1, y1, x2, y2)); * * // Let's write d along the line we are drawing! * push(); @@ -66125,12 +67456,12 @@ p5.prototype.dist = function() { * background(200); * * // Compute the exp() function with a value between 0 and 2 - * var xValue = map(mouseX, 0, width, 0, 2); - * var yValue = exp(xValue); + * let xValue = map(mouseX, 0, width, 0, 2); + * let yValue = exp(xValue); * - * var y = map(yValue, 0, 8, height, 0); + * let y = map(yValue, 0, 8, height, 0); * - * var legend = 'exp (' + nfc(xValue, 3) + ')\n= ' + nf(yValue, 1, 4); + * let legend = 'exp (' + nfc(xValue, 3) + ')\n= ' + nf(yValue, 1, 4); * stroke(150); * line(mouseX, y, mouseX, height); * fill(0); @@ -66143,7 +67474,7 @@ p5.prototype.dist = function() { * noFill(); * stroke(0); * beginShape(); - * for (var x = 0; x < width; x++) { + * for (let x = 0; x < width; x++) { * xValue = map(x, 0, width, 0, 2); * yValue = exp(xValue); * y = map(yValue, 0, 8, height, 0); @@ -66174,12 +67505,12 @@ p5.prototype.exp = Math.exp; * function draw() { * background(200); * //map, mouseX between 0 and 5. - * var ax = map(mouseX, 0, 100, 0, 5); - * var ay = 66; + * let ax = map(mouseX, 0, 100, 0, 5); + * let ay = 66; * * //Get the floor of the mapped number. - * var bx = floor(map(mouseX, 0, 100, 0, 5)); - * var by = 33; + * let bx = floor(map(mouseX, 0, 100, 0, 5)); + * let by = 33; * * // Multiply the mapped numbers by 20 to more easily * // see the changes. @@ -66205,25 +67536,28 @@ p5.prototype.floor = Math.floor; * Calculates a number between two numbers at a specific increment. The amt * parameter is the amount to interpolate between the two values where 0.0 * equal to the first point, 0.1 is very near the first point, 0.5 is - * half-way in between, etc. The lerp function is convenient for creating - * motion along a straight path and for drawing dotted lines. + * half-way in between, and 1.0 is equal to the second point. If the + * value of amt is more than 1.0 or less than 0.0, the number will be + * calculated accordingly in the ratio of the two given numbers. The lerp + * function is convenient for creating motion along a straight + * path and for drawing dotted lines. * * @method lerp * @param {Number} start first value * @param {Number} stop second value - * @param {Number} amt number between 0.0 and 1.0 + * @param {Number} amt number * @return {Number} lerped value * @example *
* function setup() { * background(200); - * var a = 20; - * var b = 80; - * var c = lerp(a, b, 0.2); - * var d = lerp(a, b, 0.5); - * var e = lerp(a, b, 0.8); + * 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); * - * var y = 50; + * let y = 50; * * strokeWeight(5); * stroke(0); // Draw the original points in black @@ -66258,18 +67592,19 @@ p5.prototype.lerp = function(start, stop, amt) { *
* function draw() { * background(200); - * var maxX = 2.8; - * var maxY = 1.5; + * let maxX = 2.8; + * let maxY = 1.5; * * // Compute the natural log of a value between 0 and maxX - * var xValue = map(mouseX, 0, width, 0, maxX); + * let xValue = map(mouseX, 0, width, 0, maxX); + * let yValue, y; * if (xValue > 0) { // Cannot take the log of a negative number. - * var yValue = log(xValue); - * var y = map(yValue, -maxY, maxY, height, 0); + * yValue = log(xValue); + * y = map(yValue, -maxY, maxY, height, 0); * * // Display the calculation occurring. - * var legend = 'log(' + nf(xValue, 1, 2) + ')\n= ' + nf(yValue, 1, 3); + * let legend = 'log(' + nf(xValue, 1, 2) + ')\n= ' + nf(yValue, 1, 3); * stroke(150); * line(mouseX, y, mouseX, height); * fill(0); @@ -66283,7 +67618,7 @@ p5.prototype.lerp = function(start, stop, amt) { * noFill(); * stroke(0); * beginShape(); - * for (var x = 0; x < width; x++) { + * for (let x = 0; x < width; x++) { * xValue = map(x, 0, width, 0, maxX); * yValue = log(xValue); * y = map(yValue, -maxY, maxY, height, 0); @@ -66315,10 +67650,10 @@ p5.prototype.log = Math.log; * @example *
* function setup() { - * var x1 = 20; - * var x2 = 80; - * var y1 = 30; - * var y2 = 70; + * let x1 = 20; + * let x2 = 80; + * let y1 = 30; + * let y2 = 70; * * line(0, 0, x1, y1); * print(mag(x1, y1)); // Prints "36.05551275463989" @@ -66357,8 +67692,8 @@ p5.prototype.mag = function(x, y) { * @return {Number} remapped number * @example *
- * var value = 25; - * var m = map(value, 0, 100, 0, width); + * let value = 25; + * let m = map(value, 0, 100, 0, width); * ellipse(m, 50, 10, 10);
* @@ -66369,11 +67704,11 @@ p5.prototype.mag = function(x, y) { * * function draw() { * background(204); - * var x1 = map(mouseX, 0, width, 25, 75); + * 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 - * var x2 = map(mouseX, 0, width, 0, 100, true); + * let x2 = map(mouseX, 0, width, 0, 100, true); * ellipse(x2, 75, 25, 25); * }
@@ -66410,18 +67745,18 @@ p5.prototype.map = function(n, start1, stop1, start2, stop2, withinBounds) { * function setup() { * // Change the elements in the array and run the sketch * // to show how max() works! - * var numArray = [2, 1, 5, 4, 8, 9]; + * let numArray = [2, 1, 5, 4, 8, 9]; * fill(0); * noStroke(); * text('Array Elements', 0, 10); * // Draw all numbers in the array - * var spacing = 15; - * var elemsY = 25; - * for (var i = 0; i < numArray.length; i++) { + * let spacing = 15; + * let elemsY = 25; + * for (let i = 0; i < numArray.length; i++) { * text(numArray[i], i * spacing, elemsY); * } - * var maxX = 33; - * var maxY = 80; + * let maxX = 33; + * let maxY = 80; * // Draw the Maximum value in the array. * textSize(32); * text(max(numArray), maxX, maxY); @@ -66460,18 +67795,18 @@ p5.prototype.max = function() { * function setup() { * // Change the elements in the array and run the sketch * // to show how min() works! - * var numArray = [2, 1, 5, 4, 8, 9]; + * let numArray = [2, 1, 5, 4, 8, 9]; * fill(0); * noStroke(); * text('Array Elements', 0, 10); * // Draw all numbers in the array - * var spacing = 15; - * var elemsY = 25; - * for (var i = 0; i < numArray.length; i++) { + * let spacing = 15; + * let elemsY = 25; + * for (let i = 0; i < numArray.length; i++) { * text(numArray[i], i * spacing, elemsY); * } - * var maxX = 33; - * var maxY = 80; + * let maxX = 33; + * let maxY = 80; * // Draw the Minimum value in the array. * textSize(32); * text(min(numArray), maxX, maxY); @@ -66500,8 +67835,7 @@ p5.prototype.min = function() { * 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 second - * example above.) + * out-of-range values are often intentional and useful. (See the example above.) * * @method norm * @param {Number} value incoming value to be normalized @@ -66512,20 +67846,21 @@ p5.prototype.min = function() { *
* function draw() { * background(200); - * var currentNum = mouseX; - * var lowerBound = 0; - * var upperBound = width; //100; - * var normalized = norm(currentNum, lowerBound, upperBound); - * var lineY = 70; + * 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); - * var s = 7; // ellipse size + * let s = 7; // ellipse size * ellipse(currentNum, lineY, s, s); * * // Draw the guide - * var guideY = lineY + 15; + * let guideY = lineY + 15; * text('0', 0, guideY); * textAlign(RIGHT); * text('100', width, guideY); @@ -66534,8 +67869,8 @@ p5.prototype.min = function() { * textAlign(LEFT); * fill(0); * textSize(32); - * var normalY = 40; - * var normalX = 20; + * let normalY = 40; + * let normalX = 20; * text(normalized, normalX, normalY); * } *
@@ -66564,8 +67899,8 @@ p5.prototype.norm = function(n, start, stop) { *
* function setup() { * //Exponentially increase the size of an ellipse. - * var eSize = 3; // Original Size - * var eLoc = 10; // Original Location + * let eSize = 3; // Original Size + * let eLoc = 10; // Original Location * * ellipse(eLoc, eLoc, eSize, eSize); * @@ -66595,12 +67930,12 @@ p5.prototype.pow = Math.pow; * function draw() { * background(200); * //map, mouseX between 0 and 5. - * var ax = map(mouseX, 0, 100, 0, 5); - * var ay = 66; + * let ax = map(mouseX, 0, 100, 0, 5); + * let ay = 66; * * // Round the mapped number. - * var bx = round(map(mouseX, 0, 100, 0, 5)); - * var by = 33; + * let bx = round(map(mouseX, 0, 100, 0, 5)); + * let by = 33; * * // Multiply the mapped numbers by 20 to more easily * // see the changes. @@ -66634,11 +67969,11 @@ p5.prototype.round = Math.round; *
* function draw() { * background(200); - * var eSize = 7; - * var x1 = map(mouseX, 0, width, 0, 10); - * var y1 = 80; - * var x2 = sq(x1); - * var y2 = 20; + * 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); @@ -66653,7 +67988,7 @@ p5.prototype.round = Math.round; * line(0, height / 2, width, height / 2); * * // Draw text. - * var spacing = 15; + * let spacing = 15; * noStroke(); * fill(0); * text('x = ' + x1, 0, y1 + spacing); @@ -66682,11 +68017,11 @@ p5.prototype.sq = function(n) { *
* function draw() { * background(200); - * var eSize = 7; - * var x1 = mouseX; - * var y1 = 80; - * var x2 = sqrt(x1); - * var y2 = 20; + * let eSize = 7; + * let x1 = mouseX; + * let y1 = 80; + * let x2 = sqrt(x1); + * let y2 = 20; * * // Draw the non-squared. * line(0, y1, width, y1); @@ -66703,7 +68038,7 @@ p5.prototype.sq = function(n) { * // Draw text. * noStroke(); * fill(0); - * var spacing = 15; + * let spacing = 15; * text('x = ' + x1, 0, y1 + spacing); * text('sqrt(x) = ' + x2, 0, y2 + spacing); * } @@ -66759,7 +68094,7 @@ function hypot(x, y, z) { module.exports = p5; -},{"../core/main":25}],53:[function(_dereq_,module,exports){ +},{"../core/main":24}],52:[function(_dereq_,module,exports){ /** * @module Math * @submodule Math @@ -66811,7 +68146,7 @@ p5.prototype.createVector = function(x, y, z) { module.exports = p5; -},{"../core/main":25}],54:[function(_dereq_,module,exports){ +},{"../core/main":24}],53:[function(_dereq_,module,exports){ ////////////////////////////////////////////////////////////// // http://mrl.nyu.edu/~perlin/noise/ @@ -66888,23 +68223,23 @@ var perlin; // will be initialized lazily by noise() or noiseSeed() * @example *
* - * var xoff = 0.0; + * let xoff = 0.0; * * function draw() { * background(204); * xoff = xoff + 0.01; - * var n = noise(xoff) * width; + * let n = noise(xoff) * width; * line(n, 0, n, height); * } * *
*
- * var noiseScale=0.02; + * let noiseScale=0.02; * * function draw() { * background(0); - * for (var x=0; x < width; x++) { - * var noiseVal = noise((mouseX+x)*noiseScale, mouseY*noiseScale); + * 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); * } @@ -67023,8 +68358,8 @@ p5.prototype.noise = function(x, y, z) { * @example *
* - * var noiseVal; - * var noiseScale = 0.02; + * let noiseVal; + * let noiseScale = 0.02; * * function setup() { * createCanvas(100, 100); @@ -67032,8 +68367,8 @@ p5.prototype.noise = function(x, y, z) { * * function draw() { * background(0); - * for (var y = 0; y < height; y++) { - * for (var x = 0; x < width / 2; x++) { + * 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); @@ -67074,7 +68409,7 @@ p5.prototype.noiseDetail = function(lod, falloff) { * @param {Number} seed the seed value * @example *
- * var xoff = 0.0; + * let xoff = 0.0; * * function setup() { * noiseSeed(99); @@ -67083,7 +68418,7 @@ p5.prototype.noiseDetail = function(lod, falloff) { * * function draw() { * xoff = xoff + .01; - * var n = noise(xoff) * width; + * let n = noise(xoff) * width; * line(n, 0, n, height); * } * @@ -67134,7 +68469,7 @@ p5.prototype.noiseSeed = function(seed) { module.exports = p5; -},{"../core/main":25}],55:[function(_dereq_,module,exports){ +},{"../core/main":24}],54:[function(_dereq_,module,exports){ /** * @module Math * @submodule Math @@ -67172,8 +68507,8 @@ var constants = _dereq_('../core/constants'); * @example *
* - * var v1 = createVector(40, 50); - * var v2 = createVector(40, 50); + * let v1 = createVector(40, 50); + * let v2 = createVector(40, 50); * * ellipse(v1.x, v1.y, 50, 50); * ellipse(v2.x, v2.y, 50, 50); @@ -67228,7 +68563,7 @@ p5.Vector = function Vector() { *
* * function setup() { - * var v = createVector(20, 30); + * let v = createVector(20, 30); * print(String(v)); // prints "p5.Vector Object : [20, 30, 0]" * } * @@ -67239,8 +68574,8 @@ p5.Vector = function Vector() { * function draw() { * background(240); * - * var v0 = createVector(0, 0); - * var v1 = createVector(mouseX, mouseY); + * let v0 = createVector(0, 0); + * let v1 = createVector(mouseX, mouseY); * drawArrow(v0, v1, 'black'); * * noStroke(); @@ -67256,7 +68591,7 @@ p5.Vector = function Vector() { * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); - * var arrowSize = 7; + * let arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); @@ -67280,11 +68615,11 @@ p5.Vector.prototype.toString = function p5VectorToString() { *
* * function setup() { - * var v = createVector(1, 2, 3); + * let v = createVector(1, 2, 3); * v.set(4, 5, 6); // Sets vector to [4, 5, 6] * - * var v1 = createVector(0, 0, 0); - * var arr = [1, 2, 3]; + * let v1 = createVector(0, 0, 0); + * let arr = [1, 2, 3]; * v1.set(arr); // Sets vector to [1, 2, 3] * } * @@ -67292,7 +68627,7 @@ p5.Vector.prototype.toString = function p5VectorToString() { * *
* - * var v0, v1; + * let v0, v1; * function setup() { * createCanvas(100, 100); * @@ -67319,7 +68654,7 @@ p5.Vector.prototype.toString = function p5VectorToString() { * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); - * var arrowSize = 7; + * let arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); @@ -67359,8 +68694,8 @@ p5.Vector.prototype.set = function set(x, y, z) { * @example *
* - * var v1 = createVector(1, 2, 3); - * var v2 = v1.copy(); + * 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" * @@ -67388,7 +68723,7 @@ p5.Vector.prototype.copy = function copy() { * @example *
* - * var v = createVector(1, 2, 3); + * let v = createVector(1, 2, 3); * v.add(4, 5, 6); * // v's components are set to [5, 7, 9] * @@ -67397,10 +68732,10 @@ p5.Vector.prototype.copy = function copy() { *
* * // Static method - * var v1 = createVector(1, 2, 3); - * var v2 = createVector(2, 3, 4); + * let v1 = createVector(1, 2, 3); + * let v2 = createVector(2, 3, 4); * - * var v3 = p5.Vector.add(v1, v2); + * let v3 = p5.Vector.add(v1, v2); * // v3 has components [3, 5, 7] * print(v3); * @@ -67412,14 +68747,14 @@ p5.Vector.prototype.copy = function copy() { * function draw() { * background(240); * - * var v0 = createVector(0, 0); - * var v1 = createVector(mouseX, mouseY); + * let v0 = createVector(0, 0); + * let v1 = createVector(mouseX, mouseY); * drawArrow(v0, v1, 'red'); * - * var v2 = createVector(-30, 20); + * let v2 = createVector(-30, 20); * drawArrow(v1, v2, 'blue'); * - * var v3 = p5.Vector.add(v1, v2); + * let v3 = p5.Vector.add(v1, v2); * drawArrow(v0, v3, 'purple'); * } * @@ -67432,7 +68767,7 @@ p5.Vector.prototype.copy = function copy() { * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); - * var arrowSize = 7; + * let arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); @@ -67478,7 +68813,7 @@ p5.Vector.prototype.add = function add(x, y, z) { * @example *
* - * var v = createVector(4, 5, 6); + * let v = createVector(4, 5, 6); * v.sub(1, 1, 1); * // v's components are set to [3, 4, 5] * @@ -67487,10 +68822,10 @@ p5.Vector.prototype.add = function add(x, y, z) { *
* * // Static method - * var v1 = createVector(2, 3, 4); - * var v2 = createVector(1, 2, 3); + * let v1 = createVector(2, 3, 4); + * let v2 = createVector(1, 2, 3); * - * var v3 = p5.Vector.sub(v1, v2); + * let v3 = p5.Vector.sub(v1, v2); * // v3 has components [1, 1, 1] * print(v3); * @@ -67502,14 +68837,14 @@ p5.Vector.prototype.add = function add(x, y, z) { * function draw() { * background(240); * - * var v0 = createVector(0, 0); - * var v1 = createVector(70, 50); + * let v0 = createVector(0, 0); + * let v1 = createVector(70, 50); * drawArrow(v0, v1, 'red'); * - * var v2 = createVector(mouseX, mouseY); + * let v2 = createVector(mouseX, mouseY); * drawArrow(v0, v2, 'blue'); * - * var v3 = p5.Vector.sub(v1, v2); + * let v3 = p5.Vector.sub(v1, v2); * drawArrow(v2, v3, 'purple'); * } * @@ -67522,7 +68857,7 @@ p5.Vector.prototype.add = function add(x, y, z) { * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); - * var arrowSize = 7; + * let arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); @@ -67565,7 +68900,7 @@ p5.Vector.prototype.sub = function sub(x, y, z) { * @example *
* - * var v = createVector(1, 2, 3); + * let v = createVector(1, 2, 3); * v.mult(2); * // v's components are set to [2, 4, 6] * @@ -67574,8 +68909,8 @@ p5.Vector.prototype.sub = function sub(x, y, z) { *
* * // Static method - * var v1 = createVector(1, 2, 3); - * var v2 = p5.Vector.mult(v1, 2); + * let v1 = createVector(1, 2, 3); + * let v2 = p5.Vector.mult(v1, 2); * // v2 has components [2, 4, 6] * print(v2); * @@ -67586,12 +68921,12 @@ p5.Vector.prototype.sub = function sub(x, y, z) { * function draw() { * background(240); * - * var v0 = createVector(50, 50); - * var v1 = createVector(25, -25); + * let v0 = createVector(50, 50); + * let v1 = createVector(25, -25); * drawArrow(v0, v1, 'red'); * - * var num = map(mouseX, 0, width, -2, 2, true); - * var v2 = p5.Vector.mult(v1, num); + * let num = map(mouseX, 0, width, -2, 2, true); + * let v2 = p5.Vector.mult(v1, num); * drawArrow(v0, v2, 'blue'); * * noStroke(); @@ -67607,7 +68942,7 @@ p5.Vector.prototype.sub = function sub(x, y, z) { * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); - * var arrowSize = 7; + * let arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); @@ -67640,7 +68975,7 @@ p5.Vector.prototype.mult = function mult(n) { * @example *
* - * var v = createVector(6, 4, 2); + * let v = createVector(6, 4, 2); * v.div(2); //v's components are set to [3, 2, 1] * *
@@ -67648,8 +68983,8 @@ p5.Vector.prototype.mult = function mult(n) { *
* * // Static method - * var v1 = createVector(6, 4, 2); - * var v2 = p5.Vector.div(v1, 2); + * let v1 = createVector(6, 4, 2); + * let v2 = p5.Vector.div(v1, 2); * // v2 has components [3, 2, 1] * print(v2); * @@ -67660,12 +68995,12 @@ p5.Vector.prototype.mult = function mult(n) { * function draw() { * background(240); * - * var v0 = createVector(0, 100); - * var v1 = createVector(50, -50); + * let v0 = createVector(0, 100); + * let v1 = createVector(50, -50); * drawArrow(v0, v1, 'red'); * - * var num = map(mouseX, 0, width, 10, 0.5, true); - * var v2 = p5.Vector.div(v1, num); + * let num = map(mouseX, 0, width, 10, 0.5, true); + * let v2 = p5.Vector.div(v1, num); * drawArrow(v0, v2, 'blue'); * * noStroke(); @@ -67681,7 +69016,7 @@ p5.Vector.prototype.mult = function mult(n) { * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); - * var arrowSize = 7; + * let arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); @@ -67719,8 +69054,8 @@ p5.Vector.prototype.div = function div(n) { * function draw() { * background(240); * - * var v0 = createVector(0, 0); - * var v1 = createVector(mouseX, mouseY); + * let v0 = createVector(0, 0); + * let v1 = createVector(mouseX, mouseY); * drawArrow(v0, v1, 'black'); * * noStroke(); @@ -67736,7 +69071,7 @@ p5.Vector.prototype.div = function div(n) { * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); - * var arrowSize = 7; + * let arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); @@ -67745,8 +69080,8 @@ p5.Vector.prototype.div = function div(n) { *
*
* - * var v = createVector(20.0, 30.0, 40.0); - * var m = v.mag(); + * let v = createVector(20.0, 30.0, 40.0); + * let m = v.mag(); * print(m); // Prints "53.85164807134504" * *
@@ -67767,7 +69102,7 @@ p5.Vector.prototype.mag = function mag() { *
* * // Static method - * var v1 = createVector(6, 4, 2); + * let v1 = createVector(6, 4, 2); * print(v1.magSq()); // Prints "56" * *
@@ -67777,8 +69112,8 @@ p5.Vector.prototype.mag = function mag() { * function draw() { * background(240); * - * var v0 = createVector(0, 0); - * var v1 = createVector(mouseX, mouseY); + * let v0 = createVector(0, 0); + * let v1 = createVector(mouseX, mouseY); * drawArrow(v0, v1, 'black'); * * noStroke(); @@ -67794,7 +69129,7 @@ p5.Vector.prototype.mag = function mag() { * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); - * var arrowSize = 7; + * let arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); @@ -67824,8 +69159,8 @@ p5.Vector.prototype.magSq = function magSq() { * @example *
* - * var v1 = createVector(1, 2, 3); - * var v2 = createVector(2, 3, 4); + * let v1 = createVector(1, 2, 3); + * let v2 = createVector(2, 3, 4); * * print(v1.dot(v2)); // Prints "20" * @@ -67834,8 +69169,8 @@ p5.Vector.prototype.magSq = function magSq() { *
* * //Static method - * var v1 = createVector(1, 2, 3); - * var v2 = createVector(3, 2, 1); + * let v1 = createVector(1, 2, 3); + * let v2 = createVector(3, 2, 1); * print(p5.Vector.dot(v1, v2)); // Prints "10" * *
@@ -67863,8 +69198,8 @@ p5.Vector.prototype.dot = function dot(x, y, z) { * @example *
* - * var v1 = createVector(1, 2, 3); - * var v2 = createVector(1, 2, 3); + * let v1 = createVector(1, 2, 3); + * let v2 = createVector(1, 2, 3); * * v1.cross(v2); // v's components are [0, 0, 0] * @@ -67873,10 +69208,10 @@ p5.Vector.prototype.dot = function dot(x, y, z) { *
* * // Static method - * var v1 = createVector(1, 0, 0); - * var v2 = createVector(0, 1, 0); + * let v1 = createVector(1, 0, 0); + * let v2 = createVector(0, 1, 0); * - * var crossProduct = p5.Vector.cross(v1, v2); + * let crossProduct = p5.Vector.cross(v1, v2); * // crossProduct has components [0, 0, 1] * print(crossProduct); * @@ -67903,10 +69238,10 @@ p5.Vector.prototype.cross = function cross(v) { * @example *
* - * var v1 = createVector(1, 0, 0); - * var v2 = createVector(0, 1, 0); + * let v1 = createVector(1, 0, 0); + * let v2 = createVector(0, 1, 0); * - * var distance = v1.dist(v2); // distance is 1.4142... + * let distance = v1.dist(v2); // distance is 1.4142... * print(distance); * *
@@ -67914,10 +69249,10 @@ p5.Vector.prototype.cross = function cross(v) { *
* * // Static method - * var v1 = createVector(1, 0, 0); - * var v2 = createVector(0, 1, 0); + * let v1 = createVector(1, 0, 0); + * let v2 = createVector(0, 1, 0); * - * var distance = p5.Vector.dist(v1, v2); + * let distance = p5.Vector.dist(v1, v2); * // distance is 1.4142... * print(distance); * @@ -67928,12 +69263,12 @@ p5.Vector.prototype.cross = function cross(v) { * function draw() { * background(240); * - * var v0 = createVector(0, 0); + * let v0 = createVector(0, 0); * - * var v1 = createVector(70, 50); + * let v1 = createVector(70, 50); * drawArrow(v0, v1, 'red'); * - * var v2 = createVector(mouseX, mouseY); + * let v2 = createVector(mouseX, mouseY); * drawArrow(v0, v2, 'blue'); * * noStroke(); @@ -67949,7 +69284,7 @@ p5.Vector.prototype.cross = function cross(v) { * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); - * var arrowSize = 7; + * let arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); @@ -67972,7 +69307,7 @@ p5.Vector.prototype.dist = function dist(v) { * @example *
* - * var v = createVector(10, 20, 2); + * let v = createVector(10, 20, 2); * // v has components [10.0, 20.0, 2.0] * v.normalize(); * // v's components are set to @@ -67984,8 +69319,8 @@ p5.Vector.prototype.dist = function dist(v) { * function draw() { * background(240); * - * var v0 = createVector(50, 50); - * var v1 = createVector(mouseX - 50, mouseY - 50); + * let v0 = createVector(50, 50); + * let v1 = createVector(mouseX - 50, mouseY - 50); * * drawArrow(v0, v1, 'red'); * v1.normalize(); @@ -68004,7 +69339,7 @@ p5.Vector.prototype.dist = function dist(v) { * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); - * var arrowSize = 7; + * let arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); @@ -68030,7 +69365,7 @@ p5.Vector.prototype.normalize = function normalize() { * @example *
* - * var v = createVector(10, 20, 2); + * let v = createVector(10, 20, 2); * // v has components [10.0, 20.0, 2.0] * v.limit(5); * // v's components are set to @@ -68042,8 +69377,8 @@ p5.Vector.prototype.normalize = function normalize() { * function draw() { * background(240); * - * var v0 = createVector(50, 50); - * var v1 = createVector(mouseX - 50, mouseY - 50); + * let v0 = createVector(50, 50); + * let v1 = createVector(mouseX - 50, mouseY - 50); * * drawArrow(v0, v1, 'red'); * drawArrow(v0, v1.limit(35), 'blue'); @@ -68061,7 +69396,7 @@ p5.Vector.prototype.normalize = function normalize() { * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); - * var arrowSize = 7; + * let arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); @@ -68088,7 +69423,7 @@ p5.Vector.prototype.limit = function limit(max) { * @example *
* - * var v = createVector(10, 20, 2); + * let v = createVector(10, 20, 2); * // v has components [10.0, 20.0, 2.0] * v.setMag(10); * // v's components are set to [6.0, 8.0, 0.0] @@ -68100,12 +69435,12 @@ p5.Vector.prototype.limit = function limit(max) { * function draw() { * background(240); * - * var v0 = createVector(0, 0); - * var v1 = createVector(50, 50); + * let v0 = createVector(0, 0); + * let v1 = createVector(50, 50); * * drawArrow(v0, v1, 'red'); * - * var length = map(mouseX, 0, width, 0, 141, true); + * let length = map(mouseX, 0, width, 0, 141, true); * v1.setMag(length); * drawArrow(v0, v1, 'blue'); * @@ -68122,7 +69457,7 @@ p5.Vector.prototype.limit = function limit(max) { * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); - * var arrowSize = 7; + * let arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); @@ -68143,7 +69478,7 @@ p5.Vector.prototype.setMag = function setMag(n) { *
* * function setup() { - * var v1 = createVector(30, 50); + * let v1 = createVector(30, 50); * print(v1.heading()); // 1.0303768265243125 * * v1 = createVector(40, 50); @@ -68160,12 +69495,12 @@ p5.Vector.prototype.setMag = function setMag(n) { * function draw() { * background(240); * - * var v0 = createVector(50, 50); - * var v1 = createVector(mouseX - 50, mouseY - 50); + * let v0 = createVector(50, 50); + * let v1 = createVector(mouseX - 50, mouseY - 50); * * drawArrow(v0, v1, 'black'); * - * var myHeading = v1.heading(); + * let myHeading = v1.heading(); * noStroke(); * text( * 'vector heading: ' + @@ -68189,7 +69524,7 @@ p5.Vector.prototype.setMag = function setMag(n) { * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); - * var arrowSize = 7; + * let arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); @@ -68213,7 +69548,7 @@ p5.Vector.prototype.heading = function heading() { * @example *
* - * var v = createVector(10.0, 20.0); + * 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] @@ -68222,12 +69557,12 @@ p5.Vector.prototype.heading = function heading() { * *
* - * var angle = 0; + * let angle = 0; * function draw() { * background(240); * - * var v0 = createVector(50, 50); - * var v1 = createVector(50, 0); + * let v0 = createVector(50, 50); + * let v1 = createVector(50, 0); * * drawArrow(v0, v1.rotate(angle), 'black'); * angle += 0.01; @@ -68242,7 +69577,7 @@ p5.Vector.prototype.heading = function heading() { * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); - * var arrowSize = 7; + * let arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); @@ -68267,10 +69602,10 @@ p5.Vector.prototype.rotate = function rotate(a) { * @example *
* - * var v1 = createVector(1, 0, 0); - * var v2 = createVector(0, 1, 0); + * let v1 = createVector(1, 0, 0); + * let v2 = createVector(0, 1, 0); * - * var angle = v1.angleBetween(v2); + * let angle = v1.angleBetween(v2); * // angle is PI/2 * print(angle); * @@ -68280,15 +69615,15 @@ p5.Vector.prototype.rotate = function rotate(a) { * * function draw() { * background(240); - * var v0 = createVector(50, 50); + * let v0 = createVector(50, 50); * - * var v1 = createVector(50, 0); + * let v1 = createVector(50, 0); * drawArrow(v0, v1, 'red'); * - * var v2 = createVector(mouseX - 50, mouseY - 50); + * let v2 = createVector(mouseX - 50, mouseY - 50); * drawArrow(v0, v2, 'blue'); * - * var angleBetween = v1.angleBetween(v2); + * let angleBetween = v1.angleBetween(v2); * noStroke(); * text( * 'angle between: ' + @@ -68312,7 +69647,7 @@ p5.Vector.prototype.rotate = function rotate(a) { * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); - * var arrowSize = 7; + * let arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); @@ -68347,7 +69682,7 @@ p5.Vector.prototype.angleBetween = function angleBetween(v) { * @example *
* - * var v = createVector(1, 1, 0); + * let v = createVector(1, 1, 0); * * v.lerp(3, 3, 0, 0.5); // v now has components [2,2,0] * @@ -68355,10 +69690,10 @@ p5.Vector.prototype.angleBetween = function angleBetween(v) { * *
* - * var v1 = createVector(0, 0, 0); - * var v2 = createVector(100, 100, 0); + * let v1 = createVector(0, 0, 0); + * let v2 = createVector(100, 100, 0); * - * var v3 = p5.Vector.lerp(v1, v2, 0.5); + * let v3 = p5.Vector.lerp(v1, v2, 0.5); * // v3 has components [50,50,0] * print(v3); * @@ -68366,24 +69701,24 @@ p5.Vector.prototype.angleBetween = function angleBetween(v) { * *
* - * var step = 0.01; - * var amount = 0; + * let step = 0.01; + * let amount = 0; * * function draw() { * background(240); - * var v0 = createVector(0, 0); + * let v0 = createVector(0, 0); * - * var v1 = createVector(mouseX, mouseY); + * let v1 = createVector(mouseX, mouseY); * drawArrow(v0, v1, 'red'); * - * var v2 = createVector(90, 90); + * let v2 = createVector(90, 90); * drawArrow(v0, v2, 'blue'); * * if (amount > 1 || amount < 0) { * step *= -1; * } * amount += step; - * var v3 = p5.Vector.lerp(v1, v2, amount); + * let v3 = p5.Vector.lerp(v1, v2, amount); * * drawArrow(v0, v3, 'purple'); * } @@ -68397,7 +69732,7 @@ p5.Vector.prototype.angleBetween = function angleBetween(v) { * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); - * var arrowSize = 7; + * let arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); @@ -68433,7 +69768,7 @@ p5.Vector.prototype.lerp = function lerp(x, y, z, amt) { *
* * function setup() { - * var v = createVector(20, 30); + * let v = createVector(20, 30); * print(v.array()); // Prints : Array [20, 30, 0] * } * @@ -68441,8 +69776,8 @@ p5.Vector.prototype.lerp = function lerp(x, y, z, amt) { * *
* - * var v = createVector(10.0, 20.0, 30.0); - * var f = v.array(); + * 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" @@ -68464,9 +69799,9 @@ p5.Vector.prototype.array = function array() { * @example *
* - * var v1 = createVector(5, 10, 20); - * var v2 = createVector(5, 10, 20); - * var v3 = createVector(13, 10, 19); + * 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 @@ -68475,9 +69810,9 @@ p5.Vector.prototype.array = function array() { * *
* - * var v1 = createVector(10.0, 20.0, 30.0); - * var v2 = createVector(10.0, 20.0, 30.0); - * var v3 = createVector(0.0, 0.0, 0.0); + * 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 * @@ -68525,21 +69860,21 @@ p5.Vector.prototype.equals = function equals(x, y, z) { * // Create a variable, proportional to the mouseX, * // varying from 0-360, to represent an angle in degrees. * angleMode(DEGREES); - * var myDegrees = map(mouseX, 0, width, 0, 360); + * 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.) - * var readout = 'angle = ' + nfc(myDegrees, 1) + '\xB0'; + * 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. - * var v = p5.Vector.fromAngle(radians(myDegrees), 30); - * var vx = v.x; - * var vy = v.y; + * let v = p5.Vector.fromAngle(radians(myDegrees), 30); + * let vx = v.x; + * let vy = v.y; * * push(); * translate(width / 2, height / 2); @@ -68581,7 +69916,7 @@ p5.Vector.fromAngle = function fromAngle(angle, length) { * function draw() { * background(255); * - * var t = millis() / 1000; + * let t = millis() / 1000; * * // add three point lights * pointLight(color('#f00'), p5.Vector.fromAngles(t * 1.0, t * 1.3, 100)); @@ -68618,7 +69953,7 @@ p5.Vector.fromAngles = function(theta, phi, length) { * @example *
* - * var v = p5.Vector.random2D(); + * 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 @@ -68636,8 +69971,8 @@ p5.Vector.fromAngles = function(theta, phi, length) { * function draw() { * background(240); * - * var v0 = createVector(50, 50); - * var v1 = p5.Vector.random2D(); + * let v0 = createVector(50, 50); + * let v1 = p5.Vector.random2D(); * drawArrow(v0, v1.mult(50), 'black'); * } * @@ -68650,7 +69985,7 @@ p5.Vector.fromAngles = function(theta, phi, length) { * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); - * var arrowSize = 7; + * let arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); @@ -68671,7 +70006,7 @@ p5.Vector.random2D = function random2D() { * @example *
* - * var v = p5.Vector.random3D(); + * 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 @@ -68888,7 +70223,7 @@ p5.Vector.mag = function mag(vecT) { module.exports = p5.Vector; -},{"../core/constants":19,"../core/main":25}],56:[function(_dereq_,module,exports){ +},{"../core/constants":18,"../core/main":24}],55:[function(_dereq_,module,exports){ /** * @module Math * @submodule Random @@ -68949,8 +70284,8 @@ var lcg = (function() { *
* * randomSeed(99); - * for (var i = 0; i < 100; i++) { - * var r = random(0, 255); + * for (let i = 0; i < 100; i++) { + * let r = random(0, 255); * stroke(r); * line(i, 0, i, 100); * } @@ -68991,8 +70326,8 @@ p5.prototype.randomSeed = function(seed) { * @example *
* - * for (var i = 0; i < 100; i++) { - * var r = random(50); + * for (let i = 0; i < 100; i++) { + * let r = random(50); * stroke(r * 5); * line(50, i, 50 + r, i); * } @@ -69000,8 +70335,8 @@ p5.prototype.randomSeed = function(seed) { *
*
* - * for (var i = 0; i < 100; i++) { - * var r = random(-50, 50); + * for (let i = 0; i < 100; i++) { + * let r = random(-50, 50); * line(50, i, 50 + r, i); * } * @@ -69009,8 +70344,8 @@ p5.prototype.randomSeed = function(seed) { *
* * // Get a random element from an array using the random(Array) syntax - * var words = ['apple', 'bear', 'cat', 'dog']; - * var word = random(words); // select random word + * let words = ['apple', 'bear', 'cat', 'dog']; + * let word = random(words); // select random word * text(word, 10, 50); // draw the word * *
@@ -69075,19 +70410,19 @@ p5.prototype.random = function(min, max) { * @example *
* - * for (var y = 0; y < 100; y++) { - * var x = randomGaussian(50, 15); + * for (let y = 0; y < 100; y++) { + * let x = randomGaussian(50, 15); * line(50, y, x, y); * } * *
*
* - * var distribution = new Array(360); + * let distribution = new Array(360); * * function setup() { * createCanvas(100, 100); - * for (var i = 0; i < distribution.length; i++) { + * for (let i = 0; i < distribution.length; i++) { * distribution[i] = floor(randomGaussian(0, 15)); * } * } @@ -69097,10 +70432,10 @@ p5.prototype.random = function(min, max) { * * translate(width / 2, width / 2); * - * for (var i = 0; i < distribution.length; i++) { + * for (let i = 0; i < distribution.length; i++) { * rotate(TWO_PI / distribution.length); * stroke(0); - * var dist = abs(distribution[i]); + * let dist = abs(distribution[i]); * line(0, 0, dist, 0); * } * } @@ -69134,7 +70469,7 @@ p5.prototype.randomGaussian = function(mean, sd) { module.exports = p5; -},{"../core/main":25}],57:[function(_dereq_,module,exports){ +},{"../core/main":24}],56:[function(_dereq_,module,exports){ /** * @module Math * @submodule Trigonometry @@ -69166,9 +70501,9 @@ p5.prototype._angleMode = constants.RADIANS; * @example *
* - * var a = PI; - * var c = cos(a); - * var ac = acos(c); + * let a = PI; + * let c = cos(a); + * let ac = acos(c); * // Prints: "3.1415927 : -1.0 : 3.1415927" * print(a + ' : ' + c + ' : ' + ac); * @@ -69176,9 +70511,9 @@ p5.prototype._angleMode = constants.RADIANS; * *
* - * var a = PI + PI / 4.0; - * var c = cos(a); - * var ac = acos(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); * @@ -69200,9 +70535,9 @@ p5.prototype.acos = function(ratio) { * @example *
* - * var a = PI + PI / 3; - * var s = sin(a); - * var as = asin(s); + * let a = PI + PI / 3; + * let s = sin(a); + * let as = asin(s); * // Prints: "1.0471976 : 0.86602545 : 1.0471976" * print(a + ' : ' + s + ' : ' + as); * @@ -69210,9 +70545,9 @@ p5.prototype.acos = function(ratio) { * *
* - * var a = PI + PI / 3.0; - * var s = sin(a); - * var as = asin(s); + * let a = PI + PI / 3.0; + * let s = sin(a); + * let as = asin(s); * // Prints: "4.1887903 : -0.86602545 : -1.0471976" * print(a + ' : ' + s + ' : ' + as); * @@ -69235,9 +70570,9 @@ p5.prototype.asin = function(ratio) { * @example *
* - * var a = PI + PI / 3; - * var t = tan(a); - * var at = atan(t); + * let a = PI + PI / 3; + * let t = tan(a); + * let at = atan(t); * // Prints: "1.0471976 : 1.7320509 : 1.0471976" * print(a + ' : ' + t + ' : ' + at); * @@ -69245,9 +70580,9 @@ p5.prototype.asin = function(ratio) { * *
* - * var a = PI + PI / 3.0; - * var t = tan(a); - * var at = atan(t); + * let a = PI + PI / 3.0; + * let t = tan(a); + * let at = atan(t); * // Prints: "4.1887903 : 1.7320513 : 1.0471977" * print(a + ' : ' + t + ' : ' + at); * @@ -69279,7 +70614,7 @@ p5.prototype.atan = function(ratio) { * function draw() { * background(204); * translate(width / 2, height / 2); - * var a = atan2(mouseY - height / 2, mouseX - width / 2); + * let a = atan2(mouseY - height / 2, mouseX - width / 2); * rotate(a); * rect(-30, -5, 60, 10); * } @@ -69305,9 +70640,9 @@ p5.prototype.atan2 = function(y, x) { * @example *
* - * var a = 0.0; - * var inc = TWO_PI / 25.0; - * for (var i = 0; i < 25; i++) { + * 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; * } @@ -69333,9 +70668,9 @@ p5.prototype.cos = function(angle) { * @example *
* - * var a = 0.0; - * var inc = TWO_PI / 25.0; - * for (var i = 0; i < 25; i++) { + * 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; * } @@ -69361,9 +70696,9 @@ p5.prototype.sin = function(angle) { * @example *
* - * var a = 0.0; - * var inc = TWO_PI / 50.0; - * for (var i = 0; i < 100; i = i + 2) { + * 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; * } @@ -69393,8 +70728,8 @@ p5.prototype.tan = function(angle) { * @example *
* - * var rad = PI / 4; - * var deg = degrees(rad); + * let rad = PI / 4; + * let deg = degrees(rad); * print(rad + ' radians is ' + deg + ' degrees'); * // Prints: 0.7853981633974483 radians is 45 degrees * @@ -69419,8 +70754,8 @@ p5.prototype.degrees = function(angle) { * @example *
* - * var deg = 45.0; - * var rad = radians(deg); + * let deg = 45.0; + * let rad = radians(deg); * print(deg + ' degrees is ' + rad + ' radians'); * // Prints: 45 degrees is 0.7853981633974483 radians * @@ -69442,14 +70777,14 @@ p5.prototype.radians = function(angle) { * function draw() { * background(204); * angleMode(DEGREES); // Change the mode to DEGREES - * var a = atan2(mouseY - height / 2, mouseX - width / 2); + * 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); // var a stays the same + * rotate(a); // variable a stays the same * rect(-40, -5, 20, 10); // Smaller rectangle is rotating in radians * } * @@ -69513,7 +70848,7 @@ p5.prototype._fromRadians = function(angle) { module.exports = p5; -},{"../core/constants":19,"../core/main":25}],58:[function(_dereq_,module,exports){ +},{"../core/constants":18,"../core/main":24}],57:[function(_dereq_,module,exports){ /** * @module Typography * @submodule Attributes @@ -69609,7 +70944,7 @@ p5.prototype.textAlign = function(horizAlign, vertAlign) { *
* * // Text to display. The "\n" is a "new line" character - * var lines = 'L1\nL2\nL3'; + * let lines = 'L1\nL2\nL3'; * textSize(12); * * textLeading(10); // Set leading to 10 @@ -69668,13 +71003,13 @@ p5.prototype.textSize = function(theSize) { }; /** - * Sets/gets the style of the text for system fonts to NORMAL, ITALIC, or BOLD. + * Sets/gets the style of the text for system fonts to NORMAL, ITALIC, BOLD or BOLDITALIC. * Note: this may be is overridden by CSS styling. For non-system fonts * (opentype, truetype, etc.) please load styled fonts instead. * * @method textStyle * @param {Constant} theStyle styling for text, either NORMAL, - * ITALIC, or BOLD + * ITALIC, BOLD or BOLDITALIC * @chainable * @example *
@@ -69682,16 +71017,18 @@ p5.prototype.textSize = function(theSize) { * strokeWeight(0); * textSize(12); * textStyle(NORMAL); - * text('Font Style Normal', 10, 30); + * text('Font Style Normal', 10, 15); * textStyle(ITALIC); - * text('Font Style Italic', 10, 60); + * text('Font Style Italic', 10, 40); * textStyle(BOLD); - * text('Font Style Bold', 10, 90); + * text('Font Style Bold', 10, 65); + * textStyle(BOLDITALIC); + * text('Font Style Bold Italic', 10, 90); * *
* * @alt - *words Font Style Normal displayed normally, Italic in italic and bold in bold + *words Font Style Normal displayed normally, Italic in italic, bold in bold and bold italic in bold italics. */ /** * @method textStyle @@ -69713,13 +71050,13 @@ p5.prototype.textStyle = function(theStyle) { * * textSize(28); * - * var aChar = 'P'; - * var cWidth = textWidth(aChar); + * let aChar = 'P'; + * let cWidth = textWidth(aChar); * text(aChar, 0, 40); * line(cWidth, 0, cWidth, 50); * - * var aString = 'p5.js'; - * var sWidth = textWidth(aString); + * let aString = 'p5.js'; + * let sWidth = textWidth(aString); * text(aString, 0, 85); * line(sWidth, 50, sWidth, 100); * @@ -69746,11 +71083,11 @@ p5.prototype.textWidth = function(theText) { * @example *
* - * var base = height * 0.75; - * var scalar = 0.8; // Different for each font + * let base = height * 0.75; + * let scalar = 0.8; // Different for each font * * textSize(32); // Set initial text size - * var asc = textAscent() * scalar; // Calc ascent + * let asc = textAscent() * scalar; // Calc ascent * line(0, base - asc, width, base - asc); * text('dp', 0, base); // Draw text on baseline * @@ -69775,11 +71112,11 @@ p5.prototype.textAscent = function() { * @example *
* - * var base = height * 0.75; - * var scalar = 0.8; // Different for each font + * let base = height * 0.75; + * let scalar = 0.8; // Different for each font * * textSize(32); // Set initial text size - * var desc = textDescent() * scalar; // Calc ascent + * let desc = textDescent() * scalar; // Calc ascent * line(0, base + desc, width, base + desc); * text('dp', 0, base); // Draw text on baseline * @@ -69804,7 +71141,7 @@ p5.prototype._updateTextMetrics = function() { module.exports = p5; -},{"../core/main":25}],59:[function(_dereq_,module,exports){ +},{"../core/main":24}],58:[function(_dereq_,module,exports){ /** * @module Typography * @submodule Loading & Displaying @@ -69827,7 +71164,7 @@ _dereq_('../core/error_helpers'); * is executed. *

* The path to the font should be relative to the HTML file - * that links in your sketch. Loading an from a URL or other + * 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. * @@ -69844,9 +71181,9 @@ _dereq_('../core/error_helpers'); * operation will have completed before setup() and draw() are called.

* *
- * var myFont; + * let myFont; * function preload() { - * myFont = loadFont('assets/AvenirNextLTPro-Demi.otf'); + * myFont = loadFont('assets/inconsolata.otf'); * } * * function setup() { @@ -69862,7 +71199,7 @@ _dereq_('../core/error_helpers'); * *
* function setup() { - * loadFont('assets/AvenirNextLTPro-Demi.otf', drawText); + * loadFont('assets/inconsolata.otf', drawText); * } * * function drawText(font) { @@ -69872,17 +71209,17 @@ _dereq_('../core/error_helpers'); * } *
* - *

You can also use the string name of the font to style other HTML + *

You can also use the font filename string (without the file extension) to style other HTML * elements.

* *
* function preload() { - * loadFont('assets/Avenir.otf'); + * loadFont('assets/inconsolata.otf'); * } * * function setup() { - * var myDiv = createDiv('hello there'); - * myDiv.style('font-family', 'Avenir'); + * let myDiv = createDiv('hello there'); + * myDiv.style('font-family', 'Inconsolata'); * } *
* @@ -69898,10 +71235,10 @@ p5.prototype.loadFont = function(path, onSuccess, onError) { var self = this; opentype.load(path, function(err, font) { if (err) { + p5._friendlyFileLoadError(4, path); if (typeof onError !== 'undefined') { return onError(err); } - p5._friendlyFileLoadError(4, path); console.error(err, path); return; } @@ -69993,7 +71330,7 @@ p5.prototype.loadFont = function(path, onSuccess, onError) { *
*
* - * var s = 'The quick brown fox jumped over the lazy dog.'; + * let s = 'The quick brown fox jumped over the lazy dog.'; * fill(50); * text(s, 10, 10, 70, 80); // Text wraps within text box * @@ -70001,19 +71338,19 @@ p5.prototype.loadFont = function(path, onSuccess, onError) { * *
* - * var avenir; + * let inconsolata; * function preload() { - * avenir = loadFont('assets/Avenir.otf'); + * inconsolata = loadFont('assets/inconsolata.otf'); * } * function setup() { * createCanvas(100, 100, WEBGL); - * textFont(avenir); + * textFont(inconsolata); * textSize(width / 3); * textAlign(CENTER, CENTER); * } * function draw() { * background(0); - * var time = millis(); + * let time = millis(); * rotateX(time / 1000); * rotateZ(time / 1234); * text('p5.js', 0, 0); @@ -70055,7 +71392,7 @@ p5.prototype.text = function(str, x, y, maxWidth, maxHeight) { *
*
* - * var fontRegular, fontItalic, fontBold; + * let fontRegular, fontItalic, fontBold; * function preload() { * fontRegular = loadFont('assets/Regular.otf'); * fontItalic = loadFont('assets/Italic.ttf'); @@ -70112,7 +71449,7 @@ p5.prototype.textFont = function(theFont, theSize) { module.exports = p5; -},{"../core/constants":19,"../core/error_helpers":21,"../core/main":25,"opentype.js":11}],60:[function(_dereq_,module,exports){ +},{"../core/constants":18,"../core/error_helpers":20,"../core/main":24,"opentype.js":10}],59:[function(_dereq_,module,exports){ /** * This module defines the p5.Font class and functions for * drawing text to the display canvas. @@ -70127,12 +71464,6 @@ module.exports = p5; var p5 = _dereq_('../core/main'); var constants = _dereq_('../core/constants'); -/* - * TODO: - * -- kerning - * -- alignment: justified? - */ - /** * Base class for font handling * @class p5.Font @@ -70150,11 +71481,6 @@ p5.Font = function(p) { this.font = undefined; }; -p5.Font.prototype.list = function() { - // TODO - throw new Error('not yet implemented'); -}; - /** * Returns a tight bounding box for the given text string using this * font (currently only supports single lines) @@ -70163,23 +71489,26 @@ p5.Font.prototype.list = function() { * @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) + * @param {Number} [fontSize] font size to use (optional) Default is 12. * @param {Object} [options] opentype options (optional) + * opentype fonts contains alignment and baseline options. + * Default is 'LEFT' and 'alphabetic' + * * * @return {Object} a rectangle object with properties: x, y, w, h * * @example *
* - * var font; - * var textString = 'Lorem ipsum dolor sit amet.'; + * let font; + * let textString = 'Lorem ipsum dolor sit amet.'; * function preload() { * font = loadFont('./assets/Regular.otf'); * } * function setup() { * background(210); * - * var bbox = font.textBounds(textString, 10, 30, 12); + * let bbox = font.textBounds(textString, 10, 30, 12); * fill(255); * stroke(0); * rect(bbox.x, bbox.y, bbox.w, bbox.h); @@ -70197,21 +71526,28 @@ p5.Font.prototype.list = function() { *words Lorem ipsum dol go off canvas and contained by white bounding box * */ -p5.Font.prototype.textBounds = function(str, x, y, fontSize, options) { +p5.Font.prototype.textBounds = function(str, x, y, fontSize, opts) { x = x !== undefined ? x : 0; y = y !== undefined ? y : 0; - fontSize = fontSize || this.parent._renderer._textSize; // 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 = - (options && options.renderer && options.renderer._pInst) || this.parent, - renderer = p._renderer, - alignment = renderer._textAlign || constants.LEFT, - baseline = renderer._textBaseline || constants.BASELINE, - key = cacheKey('textBounds', str, x, y, fontSize, alignment, baseline), + var p = (opts && opts.renderer && opts.renderer._pInst) || this.parent, + ctx = p._renderer.drawingContext, + alignment = ctx.textAlign || constants.LEFT, + baseline = ctx.textBaseline || constants.BASELINE, + cacheResults = false, + result, + 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, @@ -70223,7 +71559,7 @@ p5.Font.prototype.textBounds = function(str, x, y, fontSize, options) { yCoords = [], scale = this._scale(fontSize); - this.font.forEachGlyph(str, x, y, fontSize, options, function( + this.font.forEachGlyph(str, x, y, fontSize, opts, function( glyph, gX, gY, @@ -70251,7 +71587,7 @@ p5.Font.prototype.textBounds = function(str, x, y, fontSize, options) { // Bounds are now calculated, so shift the x & y to match alignment settings pos = this._handleAlignment( - renderer, + p._renderer, str, result.x, result.y, @@ -70261,9 +71597,9 @@ p5.Font.prototype.textBounds = function(str, x, y, fontSize, options) { result.x = pos.x; result.y = pos.y; - this.cache[ - cacheKey('textBounds', str, x, y, fontSize, alignment, baseline) - ] = result; + if (cacheResults) { + this.cache[key] = result; + } } return result; @@ -70280,7 +71616,7 @@ p5.Font.prototype.textBounds = function(str, x, y, fontSize, options) { * @param {Object} [options] an (optional) object that can contain: * *
sampleFactor - the ratio of path-length to number of samples - * (default=.25); higher values yield more points and are therefore + * (default=.1); higher values yield more points and are therefore * more precise * *
simplifyThreshold - if set to a non-zero value, collinear points will be @@ -70291,13 +71627,13 @@ p5.Font.prototype.textBounds = function(str, x, y, fontSize, options) { * @example *
* - * var font; + * let font; * function preload() { - * font = loadFont('./assets/Avenir.otf'); + * font = loadFont('assets/inconsolata.otf'); * } * - * var points; - * var bounds; + * let points; + * let bounds; * function setup() { * createCanvas(100, 100); * stroke(0); @@ -70314,8 +71650,8 @@ p5.Font.prototype.textBounds = function(str, x, y, fontSize, options) { * background(255); * beginShape(); * translate(-bounds.x * width / bounds.w, -bounds.y * height / bounds.h); - * for (var i = 0; i < points.length; i++) { - * var p = points[i]; + * 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, @@ -70606,8 +71942,7 @@ function pathToPoints(cmds, options) { } if (opts.simplifyThreshold) { - /*var count = */ simplify(pts, opts.simplifyThreshold); - //console.log('Simplify: removed ' + count + ' pts'); + simplify(pts, opts.simplifyThreshold); } return pts; @@ -71350,15 +72685,14 @@ function base3(t, p1, p2, p3, p4) { function cacheKey() { var hash = ''; for (var i = arguments.length - 1; i >= 0; --i) { - var v = arguments[i]; - hash += v === Object(v) ? JSON.stringify(v) : v; + hash += '?' + arguments[i]; } return hash; } module.exports = p5; -},{"../core/constants":19,"../core/main":25}],61:[function(_dereq_,module,exports){ +},{"../core/constants":18,"../core/main":24}],60:[function(_dereq_,module,exports){ /** * @module Data * @submodule Array Functions @@ -71555,7 +72889,6 @@ p5.prototype.shorten = function(list) { * Fisher-Yates Shuffle Algorithm. * * @method shuffle - * @deprecated See shuffling an array with JS instead. * @param {Array} array Array to shuffle * @param {Boolean} [bool] modify passed array * @return {Array} shuffled Array @@ -71713,7 +73046,7 @@ p5.prototype.subset = function(list, start, count) { module.exports = p5; -},{"../core/main":25}],62:[function(_dereq_,module,exports){ +},{"../core/main":24}],61:[function(_dereq_,module,exports){ /** * @module Data * @submodule Conversion @@ -71743,6 +73076,11 @@ var p5 = _dereq_('../core/main'); * var diameter = float(str); * ellipse(width / 2, height / 2, diameter, diameter); *
+ *
+ * print(float('10.31')); // 10.31 + * print(float('Infinity')); // Infinity + * print(float('-Infinity')); // -Infinity + *
* * @alt * 20 by 20 white ellipse in the center of the canvas @@ -71773,6 +73111,8 @@ p5.prototype.float = function(str) { * 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 *
*/ /** @@ -71782,7 +73122,11 @@ p5.prototype.float = function(str) { */ p5.prototype.int = function(n, radix) { radix = radix || 10; - if (typeof n === 'string') { + 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; @@ -71838,7 +73182,7 @@ p5.prototype.str = function(n) { * print(boolean(1)); // true * print(boolean('true')); // true * print(boolean('abcd')); // false - * print(boolean([0, 12, 'true'])); // [false, true, false] + * print(boolean([0, 12, 'true'])); // [false, true, true] *
*/ p5.prototype.boolean = function(n) { @@ -71968,6 +73312,8 @@ p5.prototype.unchar = function(n) { * print(hex(255)); // "000000FF" * print(hex(255, 6)); // "0000FF" * print(hex([0, 127, 255], 6)); // [ "000000", "00007F", "0000FF" ] + * print(Infinity); // "FFFFFFFF" + * print(-Infinity); // "00000000" *
*/ /** @@ -71982,6 +73328,9 @@ p5.prototype.hex = function(n, digits) { return n.map(function(n) { return p5.prototype.hex(n, digits); }); + } else if (n === Infinity || n === -Infinity) { + var c = n === Infinity ? 'F' : '0'; + return c.repeat(digits); } else if (typeof n === 'number') { if (n < 0) { n = 0xffffffff + n + 1; @@ -72030,7 +73379,7 @@ p5.prototype.unhex = function(n) { module.exports = p5; -},{"../core/main":25}],63:[function(_dereq_,module,exports){ +},{"../core/main":24}],62:[function(_dereq_,module,exports){ /** * @module Data * @submodule String Functions @@ -72167,6 +73516,11 @@ p5.prototype.matchAll = function(str, reg) { * 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 @@ -72179,30 +73533,31 @@ p5.prototype.matchAll = function(str, reg) { * @example *
* + * var myFont; + * function preload() { + * myFont = loadFont('assets/fonts/inconsolata.ttf'); + * } * function setup() { * background(200); - * var num = 112.53106115; + * var num1 = 321; + * var num2 = -1321; * * noStroke(); * fill(0); - * textSize(14); - * // Draw formatted numbers - * text(nf(num, 5, 2), 10, 20); - * - * text(nf(num, 4, 3), 10, 55); - * - * text(nf(num, 3, 6), 10, 85); + * textFont(myFont); + * textSize(22); * - * // Draw dividing lines + * text(nf(num1, 4, 2), 10, 30); + * text(nf(num2, 4, 2), 10, 80); + * // Draw dividing line * stroke(120); - * line(0, 30, width, 30); - * line(0, 65, width, 65); + * line(0, 50, width, 50); * } * *
* * @alt - * "0011253" top left, "0112.531" mid left, "112.531061" bottom left canvas + * "0321.00" middle top, -1321.00" middle bottom canvas */ /** * @method nf @@ -72407,10 +73762,18 @@ function addNfp(num) { /** * Utility function for formatting numbers into strings. Similar to nf() but - * puts a " " (space) 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 the digits, left, and right - * parameters should always be positive integers. + * 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 positive + * 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 @@ -72423,19 +73786,27 @@ function addNfp(num) { * @example *
* + * var myFont; + * function preload() { + * myFont = loadFont('assets/fonts/inconsolata.ttf'); + * } * function setup() { * background(200); - * var num1 = 11253106.115; - * var num2 = -11253106.115; + * var num1 = 321; + * var num2 = -1321; * * noStroke(); * fill(0); - * textSize(12); - * // Draw formatted numbers - * text(nfs(num1, 4, 2), 10, 30); + * textFont(myFont); + * textSize(22); * + * // nfs() aligns num1 (positive number) with num2 (negative number) by + * // adding a blank space in front of the num1 (positive number) + * // [left = 4] in num1 add one 0 in front, to align the digits with num2 + * // [right = 2] in num1 and num2 adds two 0's after both numbers + * // To see the differences check the example of nf() too. + * text(nfs(num1, 4, 2), 10, 30); * text(nfs(num2, 4, 2), 10, 80); - * * // Draw dividing line * stroke(120); * line(0, 50, width, 50); @@ -72444,7 +73815,7 @@ function addNfp(num) { *
* * @alt - * "11253106.11" top middle and "-11253106.11" displayed bottom middle + * "0321.00" top middle and "-1321.00" displayed bottom middle */ /** * @method nfs @@ -72592,7 +73963,7 @@ p5.prototype.trim = function(str) { module.exports = p5; -},{"../core/error_helpers":21,"../core/main":25}],64:[function(_dereq_,module,exports){ +},{"../core/error_helpers":20,"../core/main":24}],63:[function(_dereq_,module,exports){ /** * @module IO * @submodule Time & Date @@ -72761,7 +74132,7 @@ p5.prototype.year = function() { module.exports = p5; -},{"../core/main":25}],65:[function(_dereq_,module,exports){ +},{"../core/main":24}],64:[function(_dereq_,module,exports){ /** * @module Shape * @submodule 3D Primitives @@ -72771,7 +74142,6 @@ module.exports = p5; */ 'use strict'; - var p5 = _dereq_('../core/main'); _dereq_('./p5.Geometry'); var constants = _dereq_('../core/constants'); @@ -72789,7 +74159,8 @@ var constants = _dereq_('../core/constants'); * @example *
* - * //draw a plane with width 50 and height 50 + * // draw a plane + * // with width 50 and height 50 * function setup() { * createCanvas(100, 100, WEBGL); * } @@ -72873,7 +74244,8 @@ p5.prototype.plane = function(width, height, detailX, detailY) { * @example *
* - * //draw a spinning box with width, height and depth 200 + * // draw a spinning box + * // with width, height and depth of 50 * function setup() { * createCanvas(100, 100, WEBGL); * } @@ -72990,7 +74362,7 @@ p5.prototype.box = function(width, height, depth, detailX, detailY) { * @example *
* - * // draw a sphere with radius 200 + * // draw a sphere with radius 40 * function setup() { * createCanvas(100, 100, WEBGL); * } @@ -73045,10 +74417,11 @@ var _truncatedCone = function( topCap = topCap === undefined ? topRadius !== 0 : topCap; var start = bottomCap ? -2 : 0; var end = detailY + (topCap ? 2 : 0); - var vertsOnLayer = {}; //ensure constant slant for interior vertex normals var slant = Math.atan2(bottomRadius - topRadius, height); - var yy, ii, jj, nextii, nextjj; + 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; @@ -73073,29 +74446,25 @@ var _truncatedCone = function( } y -= height / 2; //shift coordiate origin to the center of object - vertsOnLayer[yy] = ringRadius === 0 ? 1 : detailX; - for (ii = 0; ii < vertsOnLayer[yy]; ++ii) { + for (ii = 0; ii < detailX; ++ii) { var u = ii / detailX; + var ur = 2 * Math.PI * u; + var sur = Math.sin(ur); + var cur = Math.cos(ur); + //VERTICES - this.vertices.push( - new p5.Vector( - Math.sin(u * 2 * Math.PI) * ringRadius, - y, - Math.cos(u * 2 * Math.PI) * ringRadius - ) - ); + this.vertices.push(new p5.Vector(sur * ringRadius, y, cur * ringRadius)); + //VERTEX NORMALS - this.vertexNormals.push( - new p5.Vector( - yy < 0 || yy > detailY - ? 0 - : Math.sin(u * 2 * Math.PI) * Math.cos(slant), - yy < 0 ? -1 : yy > detailY ? 1 : Math.sin(slant), - yy < 0 || yy > detailY - ? 0 - : Math.cos(u * 2 * Math.PI) * Math.cos(slant) - ) - ); + var vertexNormal; + if (yy < 0) { + vertexNormal = new p5.Vector(0, -1, 0); + } else if (yy > detailY && topRadius) { + vertexNormal = new p5.Vector(0, 1, 0); + } else { + vertexNormal = new p5.Vector(sur * cosSlant, sinSlant, cur * cosSlant); + } + this.vertexNormals.push(vertexNormal); //UVs this.uvs.push(u, v); } @@ -73103,52 +74472,39 @@ var _truncatedCone = function( var startIndex = 0; if (bottomCap) { - for (jj = 0; jj < vertsOnLayer[-1]; ++jj) { - nextjj = (jj + 1) % vertsOnLayer[-1]; + for (jj = 0; jj < detailX; ++jj) { + var nextjj = (jj + 1) % detailX; this.faces.push([ - startIndex, - startIndex + 1 + nextjj, - startIndex + 1 + jj + startIndex + jj, + startIndex + detailX + nextjj, + startIndex + detailX + jj ]); } - startIndex += vertsOnLayer[-2] + vertsOnLayer[-1]; + startIndex += detailX * 2; } for (yy = 0; yy < detailY; ++yy) { - for (ii = 0; ii < vertsOnLayer[yy]; ++ii) { - if (vertsOnLayer[yy + 1] === 1) { - //top layer - nextii = (ii + 1) % vertsOnLayer[yy]; - this.faces.push([ - startIndex + ii, - startIndex + nextii, - startIndex + vertsOnLayer[yy] - ]); - } else { - //other side faces - //should have vertsOnLayer[yy] === vertsOnLayer[yy + 1] - nextii = (ii + 1) % vertsOnLayer[yy]; - this.faces.push([ - startIndex + ii, - startIndex + nextii, - startIndex + vertsOnLayer[yy] + nextii - ]); - this.faces.push([ - startIndex + ii, - startIndex + vertsOnLayer[yy] + nextii, - startIndex + vertsOnLayer[yy] + ii - ]); - } + 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 += vertsOnLayer[yy]; + startIndex += detailX; } if (topCap) { - startIndex += vertsOnLayer[detailY]; - for (ii = 0; ii < vertsOnLayer[detailY + 1]; ++ii) { - nextii = (ii + 1) % vertsOnLayer[detailY + 1]; + startIndex += detailX; + for (ii = 0; ii < detailX; ++ii) { this.faces.push([ startIndex + ii, - startIndex + nextii, - startIndex + vertsOnLayer[detailY + 1] + startIndex + (ii + 1) % detailX, + startIndex + detailX ]); } } @@ -73171,7 +74527,8 @@ var _truncatedCone = function( * @example *
* - * //draw a spinning cylinder with radius 20 and height 50 + * // draw a spinning cylinder + * // with radius 20 and height 50 * function setup() { * createCanvas(100, 100, WEBGL); * } @@ -73228,7 +74585,7 @@ p5.prototype.cylinder = function( bottomCap, topCap ); - cylinderGeom.computeNormals(); + // normals are computed in call to _truncatedCone if (detailX <= 24 && detailY <= 16) { cylinderGeom._makeTriangleEdges()._edgesToVertices(); } else { @@ -73261,7 +74618,8 @@ p5.prototype.cylinder = function( * @example *
* - * //draw a spinning cone with radius 40 and height 70 + * // draw a spinning cone + * // with radius 40 and height 70 * function setup() { * createCanvas(100, 100, WEBGL); * } @@ -73298,8 +74656,6 @@ p5.prototype.cone = function(radius, height, detailX, detailY, cap) { if (!this._renderer.geometryInHash(gId)) { var coneGeom = new p5.Geometry(detailX, detailY); _truncatedCone.call(coneGeom, 1, 0, 1, detailX, detailY, cap, false); - //for cones we need to average Normals - coneGeom.computeNormals(); if (detailX <= 24 && detailY <= 16) { coneGeom._makeTriangleEdges()._edgesToVertices(); } else { @@ -73319,9 +74675,9 @@ p5.prototype.cone = function(radius, height, detailX, detailY, cap) { /** * Draw an ellipsoid with given radius * @method ellipsoid - * @param {Number} [radiusx] xradius of circle - * @param {Number} [radiusy] yradius of circle - * @param {Number} [radiusz] zradius of circle + * @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 @@ -73334,14 +74690,15 @@ p5.prototype.cone = function(radius, height, detailX, detailY, cap) { * @example *
* - * // draw an ellipsoid with radius 20, 30 and 40. + * // draw an ellipsoid + * // with radius 30, 40 and 40. * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); - * ellipsoid(20, 30, 40); + * ellipsoid(30, 40, 40); * } * *
@@ -73421,7 +74778,8 @@ p5.prototype.ellipsoid = function(radiusX, radiusY, radiusZ, detailX, detailY) { * @example *
* - * //draw a spinning torus with radius 200 and tube radius 60 + * // draw a spinning torus + * // with ring radius 30 and tube radius 15 * function setup() { * createCanvas(100, 100, WEBGL); * } @@ -73430,7 +74788,7 @@ p5.prototype.ellipsoid = function(radiusX, radiusY, radiusZ, detailX, detailY) { * background(200); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); - * torus(50, 15); + * torus(30, 15); * } * *
@@ -73539,15 +74897,13 @@ p5.prototype.torus = function(radius, tubeRadius, detailX, detailY) { *
*/ p5.RendererGL.prototype.point = function(x, y, z) { - this._usePointShader(); - this.curPointShader.bindShader(); if (typeof z === 'undefined') { z = 0; } + var _vertex = []; _vertex.push(new p5.Vector(x, y, z)); this._drawPoints(_vertex, this._pointVertexBuffer); - this.curPointShader.unbindShader(); return this; }; @@ -73734,7 +75090,7 @@ p5.RendererGL.prototype.arc = function(args) { }; p5.RendererGL.prototype.rect = function(args) { - var perPixelLighting = this.attributes.perPixelLighting; + var perPixelLighting = this._pInst._glAttributes.perPixelLighting; var x = args[0]; var y = args[1]; var width = args[2]; @@ -73788,30 +75144,39 @@ p5.RendererGL.prototype.rect = function(args) { return this; }; -p5.RendererGL.prototype.quad = function(x1, y1, x2, y2, x3, y3, x4, y4) { +// prettier-ignore +p5.RendererGL.prototype.quad = function(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) { var gId = 'quad|' + x1 + '|' + y1 + '|' + + z1 + + '|' + x2 + '|' + y2 + '|' + + z2 + + '|' + x3 + '|' + y3 + '|' + + z3 + + '|' + x4 + '|' + - y4; + y4 + + '|' + + z4; if (!this.geometryInHash(gId)) { var _quad = function() { - this.vertices.push(new p5.Vector(x1, y1, 0)); - this.vertices.push(new p5.Vector(x2, y2, 0)); - this.vertices.push(new p5.Vector(x3, y3, 0)); - this.vertices.push(new p5.Vector(x4, y4, 0)); + this.vertices.push(new p5.Vector(x1, y1, z1)); + this.vertices.push(new p5.Vector(x2, y2, z2)); + this.vertices.push(new p5.Vector(x3, y3, z3)); + this.vertices.push(new p5.Vector(x4, y4, z4)); this.uvs.push(0, 0, 1, 0, 1, 1, 0, 1); this.strokeIndices = [[0, 1], [1, 2], [2, 3], [3, 0]]; }; @@ -73845,15 +75210,14 @@ p5.RendererGL.prototype.bezier = function( z4 ) { if (arguments.length === 8) { - x4 = x3; y4 = y3; + x4 = x3; + y3 = z2; x3 = y2; - y3 = x2; - x2 = z1; 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++) { @@ -74310,9 +75674,55 @@ p5.RendererGL.prototype.curveVertex = function() { } }; +p5.RendererGL.prototype.image = function( + img, + sx, + sy, + sWidth, + sHeight, + dx, + dy, + dWidth, + dHeight +) { + this._pInst.push(); + + 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(); +}; + module.exports = p5; -},{"../core/constants":19,"../core/main":25,"./p5.Geometry":71}],66:[function(_dereq_,module,exports){ +},{"../core/constants":18,"../core/main":24,"./p5.Geometry":70}],65:[function(_dereq_,module,exports){ /** * @module Lights, Camera * @submodule Interaction @@ -74619,13 +76029,13 @@ p5.prototype.orbitControl = function(sensitivityX, sensitivityY) { * @method debugMode * @param {Number} [gridSize] * @param {Number} [gridDivisions] - * @param {Number} [xOff] - * @param {Number} [yOff] - * @param {Number} [zOff] + * @param {Number} [gridXOff] + * @param {Number} [gridYOff] + * @param {Number} [gridZOff] * @param {Number} [axesSize] - * @param {Number} [xOff] - * @param {Number} [yOff] - * @param {Number} [zOff] + * @param {Number} [axesXOff] + * @param {Number} [axesYOff] + * @param {Number} [axesZOff] */ p5.prototype.debugMode = function() { @@ -74883,7 +76293,7 @@ p5.prototype._axesIcon = function(size, xOff, yOff, zOff) { module.exports = p5; -},{"../core/constants":19,"../core/main":25}],67:[function(_dereq_,module,exports){ +},{"../core/constants":18,"../core/main":24}],66:[function(_dereq_,module,exports){ /** * @module Lights, Camera * @submodule Lights @@ -74919,7 +76329,7 @@ var p5 = _dereq_('../core/main'); * ambientLight(150); * ambientMaterial(250); * noStroke(); - * sphere(25); + * sphere(40); * } * *
@@ -74959,27 +76369,13 @@ p5.prototype.ambientLight = function(v1, v2, v3, a) { p5._validateParameters('ambientLight', arguments); var color = this.color.apply(this, arguments); - var shader = this._renderer._useLightShader(); - - //@todo this is a bit icky. array uniforms have - //to be multiples of the type 3(rgb) in this case. - //a preallocated Float32Array(24) that we copy into - //would be better - shader.setUniform('uUseLighting', true); - //in case there's no material color for the geometry - shader.setUniform('uMaterialColor', this._renderer.curFillColor); - this._renderer.ambientLightColors.push( color._array[0], color._array[1], color._array[2] ); - shader.setUniform('uAmbientColor', this._renderer.ambientLightColors); - shader.setUniform( - 'uAmbientLightCount', - this._renderer.ambientLightColors.length / 3 - ); + this._renderer._enableLighting = true; return this; }; @@ -75002,12 +76398,11 @@ p5.prototype.ambientLight = function(v1, v2, v3, a) { * function draw() { * background(0); * //move your mouse to change light direction - * var dirX = (mouseX / width - 0.5) * 2; - * var dirY = (mouseY / height - 0.5) * 2; - * directionalLight(250, 250, 250, -dirX, -dirY, 0.25); - * ambientMaterial(250); + * let dirX = (mouseX / width - 0.5) * 2; + * let dirY = (mouseY / height - 0.5) * 2; + * directionalLight(250, 250, 250, -dirX, -dirY, -1); * noStroke(); - * sphere(25); + * sphere(40); * } * *
@@ -75047,7 +76442,6 @@ p5.prototype.ambientLight = function(v1, v2, v3, a) { p5.prototype.directionalLight = function(v1, v2, v3, x, y, z) { this._assert3d('directionalLight'); p5._validateParameters('directionalLight', arguments); - var shader = this._renderer._useLightShader(); //@TODO: check parameters number var color; @@ -75068,29 +76462,18 @@ p5.prototype.directionalLight = function(v1, v2, v3, x, y, z) { _y = v.y; _z = v.z; } - shader.setUniform('uUseLighting', true); - //in case there's no material color for the geometry - shader.setUniform('uMaterialColor', this._renderer.curFillColor); // normalize direction var l = Math.sqrt(_x * _x + _y * _y + _z * _z); this._renderer.directionalLightDirections.push(_x / l, _y / l, _z / l); - shader.setUniform( - 'uLightingDirection', - this._renderer.directionalLightDirections - ); this._renderer.directionalLightColors.push( color._array[0], color._array[1], color._array[2] ); - shader.setUniform('uDirectionalColor', this._renderer.directionalLightColors); - shader.setUniform( - 'uDirectionalLightCount', - this._renderer.directionalLightColors.length / 3 - ); + this._renderer._enableLighting = true; return this; }; @@ -75115,8 +76498,8 @@ p5.prototype.directionalLight = function(v1, v2, v3, x, y, z) { * function draw() { * background(0); * //move your mouse to change light position - * var locX = mouseX - width / 2; - * var locY = mouseY - height / 2; + * 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 @@ -75125,9 +76508,8 @@ p5.prototype.directionalLight = function(v1, v2, v3, x, y, z) { * // | | * // -width/2,height/2--------width/2,height/2 * pointLight(250, 250, 250, locX, locY, 50); - * ambientMaterial(250); * noStroke(); - * sphere(25); + * sphere(40); * } *
*
@@ -75165,6 +76547,7 @@ p5.prototype.directionalLight = function(v1, v2, v3, x, y, z) { p5.prototype.pointLight = function(v1, v2, v3, x, y, z) { this._assert3d('pointLight'); p5._validateParameters('pointLight', arguments); + //@TODO: check parameters number var color; if (v1 instanceof p5.Color) { @@ -75185,32 +76568,52 @@ p5.prototype.pointLight = function(v1, v2, v3, x, y, z) { _z = v.z; } - var shader = this._renderer._useLightShader(); - shader.setUniform('uUseLighting', true); - //in case there's no material color for the geometry - shader.setUniform('uMaterialColor', this._renderer.curFillColor); - this._renderer.pointLightPositions.push(_x, _y, _z); - shader.setUniform('uPointLightLocation', this._renderer.pointLightPositions); - this._renderer.pointLightColors.push( color._array[0], color._array[1], color._array[2] ); - shader.setUniform('uPointLightColor', this._renderer.pointLightColors); - shader.setUniform( - 'uPointLightCount', - this._renderer.pointLightColors.length / 3 - ); + this._renderer._enableLighting = true; return this; }; +/** + * Sets the default ambient and directional light. The defaults are ambientLight(128, 128, 128) and directionalLight(128, 128, 128, 0, 0, -1). Lights need to be included in the draw() to remain persistent in a looping program. Placing them in the setup() of a looping program will cause them to only have an effect the first time through the loop. + * @method lights + * @chainable + * @example + *
+ * + * function setup() { + * createCanvas(100, 100, WEBGL); + * } + * function draw() { + * background(0); + * lights(); + * rotateX(millis() / 1000); + * rotateY(millis() / 1000); + * rotateZ(millis() / 1000); + * box(); + * } + * + *
+ * + * @alt + * the light is partially ambient and partially directional + */ +p5.prototype.lights = function() { + this._assert3d('lights'); + this.ambientLight(128, 128, 128); + this.directionalLight(128, 128, 128, 0, 0, -1); + return this; +}; + module.exports = p5; -},{"../core/main":25}],68:[function(_dereq_,module,exports){ +},{"../core/main":24}],67:[function(_dereq_,module,exports){ /** * @module Shape * @submodule 3D Models @@ -75249,7 +76652,7 @@ _dereq_('./p5.Geometry'); *
* * //draw a spinning octahedron - * var octahedron; + * let octahedron; * * function preload() { * octahedron = loadModel('assets/octahedron.obj'); @@ -75275,7 +76678,7 @@ _dereq_('./p5.Geometry'); *
* * //draw a spinning teapot - * var teapot; + * let teapot; * * function preload() { * // Load model with normalise parameter set to true @@ -75463,7 +76866,7 @@ function parseObj(model, lines) { *
* * //draw a spinning octahedron - * var octahedron; + * let octahedron; * * function preload() { * octahedron = loadModel('assets/octahedron.obj'); @@ -75501,7 +76904,7 @@ p5.prototype.model = function(model) { module.exports = p5; -},{"../core/main":25,"./p5.Geometry":71}],69:[function(_dereq_,module,exports){ +},{"../core/main":24,"./p5.Geometry":70}],68:[function(_dereq_,module,exports){ /** * @module Lights, Camera * @submodule Material @@ -75525,17 +76928,22 @@ _dereq_('./p5.Texture'); * if the parameters defined in the shader match the names. * * @method loadShader - * @param {String} [vertFilename] path to file containing vertex shader + * @param {String} vertFilename path to file containing vertex shader * source code - * @param {String} [fragFilename] path to file containing fragment shader + * @param {String} fragFilename path to file containing fragment shader * source code + * @param {function} [callback] callback to be executed after loadShader + * completes. On success, the Shader object is passed as the first argument. + * @param {function} [errorCallback] callback to be executed when an error + * occurs inside loadShader. On error, the error is passed as the first + * argument. * @return {p5.Shader} a shader object created from the provided * vertex and fragment shader files. * * @example *
* - * var mandel; + * let mandel; * function preload() { * // load the shader definitions from files * mandel = loadShader('assets/shader.vert', 'assets/shader.frag'); @@ -75558,28 +76966,53 @@ _dereq_('./p5.Texture'); * @alt * zooming Mandelbrot set. a colorful, infinitely detailed fractal. */ -p5.prototype.loadShader = function(vertFilename, fragFilename) { +p5.prototype.loadShader = function( + vertFilename, + fragFilename, + callback, + errorCallback +) { p5._validateParameters('loadShader', arguments); + if (!errorCallback) { + errorCallback = console.error; + } + var loadedShader = new p5.Shader(); var self = this; var loadedFrag = false; var loadedVert = false; - this.loadStrings(fragFilename, function(result) { - loadedShader._fragSrc = result.join('\n'); - loadedFrag = true; - if (loadedVert) { - self._decrementPreload(); - } - }); - this.loadStrings(vertFilename, function(result) { - loadedShader._vertSrc = result.join('\n'); - loadedVert = true; - if (loadedFrag) { - self._decrementPreload(); + var onLoad = function() { + 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; }; @@ -75595,16 +77028,16 @@ p5.prototype.loadShader = function(vertFilename, fragFilename) { *
* * // the 'varying's are shared between both vertex & fragment shaders - * var varying = 'precision highp float; varying vec2 vPos;'; + * let varying = 'precision highp float; varying vec2 vPos;'; * * // the vertex shader is called for each vertex - * var vs = + * let vs = * varying + * 'attribute vec3 aPosition;' + * 'void main() { vPos = (gl_Position = vec4(aPosition,1.0)).xy; }'; * * // the fragment shader is called for each pixel - * var fs = + * let fs = * varying + * 'uniform vec2 p;' + * 'uniform float r;' + @@ -75622,7 +77055,7 @@ p5.prototype.loadShader = function(vertFilename, fragFilename) { * ' 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);' + * '}'; * - * var mandel; + * let mandel; * function setup() { * createCanvas(100, 100, WEBGL); * @@ -75666,14 +77099,33 @@ p5.prototype.createShader = function(vertSrc, fragSrc) { p5.prototype.shader = function(s) { this._assert3d('shader'); p5._validateParameters('shader', arguments); + if (s._renderer === undefined) { s._renderer = this._renderer; } + if (s.isStrokeShader()) { - this._renderer.setStrokeShader(s); + this._renderer.userStrokeShader = s; } else { - this._renderer.setFillShader(s); + this._renderer.userFillShader = s; + this._renderer._useNormalMaterial = false; } + + s.init(); + + return this; +}; + +/** + * This function restores the default shaders in WEBGL mode. Code that runs + * after resetShader() will not be affected by previously defined + * shaders. Should be run after shader(). + * + * @method resetShader + * @chainable + */ +p5.prototype.resetShader = function() { + this._renderer.userFillShader = this._renderer.userStrokeShader = null; return this; }; @@ -75693,7 +77145,7 @@ p5.prototype.shader = function(s) { * function draw() { * background(200); * normalMaterial(); - * sphere(50); + * sphere(40); * } * *
@@ -75706,8 +77158,10 @@ p5.prototype.normalMaterial = function() { this._assert3d('normalMaterial'); p5._validateParameters('normalMaterial', arguments); this._renderer.drawMode = constants.FILL; - this._renderer.setFillShader(this._renderer._getNormalShader()); + this._renderer._useSpecularMaterial = false; + this._renderer._useNormalMaterial = true; this._renderer.curFillColor = [1, 1, 1, 1]; + this._renderer._setProperty('_doFill', true); this.noStroke(); return this; }; @@ -75722,7 +77176,7 @@ p5.prototype.normalMaterial = function() { * @example *
* - * var img; + * let img; * function preload() { * img = loadImage('assets/laDefense.jpg'); * } @@ -75745,11 +77199,12 @@ p5.prototype.normalMaterial = function() { * *
* - * var pg; + * let pg; + * * function setup() { * createCanvas(100, 100, WEBGL); * pg = createGraphics(200, 200); - * pg.textSize(100); + * pg.textSize(75); * } * * function draw() { @@ -75758,18 +77213,19 @@ p5.prototype.normalMaterial = function() { * pg.text('hello!', 0, 100); * //pass image as texture * texture(pg); - * plane(200); + * rotateX(0.5); + * noStroke(); + * plane(50); * } * *
* *
* - * var vid; + * let vid; * function preload() { * vid = createVideo('assets/fingers.mov'); * vid.hide(); - * vid.loop(); * } * function setup() { * createCanvas(100, 100, WEBGL); @@ -75779,7 +77235,11 @@ p5.prototype.normalMaterial = function() { * background(0); * //pass video frame as texture * texture(vid); - * plane(200); + * rect(-40, -40, 80, 80); + * } + * + * function mousePressed() { + * vid.loop(); * } * *
@@ -75793,15 +77253,170 @@ p5.prototype.normalMaterial = function() { p5.prototype.texture = function(tex) { this._assert3d('texture'); p5._validateParameters('texture', arguments); + this._renderer.drawMode = constants.TEXTURE; - var shader = this._renderer._useLightShader(); - shader.setUniform('uSpecular', false); - shader.setUniform('isTexture', true); - shader.setUniform('uSampler', tex); - this.noStroke(); + this._renderer._useSpecularMaterial = false; + this._renderer._useNormalMaterial = false; + this._renderer._tex = tex; + this._renderer._setProperty('_doFill', true); + return this; }; +/** + * Sets the coordinate space for texture mapping. The default mode is IMAGE + * which refers to the actual coordinates of the image. + * NORMAL refers to a normalized space of values ranging from 0 to 1. + * This function only works in WEBGL mode. + * + * With IMAGE, if an image is 100 x 200 pixels, mapping the image onto the entire + * size of a quad would require the points (0,0) (100, 0) (100,200) (0,200). + * The same mapping in NORMAL is (0,0) (1,0) (1,1) (0,1). + * @method textureMode + * @param {Constant} mode either IMAGE or NORMAL + * @example + *
+ * + * let img; + * + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * } + * + * function draw() { + * texture(img); + * textureMode(NORMAL); + * beginShape(); + * vertex(-50, -50, 0, 0); + * vertex(50, -50, 1, 0); + * vertex(50, 50, 1, 1); + * vertex(-50, 50, 0, 1); + * endShape(); + * } + * + *
+ * + * @alt + * the underside of a white umbrella and gridded ceiling above + * + *
+ * + * let img; + * + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * } + * + * function draw() { + * texture(img); + * textureMode(NORMAL); + * beginShape(); + * vertex(-50, -50, 0, 0); + * vertex(50, -50, img.width, 0); + * vertex(50, 50, img.width, img.height); + * vertex(-50, 50, 0, img.height); + * endShape(); + * } + * + *
+ * + * @alt + * the underside of a white umbrella and gridded ceiling above + * + */ +p5.prototype.textureMode = function(mode) { + if (mode !== constants.IMAGE && mode !== constants.NORMAL) { + console.warn( + 'You tried to set ' + mode + ' textureMode only supports IMAGE & NORMAL ' + ); + } else { + this._renderer.textureMode = mode; + } +}; + +/** + * Sets the global texture wrapping mode. This controls how textures behave + * when their uv's go outside of the 0 - 1 range. There are three options: + * CLAMP, REPEAT, and MIRROR. + * + * CLAMP causes the pixels at the edge of the texture to extend to the bounds + * REPEAT causes the texture to tile repeatedly until reaching the bounds + * MIRROR works similarly to REPEAT but it flips the texture with every new tile + * + * REPEAT & MIRROR are only available if the texture + * is a power of two size (128, 256, 512, 1024, etc.). + * + * This method will affect all textures in your sketch until a subsequent + * textureWrap call is made. + * + * If only one argument is provided, it will be applied to both the + * horizontal and vertical axes. + * @method textureWrap + * @param {Constant} wrapX either CLAMP, REPEAT, or MIRROR + * @param {Constant} [wrapY] either CLAMP, REPEAT, or MIRROR + * @example + *
+ * + * let img; + * function preload() { + * img = loadImage('assets/rockies128.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * textureWrap(MIRROR); + * } + * + * function draw() { + * background(0); + * + * let dX = mouseX; + * let dY = mouseY; + * + * let u = lerp(1.0, 2.0, dX); + * let v = lerp(1.0, 2.0, dY); + * + * scale(width / 2); + * + * texture(img); + * + * beginShape(TRIANGLES); + * vertex(-1, -1, 0, 0, 0); + * vertex(1, -1, 0, u, 0); + * vertex(1, 1, 0, u, v); + * + * vertex(1, 1, 0, u, v); + * vertex(-1, 1, 0, 0, v); + * vertex(-1, -1, 0, 0, 0); + * endShape(); + * } + * + *
+ * + * @alt + * an image of the rocky mountains repeated in mirrored tiles + * + */ +p5.prototype.textureWrap = function(wrapX, wrapY) { + wrapY = wrapY || wrapX; + + this._renderer.textureWrapX = wrapX; + this._renderer.textureWrapY = wrapY; + + var textures = this._renderer.textures; + for (var i = 0; i < textures.length; i++) { + textures[i].setWrapMode(wrapX, wrapY); + } +}; + /** * Ambient material for geometry with a given color. You can view all * possible materials in this @@ -75821,10 +77436,10 @@ p5.prototype.texture = function(tex) { * } * function draw() { * background(0); - * ambientLight(100); - * pointLight(250, 250, 250, 100, 100, 0); - * ambientMaterial(250); - * sphere(50); + * noStroke(); + * ambientLight(200); + * ambientMaterial(70, 130, 230); + * sphere(40); * } *
*
@@ -75841,13 +77456,14 @@ p5.prototype.texture = function(tex) { p5.prototype.ambientMaterial = function(v1, v2, v3, a) { this._assert3d('ambientMaterial'); p5._validateParameters('ambientMaterial', arguments); + var color = p5.prototype.color.apply(this, arguments); this._renderer.curFillColor = color._array; + this._renderer._useSpecularMaterial = false; + this._renderer._useNormalMaterial = false; + this._renderer._enableLighting = true; + this._renderer._tex = null; - var shader = this._renderer._useLightShader(); - shader.setUniform('uMaterialColor', this._renderer.curFillColor); - shader.setUniform('uSpecular', false); - shader.setUniform('isTexture', false); return this; }; @@ -75870,10 +77486,11 @@ p5.prototype.ambientMaterial = function(v1, v2, v3, a) { * } * function draw() { * background(0); - * ambientLight(100); - * pointLight(250, 250, 250, 100, 100, 0); + * noStroke(); + * ambientLight(50); + * pointLight(250, 250, 250, 100, 100, 30); * specularMaterial(250); - * sphere(50); + * sphere(40); * } *
*
@@ -75890,13 +77507,59 @@ p5.prototype.ambientMaterial = function(v1, v2, v3, a) { p5.prototype.specularMaterial = function(v1, v2, v3, a) { this._assert3d('specularMaterial'); p5._validateParameters('specularMaterial', arguments); + var color = p5.prototype.color.apply(this, arguments); this._renderer.curFillColor = color._array; + this._renderer._useSpecularMaterial = true; + this._renderer._useNormalMaterial = false; + this._renderer._enableLighting = true; + this._renderer._tex = null; - var shader = this._renderer._useLightShader(); - shader.setUniform('uMaterialColor', this._renderer.curFillColor); - shader.setUniform('uSpecular', true); - shader.setUniform('isTexture', false); + return this; +}; + +/** + * Sets the amount of gloss in the surface of shapes. + * Used in combination with specularMaterial() in setting + * the material properties of shapes. The default and minimum value is 1. + * @method shininess + * @param {Number} shine Degree of Shininess. + * Defaults to 1. + * @chainable + * @example + *
+ * + * function setup() { + * createCanvas(100, 100, WEBGL); + * } + * function draw() { + * background(0); + * noStroke(); + * let locX = mouseX - width / 2; + * let locY = mouseY - height / 2; + * ambientLight(60, 60, 60); + * pointLight(255, 255, 255, locX, locY, 50); + * specularMaterial(250); + * translate(-25, 0, 0); + * shininess(1); + * sphere(20); + * translate(50, 0, 0); + * shininess(20); + * sphere(20); + * } + * + *
+ * @alt + * Shininess on Camera changes position with mouse + */ +p5.prototype.shininess = function(shine) { + this._assert3d('shininess'); + p5._validateParameters('shininess', arguments); + + if (shine < 1) { + shine = 1; + } + this._renderer._useShininess = shine; return this; }; @@ -75914,8 +77577,7 @@ p5.RendererGL.prototype._applyColorBlend = function(colors) { if (isTexture || colors[colors.length - 1] < 1.0) { gl.depthMask(isTexture); gl.enable(gl.BLEND); - gl.blendEquation(gl.FUNC_ADD); - gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); + this._applyBlendMode(); } else { gl.depthMask(true); gl.disable(gl.BLEND); @@ -75923,9 +77585,75 @@ p5.RendererGL.prototype._applyColorBlend = function(colors) { return colors; }; +/** + * @private sets blending in gl context to curBlendMode + * @param {Number[]} color [description] + * @return {Number[]]} Normalized numbers array + */ +p5.RendererGL.prototype._applyBlendMode = function() { + var gl = this.GL; + switch (this.curBlendMode) { + case constants.BLEND: + case constants.ADD: + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); + break; + case constants.MULTIPLY: + gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); + gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ONE, gl.ONE); + break; + case constants.SCREEN: + gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); + gl.blendFuncSeparate(gl.ONE_MINUS_DST_COLOR, gl.ONE, gl.ONE, gl.ONE); + break; + case constants.EXCLUSION: + gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); + gl.blendFuncSeparate( + gl.ONE_MINUS_DST_COLOR, + gl.ONE_MINUS_SRC_COLOR, + gl.ONE, + gl.ONE + ); + break; + case constants.REPLACE: + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ZERO); + break; + case constants.SUBTRACT: + gl.blendEquationSeparate(gl.FUNC_REVERSE_SUBTRACT, gl.FUNC_ADD); + gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE); + break; + case constants.DARKEST: + if (this.blendExt) { + gl.blendEquationSeparate(this.blendExt.MIN_EXT, gl.FUNC_ADD); + gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE); + } else { + console.warn( + 'blendMode(DARKEST) does not work in your browser in WEBGL mode.' + ); + } + break; + case constants.LIGHTEST: + if (this.blendExt) { + gl.blendEquationSeparate(this.blendExt.MAX_EXT, gl.FUNC_ADD); + gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE); + } else { + console.warn( + 'blendMode(LIGHTEST) does not work in your browser in WEBGL mode.' + ); + } + break; + default: + console.error( + 'Oops! Somehow RendererGL set curBlendMode to an unsupported mode.' + ); + break; + } +}; + module.exports = p5; -},{"../core/constants":19,"../core/main":25,"./p5.Texture":77}],70:[function(_dereq_,module,exports){ +},{"../core/constants":18,"../core/main":24,"./p5.Texture":76}],69:[function(_dereq_,module,exports){ /** * @module Lights, Camera * @submodule Camera @@ -76165,8 +77893,8 @@ p5.prototype.createCamera = function() { * @example *
* - * var cam; - * var delta = 0.01; + * let cam; + * let delta = 0.01; * * function setup() { * createCanvas(100, 100, WEBGL); @@ -76265,7 +77993,6 @@ p5.Camera.prototype.perspective = function(fovy, aspect, near, far) { ); } - this.cameraFOV = this._renderer._pInst._toRadians(fovy); this.aspectRatio = aspect; this.cameraNear = near; this.cameraFar = far; @@ -76385,7 +78112,7 @@ p5.Camera.prototype._rotateView = function(a, x, y, z) { centerZ -= this.eyeZ; var rotation = p5.Matrix.identity(this._renderer._pInst); - rotation.rotate(a, x, y, z); + rotation.rotate(this._renderer._pInst._toRadians(a), x, y, z); // prettier-ignore var rotatedCenter = [ @@ -76421,8 +78148,8 @@ p5.Camera.prototype._rotateView = function(a, x, y, z) { * @example *
* - * var cam; - * var delta = 0.01; + * let cam; + * let delta = 0.01; * * function setup() { * createCanvas(100, 100, WEBGL); @@ -76480,8 +78207,8 @@ p5.Camera.prototype.pan = function(amount) { * @example *
* - * var cam; - * var delta = 0.01; + * let cam; + * let delta = 0.01; * * function setup() { * createCanvas(100, 100, WEBGL); @@ -76539,7 +78266,7 @@ p5.Camera.prototype.tilt = function(amount) { * @example *
* - * var cam; + * let cam; * * function setup() { * createCanvas(100, 100, WEBGL); @@ -76687,8 +78414,8 @@ p5.Camera.prototype.camera = function( *
* * // see the camera move along its own axes while maintaining its orientation - * var cam; - * var delta = 0.5; + * let cam; + * let delta = 0.5; * * function setup() { * createCanvas(100, 100, WEBGL); @@ -76761,7 +78488,7 @@ p5.Camera.prototype.move = function(x, y, z) { * * // press '1' '2' or '3' keys to set camera position * - * var cam; + * let cam; * * function setup() { * createCanvas(100, 100, WEBGL); @@ -77023,8 +78750,8 @@ p5.Camera.prototype._isActive = function() { * @example *
* - * var cam1, cam2; - * var currentCamera; + * let cam1, cam2; + * let currentCamera; * * function setup() { * createCanvas(100, 100, WEBGL); @@ -77111,7 +78838,7 @@ p5.prototype.setCamera = function(cam) { module.exports = p5.Camera; -},{"../core/main":25}],71:[function(_dereq_,module,exports){ +},{"../core/main":24}],70:[function(_dereq_,module,exports){ //some of the functions are adjusted from Three.js(http://threejs.org) 'use strict'; @@ -77391,7 +79118,7 @@ p5.Geometry.prototype.normalize = function() { module.exports = p5.Geometry; -},{"../core/main":25}],72:[function(_dereq_,module,exports){ +},{"../core/main":24}],71:[function(_dereq_,module,exports){ /** * @requires constants * @todo see methods below needing further implementation. @@ -77817,6 +79544,8 @@ p5.Matrix.prototype.mult = function(multMatrix) { _src = multMatrix.mat4; } else if (isMatrixArray(multMatrix)) { _src = multMatrix; + } else if (arguments.length === 16) { + _src = arguments; } else { return; // nothing to do. } @@ -77861,6 +79590,63 @@ p5.Matrix.prototype.mult = function(multMatrix) { return this; }; +p5.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 p5.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 @@ -77905,8 +79691,6 @@ p5.Matrix.prototype.scale = function(x, y, z) { * inspired by Toji's gl-matrix lib, mat4 rotation */ p5.Matrix.prototype.rotate = function(a, x, y, z) { - var _a = this.p5 ? this.p5._toRadians(a) : a; - if (x instanceof p5.Vector) { // x is a vector, extract the components from it. y = x.y; @@ -77938,8 +79722,8 @@ p5.Matrix.prototype.rotate = function(a, x, y, z) { var a23 = this.mat4[11]; //sin,cos, and tan of respective angle - var sA = Math.sin(_a); - var cA = Math.cos(_a); + 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; @@ -78112,7 +79896,7 @@ p5.Matrix.prototype.ortho = function(left, right, bottom, top, near, far) { module.exports = p5.Matrix; -},{"../core/main":25}],73:[function(_dereq_,module,exports){ +},{"../core/main":24}],72:[function(_dereq_,module,exports){ /** * Welcome to RendererGL Immediate Mode. * Immediate mode is used for drawing custom shapes @@ -78217,6 +80001,21 @@ p5.RendererGL.prototype.vertex = function(x, y) { vertexColor[3] ); + if (this.textureMode === constants.IMAGE) { + if (this._tex !== null) { + if (this._tex.width > 0 && this._tex.height > 0) { + u /= this._tex.width; + v /= this._tex.height; + } + } else if (this._tex === null && arguments.length >= 4) { + // Only throw this warning if custom uv's have been provided + console.warn( + 'You must first call texture() before using' + + ' vertex() with image based u and v coordinates' + ); + } + } + this.immediateMode.uvCoords.push(u, v); this.immediateMode._bezierVertex[0] = x; @@ -78243,19 +80042,33 @@ p5.RendererGL.prototype.endShape = function( shapeKind ) { if (this.immediateMode.shapeMode === constants.POINTS) { - this._usePointShader(); - this.curPointShader.bindShader(); this._drawPoints( this.immediateMode.vertices, this.immediateMode.pointVertexBuffer ); - this.curPointShader.unbindShader(); } else if (this.immediateMode.vertices.length > 1) { - this._useImmediateModeShader(); - if (this._doStroke && this.drawMode !== constants.TEXTURE) { - for (var i = 0; i < this.immediateMode.vertices.length - 1; i++) { + if (this.immediateMode.shapeMode === constants.TRIANGLE_STRIP) { + var i; + for (i = 0; i < this.immediateMode.vertices.length - 2; i++) { + this.immediateMode.edges.push([i, i + 1]); + this.immediateMode.edges.push([i, i + 2]); + } this.immediateMode.edges.push([i, i + 1]); + } else if (this.immediateMode.shapeMode === constants.TRIANGLES) { + for (i = 0; i < this.immediateMode.vertices.length - 2; i = i + 3) { + this.immediateMode.edges.push([i, i + 1]); + this.immediateMode.edges.push([i + 1, i + 2]); + this.immediateMode.edges.push([i + 2, i]); + } + } else if (this.immediateMode.shapeMode === constants.LINES) { + for (i = 0; i < this.immediateMode.vertices.length - 1; i = i + 2) { + this.immediateMode.edges.push([i, i + 1]); + } + } else { + for (i = 0; i < this.immediateMode.vertices.length - 1; i++) { + this.immediateMode.edges.push([i, i + 1]); + } } if (mode === constants.CLOSE) { this.immediateMode.edges.push([ @@ -78268,7 +80081,7 @@ p5.RendererGL.prototype.endShape = function( this._drawStrokeImmediateMode(); } - if (this._doFill) { + if (this._doFill && this.immediateMode.shapeMode !== constants.LINES) { if (this.isBezier || this.isQuadratic || this.isCurve) { var contours = [ new Float32Array(this._vToNArray(this.immediateMode.vertices)) @@ -78323,10 +80136,11 @@ p5.RendererGL.prototype._drawFillImmediateMode = function( shapeKind ) { var gl = this.GL; - this.curFillShader.bindShader(); + var shader = this._getImmediateFillShader(); + this._setFillUniforms(shader); // initialize the fill shader's 'aPosition' buffer - if (this.curFillShader.attributes.aPosition) { + if (shader.attributes.aPosition) { //vertex position Attribute this._bindBuffer( this.immediateMode.vertexBuffer, @@ -78336,8 +80150,8 @@ p5.RendererGL.prototype._drawFillImmediateMode = function( gl.DYNAMIC_DRAW ); - this.curFillShader.enableAttrib( - this.curFillShader.attributes.aPosition.location, + shader.enableAttrib( + shader.attributes.aPosition.location, 3, gl.FLOAT, false, @@ -78347,10 +80161,7 @@ p5.RendererGL.prototype._drawFillImmediateMode = function( } // initialize the fill shader's 'aVertexColor' buffer - if ( - this.drawMode === constants.FILL && - this.curFillShader.attributes.aVertexColor - ) { + if (this.drawMode === constants.FILL && shader.attributes.aVertexColor) { this._bindBuffer( this.immediateMode.colorBuffer, gl.ARRAY_BUFFER, @@ -78359,8 +80170,8 @@ p5.RendererGL.prototype._drawFillImmediateMode = function( gl.DYNAMIC_DRAW ); - this.curFillShader.enableAttrib( - this.curFillShader.attributes.aVertexColor.location, + shader.enableAttrib( + shader.attributes.aVertexColor.location, 4, gl.FLOAT, false, @@ -78370,10 +80181,7 @@ p5.RendererGL.prototype._drawFillImmediateMode = function( } // initialize the fill shader's 'aTexCoord' buffer - if ( - this.drawMode === constants.TEXTURE && - this.curFillShader.attributes.aTexCoord - ) { + if (this.drawMode === constants.TEXTURE && shader.attributes.aTexCoord) { //texture coordinate Attribute this._bindBuffer( this.immediateMode.uvBuffer, @@ -78383,8 +80191,8 @@ p5.RendererGL.prototype._drawFillImmediateMode = function( gl.DYNAMIC_DRAW ); - this.curFillShader.enableAttrib( - this.curFillShader.attributes.aTexCoord.location, + shader.enableAttrib( + shader.attributes.aTexCoord.location, 2, gl.FLOAT, false, @@ -78400,7 +80208,10 @@ p5.RendererGL.prototype._drawFillImmediateMode = function( case constants.LINES: case constants.TRIANGLES: this.immediateMode.shapeMode = - this.isBezier || this.isQuadratic || this.isCurve + this.isBezier || + this.isQuadratic || + this.isCurve || + this.immediateMode.shapeMode === constants.TRIANGLES ? constants.TRIANGLES : constants.TRIANGLE_FAN; break; @@ -78434,18 +80245,19 @@ p5.RendererGL.prototype._drawFillImmediateMode = function( this.immediateMode.vertices.length ); - this._pInst._pixelsDirty = true; + this._pixelsState._pixelsDirty = true; } // todo / optimizations? leave bound until another shader is set? - this.curFillShader.unbindShader(); + shader.unbindShader(); }; p5.RendererGL.prototype._drawStrokeImmediateMode = function() { var gl = this.GL; - this.curStrokeShader.bindShader(); + var shader = this._getImmediateStrokeShader(); + this._setStrokeUniforms(shader); // initialize the stroke shader's 'aPosition' buffer - if (this.curStrokeShader.attributes.aPosition) { + if (shader.attributes.aPosition) { this._bindBuffer( this.immediateMode.lineVertexBuffer, gl.ARRAY_BUFFER, @@ -78454,8 +80266,8 @@ p5.RendererGL.prototype._drawStrokeImmediateMode = function() { gl.STATIC_DRAW ); - this.curStrokeShader.enableAttrib( - this.curStrokeShader.attributes.aPosition.location, + shader.enableAttrib( + shader.attributes.aPosition.location, 3, gl.FLOAT, false, @@ -78465,7 +80277,7 @@ p5.RendererGL.prototype._drawStrokeImmediateMode = function() { } // initialize the stroke shader's 'aDirection' buffer - if (this.curStrokeShader.attributes.aDirection) { + if (shader.attributes.aDirection) { this._bindBuffer( this.immediateMode.lineNormalBuffer, gl.ARRAY_BUFFER, @@ -78473,8 +80285,8 @@ p5.RendererGL.prototype._drawStrokeImmediateMode = function() { Float32Array, gl.STATIC_DRAW ); - this.curStrokeShader.enableAttrib( - this.curStrokeShader.attributes.aDirection.location, + shader.enableAttrib( + shader.attributes.aDirection.location, 4, gl.FLOAT, false, @@ -78486,15 +80298,14 @@ p5.RendererGL.prototype._drawStrokeImmediateMode = function() { this._applyColorBlend(this.curStrokeColor); gl.drawArrays(gl.TRIANGLES, 0, this.immediateMode.lineVertices.length); - // todo / optimizations? leave bound until another shader is set? - this.curStrokeShader.unbindShader(); + this._pixelsState._pixelsDirty = true; - this._pInst._pixelsDirty = true; + shader.unbindShader(); }; module.exports = p5.RendererGL; -},{"../core/constants":19,"../core/main":25}],74:[function(_dereq_,module,exports){ +},{"../core/constants":18,"../core/main":24}],73:[function(_dereq_,module,exports){ //Retained Mode. The default mode for rendering 3D primitives //in WEBGL. 'use strict'; @@ -78557,10 +80368,11 @@ p5.RendererGL.prototype.createBuffers = function(gId, obj) { geometry.numberOfItems = obj.faces.length * 3; geometry.lineVertexCount = obj.lineVertices.length; - this._useColorShader(); + var strokeShader = this._getRetainedStrokeShader(); + strokeShader.bindShader(); // initialize the stroke shader's 'aPosition' buffer, if used - if (this.curStrokeShader.attributes.aPosition) { + if (strokeShader.attributes.aPosition) { geometry.lineVertexBuffer = gl.createBuffer(); this._bindBuffer( @@ -78571,8 +80383,8 @@ p5.RendererGL.prototype.createBuffers = function(gId, obj) { gl.STATIC_DRAW ); - this.curStrokeShader.enableAttrib( - this.curStrokeShader.attributes.aPosition.location, + strokeShader.enableAttrib( + strokeShader.attributes.aPosition.location, 3, gl.FLOAT, false, @@ -78582,7 +80394,7 @@ p5.RendererGL.prototype.createBuffers = function(gId, obj) { } // initialize the stroke shader's 'aDirection' buffer, if used - if (this.curStrokeShader.attributes.aDirection) { + if (strokeShader.attributes.aDirection) { geometry.lineNormalBuffer = gl.createBuffer(); this._bindBuffer( @@ -78593,8 +80405,8 @@ p5.RendererGL.prototype.createBuffers = function(gId, obj) { gl.STATIC_DRAW ); - this.curStrokeShader.enableAttrib( - this.curStrokeShader.attributes.aDirection.location, + strokeShader.enableAttrib( + strokeShader.attributes.aDirection.location, 4, gl.FLOAT, false, @@ -78602,9 +80414,13 @@ p5.RendererGL.prototype.createBuffers = function(gId, obj) { 0 ); } + strokeShader.unbindShader(); + + var fillShader = this._getRetainedFillShader(); + fillShader.bindShader(); // initialize the fill shader's 'aPosition' buffer, if used - if (this.curFillShader.attributes.aPosition) { + if (fillShader.attributes.aPosition) { geometry.vertexBuffer = gl.createBuffer(); // allocate space for vertex positions @@ -78616,8 +80432,8 @@ p5.RendererGL.prototype.createBuffers = function(gId, obj) { gl.STATIC_DRAW ); - this.curFillShader.enableAttrib( - this.curFillShader.attributes.aPosition.location, + fillShader.enableAttrib( + fillShader.attributes.aPosition.location, 3, gl.FLOAT, false, @@ -78637,7 +80453,7 @@ p5.RendererGL.prototype.createBuffers = function(gId, obj) { ); // initialize the fill shader's 'aNormal' buffer, if used - if (this.curFillShader.attributes.aNormal) { + if (fillShader.attributes.aNormal) { geometry.normalBuffer = gl.createBuffer(); // allocate space for normals @@ -78649,8 +80465,8 @@ p5.RendererGL.prototype.createBuffers = function(gId, obj) { gl.STATIC_DRAW ); - this.curFillShader.enableAttrib( - this.curFillShader.attributes.aNormal.location, + fillShader.enableAttrib( + fillShader.attributes.aNormal.location, 3, gl.FLOAT, false, @@ -78660,7 +80476,7 @@ p5.RendererGL.prototype.createBuffers = function(gId, obj) { } // initialize the fill shader's 'aTexCoord' buffer, if used - if (this.curFillShader.attributes.aTexCoord) { + if (fillShader.attributes.aTexCoord) { geometry.uvBuffer = gl.createBuffer(); // tex coords @@ -78672,8 +80488,8 @@ p5.RendererGL.prototype.createBuffers = function(gId, obj) { gl.STATIC_DRAW ); - this.curFillShader.enableAttrib( - this.curFillShader.attributes.aTexCoord.location, + fillShader.enableAttrib( + fillShader.attributes.aTexCoord.location, 2, gl.FLOAT, false, @@ -78681,7 +80497,7 @@ p5.RendererGL.prototype.createBuffers = function(gId, obj) { 0 ); } - //} + fillShader.unbindShader(); return geometry; }; @@ -78693,17 +80509,17 @@ p5.RendererGL.prototype.createBuffers = function(gId, obj) { */ p5.RendererGL.prototype.drawBuffers = function(gId) { var gl = this.GL; - this._useColorShader(); var geometry = this.gHash[gId]; if (this._doStroke && geometry.lineVertexCount > 0) { - this.curStrokeShader.bindShader(); + var strokeShader = this._getRetainedStrokeShader(); + this._setStrokeUniforms(strokeShader); // bind the stroke shader's 'aPosition' buffer if (geometry.lineVertexBuffer) { this._bindBuffer(geometry.lineVertexBuffer, gl.ARRAY_BUFFER); - this.curStrokeShader.enableAttrib( - this.curStrokeShader.attributes.aPosition.location, + strokeShader.enableAttrib( + strokeShader.attributes.aPosition.location, 3, gl.FLOAT, false, @@ -78715,8 +80531,8 @@ p5.RendererGL.prototype.drawBuffers = function(gId) { // bind the stroke shader's 'aDirection' buffer if (geometry.lineNormalBuffer) { this._bindBuffer(geometry.lineNormalBuffer, gl.ARRAY_BUFFER); - this.curStrokeShader.enableAttrib( - this.curStrokeShader.attributes.aDirection.location, + strokeShader.enableAttrib( + strokeShader.attributes.aDirection.location, 4, gl.FLOAT, false, @@ -78727,18 +80543,19 @@ p5.RendererGL.prototype.drawBuffers = function(gId) { this._applyColorBlend(this.curStrokeColor); this._drawArrays(gl.TRIANGLES, gId); - this.curStrokeShader.unbindShader(); + strokeShader.unbindShader(); } if (this._doFill !== false) { - this.curFillShader.bindShader(); + var fillShader = this._getRetainedFillShader(); + this._setFillUniforms(fillShader); // bind the fill shader's 'aPosition' buffer if (geometry.vertexBuffer) { //vertex position buffer this._bindBuffer(geometry.vertexBuffer, gl.ARRAY_BUFFER); - this.curFillShader.enableAttrib( - this.curFillShader.attributes.aPosition.location, + fillShader.enableAttrib( + fillShader.attributes.aPosition.location, 3, gl.FLOAT, false, @@ -78755,8 +80572,8 @@ p5.RendererGL.prototype.drawBuffers = function(gId) { // bind the fill shader's 'aNormal' buffer if (geometry.normalBuffer) { this._bindBuffer(geometry.normalBuffer, gl.ARRAY_BUFFER); - this.curFillShader.enableAttrib( - this.curFillShader.attributes.aNormal.location, + fillShader.enableAttrib( + fillShader.attributes.aNormal.location, 3, gl.FLOAT, false, @@ -78769,8 +80586,8 @@ p5.RendererGL.prototype.drawBuffers = function(gId) { if (geometry.uvBuffer) { // uv buffer this._bindBuffer(geometry.uvBuffer, gl.ARRAY_BUFFER); - this.curFillShader.enableAttrib( - this.curFillShader.attributes.aTexCoord.location, + fillShader.enableAttrib( + fillShader.attributes.aTexCoord.location, 2, gl.FLOAT, false, @@ -78781,7 +80598,7 @@ p5.RendererGL.prototype.drawBuffers = function(gId) { this._applyColorBlend(this.curFillColor); this._drawElements(gl.TRIANGLES, gId); - this.curFillShader.unbindShader(); + fillShader.unbindShader(); } return this; }; @@ -78818,7 +80635,7 @@ p5.RendererGL.prototype.drawBuffersScaled = function( p5.RendererGL.prototype._drawArrays = function(drawMode, gId) { this.GL.drawArrays(drawMode, 0, this.gHash[gId].lineVertexCount); - this._pInst._pixelsDirty = true; + this._pixelsState._pixelsDirty = true; return this; }; @@ -78829,11 +80646,13 @@ p5.RendererGL.prototype._drawElements = function(drawMode, gId) { this.GL.UNSIGNED_SHORT, 0 ); - this._pInst._pixelsDirty = true; + this._pixelsState._pixelsDirty = true; }; p5.RendererGL.prototype._drawPoints = function(vertices, vertexBuffer) { var gl = this.GL; + var pointShader = this._getImmediatePointShader(); + this._setPointUniforms(pointShader); this._bindBuffer( vertexBuffer, @@ -78843,8 +80662,8 @@ p5.RendererGL.prototype._drawPoints = function(vertices, vertexBuffer) { gl.STATIC_DRAW ); - this.curPointShader.enableAttrib( - this.curPointShader.attributes.aPosition.location, + pointShader.enableAttrib( + pointShader.attributes.aPosition.location, 3, gl.FLOAT, false, @@ -78853,11 +80672,14 @@ p5.RendererGL.prototype._drawPoints = function(vertices, vertexBuffer) { ); gl.drawArrays(gl.Points, 0, vertices.length); + + pointShader.unbindShader(); + this._pixelsState._pixelsDirty = true; }; module.exports = p5.RendererGL; -},{"../core/main":25}],75:[function(_dereq_,module,exports){ +},{"../core/main":24}],74:[function(_dereq_,module,exports){ 'use strict'; var p5 = _dereq_('../core/main'); @@ -78876,10 +80698,10 @@ var defaultShaders = { normalVert: "attribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\n\nvarying vec3 vVertexNormal;\nvarying highp vec2 vVertTexCoord;\n\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vVertexNormal = normalize(vec3( uNormalMatrix * aNormal ));\n vVertTexCoord = aTexCoord;\n}\n", normalFrag: "precision mediump float;\nvarying vec3 vVertexNormal;\nvoid main(void) {\n gl_FragColor = vec4(vVertexNormal, 1.0);\n}", basicFrag: "precision mediump float;\nvarying vec3 vVertexNormal;\nuniform vec4 uMaterialColor;\nvoid main(void) {\n gl_FragColor = uMaterialColor;\n}", - lightVert: "attribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nuniform mat4 uViewMatrix;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\nuniform int uAmbientLightCount;\nuniform int uDirectionalLightCount;\nuniform int uPointLightCount;\n\nuniform vec3 uAmbientColor[8];\nuniform vec3 uLightingDirection[8];\nuniform vec3 uDirectionalColor[8];\nuniform vec3 uPointLightLocation[8];\nuniform vec3 uPointLightColor[8];\nuniform bool uSpecular;\n\nvarying vec3 vVertexNormal;\nvarying vec2 vVertTexCoord;\nvarying vec3 vLightWeighting;\n\nvoid main(void){\n\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n\n vec3 vertexNormal = normalize(vec3( uNormalMatrix * aNormal ));\n vVertexNormal = vertexNormal;\n vVertTexCoord = aTexCoord;\n\n vec4 mvPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n vec3 eyeDirection = normalize(-mvPosition.xyz);\n\n float shininess = 32.0;\n float specularFactor = 2.0;\n float diffuseFactor = 0.3;\n\n vec3 ambientLightFactor = vec3(0.0);\n\n for (int i = 0; i < 8; i++) {\n if (uAmbientLightCount == i) break;\n ambientLightFactor += uAmbientColor[i];\n }\n\n\n vec3 directionalLightFactor = vec3(0.0);\n\n for (int j = 0; j < 8; j++) {\n if (uDirectionalLightCount == j) break;\n vec3 dir = uLightingDirection[j];\n float directionalLightWeighting = max(dot(vertexNormal, -dir), 0.0);\n directionalLightFactor += uDirectionalColor[j] * directionalLightWeighting;\n }\n\n\n vec3 pointLightFactor = vec3(0.0);\n\n for (int k = 0; k < 8; k++) {\n if (uPointLightCount == k) break;\n vec3 loc = (uViewMatrix * vec4(uPointLightLocation[k], 1.0)).xyz;\n vec3 lightDirection = normalize(loc - mvPosition.xyz);\n\n float directionalLightWeighting = max(dot(vertexNormal, lightDirection), 0.0);\n\n float specularLightWeighting = 0.0;\n if (uSpecular ){\n vec3 reflectionDirection = reflect(-lightDirection, vertexNormal);\n specularLightWeighting = pow(max(dot(reflectionDirection, eyeDirection), 0.0), shininess);\n }\n\n pointLightFactor += uPointLightColor[k] * (specularFactor * specularLightWeighting\n + directionalLightWeighting * diffuseFactor);\n }\n\n vLightWeighting = ambientLightFactor + directionalLightFactor + pointLightFactor;\n}\n", + lightVert: "attribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nuniform mat4 uViewMatrix;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\nuniform int uAmbientLightCount;\nuniform int uDirectionalLightCount;\nuniform int uPointLightCount;\n\nuniform vec3 uAmbientColor[8];\nuniform vec3 uLightingDirection[8];\nuniform vec3 uDirectionalColor[8];\nuniform vec3 uPointLightLocation[8];\nuniform vec3 uPointLightColor[8];\nuniform bool uSpecular;\nuniform float uShininess;\n\nvarying vec3 vVertexNormal;\nvarying vec2 vVertTexCoord;\nvarying vec3 vLightWeighting;\n\nvoid main(void){\n\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n\n vec3 vertexNormal = normalize(vec3( uNormalMatrix * aNormal ));\n vVertexNormal = vertexNormal;\n vVertTexCoord = aTexCoord;\n\n vec4 mvPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n vec3 eyeDirection = normalize(-mvPosition.xyz);\n\n float specularFactor = 2.0;\n float diffuseFactor = 0.3;\n\n vec3 ambientLightFactor = vec3(0.0);\n\n for (int i = 0; i < 8; i++) {\n if (uAmbientLightCount == i) break;\n ambientLightFactor += uAmbientColor[i];\n }\n\n\n vec3 directionalLightFactor = vec3(0.0);\n\n for (int j = 0; j < 8; j++) {\n if (uDirectionalLightCount == j) break;\n vec3 dir = uLightingDirection[j];\n float directionalLightWeighting = max(dot(vertexNormal, -dir), 0.0);\n directionalLightFactor += uDirectionalColor[j] * directionalLightWeighting;\n }\n\n\n vec3 pointLightFactor = vec3(0.0);\n\n for (int k = 0; k < 8; k++) {\n if (uPointLightCount == k) break;\n vec3 loc = (uViewMatrix * vec4(uPointLightLocation[k], 1.0)).xyz;\n vec3 lightDirection = normalize(loc - mvPosition.xyz);\n\n float directionalLightWeighting = max(dot(vertexNormal, lightDirection), 0.0);\n\n float specularLightWeighting = 0.0;\n if (uSpecular ){\n vec3 reflectionDirection = reflect(-lightDirection, vertexNormal);\n specularLightWeighting = pow(max(dot(reflectionDirection, eyeDirection), 0.0), uShininess);\n }\n\n pointLightFactor += uPointLightColor[k] * (specularFactor * specularLightWeighting\n + directionalLightWeighting * diffuseFactor);\n }\n\n vLightWeighting = ambientLightFactor + directionalLightFactor + pointLightFactor;\n}\n", lightTextureFrag: "precision mediump float;\n\nuniform vec4 uMaterialColor;\nuniform sampler2D uSampler;\nuniform bool isTexture;\nuniform bool uUseLighting;\n\nvarying vec3 vLightWeighting;\nvarying highp vec2 vVertTexCoord;\n\nvoid main(void) {\n gl_FragColor = isTexture ? texture2D(uSampler, vVertTexCoord) : uMaterialColor;\n if (uUseLighting)\n gl_FragColor.rgb *= vLightWeighting;\n}", phongVert: "precision mediump float;\n\nattribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nuniform vec3 uAmbientColor[8];\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\nuniform int uAmbientLightCount;\n\nvarying vec3 vNormal;\nvarying vec2 vTexCoord;\nvarying vec3 vViewPosition;\nvarying vec3 vAmbientColor;\n\nvoid main(void){\n\n vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n\n // Pass varyings to fragment shader\n vViewPosition = viewModelPosition.xyz;\n gl_Position = uProjectionMatrix * viewModelPosition; \n\n vNormal = normalize(uNormalMatrix * normalize(aNormal));\n vTexCoord = aTexCoord;\n\n vAmbientColor = vec3(0.0);\n for (int i = 0; i < 8; i++) {\n if (uAmbientLightCount == i) break;\n vAmbientColor += uAmbientColor[i];\n }\n}\n", - phongFrag: "precision mediump float;\n\n//uniform mat4 uModelViewMatrix;\nuniform mat4 uViewMatrix;\n\nuniform vec4 uMaterialColor;\nuniform sampler2D uSampler;\nuniform bool isTexture;\nuniform bool uUseLighting;\n\nuniform vec3 uLightingDirection[8];\nuniform vec3 uDirectionalColor[8];\nuniform vec3 uPointLightLocation[8];\nuniform vec3 uPointLightColor[8];\nuniform bool uSpecular;\n\nuniform int uDirectionalLightCount;\nuniform int uPointLightCount;\n\nvarying vec3 vNormal;\nvarying vec2 vTexCoord;\nvarying vec3 vViewPosition;\nvarying vec3 vAmbientColor;\n\nvec3 V;\nvec3 N;\n\nconst float shininess = 32.0;\nconst float specularFactor = 2.0;\nconst float diffuseFactor = 0.73;\n\nstruct LightResult {\n\tfloat specular;\n\tfloat diffuse;\n};\n\nfloat phongSpecular(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float shininess) {\n\n vec3 R = normalize(reflect(-lightDirection, surfaceNormal)); \n return pow(max(0.0, dot(R, viewDirection)), shininess);\n}\n\nfloat lambertDiffuse(\n vec3 lightDirection,\n vec3 surfaceNormal) {\n return max(0.0, dot(-lightDirection, surfaceNormal));\n}\n\nLightResult light(vec3 lightVector) {\n\n vec3 L = normalize(lightVector);\n\n //compute our diffuse & specular terms\n LightResult lr;\n if (uSpecular)\n lr.specular = phongSpecular(L, V, N, shininess);\n lr.diffuse = lambertDiffuse(L, N);\n return lr;\n}\n\nvoid main(void) {\n\n V = normalize(vViewPosition);\n N = vNormal;\n\n vec3 diffuse = vec3(0.0);\n float specular = 0.0;\n\n for (int j = 0; j < 8; j++) {\n if (uDirectionalLightCount == j) break;\n\n LightResult result = light(uLightingDirection[j]);\n diffuse += result.diffuse * uDirectionalColor[j];\n specular += result.specular;\n }\n\n for (int k = 0; k < 8; k++) {\n if (uPointLightCount == k) break;\n\n vec3 lightPosition = (uViewMatrix * vec4(uPointLightLocation[k], 1.0)).xyz;\n vec3 lightVector = vViewPosition - lightPosition;\n\t\n //calculate attenuation\n float lightDistance = length(lightVector);\n float falloff = 500.0 / (lightDistance + 500.0);\n\n LightResult result = light(lightVector);\n diffuse += result.diffuse * falloff * uPointLightColor[k];\n specular += result.specular * falloff;\n }\n\n gl_FragColor = isTexture ? texture2D(uSampler, vTexCoord) : uMaterialColor;\n gl_FragColor.rgb = gl_FragColor.rgb * (diffuse * diffuseFactor + vAmbientColor) + specular * specularFactor;\n}", + phongFrag: "precision mediump float;\n\n//uniform mat4 uModelViewMatrix;\nuniform mat4 uViewMatrix;\n\nuniform vec4 uMaterialColor;\nuniform sampler2D uSampler;\nuniform bool isTexture;\nuniform bool uUseLighting;\n\nuniform vec3 uLightingDirection[8];\nuniform vec3 uDirectionalColor[8];\nuniform vec3 uPointLightLocation[8];\nuniform vec3 uPointLightColor[8];\nuniform bool uSpecular;\nuniform float uShininess;\n\nuniform int uDirectionalLightCount;\nuniform int uPointLightCount;\n\nvarying vec3 vNormal;\nvarying vec2 vTexCoord;\nvarying vec3 vViewPosition;\nvarying vec3 vAmbientColor;\n\nvec3 V;\nvec3 N;\n\nconst float specularFactor = 2.0;\nconst float diffuseFactor = 0.73;\n\nstruct LightResult {\n\tfloat specular;\n\tfloat diffuse;\n};\n\nfloat phongSpecular(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float shininess) {\n\n vec3 R = normalize(reflect(-lightDirection, surfaceNormal)); \n return pow(max(0.0, dot(R, viewDirection)), shininess);\n}\n\nfloat lambertDiffuse(\n vec3 lightDirection,\n vec3 surfaceNormal) {\n return max(0.0, dot(-lightDirection, surfaceNormal));\n}\n\nLightResult light(vec3 lightVector) {\n\n vec3 L = normalize(lightVector);\n\n //compute our diffuse & specular terms\n LightResult lr;\n if (uSpecular)\n lr.specular = phongSpecular(L, V, N, uShininess);\n lr.diffuse = lambertDiffuse(L, N);\n return lr;\n}\n\nvoid main(void) {\n\n V = normalize(vViewPosition);\n N = vNormal;\n\n vec3 diffuse = vec3(0.0);\n float specular = 0.0;\n\n for (int j = 0; j < 8; j++) {\n if (uDirectionalLightCount == j) break;\n\n LightResult result = light(uLightingDirection[j]);\n diffuse += result.diffuse * uDirectionalColor[j];\n specular += result.specular;\n }\n\n for (int k = 0; k < 8; k++) {\n if (uPointLightCount == k) break;\n\n vec3 lightPosition = (uViewMatrix * vec4(uPointLightLocation[k], 1.0)).xyz;\n vec3 lightVector = vViewPosition - lightPosition;\n\t\n //calculate attenuation\n float lightDistance = length(lightVector);\n float falloff = 500.0 / (lightDistance + 500.0);\n\n LightResult result = light(lightVector);\n diffuse += result.diffuse * falloff * uPointLightColor[k];\n specular += result.specular * falloff;\n }\n\n gl_FragColor = isTexture ? texture2D(uSampler, vTexCoord) : uMaterialColor;\n gl_FragColor.rgb = gl_FragColor.rgb * (diffuse * diffuseFactor + vAmbientColor) + specular * specularFactor;\n}", fontVert: "precision mediump float;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nuniform vec4 uGlyphRect;\nuniform float uGlyphOffset;\n\nvarying vec2 vTexCoord;\nvarying float w;\n\nvoid main() {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n\n // scale by the size of the glyph's rectangle\n positionVec4.xy *= uGlyphRect.zw - uGlyphRect.xy;\n\n // move to the corner of the glyph\n positionVec4.xy += uGlyphRect.xy;\n\n // move to the letter's line offset\n positionVec4.x += uGlyphOffset;\n \n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vTexCoord = aTexCoord;\n w = gl_Position.w;\n}\n", fontFrag: "#extension GL_OES_standard_derivatives : enable\nprecision mediump float;\n\n#if 0\n // simulate integer math using floats\n\t#define int float\n\t#define ivec2 vec2\n\t#define INT(x) float(x)\n\n\tint ifloor(float v) { return floor(v); }\n\tivec2 ifloor(vec2 v) { return floor(v); }\n\n#else\n // use native integer math\n\tprecision mediump int;\n\t#define INT(x) x\n\n\tint ifloor(float v) { return int(v); }\n\tint ifloor(int v) { return v; }\n\tivec2 ifloor(vec2 v) { return ivec2(v); }\n\n#endif\n\nuniform sampler2D uSamplerStrokes;\nuniform sampler2D uSamplerRowStrokes;\nuniform sampler2D uSamplerRows;\nuniform sampler2D uSamplerColStrokes;\nuniform sampler2D uSamplerCols;\n\nuniform ivec2 uStrokeImageSize;\nuniform ivec2 uCellsImageSize;\nuniform ivec2 uGridImageSize;\n\nuniform ivec2 uGridOffset;\nuniform ivec2 uGridSize;\nuniform vec4 uMaterialColor;\n\nvarying vec2 vTexCoord;\n\n// some helper functions\nint round(float v) { return ifloor(v + 0.5); }\nivec2 round(vec2 v) { return ifloor(v + 0.5); }\nfloat saturate(float v) { return clamp(v, 0.0, 1.0); }\nvec2 saturate(vec2 v) { return clamp(v, 0.0, 1.0); }\n\nint mul(float v1, int v2) {\n return ifloor(v1 * float(v2));\n}\n\nivec2 mul(vec2 v1, ivec2 v2) {\n return ifloor(v1 * vec2(v2) + 0.5);\n}\n\n// unpack a 16-bit integer from a float vec2\nint getInt16(vec2 v) {\n ivec2 iv = round(v * 255.0);\n return iv.x * INT(128) + iv.y;\n}\n\nvec2 pixelScale;\nvec2 coverage = vec2(0.0);\nvec2 weight = vec2(0.5);\nconst float minDistance = 1.0/8192.0;\nconst float hardness = 1.05; // amount of antialias\n\n// the maximum number of curves in a glyph\nconst int N = INT(250);\n\n// retrieves an indexed pixel from a sampler\nvec4 getTexel(sampler2D sampler, int pos, ivec2 size) {\n int width = size.x;\n int y = ifloor(pos / width);\n int x = pos - y * width; // pos % width\n\n return texture2D(sampler, (vec2(x, y) + 0.5) / vec2(size));\n}\n\nvoid calulateCrossings(vec2 p0, vec2 p1, vec2 p2, out vec2 C1, out vec2 C2) {\n\n // get the coefficients of the quadratic in t\n vec2 a = p0 - p1 * 2.0 + p2;\n vec2 b = p0 - p1;\n vec2 c = p0 - vTexCoord;\n\n // found out which values of 't' it crosses the axes\n vec2 surd = sqrt(max(vec2(0.0), b * b - a * c));\n vec2 t1 = ((b - surd) / a).yx;\n vec2 t2 = ((b + surd) / a).yx;\n\n // approximate straight lines to avoid rounding errors\n if (abs(a.y) < 0.001)\n t1.x = t2.x = c.y / (2.0 * b.y);\n\n if (abs(a.x) < 0.001)\n t1.y = t2.y = c.x / (2.0 * b.x);\n\n // plug into quadratic formula to find the corrdinates of the crossings\n C1 = ((a * t1 - b * 2.0) * t1 + c) * pixelScale;\n C2 = ((a * t2 - b * 2.0) * t2 + c) * pixelScale;\n}\n\nvoid coverageX(vec2 p0, vec2 p1, vec2 p2) {\n\n vec2 C1, C2;\n calulateCrossings(p0, p1, p2, C1, C2);\n\n // determine on which side of the x-axis the points lie\n bool y0 = p0.y > vTexCoord.y;\n bool y1 = p1.y > vTexCoord.y;\n bool y2 = p2.y > vTexCoord.y;\n\n // could web be under the curve (after t1)?\n if (y1 ? !y2 : y0) {\n // add the coverage for t1\n coverage.x += saturate(C1.x + 0.5);\n // calculate the anti-aliasing for t1\n weight.x = min(weight.x, abs(C1.x));\n }\n\n // are we outside the curve (after t2)?\n if (y1 ? !y0 : y2) {\n // subtract the coverage for t2\n coverage.x -= saturate(C2.x + 0.5);\n // calculate the anti-aliasing for t2\n weight.x = min(weight.x, abs(C2.x));\n }\n}\n\n// this is essentially the same as coverageX, but with the axes swapped\nvoid coverageY(vec2 p0, vec2 p1, vec2 p2) {\n\n vec2 C1, C2;\n calulateCrossings(p0, p1, p2, C1, C2);\n\n bool x0 = p0.x > vTexCoord.x;\n bool x1 = p1.x > vTexCoord.x;\n bool x2 = p2.x > vTexCoord.x;\n\n if (x1 ? !x2 : x0) {\n coverage.y -= saturate(C1.y + 0.5);\n weight.y = min(weight.y, abs(C1.y));\n }\n\n if (x1 ? !x0 : x2) {\n coverage.y += saturate(C2.y + 0.5);\n weight.y = min(weight.y, abs(C2.y));\n }\n}\n\nvoid main() {\n\n // calculate the pixel scale based on screen-coordinates\n pixelScale = hardness / fwidth(vTexCoord);\n\n // which grid cell is this pixel in?\n ivec2 gridCoord = ifloor(vTexCoord * vec2(uGridSize));\n\n // intersect curves in this row\n {\n // the index into the row info bitmap\n int rowIndex = gridCoord.y + uGridOffset.y;\n // fetch the info texel\n vec4 rowInfo = getTexel(uSamplerRows, rowIndex, uGridImageSize);\n // unpack the rowInfo\n int rowStrokeIndex = getInt16(rowInfo.xy);\n int rowStrokeCount = getInt16(rowInfo.zw);\n\n for (int iRowStroke = INT(0); iRowStroke < N; iRowStroke++) {\n if (iRowStroke >= rowStrokeCount)\n break;\n\n // each stroke is made up of 3 points: the start and control point\n // and the start of the next curve.\n // fetch the indices of this pair of strokes:\n vec4 strokeIndices = getTexel(uSamplerRowStrokes, rowStrokeIndex++, uCellsImageSize);\n\n // unpack the stroke index\n int strokePos = getInt16(strokeIndices.xy);\n\n // fetch the two strokes\n vec4 stroke0 = getTexel(uSamplerStrokes, strokePos + INT(0), uStrokeImageSize);\n vec4 stroke1 = getTexel(uSamplerStrokes, strokePos + INT(1), uStrokeImageSize);\n\n // calculate the coverage\n coverageX(stroke0.xy, stroke0.zw, stroke1.xy);\n }\n }\n\n // intersect curves in this column\n {\n int colIndex = gridCoord.x + uGridOffset.x;\n vec4 colInfo = getTexel(uSamplerCols, colIndex, uGridImageSize);\n int colStrokeIndex = getInt16(colInfo.xy);\n int colStrokeCount = getInt16(colInfo.zw);\n \n for (int iColStroke = INT(0); iColStroke < N; iColStroke++) {\n if (iColStroke >= colStrokeCount)\n break;\n\n vec4 strokeIndices = getTexel(uSamplerColStrokes, colStrokeIndex++, uCellsImageSize);\n\n int strokePos = getInt16(strokeIndices.xy);\n vec4 stroke0 = getTexel(uSamplerStrokes, strokePos + INT(0), uStrokeImageSize);\n vec4 stroke1 = getTexel(uSamplerStrokes, strokePos + INT(1), uStrokeImageSize);\n coverageY(stroke0.xy, stroke0.zw, stroke1.xy);\n }\n }\n\n weight = saturate(1.0 - weight * 2.0);\n float distance = max(weight.x + weight.y, minDistance); // manhattan approx.\n float antialias = abs(dot(coverage, weight) / distance);\n float cover = min(abs(coverage.x), abs(coverage.y));\n gl_FragColor = uMaterialColor;\n gl_FragColor.a *= saturate(max(antialias, cover));\n}", lineVert: "/*\n Part of the Processing project - http://processing.org\n Copyright (c) 2012-15 The Processing Foundation\n Copyright (c) 2004-12 Ben Fry and Casey Reas\n Copyright (c) 2001-04 Massachusetts Institute of Technology\n This library is free software; you can redistribute it and/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation, version 2.1.\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n You should have received a copy of the GNU Lesser General\n Public License along with this library; if not, write to the\n Free Software Foundation, Inc., 59 Temple Place, Suite 330,\n Boston, MA 02111-1307 USA\n*/\n\n#define PROCESSING_LINE_SHADER\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform float uStrokeWeight;\n\nuniform vec4 uViewport;\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.\nvec3 scale = vec3(0.9995);\n\nattribute vec4 aPosition;\nattribute vec4 aDirection;\n \nvoid main() {\n vec4 posp = uModelViewMatrix * aPosition;\n vec4 posq = uModelViewMatrix * (aPosition + vec4(aDirection.xyz, 0));\n\n // Moving vertices slightly toward the camera\n // to avoid depth-fighting with the fill triangles.\n // Discussed here:\n // http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=252848 \n posp.xyz = posp.xyz * scale;\n posq.xyz = posq.xyz * scale;\n\n vec4 p = uProjectionMatrix * posp;\n vec4 q = uProjectionMatrix * posq;\n\n // formula to convert from clip space (range -1..1) to screen space (range 0..[width or height])\n // screen_p = (p.xy/p.w + <1,1>) * 0.5 * uViewport.zw\n\n // prevent division by W by transforming the tangent formula (div by 0 causes\n // the line to disappear, see https://github.com/processing/processing/issues/5183)\n // t = screen_q - screen_p\n //\n // tangent is normalized and we don't care which aDirection it points to (+-)\n // t = +- normalize( screen_q - screen_p )\n // t = +- normalize( (q.xy/q.w+<1,1>)*0.5*uViewport.zw - (p.xy/p.w+<1,1>)*0.5*uViewport.zw )\n //\n // extract common factor, <1,1> - <1,1> cancels out\n // t = +- normalize( (q.xy/q.w - p.xy/p.w) * 0.5 * uViewport.zw )\n //\n // convert to common divisor\n // t = +- normalize( ((q.xy*p.w - p.xy*q.w) / (p.w*q.w)) * 0.5 * uViewport.zw )\n //\n // remove the common scalar divisor/factor, not needed due to normalize and +-\n // (keep uViewport - can't remove because it has different components for x and y\n // and corrects for aspect ratio, see https://github.com/processing/processing/issues/5181)\n // t = +- normalize( (q.xy*p.w - p.xy*q.w) * uViewport.zw )\n\n vec2 tangent = normalize((q.xy*p.w - p.xy*q.w) * uViewport.zw);\n\n // flip tangent to normal (it's already normalized)\n vec2 normal = vec2(-tangent.y, tangent.x);\n\n float thickness = aDirection.w * uStrokeWeight;\n vec2 offset = normal * thickness / 2.0;\n\n // 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 vec2 perspScale = (uProjectionMatrix * vec4(1, -1, 0, 0)).xy;\n\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 vec2 noPerspScale = p.w / (0.5 * uViewport.zw);\n\n //gl_Position.xy = p.xy + offset.xy * mix(noPerspScale, perspScale, float(perspective > 0));\n gl_Position.xy = p.xy + offset.xy * perspScale;\n gl_Position.zw = p.zw;\n}\n", @@ -78900,27 +80722,15 @@ var defaultShaders = { */ p5.RendererGL = function(elt, pInst, isMainCanvas, attr) { p5.Renderer.call(this, elt, pInst, isMainCanvas); - this.attributes = {}; - attr = attr || {}; - this.attributes.alpha = attr.alpha === undefined ? true : attr.alpha; - this.attributes.depth = attr.depth === undefined ? true : attr.depth; - this.attributes.stencil = attr.stencil === undefined ? true : attr.stencil; - this.attributes.antialias = - attr.antialias === undefined ? false : attr.antialias; - this.attributes.premultipliedAlpha = - attr.premultipliedAlpha === undefined ? false : attr.premultipliedAlpha; - this.attributes.preserveDrawingBuffer = - attr.preserveDrawingBuffer === undefined - ? true - : attr.preserveDrawingBuffer; - this.attributes.perPixelLighting = - attr.perPixelLighting === undefined ? false : attr.perPixelLighting; + this._setAttributeDefaults(pInst); this._initContext(); this.isP3D = true; //lets us know we're in 3d mode this.GL = this.drawingContext; // lights + this._enableLighting = false; + this.ambientLightColors = []; this.directionalLightDirections = []; this.directionalLightColors = []; @@ -78928,6 +80738,15 @@ p5.RendererGL = function(elt, pInst, isMainCanvas, attr) { this.pointLightPositions = []; this.pointLightColors = []; + this.curFillColor = [1, 1, 1, 1]; + this.curStrokeColor = [0, 0, 0, 1]; + this.curBlendMode = constants.BLEND; + this.blendExt = this.GL.getExtension('EXT_blend_minmax'); + + this._useSpecularMaterial = false; + this._useNormalMaterial = false; + this._useShininess = 1; + /** * model view, projection, & normal * matrices @@ -78950,31 +80769,28 @@ p5.RendererGL = function(elt, pInst, isMainCanvas, attr) { this._defaultColorShader = undefined; this._defaultPointShader = undefined; - this.curFillShader = undefined; - this.curStrokeShader = undefined; - this.curPointShader = undefined; - - this._useColorShader(); - this.setStrokeShader(this._getLineShader()); - this._usePointShader(); - this._pointVertexBuffer = this.GL.createBuffer(); + this.userFillShader = undefined; + this.userStrokeShader = undefined; + this.userPointShader = undefined; + //Imediate Mode //default drawing is done in Retained Mode this.isImmediateDrawing = false; this.immediateMode = {}; - // note: must call fill() and stroke () AFTER - // default shader has been set. - this.fill(255, 255, 255, 255); - //this.stroke(0, 0, 0, 255); this.pointSize = 5.0; //default point size - this.strokeWeight(1); - this.stroke(0, 0, 0); + this.curStrokeWeight = 1; + // array of textures created in this gl context via this.getTexture(src) this.textures = []; + this.textureMode = constants.IMAGE; + // default wrap settings + this.textureWrapX = constants.CLAMP; + this.textureWrapY = constants.CLAMP; + this._tex = null; this._curveTightness = 6; // lookUpTable for coefficients needed to be calculated for bezierVertex, same are used for curveVertex @@ -78990,6 +80806,7 @@ p5.RendererGL = function(elt, pInst, isMainCanvas, attr) { this._tessy = this._initTessy(); this.fontInfos = {}; + return this; }; @@ -78999,11 +80816,29 @@ p5.RendererGL.prototype = Object.create(p5.Renderer.prototype); // Setting ////////////////////////////////////////////// +p5.RendererGL.prototype._setAttributeDefaults = function(pInst) { + var defaults = { + alpha: false, + depth: true, + stencil: true, + antialias: false, + premultipliedAlpha: false, + preserveDrawingBuffer: true, + perPixelLighting: false + }; + if (pInst._glAttributes === null) { + pInst._glAttributes = defaults; + } else { + pInst._glAttributes = Object.assign(defaults, pInst._glAttributes); + } + return; +}; + p5.RendererGL.prototype._initContext = function() { try { this.drawingContext = - this.canvas.getContext('webgl', this.attributes) || - this.canvas.getContext('experimental-webgl', this.attributes); + 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 { @@ -79024,7 +80859,7 @@ p5.RendererGL.prototype._initContext = function() { //This is helper function to reset the context anytime the attributes //are changed with setAttributes() -p5.RendererGL.prototype._resetContext = function(attr, options, callback) { +p5.RendererGL.prototype._resetContext = function(options, callback) { var w = this.width; var h = this.height; var defaultId = this.canvas.id; @@ -79041,7 +80876,7 @@ p5.RendererGL.prototype._resetContext = function(attr, options, callback) { } this._pInst.canvas = c; - var renderer = new p5.RendererGL(this._pInst.canvas, this._pInst, true, attr); + var renderer = new p5.RendererGL(this._pInst.canvas, this._pInst, true); this._pInst._setProperty('_renderer', renderer); renderer.resize(w, h); renderer._applyDefaults(); @@ -79062,13 +80897,19 @@ p5.RendererGL.prototype._resetContext = function(attr, options, callback) { */ /** * Set attributes for the WebGL Drawing context. - * This is a way of adjusting ways that the WebGL + * This is a way of adjusting how the WebGL * renderer works to fine-tune the display and performance. - * This should be put in setup(). + *

+ * Note that this will reinitialize the drawing context + * if called after the WebGL canvas is made. + *

+ * If an object is passed as the parameter, all attributes + * not declared in the object will be set to defaults. + *

* The available attributes are: *
* alpha - indicates if the canvas contains an alpha buffer - * default is true + * default is false *

* depth - indicates whether the drawing buffer has a depth buffer * of at least 16 bits - default is true @@ -79121,8 +80962,8 @@ p5.RendererGL.prototype._resetContext = function(attr, options, callback) { *
* * function setup() { - * createCanvas(100, 100, WEBGL); * setAttributes('antialias', true); + * createCanvas(100, 100, WEBGL); * } * * function draw() { @@ -79175,7 +81016,7 @@ p5.RendererGL.prototype._resetContext = function(attr, options, callback) { * rotateX(t * 0.77); * rotateY(t * 0.83); * rotateZ(t * 0.91); - * torus(width * 0.3, width * 0.07, 30, 10); + * torus(width * 0.3, width * 0.07, 24, 10); * } * * function mousePressed() { @@ -79200,18 +81041,48 @@ p5.RendererGL.prototype._resetContext = function(attr, options, callback) { */ p5.prototype.setAttributes = function(key, value) { - this._assert3d('setAttributes'); - //@todo_FES - var attr; + var unchanged = true; if (typeof value !== 'undefined') { - attr = {}; - attr[key] = value; + //first time modifying the attributes + if (this._glAttributes === null) { + this._glAttributes = {}; + } + if (this._glAttributes[key] !== value) { + //changing value of previously altered attribute + this._glAttributes[key] = value; + unchanged = false; + } + //setting all attributes with some change } else if (key instanceof Object) { - attr = key; + 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.gHash) { + if (this._renderer.gHash.hasOwnProperty(x)) { + console.error( + 'Sorry, Could not set the attributes, you need to call setAttributes() ' + + 'before calling the other drawing methods in setup()' + ); + return; + } + } } + this.push(); - this._renderer._resetContext(attr); + this._renderer._resetContext(); this.pop(); + + if (this._renderer._curCamera) { + this._renderer._curCamera._renderer = this._renderer; + } }; /** @@ -79248,6 +81119,8 @@ p5.RendererGL.prototype._update = function() { this.pointLightPositions.length = 0; this.pointLightColors.length = 0; + + this._enableLighting = false; }; /** @@ -79262,13 +81135,9 @@ p5.RendererGL.prototype.background = function() { this.GL.clearColor(_r, _g, _b, _a); this.GL.depthMask(true); this.GL.clear(this.GL.COLOR_BUFFER_BIT | this.GL.DEPTH_BUFFER_BIT); + this._pixelsState._pixelsDirty = true; }; -//@TODO implement this -// p5.RendererGL.prototype.clear = function() { -//@TODO -// }; - ////////////////////////////////////////////// // COLOR ////////////////////////////////////////////// @@ -79309,14 +81178,9 @@ p5.RendererGL.prototype.fill = function(v1, v2, v3, a) { //see material.js for more info on color blending in webgl var color = p5.prototype.color.apply(this._pInst, arguments); this.curFillColor = color._array; - - if (this.isImmediateDrawing) { - this.setFillShader(this._getImmediateModeShader()); - } else { - this.setFillShader(this._getColorShader()); - } this.drawMode = constants.FILL; - this.curFillShader.setUniform('uMaterialColor', this.curFillColor); + this._useNormalMaterial = false; + this._tex = null; }; /** @@ -79356,8 +81220,37 @@ p5.RendererGL.prototype.stroke = function(r, g, b, a) { arguments[3] = 255; var color = p5.prototype.color.apply(this._pInst, arguments); this.curStrokeColor = color._array; - this.curStrokeShader.setUniform('uMaterialColor', this.curStrokeColor); - this.curPointShader.setUniform('uMaterialColor', color._array); +}; + +p5.RendererGL.prototype.strokeCap = function(cap) { + // @TODO : to be implemented + console.error('Sorry, strokeCap() is not yet implemented in WEBGL mode'); +}; + +p5.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 + ) + 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.' + ); + } }; /** @@ -79404,37 +81297,32 @@ p5.RendererGL.prototype.strokeWeight = function(w) { if (this.curStrokeWeight !== w) { this.pointSize = w; this.curStrokeWeight = w; - this.curStrokeShader.setUniform('uStrokeWeight', w); - this.curPointShader.setUniform('uPointSize', w); } }; -/** - * 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(). - *

- * If the pixel requested is outside of the image window, [0,0,0,255] is - * returned. - *

- * 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) is using pixels[] with pixel density d - * - * @private - * @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 {Number[]|Color|p5.Image} color of pixel at x,y in array format - * [R, G, B, A] or p5.Image - */ -p5.RendererGL.prototype.get = function(x, y, w, h) { - return p5.Renderer2D.prototype.get.apply(this, [x, y, w, h]); +// x,y are canvas-relative (pre-scaled by _pixelDensity) +p5.RendererGL.prototype._getPixel = function(x, y) { + var pixelsState = this._pixelsState; + var imageData, index; + if (pixelsState._pixelsDirty) { + imageData = new Uint8Array(4); + // prettier-ignore + this.drawingContext.readPixels( + x, y, 1, 1, + this.drawingContext.RGBA, this.drawingContext.UNSIGNED_BYTE, + imageData + ); + index = 0; + } else { + imageData = pixelsState.pixels; + index = (Math.floor(x) + Math.floor(y) * this.canvas.width) * 4; + } + return [ + imageData[index + 0], + imageData[index + 1], + imageData[index + 2], + imageData[index + 3] + ]; }; /** @@ -79448,37 +81336,34 @@ p5.RendererGL.prototype.get = function(x, y, w, h) { */ p5.RendererGL.prototype.loadPixels = function() { + var pixelsState = this._pixelsState; + if (!pixelsState._pixelsDirty) return; + pixelsState._pixelsDirty = false; + //@todo_FES - if (this.attributes.preserveDrawingBuffer !== true) { + if (this._pInst._glAttributes.preserveDrawingBuffer !== true) { console.log( 'loadPixels only works in WebGL when preserveDrawingBuffer ' + 'is true.' ); return; } - var pd = this._pInst._pixelDensity; - var x = 0; - var y = 0; - var w = this.width; - var h = this.height; - w *= pd; - h *= pd; + //if there isn't a renderer-level temporary pixels buffer //make a new one - if (typeof this.pixels === 'undefined') { - this.pixels = new Uint8Array( - this.GL.drawingBufferWidth * this.GL.drawingBufferHeight * 4 - ); + var pixels = pixelsState.pixels; + var len = this.GL.drawingBufferWidth * this.GL.drawingBufferHeight * 4; + if (!(pixels instanceof Uint8Array) || pixels.length !== len) { + pixels = new Uint8Array(len); + this._pixelsState._setProperty('pixels', pixels); } + + var pd = this._pInst._pixelDensity; + // prettier-ignore this.GL.readPixels( - x, - y, - w, - h, - this.GL.RGBA, - this.GL.UNSIGNED_BYTE, - this.pixels + 0, 0, this.width * pd, this.height * pd, + this.GL.RGBA, this.GL.UNSIGNED_BYTE, + pixels ); - this._pInst._setProperty('pixels', this.pixels); }; ////////////////////////////////////////////// @@ -79508,9 +81393,14 @@ p5.RendererGL.prototype.resize = function(w, h) { this._curCamera._resize(); //resize pixels buffer - if (typeof this.pixels !== 'undefined') { - this.pixels = new Uint8Array( - this.GL.drawingBufferWidth * this.GL.drawingBufferHeight * 4 + var pixelsState = this._pixelsState; + pixelsState._pixelsDirty = true; + if (typeof pixelsState.pixels !== 'undefined') { + pixelsState._setProperty( + 'pixels', + new Uint8Array( + this.GL.drawingBufferWidth * this.GL.drawingBufferHeight * 4 + ) ); } }; @@ -79531,6 +81421,21 @@ p5.RendererGL.prototype.clear = function() { var _a = arguments[3] || 0; this.GL.clearColor(_r, _g, _b, _a); this.GL.clear(this.GL.COLOR_BUFFER_BIT | this.GL.DEPTH_BUFFER_BIT); + this._pixelsState._pixelsDirty = true; +}; + +p5.RendererGL.prototype.applyMatrix = function(a, b, c, d, e, f) { + if (arguments.length === 16) { + p5.Matrix.prototype.apply.apply(this.uMVMatrix, arguments); + } else { + // prettier-ignore + this.uMVMatrix.apply([ + a, b, 0, 0, + c, d, 0, 0, + 0, 0, 1, 0, + e, f, 0, 1, + ]); + } }; /** @@ -79569,7 +81474,6 @@ p5.RendererGL.prototype.rotate = function(rad, axis) { if (typeof axis === 'undefined') { return this.rotateZ(rad); } - arguments[0] = this._pInst._fromRadians(rad); p5.Matrix.prototype.rotate.apply(this.uMVMatrix, arguments); return this; }; @@ -79604,6 +81508,31 @@ p5.RendererGL.prototype.push = function() { // this preserves any references stored using 'createCamera' this._curCamera = this._curCamera.copy(); + properties.ambientLightColors = this.ambientLightColors.slice(); + + properties.directionalLightDirections = this.directionalLightDirections.slice(); + properties.directionalLightColors = this.directionalLightColors.slice(); + + properties.pointLightPositions = this.pointLightPositions.slice(); + properties.pointLightColors = this.pointLightColors.slice(); + + properties.userFillShader = this.userFillShader; + properties.userStrokeShader = this.userStrokeShader; + properties.userPointShader = this.userPointShader; + + properties.pointSize = this.pointSize; + properties.curStrokeWeight = this.curStrokeWeight; + properties.curStrokeColor = this.curStrokeColor; + properties.curFillColor = this.curFillColor; + + properties._useSpecularMaterial = this._useSpecularMaterial; + properties._useShininess = this._useShininess; + + properties._enableLighting = this._enableLighting; + properties._useNormalMaterial = this._useNormalMaterial; + properties._tex = this._tex; + properties.drawMode = this.drawMode; + return style; }; @@ -79617,116 +81546,86 @@ p5.RendererGL.prototype.resetMatrix = function() { ////////////////////////////////////////////// /* - * Initializes and uses the specified shader, then returns - * that shader. Note: initialization and resetting the program - * is only used if needed (say, if a new value is provided) - * so it is safe to call this method with the same shader multiple - * times without a signficant performance hit). - * - * @method setFillShader - * @param {p5.Shader} [s] a p5.Shader object - * @return {p5.Shader} the current, updated fill 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. */ -p5.RendererGL.prototype.setFillShader = function(s) { - if (this.curFillShader !== s) { - // only do setup etc. if shader is actually new. - this.curFillShader = s; - // safe to do this multiple times; - // init() will bail early if has already been run. - this.curFillShader.init(); - //this.curFillShader.useProgram(); +p5.RendererGL.prototype._getImmediateStrokeShader = function() { + // select the stroke shader to use + var stroke = this.userStrokeShader; + if (!stroke || !stroke.isStrokeShader()) { + return this._getLineShader(); } - // always return this.curFillShader, even if no change was made. - return this.curFillShader; + return stroke; }; -p5.RendererGL.prototype.setPointShader = function(s) { - if (this.curPointShader !== s) { - // only do setup etc. if shader is actually new. - this.curPointShader = s; - - // safe to do this multiple times; - // init() will bail early if has already been run. - this.curPointShader.init(); - } - return this.curPointShader; -}; +p5.RendererGL.prototype._getRetainedStrokeShader = + p5.RendererGL.prototype._getImmediateStrokeShader; /* - * @method setStrokeShader - * @param {p5.Shader} [s] a p5.Shader object - * @return {p5.Shader} the current, updated stroke shader + * selects which fill shader should be used based on renderer state, + * for use with begin/endShape and immediate vertex mode. */ -p5.RendererGL.prototype.setStrokeShader = function(s) { - if (this.curStrokeShader !== s) { - // only do setup etc. if shader is actually new. - this.curStrokeShader = s; - // safe to do this multiple times; - // init() will bail early if has already been run. - this.curStrokeShader.init(); - //this.curStrokeShader.useProgram(); +p5.RendererGL.prototype._getImmediateFillShader = function() { + if (this._useNormalMaterial) { + return this._getNormalShader(); } - // always return this.curLineShader, even if no change was made. - return this.curStrokeShader; + + 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._getImmediateModeShader(); + } + return fill; }; /* - * 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. - * - * + * selects which fill shader should be used based on renderer state + * for retained mode. */ - -p5.RendererGL.prototype._useLightShader = function() { - if (!this.curFillShader || !this.curFillShader.isLightShader()) { - this.setFillShader(this._getLightShader()); +p5.RendererGL.prototype._getRetainedFillShader = function() { + if (this._useNormalMaterial) { + return this._getNormalShader(); } - return this.curFillShader; -}; -p5.RendererGL.prototype._useColorShader = function() { - // looking at the code within the glsl files, I'm not really - // sure why these are two different shaders. but, they are, - // and if we're drawing in retain mode but the shader is the - // immediate mode one, we need to switch. - - // TODO: what if curFillShader is _any_ other shader? - if ( - !this.curFillShader || - this.curFillShader === this._defaultImmediateModeShader - ) { - // there are different immediate mode and retain mode color shaders. - // if we're using the immediate mode one, we need to switch to - // one that works for retain mode. - this.setFillShader(this._getColorShader()); + 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 this.curFillShader; + return fill; }; -p5.RendererGL.prototype._usePointShader = function() { - if (!this.curPointShader) { - this.setPointShader(this._getPointShader()); +p5.RendererGL.prototype._getImmediatePointShader = function() { + // select the point shader to use + var point = this.userPointShader; + if (!point || !point.isPointShader()) { + return this._getPointShader(); } - return this.curPointShader; + return point; }; -p5.RendererGL.prototype._useImmediateModeShader = function() { - // TODO: what if curFillShader is _any_ other shader? - if (!this.curFillShader || this.curFillShader === this._defaultColorShader) { - // this is the fill/stroke shader for retain mode. - // must switch to immediate mode shader before drawing! - this.setFillShader(this._getImmediateModeShader()); - // note that if we're using the texture shader... - // this shouldn't change. :) - } - return this.curFillShader; -}; +p5.RendererGL.prototype._getRetainedLineShader = + p5.RendererGL.prototype._getImmediateLineShader; p5.RendererGL.prototype._getLightShader = function() { if (!this._defaultLightShader) { - if (this.attributes.perPixelLighting) { + if (this._pInst._glAttributes.perPixelLighting) { this._defaultLightShader = new p5.Shader( this, defaultShaders.phongVert, @@ -79740,7 +81639,7 @@ p5.RendererGL.prototype._getLightShader = function() { ); } } - //this.drawMode = constants.FILL; + return this._defaultLightShader; }; @@ -79752,7 +81651,7 @@ p5.RendererGL.prototype._getImmediateModeShader = function() { defaultShaders.vertexColorFrag ); } - //this.drawMode = constants.FILL; + return this._defaultImmediateModeShader; }; @@ -79764,7 +81663,7 @@ p5.RendererGL.prototype._getNormalShader = function() { defaultShaders.normalFrag ); } - //this.drawMode = constants.FILL; + return this._defaultNormalShader; }; @@ -79776,7 +81675,7 @@ p5.RendererGL.prototype._getColorShader = function() { defaultShaders.basicFrag ); } - //this.drawMode = constants.FILL; + return this._defaultColorShader; }; @@ -79799,7 +81698,7 @@ p5.RendererGL.prototype._getLineShader = function() { defaultShaders.lineFrag ); } - //this.drawMode = constants.STROKE; + return this._defaultLineShader; }; @@ -79833,13 +81732,63 @@ p5.RendererGL.prototype.getTexture = function(img) { } var tex = new p5.Texture(this, img); - this.textures.push(tex); + textures.push(tex); return tex; }; -//Binds a buffer to the drawing context -//when passed more than two arguments it also updates or initializes -//the data associated with the buffer +p5.RendererGL.prototype._setStrokeUniforms = function(strokeShader) { + strokeShader.bindShader(); + + // set the uniform values + strokeShader.setUniform('uMaterialColor', this.curStrokeColor); + strokeShader.setUniform('uStrokeWeight', this.curStrokeWeight); +}; + +p5.RendererGL.prototype._setFillUniforms = function(fillShader) { + fillShader.bindShader(); + + // TODO: optimize + fillShader.setUniform('uMaterialColor', this.curFillColor); + fillShader.setUniform('isTexture', !!this._tex); + if (this._tex) { + fillShader.setUniform('uSampler', this._tex); + } + fillShader.setUniform('uSpecular', this._useSpecularMaterial); + fillShader.setUniform('uShininess', this._useShininess); + + fillShader.setUniform('uUseLighting', this._enableLighting); + + var pointLightCount = this.pointLightColors.length / 3; + fillShader.setUniform('uPointLightCount', pointLightCount); + fillShader.setUniform('uPointLightLocation', this.pointLightPositions); + fillShader.setUniform('uPointLightColor', this.pointLightColors); + + var directionalLightCount = this.directionalLightColors.length / 3; + fillShader.setUniform('uDirectionalLightCount', directionalLightCount); + fillShader.setUniform('uLightingDirection', this.directionalLightDirections); + fillShader.setUniform('uDirectionalColor', this.directionalLightColors); + + // TODO: sum these here... + var ambientLightCount = this.ambientLightColors.length / 3; + fillShader.setUniform('uAmbientLightCount', ambientLightCount); + fillShader.setUniform('uAmbientColor', this.ambientLightColors); + fillShader.bindTextures(); +}; + +p5.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); +}; + +/* Binds a buffer to the drawing context + * when passed more than two arguments it also updates or initializes + * the data associated with the buffer + */ p5.RendererGL.prototype._bindBuffer = function( buffer, target, @@ -79854,22 +81803,6 @@ p5.RendererGL.prototype._bindBuffer = function( } }; -////////////////////////// -//// SMOOTHING -///////////////////////// - -p5.RendererGL.prototype.smooth = function() { - if (this.attributes.antialias === false) { - this._pInst.setAttributes('antialias', true); - } -}; - -p5.RendererGL.prototype.noSmooth = function() { - if (this.attributes.antialias === true) { - this._pInst.setAttributes('antialias', false); - } -}; - /////////////////////////////// //// UTILITY FUNCTIONS ////////////////////////////// @@ -79948,11 +81881,13 @@ p5.RendererGL.prototype._initTessy = function initTesselator() { polyVertArray[polyVertArray.length] = data[1]; polyVertArray[polyVertArray.length] = data[2]; } + function begincallback(type) { if (type !== libtess.primitiveType.GL_TRIANGLES) { console.log('expected TRIANGLES but got type: ' + type); } } + function errorcallback(errno) { console.log('error callback'); console.log('error number: ' + errno); @@ -79961,6 +81896,7 @@ p5.RendererGL.prototype._initTessy = function initTesselator() { function combinecallback(coords, data, weight) { return [coords[0], coords[1], coords[2]]; } + function edgeCallback(flag) { // don't really care about the flag, but need no-strip/no-fan behavior } @@ -80031,7 +81967,7 @@ p5.RendererGL.prototype._bezierToCatmull = function(w) { module.exports = p5.RendererGL; -},{"../core/constants":19,"../core/main":25,"../core/p5.Renderer":28,"./p5.Camera":70,"./p5.Matrix":72,"./p5.Shader":76,"libtess":10}],76:[function(_dereq_,module,exports){ +},{"../core/constants":18,"../core/main":24,"../core/p5.Renderer":27,"./p5.Camera":69,"./p5.Matrix":71,"./p5.Shader":75,"libtess":9}],75:[function(_dereq_,module,exports){ /** * This module defines the p5.Shader class * @module Lights, Camera @@ -80224,12 +82160,10 @@ p5.Shader.prototype.bindShader = function() { if (!this._bound) { this.useProgram(); this._bound = true; - this.bindTextures(); this._setMatrixUniforms(); - if (this === this._renderer.curStrokeShader) { - this._setViewportUniform(); - } + + this.setUniform('uViewport', this._renderer._viewport); } }; @@ -80284,16 +82218,12 @@ p5.Shader.prototype._setMatrixUniforms = function() { this.setUniform('uProjectionMatrix', this._renderer.uPMatrix.mat4); this.setUniform('uModelViewMatrix', this._renderer.uMVMatrix.mat4); this.setUniform('uViewMatrix', this._renderer._curCamera.cameraMatrix.mat4); - if (this === this._renderer.curFillShader) { + if (this.uniforms.uNormalMatrix) { this._renderer.uNMatrix.inverseTranspose(this._renderer.uMVMatrix); this.setUniform('uNormalMatrix', this._renderer.uNMatrix.mat3); } }; -p5.Shader.prototype._setViewportUniform = function() { - this.setUniform('uViewport', this._renderer._viewport); -}; - /** * @method useProgram * @chainable @@ -80323,18 +82253,14 @@ p5.Shader.prototype.setUniform = function(uniformName, data) { var uniform = this.uniforms[uniformName]; if (!uniform) { - //@todo warning? return; } + var location = uniform.location; var gl = this._renderer.GL; - // todo: is this safe to do here? - // todo: store the values another way? this.useProgram(); - // TODO BIND? - switch (uniform.type) { case gl.BOOL: if (data === true) { @@ -80427,6 +82353,7 @@ p5.Shader.prototype.setUniform = function(uniformName, data) { p5.Shader.prototype.isLightShader = function() { return ( + this.attributes.aNormal !== undefined || this.uniforms.uUseLighting !== undefined || this.uniforms.uAmbientLightCount !== undefined || this.uniforms.uDirectionalLightCount !== undefined || @@ -80482,7 +82409,7 @@ p5.Shader.prototype.enableAttrib = function( module.exports = p5.Shader; -},{"../core/main":25}],77:[function(_dereq_,module,exports){ +},{"../core/main":24}],76:[function(_dereq_,module,exports){ /** * This module defines the p5.Texture class * @module Lights, Camera @@ -80570,13 +82497,16 @@ p5.Texture.prototype._getTextureDataFromSource = function() { p5.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); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this.glWrapS); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this.glWrapT); if ( this.width === 0 || @@ -80778,7 +82708,7 @@ p5.Texture.prototype.setWrapMode = function(wrapX, wrapY) { }; var widthPowerOfTwo = isPowerOfTwo(this.width); - var heightPowerOfTwo = isPowerOfTwo(this.width); + var heightPowerOfTwo = isPowerOfTwo(this.height); if (wrapX === constants.REPEAT) { if (widthPowerOfTwo && heightPowerOfTwo) { @@ -80834,7 +82764,7 @@ p5.Texture.prototype.setWrapMode = function(wrapX, wrapY) { module.exports = p5.Texture; -},{"../core/constants":19,"../core/main":25}],78:[function(_dereq_,module,exports){ +},{"../core/constants":18,"../core/main":24}],77:[function(_dereq_,module,exports){ 'use strict'; var p5 = _dereq_('../core/main'); @@ -81462,11 +83392,9 @@ p5.RendererGL.prototype._renderText = function(p, line, x, y, maxY) { p.push(); // fix to #803 // remember this state, so it can be restored later - var curFillShader = this.curFillShader; var doStroke = this._doStroke; var drawMode = this.drawMode; - this.curFillShader = null; this._doStroke = false; this.drawMode = constants.TEXTURE; @@ -81487,7 +83415,9 @@ p5.RendererGL.prototype._renderText = function(p, line, x, y, maxY) { // initialize the font shader var gl = this.GL; var initializeShader = !this._defaultFontShader; - var sh = this.setFillShader(this._getFontShader()); + var sh = this._getFontShader(); + sh.init(); + if (initializeShader) { // these are constants, really. just initialize them one-time. sh.setUniform('uGridImageSize', [gridImageWidth, gridImageHeight]); @@ -81563,16 +83493,15 @@ p5.RendererGL.prototype._renderText = function(p, line, x, y, maxY) { // clean up sh.unbindShader(); - this.curFillShader = curFillShader; this._doStroke = doStroke; this.drawMode = drawMode; p.pop(); } - this._pInst._pixelsDirty = true; + this._pixelsState._pixelsDirty = true; return p; }; -},{"../core/constants":19,"../core/main":25,"./p5.RendererGL":75,"./p5.Shader":76}]},{},[14])(14) -}); \ No newline at end of file +},{"../core/constants":18,"../core/main":24,"./p5.RendererGL":74,"./p5.Shader":75}]},{},[13])(13) +}); diff --git a/pyp5js/static/p5/p5.min.js b/pyp5js/static/p5/p5.min.js new file mode 100644 index 00000000..27791bff --- /dev/null +++ b/pyp5js/static/p5/p5.min.js @@ -0,0 +1,3 @@ +/*! p5.js v0.8.0 April 08, 2019 */ + +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).p5=e()}}(function(){return function o(a,s,h){function l(t,e){if(!s[t]){if(!a[t]){var r="function"==typeof require&&require;if(!e&&r)return r(t,!0);if(u)return u(t,!0);var i=new Error("Cannot find module '"+t+"'");throw i.code="MODULE_NOT_FOUND",i}var n=s[t]={exports:{}};a[t][0].call(n.exports,function(e){return l(a[t][1][e]||e)},n,n.exports,o,a,s,h)}return s[t].exports}for(var u="function"==typeof require&&require,e=0;e>16&255,o[a++]=t>>8&255,o[a++]=255&t;var l,u;2===n&&(t=c[e.charCodeAt(h)]<<2|c[e.charCodeAt(h+1)]>>4,o[a++]=255&t);1===n&&(t=c[e.charCodeAt(h)]<<10|c[e.charCodeAt(h+1)]<<4|c[e.charCodeAt(h+2)]>>2,o[a++]=t>>8&255,o[a++]=255&t);return o},r.fromByteArray=function(e){for(var t,r=e.length,i=r%3,n=[],o=0,a=r-i;o>2]+s[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],n.push(s[t>>10]+s[t>>4&63]+s[t<<2&63]+"="));return n.join("")};for(var s=[],c=[],p="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=0,o=i.length;n>18&63]+s[n>>12&63]+s[n>>6&63]+s[63&n]);return o.join("")}c["-".charCodeAt(0)]=62,c["_".charCodeAt(0)]=63},{}],2:[function(e,t,r){},{}],3:[function(e,t,r){"use strict";var i=e("base64-js"),o=e("ieee754");r.Buffer=c,r.SlowBuffer=function(e){+e!=e&&(e=0);return c.alloc(+e)},r.INSPECT_MAX_BYTES=50;var n=2147483647;function a(e){if(n>>1;case"base64":return I(e).length;default:if(n)return i?-1:k(e).length;t=(""+t).toLowerCase(),n=!0}}function f(e,t,r){var i=e[t];e[t]=e[r],e[r]=i}function m(e,t,r,i,n){if(0===e.length)return-1;if("string"==typeof r?(i=r,r=0):2147483647=e.length){if(n)return-1;r=e.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof t&&(t=c.from(t,i)),c.isBuffer(t))return 0===t.length?-1:v(e,t,r,i,n);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):v(e,[t],r,i,n);throw new TypeError("val must be string, number or Buffer")}function v(e,t,r,i,n){var o,a=1,s=e.length,h=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;s/=a=2,h/=2,r/=2}function l(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(n){var u=-1;for(o=r;o>>10&1023|55296),u=56320|1023&u),i.push(u),n+=c}return function(e){var t=e.length;if(t<=x)return String.fromCharCode.apply(String,e);var r="",i=0;for(;ithis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return T(this,t,r);case"utf8":case"utf-8":return _(this,t,r);case"ascii":return w(this,t,r);case"latin1":case"binary":return S(this,t,r);case"base64":return b(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,t,r);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}.apply(this,arguments)},c.prototype.equals=function(e){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===c.compare(this,e)},c.prototype.inspect=function(){var e="",t=r.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),""},c.prototype.compare=function(e,t,r,i,n){if(O(e,Uint8Array)&&(e=c.from(e,e.offset,e.byteLength)),!c.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===i&&(i=0),void 0===n&&(n=this.length),t<0||r>e.length||i<0||n>this.length)throw new RangeError("out of range index");if(n<=i&&r<=t)return 0;if(n<=i)return-1;if(r<=t)return 1;if(this===e)return 0;for(var o=(n>>>=0)-(i>>>=0),a=(r>>>=0)-(t>>>=0),s=Math.min(o,a),h=this.slice(i,n),l=e.slice(t,r),u=0;u>>=0,isFinite(r)?(r>>>=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}var n=this.length-t;if((void 0===r||nthis.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o,a,s,h,l,u,c,p,d,f=!1;;)switch(i){case"hex":return g(this,e,t,r);case"utf8":case"utf-8":return p=t,d=r,U(k(e,(c=this).length-p),c,p,d);case"ascii":return y(this,e,t,r);case"latin1":case"binary":return y(this,e,t,r);case"base64":return h=this,l=t,u=r,U(I(e),h,l,u);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return a=t,s=r,U(function(e,t){for(var r,i,n,o=[],a=0;a>8,n=r%256,o.push(n),o.push(i);return o}(e,(o=this).length-a),o,a,s);default:if(f)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),f=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var x=4096;function w(e,t,r){var i="";r=Math.min(e.length,r);for(var n=t;ne.length)throw new RangeError("Index out of range")}function R(e,t,r,i,n,o){if(r+i>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function L(e,t,r,i,n){return t=+t,r>>>=0,n||R(e,0,r,4),o.write(e,t,r,i,23,4),r+4}function P(e,t,r,i,n){return t=+t,r>>>=0,n||R(e,0,r,8),o.write(e,t,r,i,52,8),r+8}c.prototype.slice=function(e,t){var r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):r>>=0,t>>>=0,r||E(e,t,this.length);for(var i=this[e],n=1,o=0;++o>>=0,t>>>=0,r||E(e,t,this.length);for(var i=this[e+--t],n=1;0>>=0,t||E(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return e>>>=0,t||E(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return e>>>=0,t||E(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return e>>>=0,t||E(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return e>>>=0,t||E(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||E(e,t,this.length);for(var i=this[e],n=1,o=0;++o>>=0,t>>>=0,r||E(e,t,this.length);for(var i=t,n=1,o=this[e+--i];0>>=0,t||E(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){e>>>=0,t||E(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt16BE=function(e,t){e>>>=0,t||E(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt32LE=function(e,t){return e>>>=0,t||E(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return e>>>=0,t||E(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return e>>>=0,t||E(e,4,this.length),o.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return e>>>=0,t||E(e,4,this.length),o.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return e>>>=0,t||E(e,8,this.length),o.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return e>>>=0,t||E(e,8,this.length),o.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,r,i){(e=+e,t>>>=0,r>>>=0,i)||C(this,e,t,r,Math.pow(2,8*r)-1,0);var n=1,o=0;for(this[t]=255&e;++o>>=0,r>>>=0,i)||C(this,e,t,r,Math.pow(2,8*r)-1,0);var n=r-1,o=1;for(this[t+n]=255&e;0<=--n&&(o*=256);)this[t+n]=e/o&255;return t+r},c.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,1,255,0),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},c.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeIntLE=function(e,t,r,i){if(e=+e,t>>>=0,!i){var n=Math.pow(2,8*r-1);C(this,e,t,r,n-1,-n)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+r},c.prototype.writeIntBE=function(e,t,r,i){if(e=+e,t>>>=0,!i){var n=Math.pow(2,8*r-1);C(this,e,t,r,n-1,-n)}var o=r-1,a=1,s=0;for(this[t+o]=255&e;0<=--o&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+r},c.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},c.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeFloatLE=function(e,t,r){return L(this,e,t,!0,r)},c.prototype.writeFloatBE=function(e,t,r){return L(this,e,t,!1,r)},c.prototype.writeDoubleLE=function(e,t,r){return P(this,e,t,!0,r)},c.prototype.writeDoubleBE=function(e,t,r){return P(this,e,t,!1,r)},c.prototype.copy=function(e,t,r,i){if(!c.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),0=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function I(e){return i.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(D,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function U(e,t,r,i){for(var n=0;n=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function O(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function B(e){return e!=e}},{"base64-js":1,ieee754:7}],4:[function(z,r,i){(function(G,V){var e,t;e=this,t=function(){"use strict";function l(e){return"function"==typeof e}var r=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},i=0,t=void 0,n=void 0,s=function(e,t){p[i]=e,p[i+1]=t,2===(i+=2)&&(n?n(d):y())};var e="undefined"!=typeof window?window:void 0,o=e||{},a=o.MutationObserver||o.WebKitMutationObserver,h="undefined"==typeof self&&void 0!==G&&"[object process]"==={}.toString.call(G),u="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel;function c(){var e=setTimeout;return function(){return e(d,1)}}var p=new Array(1e3);function d(){for(var e=0;e>1,u=-7,c=r?n-1:0,p=r?-1:1,d=e[t+c];for(c+=p,o=d&(1<<-u)-1,d>>=-u,u+=s;0>=-u,u+=i;0>1,p=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:o-1,f=i?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=u):(a=Math.floor(Math.log(t)/Math.LN2),t*(h=Math.pow(2,-a))<1&&(a--,h*=2),2<=(t+=1<=a+c?p/h:p*Math.pow(2,1-c))*h&&(a++,h/=2),u<=a+c?(s=0,a=u):1<=a+c?(s=(t*h-1)*Math.pow(2,n),a+=c):(s=t*Math.pow(2,c-1)*Math.pow(2,n),a=0));8<=n;e[r+d]=255&s,d+=f,s/=256,n-=8);for(a=a<Math.abs(e[0])&&(t=1),Math.abs(e[2])>Math.abs(e[t])&&(t=2),t}var C=4e150;function R(e,t){e.f+=t.f,e.b.f+=t.b.f}function l(e,t,r){return e=e.a,t=t.a,r=r.a,t.b.a===e?r.b.a===e?g(t.a,r.a)?b(r.b.a,t.a,r.a)<=0:0<=b(t.b.a,r.a,t.a):b(r.b.a,e,r.a)<=0:r.b.a===e?0<=b(t.b.a,e,t.a):(t=y(t.b.a,e,t.a),(e=y(r.b.a,e,r.a))<=t)}function L(e){e.a.i=null;var t=e.e;t.a.c=t.c,t.c.a=t.a,e.e=null}function u(e,t){c(e.a),e.c=!1,(e.a=t).i=e}function P(e){for(var t=e.a.a;(e=pe(e)).a.a===t;);return e.c&&(u(e,t=p(ce(e).a.b,e.a.e)),e=pe(e)),e}function D(e,t,r){var i=new ue;return i.a=r,i.e=W(e.f,t.e,i),r.i=i}function A(e,t){switch(e.s){case 100130:return 0!=(1&t);case 100131:return 0!==t;case 100132:return 0>1]],s[a[l]])?he(r,l):le(r,l)),s[o]=null,h[o]=r.b,r.b=o}else for(r.c[-(o+1)]=null;0Math.max(a.a,h.a))return!1;if(g(o,a)){if(0i.f&&(i.f*=2,i.c=oe(i.c,i.f+1)),0===i.b?r=n:(r=i.b,i.b=i.c[i.b]),i.e[r]=t,i.c[r]=n,i.d[n]=r,i.h&&le(i,n),r}return i=e.a++,e.c[i]=t,-(i+1)}function ie(e){if(0===e.a)return se(e.b);var t=e.c[e.d[e.a-1]];if(0!==e.b.a&&g(ae(e.b),t))return se(e.b);for(;--e.a,0e.a||g(i[a],i[h])){n[r[o]=a]=o;break}n[r[o]=h]=o,o=s}}function le(e,t){for(var r=e.d,i=e.e,n=e.c,o=t,a=r[o];;){var s=o>>1,h=r[s];if(0===s||g(i[h],i[a])){n[r[o]=a]=o;break}n[r[o]=h]=o,o=s}}function ue(){this.e=this.a=null,this.f=0,this.c=this.b=this.h=this.d=!1}function ce(e){return e.e.c.b}function pe(e){return e.e.a.b}(i=q.prototype).x=function(){Y(this,0)},i.B=function(e,t){switch(e){case 100142:return;case 100140:switch(t){case 100130:case 100131:case 100132:case 100133:case 100134:return void(this.s=t)}break;case 100141:return void(this.m=!!t);default:return void Z(this,100900)}Z(this,100901)},i.y=function(e){switch(e){case 100142:return 0;case 100140:return this.s;case 100141:return this.m;default:Z(this,100900)}return!1},i.A=function(e,t,r){this.j[0]=e,this.j[1]=t,this.j[2]=r},i.z=function(e,t){var r=t||null;switch(e){case 100100:case 100106:this.h=r;break;case 100104:case 100110:this.l=r;break;case 100101:case 100107:this.k=r;break;case 100102:case 100108:this.i=r;break;case 100103:case 100109:this.p=r;break;case 100105:case 100111:this.o=r;break;case 100112:this.r=r;break;default:Z(this,100900)}},i.C=function(e,t){var r=!1,i=[0,0,0];Y(this,2);for(var n=0;n<3;++n){var o=e[n];o<-1e150&&(o=-1e150,r=!0),1e150n[l]&&(n[l]=u,a[l]=h)}if(h=0,n[1]-o[1]>n[0]-o[0]&&(h=1),n[2]-o[2]>n[h]-o[h]&&(h=2),o[h]>=n[h])i[0]=0,i[1]=0,i[2]=1;else{for(n=0,o=s[h],a=a[h],s=[0,0,0],o=[o.g[0]-a.g[0],o.g[1]-a.g[1],o.g[2]-a.g[2]],l=[0,0,0],h=r.e;h!==r;h=h.e)l[0]=h.g[0]-a.g[0],l[1]=h.g[1]-a.g[1],l[2]=h.g[2]-a.g[2],s[0]=o[1]*l[2]-o[2]*l[1],s[1]=o[2]*l[0]-o[0]*l[2],s[2]=o[0]*l[1]-o[1]*l[0],n<(u=s[0]*s[0]+s[1]*s[1]+s[2]*s[2])&&(n=u,i[0]=s[0],i[1]=s[1],i[2]=s[2]);n<=0&&(i[0]=i[1]=i[2]=0,i[E(o)]=1)}r=!0}for(s=E(i),h=this.b.c,n=(s+1)%3,a=(s+2)%3,s=0>>=1,t}function _(e,t,r){if(!t)return r;for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>16-t;return e.tag>>>=t,e.bitcount-=t,i+r}function x(e,t){for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>=1,++n,r+=t.table[n],0<=(i-=t.table[n]););return e.tag=o,e.bitcount-=n,t.trans[r+i]}function w(e,t,r){var i,n,o,a,s,h;for(i=_(e,5,257),n=_(e,5,1),o=_(e,4,4),a=0;a<19;++a)v[a]=0;for(a=0;athis.x2&&(this.x2=e)),"number"==typeof t&&((isNaN(this.y1)||isNaN(this.y2))&&(this.y1=t,this.y2=t),tthis.y2&&(this.y2=t))},C.prototype.addX=function(e){this.addPoint(e,null)},C.prototype.addY=function(e){this.addPoint(null,e)},C.prototype.addBezier=function(e,t,r,i,n,o,a,s){var h=this,l=[e,t],u=[r,i],c=[n,o],p=[a,s];this.addPoint(e,t),this.addPoint(a,s);for(var d=0;d<=1;d++){var f=6*l[d]-12*u[d]+6*c[d],m=-3*l[d]+9*u[d]-9*c[d]+3*p[d],v=3*u[d]-3*l[d];if(0!==m){var g=Math.pow(f,2)-4*v*m;if(!(g<0)){var y=(-f+Math.sqrt(g))/(2*m);0>8&255,255&e]},I.USHORT=O(2),k.SHORT=function(e){return 32768<=e&&(e=-(65536-e)),[e>>8&255,255&e]},I.SHORT=O(2),k.UINT24=function(e){return[e>>16&255,e>>8&255,255&e]},I.UINT24=O(3),k.ULONG=function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]},I.ULONG=O(4),k.LONG=function(e){return D<=e&&(e=-(2*D-e)),[e>>24&255,e>>16&255,e>>8&255,255&e]},I.LONG=O(4),k.FIXED=k.ULONG,I.FIXED=I.ULONG,k.FWORD=k.SHORT,I.FWORD=I.SHORT,k.UFWORD=k.USHORT,I.UFWORD=I.USHORT,k.LONGDATETIME=function(e){return[0,0,0,0,e>>24&255,e>>16&255,e>>8&255,255&e]},I.LONGDATETIME=O(8),k.TAG=function(e){return P.argument(4===e.length,"Tag should be exactly 4 ASCII characters."),[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]},I.TAG=O(4),k.Card8=k.BYTE,I.Card8=I.BYTE,k.Card16=k.USHORT,I.Card16=I.USHORT,k.OffSize=k.BYTE,I.OffSize=I.BYTE,k.SID=k.USHORT,I.SID=I.USHORT,k.NUMBER=function(e){return-107<=e&&e<=107?[e+139]:108<=e&&e<=1131?[247+((e-=108)>>8),255&e]:-1131<=e&&e<=-108?[251+((e=-e-108)>>8),255&e]:-32768<=e&&e<=32767?k.NUMBER16(e):k.NUMBER32(e)},I.NUMBER=function(e){return k.NUMBER(e).length},k.NUMBER16=function(e){return[28,e>>8&255,255&e]},I.NUMBER16=O(3),k.NUMBER32=function(e){return[29,e>>24&255,e>>16&255,e>>8&255,255&e]},I.NUMBER32=O(5),k.REAL=function(e){var t=e.toString(),r=/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(t);if(r){var i=parseFloat("1e"+((r[2]?+r[2]:0)+r[1].length));t=(Math.round(e*i)/i).toString()}for(var n="",o=0,a=t.length;o>8&255,t[t.length]=255&i}return t},I.UTF16=function(e){return 2*e.length};var B={"x-mac-croatian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ","x-mac-cyrillic":"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю","x-mac-gaelic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæøṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ","x-mac-greek":"Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­","x-mac-icelandic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-inuit":"ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł","x-mac-ce":"ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ",macintosh:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-romanian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-turkish":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ"};A.MACSTRING=function(e,t,r,i){var n=B[i];if(void 0!==n){for(var o="",a=0;a>8&255,h+256&255)}return o}k.MACSTRING=function(e,t){var r=function(e){if(!N)for(var t in N={},B)N[t]=new String(t);var r=N[e];if(void 0!==r){if(F){var i=F.get(r);if(void 0!==i)return i}var n=B[e];if(void 0!==n){for(var o={},a=0;a>8,t[c+1]=255&p,t=t.concat(i[u])}return t},I.TABLE=function(e){for(var t=0,r=e.fields.length,i=0;i>1,t.skip("uShort",3),e.glyphIndexMap={};for(var a=new se.Parser(r,i+n+14),s=new se.Parser(r,i+n+16+2*o),h=new se.Parser(r,i+n+16+4*o),l=new se.Parser(r,i+n+16+6*o),u=i+n+16+8*o,c=0;c>4,o=15&i;if(15===n)break;if(t+=r[n],15===o)break;t+=r[o]}return parseFloat(t)}(e);if(32<=t&&t<=246)return t-139;if(247<=t&&t<=250)return 256*(t-247)+e.parseByte()+108;if(251<=t&&t<=254)return 256*-(t-251)-e.parseByte()-108;throw new Error("Invalid b0 "+t)}function Ee(e,t,r){t=void 0!==t?t:0;var i=new se.Parser(e,t),n=[],o=[];for(r=void 0!==r?r:e.length;i.relativeOffset>1,E.length=0,R=!0}return function e(t){for(var r,i,n,o,a,s,h,l,u,c,p,d,f=0;fMath.abs(d-D)?P=p+E.shift():D=d+E.shift(),M.curveTo(y,b,_,x,h,l),M.curveTo(u,c,p,d,P,D);break;default:console.log("Glyph "+g.index+": unknown operator 1200"+m),E.length=0}break;case 14:0>3;break;case 21:2>16),f+=2;break;case 29:a=E.pop()+v.gsubrsBias,(s=v.gsubrs[a])&&e(s);break;case 30:for(;0=r.begin&&e=pe.length){var a=i.parseChar();r.names.push(i.parseString(a))}break;case 2.5:r.numberOfGlyphs=i.parseUShort(),r.offset=new Array(r.numberOfGlyphs);for(var s=0;st.value.tag?1:-1}),t.fields=t.fields.concat(i),t.fields=t.fields.concat(n),t}function vt(e,t,r){for(var i=0;i 123 are reserved for internal usage");d|=1<>>1,o=e[n].tag;if(o===t)return n;o>>1,o=e[n];if(o===t)return n;o>>1,a=(r=e[o]).start;if(a===t)return r;a(r=e[i-1]).end?0:r}function xt(e,t){this.font=e,this.tableName=t}function wt(e){xt.call(this,e,"gpos")}function St(e){xt.call(this,e,"gsub")}function Tt(e,t){var r=e.length;if(r!==t.length)return!1;for(var i=0;it.points.length-1||i.matchedPoints[1]>n.points.length-1)throw Error("Matched points out of range in "+t.name);var a=t.points[i.matchedPoints[0]],s=n.points[i.matchedPoints[1]],h={xScale:i.xScale,scale01:i.scale01,scale10:i.scale10,yScale:i.yScale,dx:0,dy:0};s=Pt([s],h)[0],h.dx=a.x-s.x,h.dy=a.y-s.y,o=Pt(n.points,h)}t.points=t.points.concat(o)}}return Dt(t.points)}(wt.prototype=xt.prototype={searchTag:yt,binSearch:bt,getTable:function(e){var t=this.font.tables[this.tableName];return!t&&e&&(t=this.font.tables[this.tableName]=this.createDefaultTable()),t},getScriptNames:function(){var e=this.getTable();return e?e.scripts.map(function(e){return e.tag}):[]},getDefaultScriptName:function(){var e=this.getTable();if(e){for(var t=!1,r=0;r=s[l-1].tag,"Features must be added in alphabetical order."),o={tag:r,feature:{params:0,lookupListIndexes:[]}},s.push(o),a.push(l),o.feature}}},getLookupTables:function(e,t,r,i,n){var o=this.getFeatureTable(e,t,r,n),a=[];if(o){for(var s,h=o.lookupListIndexes,l=this.font.tables[this.tableName].lookups,u=0;u",s),t.stack.push(Math.round(64*s))}function gr(e,t){var r=t.stack,i=r.pop(),n=t.fv,o=t.pv,a=t.ppem,s=t.deltaBase+16*(e-1),h=t.deltaShift,l=t.z0;M.DEBUG&&console.log(t.step,"DELTAP["+e+"]",i,r);for(var u=0;u>4)===a){var d=(15&p)-8;0<=d&&d++,M.DEBUG&&console.log(t.step,"DELTAPFIX",c,"by",d*h);var f=l[c];n.setRelative(f,f,d*h,o)}}}function yr(e,t){var r=t.stack,i=r.pop();M.DEBUG&&console.log(t.step,"ROUND[]"),r.push(64*t.round(i/64))}function br(e,t){var r=t.stack,i=r.pop(),n=t.ppem,o=t.deltaBase+16*(e-1),a=t.deltaShift;M.DEBUG&&console.log(t.step,"DELTAC["+e+"]",i,r);for(var s=0;s>4)===n){var u=(15&l)-8;0<=u&&u++;var c=u*a;M.DEBUG&&console.log(t.step,"DELTACFIX",h,"by",c),t.cvt[h]+=c}}}function _r(e,t){var r,i,n=t.stack,o=n.pop(),a=n.pop(),s=t.z2[o],h=t.z1[a];M.DEBUG&&console.log(t.step,"SDPVTL["+e+"]",o,a),i=e?(r=s.y-h.y,h.x-s.x):(r=h.x-s.x,h.y-s.y),t.dpv=Zt(r,i)}function xr(e,t){var r=t.stack,i=t.prog,n=t.ip;M.DEBUG&&console.log(t.step,"PUSHB["+e+"]");for(var o=0;o":"_")+(i?"R":"_")+(0===n?"Gr":1===n?"Bl":2===n?"Wh":"")+"]",e?c+"("+o.cvt[c]+","+l+")":"",p,"(d =",a,"->",h*s,")"),o.rp1=o.rp0,o.rp2=p,t&&(o.rp0=p)}Nt.prototype.exec=function(e,t){if("number"!=typeof t)throw new Error("Point size is not a number!");if(!(2",i),s.interpolate(c,o,a,h),s.touch(c)}e.loop=1},dr.bind(void 0,0),dr.bind(void 0,1),function(e){for(var t=e.stack,r=e.rp0,i=e.z0[r],n=e.loop,o=e.fv,a=e.pv,s=e.z1;n--;){var h=t.pop(),l=s[h];M.DEBUG&&console.log(e.step,(1=a.width||t>=a.height?[0,0,0,0]:this._getPixel(e,t);var s=new h.Image(r,i);return s.canvas.getContext("2d").drawImage(a,e,t,r*o,i*o,0,0,r,i),s},h.Renderer.prototype.textLeading=function(e){return"number"==typeof e?(this._setProperty("_textLeading",e),this._pInst):this._textLeading},h.Renderer.prototype.textSize=function(e){return"number"==typeof e?(this._setProperty("_textSize",e),this._setProperty("_textLeading",e*y._DEFAULT_LEADMULT),this._applyTextProperties()):this._textSize},h.Renderer.prototype.textStyle=function(e){return e?(e!==y.NORMAL&&e!==y.ITALIC&&e!==y.BOLD&&e!==y.BOLDITALIC||this._setProperty("_textStyle",e),this._applyTextProperties()):this._textStyle},h.Renderer.prototype.textAscent=function(){return null===this._textAscent&&this._updateTextMetrics(),this._textAscent},h.Renderer.prototype.textDescent=function(){return null===this._textDescent&&this._updateTextMetrics(),this._textDescent},h.Renderer.prototype.textAlign=function(e,t){return void 0!==e?(this._setProperty("_textAlign",e),void 0!==t&&this._setProperty("_textBaseline",t),this._applyTextProperties()):{horizontal:this._textAlign,vertical:this._textBaseline}},h.Renderer.prototype.text=function(e,t,r,i,n){var o,a,s,h,l,u,c,p,d=this._pInst,f=Number.MAX_VALUE;if((this._doFill||this._doStroke)&&void 0!==e){if("string"!=typeof e&&(e=e.toString()),o=(e=e.replace(/(\t)/g," ")).split("\n"),void 0!==i){for(s=p=0;sa.HALF_PI&&e<=3*a.HALF_PI?Math.atan(r/i*Math.tan(e))+a.PI:Math.atan(r/i*Math.tan(e))+a.TWO_PI,t=t<=a.HALF_PI?Math.atan(r/i*Math.tan(t)):t>a.HALF_PI&&t<=3*a.HALF_PI?Math.atan(r/i*Math.tan(t))+a.PI:Math.atan(r/i*Math.tan(t))+a.TWO_PI),t_||Math.abs(this.accelerationY-this.pAccelerationY)>_||Math.abs(this.accelerationZ-this.pAccelerationZ)>_)&&e();var t=this.deviceTurned||window.deviceTurned;if("function"==typeof t){var r=this.rotationX+180,i=this.pRotationX+180,n=f+180;0>>24],i+=x[(16711680&C)>>16],n+=x[(65280&C)>>8],o+=x[255&C],r+=P[_],s++}w[h=E+y]=a/r,S[h]=i/r,T[h]=n/r,M[h]=o/r}E+=d}for(u=(l=-R)*d,b=E=0;b>>16,e[r+1]=(65280&t[i])>>>8,e[r+2]=255&t[i],e[r+3]=(4278190080&t[i])>>>24},A._toImageData=function(e){return e instanceof ImageData?e:e.getContext("2d").getImageData(0,0,e.width,e.height)},A._createImageData=function(e,t){return A._tmpCanvas=document.createElement("canvas"),A._tmpCtx=A._tmpCanvas.getContext("2d"),this._tmpCtx.createImageData(e,t)},A.apply=function(e,t,r){var i=e.getContext("2d"),n=i.getImageData(0,0,e.width,e.height),o=t(n,r);o instanceof ImageData?i.putImageData(o,0,0,0,0,e.width,e.height):i.putImageData(n,0,0,0,0,e.width,e.height)},A.threshold=function(e,t){var r=A._toPixels(e);void 0===t&&(t=.5);for(var i=Math.floor(255*t),n=0;n>8)/i,r[n+1]=255*(a*t>>8)/i,r[n+2]=255*(s*t>>8)/i}},A.dilate=function(e){for(var t,r,i,n,o,a,s,h,l,u,c,p,d,f,m,v,g,y=A._toPixels(e),b=0,_=y.length?y.length/4:0,x=new Int32Array(_);b<_;)for(r=(t=b)+e.width;b>16&255)+151*(i>>8&255)+28*(255&i))<(m=77*(c>>16&255)+151*(c>>8&255)+28*(255&c))&&(n=c,o=m),o<(f=77*((u=A._getARGB(y,a))>>16&255)+151*(u>>8&255)+28*(255&u))&&(n=u,o=f),o<(v=77*(p>>16&255)+151*(p>>8&255)+28*(255&p))&&(n=p,o=v),o<(g=77*(d>>16&255)+151*(d>>8&255)+28*(255&d))&&(n=d,o=g),x[b++]=n;A._setPixels(y,x)},A.erode=function(e){for(var t,r,i,n,o,a,s,h,l,u,c,p,d,f,m,v,g,y=A._toPixels(e),b=0,_=y.length?y.length/4:0,x=new Int32Array(_);b<_;)for(r=(t=b)+e.width;b>16&255)+151*(c>>8&255)+28*(255&c))<(o=77*(i>>16&255)+151*(i>>8&255)+28*(255&i))&&(n=c,o=m),(f=77*((u=A._getARGB(y,a))>>16&255)+151*(u>>8&255)+28*(255&u))>16&255)+151*(p>>8&255)+28*(255&p))>16&255)+151*(d>>8&255)+28*(255&d))/g,">").replace(/"/g,""").replace(/'/g,"'")}function h(e,t){t&&!0!==t&&"true"!==t||(t=""),e||(e="untitled");var r="";return e&&-1"),n.print("");if('="text/html;charset=utf-8" />',n.print(' '),n.print(""),n.print(""),n.print(" "),"0"!==o[0]){n.print(" ");for(var u=0;u"+c),n.print(" ")}n.print(" ")}for(var p=0;p");for(var d=0;d"+f),n.print(" ")}n.print(" ")}n.print("
"),n.print(""),n.print("")}n.close(),n.clear()},v.prototype.writeFile=function(e,t,r){var i="application/octet-stream";v.prototype._isSafari()&&(i="text/plain");var n=new Blob(e,{type:i});v.prototype.downloadFile(n,t,r)},v.prototype.downloadFile=function(e,t,r){var i=h(t,r),n=i[0];if(e instanceof Blob){s("file-saver").saveAs(e,n)}else{var o=document.createElement("a");if(o.href=e,o.download=n,o.onclick=function(e){var t;t=e,document.body.removeChild(t.target),e.stopPropagation()},o.style.display="none",document.body.appendChild(o),v.prototype._isSafari()){var a="Hello, Safari user! To download this file...\n";a+="1. Go to File --\x3e Save As.\n",a+='2. Choose "Page Source" as the Format.\n',a+='3. Name it with this extension: ."'+i[1]+'"',alert(a)}o.click()}},v.prototype._checkFileExtension=h,v.prototype._isSafari=function(){return 0>>0},getSeed:function(){return t},rand:function(){return(r=(1664525*r+1013904223)%i)/i}});n.setSeed(e),b=new Array(4096);for(var o=0;o<4096;o++)b[o]=n.rand()},t.exports=i},{"../core/main":23}],53:[function(e,t,r){"use strict";var s=e("../core/main"),o=e("../core/constants");s.Vector=function(){var e,t,r;r=arguments[0]instanceof s?(this.p5=arguments[0],e=arguments[1][0]||0,t=arguments[1][1]||0,arguments[1][2]||0):(e=arguments[0]||0,t=arguments[1]||0,arguments[2]||0),this.x=e,this.y=t,this.z=r},s.Vector.prototype.toString=function(){return"p5.Vector Object : ["+this.x+", "+this.y+", "+this.z+"]"},s.Vector.prototype.set=function(e,t,r){return e instanceof s.Vector?(this.x=e.x||0,this.y=e.y||0,this.z=e.z||0):e instanceof Array?(this.x=e[0]||0,this.y=e[1]||0,this.z=e[2]||0):(this.x=e||0,this.y=t||0,this.z=r||0),this},s.Vector.prototype.copy=function(){return this.p5?new s.Vector(this.p5,[this.x,this.y,this.z]):new s.Vector(this.x,this.y,this.z)},s.Vector.prototype.add=function(e,t,r){return e instanceof s.Vector?(this.x+=e.x||0,this.y+=e.y||0,this.z+=e.z||0):e instanceof Array?(this.x+=e[0]||0,this.y+=e[1]||0,this.z+=e[2]||0):(this.x+=e||0,this.y+=t||0,this.z+=r||0),this},s.Vector.prototype.sub=function(e,t,r){return e instanceof s.Vector?(this.x-=e.x||0,this.y-=e.y||0,this.z-=e.z||0):e instanceof Array?(this.x-=e[0]||0,this.y-=e[1]||0,this.z-=e[2]||0):(this.x-=e||0,this.y-=t||0,this.z-=r||0),this},s.Vector.prototype.mult=function(e){return"number"==typeof e&&isFinite(e)?(this.x*=e,this.y*=e,this.z*=e):console.warn("p5.Vector.prototype.mult:","n is undefined or not a finite number"),this},s.Vector.prototype.div=function(e){return"number"==typeof e&&isFinite(e)?0===e?console.warn("p5.Vector.prototype.div:","divide by 0"):(this.x/=e,this.y/=e,this.z/=e):console.warn("p5.Vector.prototype.div:","n is undefined or not a finite number"),this},s.Vector.prototype.mag=function(){return Math.sqrt(this.magSq())},s.Vector.prototype.magSq=function(){var e=this.x,t=this.y,r=this.z;return e*e+t*t+r*r},s.Vector.prototype.dot=function(e,t,r){return e instanceof s.Vector?this.dot(e.x,e.y,e.z):this.x*(e||0)+this.y*(t||0)+this.z*(r||0)},s.Vector.prototype.cross=function(e){var t=this.y*e.z-this.z*e.y,r=this.z*e.x-this.x*e.z,i=this.x*e.y-this.y*e.x;return this.p5?new s.Vector(this.p5,[t,r,i]):new s.Vector(t,r,i)},s.Vector.prototype.dist=function(e){return e.copy().sub(this).mag()},s.Vector.prototype.normalize=function(){var e=this.mag();return 0!==e&&this.mult(1/e),this},s.Vector.prototype.limit=function(e){var t=this.magSq();return e*e>>0},getSeed:function(){return i},rand:function(){return(n=(1664525*n+1013904223)%o)/o}});a.prototype.randomSeed=function(e){u.setSeed(e),h=!(s=!0)},a.prototype.random=function(e,t){var r;if(r=s?u.rand():Math.random(),void 0===e)return r;if(void 0===t)return e instanceof Array?e[Math.floor(r*e.length)]:r*e;if(tg){var R=p,L=h,P=l;p=c+g*(s&&c=t&&(r=r.substring(r.length-t,r.length)),r}},i.prototype.unhex=function(e){return e instanceof Array?e.map(i.prototype.unhex):parseInt("0x"+e,16)},t.exports=i},{"../core/main":23}],61:[function(e,t,r){"use strict";var a=e("../core/main");function i(e,t,r){var i=e<0,n=i?e.toString().substring(1):e.toString(),o=n.indexOf("."),a=-1!==o?n.substring(0,o):n,s=-1!==o?n.substring(o+1):"",h=i?"-":"";if(void 0!==r){var l="";(-1!==o||0r&&(s=s.substring(0,r));for(var u=0;ui.length)for(var o=t-(i+=-1===r?".":"").length+1,a=0;a=d.TWO_PI?(t="ellipse")+"|"+u+"|":(t="arc")+"|"+s+"|"+h+"|"+l+"|"+u+"|",!this.geometryInHash(r)){var c=new E.Geometry(u,1,function(){if(this.strokeIndices=[],s.toFixed(10)!==h.toFixed(10)){l!==d.PIE&&void 0!==l||(this.vertices.push(new E.Vector(.5,.5,0)),this.uvs.push([.5,.5]));for(var e=0;e<=u;e++){var t=e/u*(h-s)+s,r=.5+Math.cos(t)/2,i=.5+Math.sin(t)/2;this.vertices.push(new E.Vector(r,i,0)),this.uvs.push([r,i]),eMath.PI?h=Math.PI:h<=0&&(h=.001);var l=Math.sin(h)*a*Math.sin(s),u=Math.cos(h)*a,c=Math.sin(h)*a*Math.cos(s);this.camera(l+this.centerX,u+this.centerY,c+this.centerZ,this.centerX,this.centerY,this.centerZ,0,1,0)},m.Camera.prototype._isActive=function(){return this===this._renderer._curCamera},m.prototype.setCamera=function(e){this._renderer._curCamera=e,this._renderer.uPMatrix.set(e.projMatrix.mat4[0],e.projMatrix.mat4[1],e.projMatrix.mat4[2],e.projMatrix.mat4[3],e.projMatrix.mat4[4],e.projMatrix.mat4[5],e.projMatrix.mat4[6],e.projMatrix.mat4[7],e.projMatrix.mat4[8],e.projMatrix.mat4[9],e.projMatrix.mat4[10],e.projMatrix.mat4[11],e.projMatrix.mat4[12],e.projMatrix.mat4[13],e.projMatrix.mat4[14],e.projMatrix.mat4[15])},t.exports=m.Camera},{"../core/main":23}],69:[function(e,t,r){"use strict";var u=e("../core/main");u.Geometry=function(e,t,r){return this.vertices=[],this.lineVertices=[],this.lineNormals=[],this.vertexNormals=[],this.faces=[],this.uvs=[],this.edges=[],this.detailX=void 0!==e?e:1,this.detailY=void 0!==t?t:1,r instanceof Function&&r.call(this),this},u.Geometry.prototype.computeFaces=function(){this.faces.length=0;for(var e,t,r,i,n=this.detailX+1,o=0;othis.vertices.length-1-this.detailX;t--)e.add(this.vertexNormals[t]);for(e=u.Vector.div(e,this.detailX),t=this.vertices.length-1;t>this.vertices.length-1-this.detailX;t--)this.vertexNormals[t]=e;return this},u.Geometry.prototype._makeTriangleEdges=function(){if(this.edges.length=0,Array.isArray(this.strokeIndices))for(var e=0,t=this.strokeIndices.length;e>7,127&p,c>>7,127&c);for(var d=0;d>7,127&f,0,0)}}return{cellImageInfo:h,dimOffset:o,dimImageInfo:n}}return(t=this.glyphInfos[e.index]={glyph:e,uGlyphRect:[i.x1,-i.y1,i.x2,-i.y2],strokeImageInfo:A,strokes:d,colInfo:O(m,this.colDimImageInfos,this.colCellImageInfos),rowInfo:O(f,this.rowDimImageInfos,this.rowCellImageInfos)}).uGridOffset=[t.colInfo.dimOffset,t.rowInfo.dimOffset],t}};B.RendererGL.prototype._renderText=function(e,t,r,i,n){if(!(n<=i)&&this._doFill){if(!this._isOpenType())return console.log("WEBGL: only opentype fonts are supported"),e;e.push();var o=this._doStroke,a=this.drawMode;this._doStroke=!1,this.drawMode=M.TEXTURE;var s=this._textFont.font,h=this._textFont._fontInfo;h||(h=this._textFont._fontInfo=new E(s));var l=this._textFont._handleAlignment(this,t,r,i),u=this._textSize/s.unitsPerEm;this.translate(l.x,l.y,0),this.scale(u,u,1);var c=this.GL,p=!this._defaultFontShader,d=this._getFontShader();d.init(),p&&(d.setUniform("uGridImageSize",[64,64]),d.setUniform("uCellsImageSize",[64,64]),d.setUniform("uStrokeImageSize",[64,64]),d.setUniform("uGridSize",[9,9])),this._applyColorBlend(this.curFillColor);var f=this.gHash.glyph;if(!f){var m=this._textGeom=new B.Geometry(1,1,function(){for(var e=0;e<=1;e++)for(var t=0;t<=1;t++)this.vertices.push(new B.Vector(t,e,0)),this.uvs.push(t,e)});m.computeFaces().computeNormals(),f=this.createBuffers("glyph",m)}this._bindBuffer(f.vertexBuffer,c.ARRAY_BUFFER),d.enableAttrib(d.attributes.aPosition.location,3,c.FLOAT,!1,0,0),this._bindBuffer(f.indexBuffer,c.ELEMENT_ARRAY_BUFFER),this._bindBuffer(f.uvBuffer,c.ARRAY_BUFFER),d.enableAttrib(d.attributes.aTexCoord.location,2,c.FLOAT,!1,0,0),d.setUniform("uMaterialColor",this.curFillColor);try{for(var v=0,g=null,y=!1,b=s.stringToGlyphs(t),_=0;_ Date: Sun, 2 Jun 2019 15:40:22 -0300 Subject: [PATCH 24/32] Respect new directory structure --- pyp5js/fs.py | 2 +- tests/test_fs.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pyp5js/fs.py b/pyp5js/fs.py index 98de70ad..09af584e 100644 --- a/pyp5js/fs.py +++ b/pyp5js/fs.py @@ -105,7 +105,7 @@ def index_html(self): @property def p5js(self): - return self.static_dir.child('p5.js') + return self.static_dir.child('p5', 'p5.min.js') @property def p5_yml(self): diff --git a/tests/test_fs.py b/tests/test_fs.py index e893fa90..b5eabcb5 100644 --- a/tests/test_fs.py +++ b/tests/test_fs.py @@ -41,7 +41,7 @@ def test_files_properties(lib_files): assert lib_files.index_html == pyp5_dir.child('templates', 'index.html') assert lib_files.index_html.exists() - assert lib_files.p5js == pyp5_dir.child('static', 'p5.js') + assert lib_files.p5js == pyp5_dir.child('static', 'p5', 'p5.min.js') assert lib_files.p5js.exists() assert lib_files.p5_yml == pyp5_dir.child('assets', 'p5_reference.yml') From 1bbc61c13a771d02c89560a9d23b247d8b0e20c7 Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sun, 2 Jun 2019 15:41:19 -0300 Subject: [PATCH 25/32] Copy p5.dom.js when creating new sketch --- pyp5js/commands.py | 4 ++-- pyp5js/fs.py | 8 ++++++++ tests/test_fs.py | 4 ++++ 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/pyp5js/commands.py b/pyp5js/commands.py index fe6fc772..6933c1ef 100644 --- a/pyp5js/commands.py +++ b/pyp5js/commands.py @@ -31,10 +31,10 @@ def new_sketch(sketch_name, sketch_dir): pyp5js_files = Pyp5jsLibFiles() templates_files = [ (pyp5js_files.base_sketch, sketch_files.sketch_py), - (pyp5js_files.p5js, sketch_files.p5js) + (pyp5js_files.p5js, sketch_files.p5js), + (pyp5js_files.p5_dom_js, sketch_files.p5_dom_js), ] - os.makedirs(sketch_files.sketch_dir) os.mkdir(sketch_files.static_dir) for src, dest in templates_files: diff --git a/pyp5js/fs.py b/pyp5js/fs.py index 09af584e..f62a0da5 100644 --- a/pyp5js/fs.py +++ b/pyp5js/fs.py @@ -42,6 +42,10 @@ def index_html(self): def p5js(self): return self.static_dir.child('p5.js') + @property + def p5_dom_js(self): + return self.static_dir.child('p5.dom.js') + @property def target_sketch(self): return self.sketch_dir.child("target_sketch.py") @@ -107,6 +111,10 @@ def index_html(self): def p5js(self): return self.static_dir.child('p5', 'p5.min.js') + @property + def p5_dom_js(self): + return self.static_dir.child('p5', 'addons', 'p5.dom.min.js') + @property def p5_yml(self): return self.assets_dir.child('p5_reference.yml') diff --git a/tests/test_fs.py b/tests/test_fs.py index b5eabcb5..7e5a1c9e 100644 --- a/tests/test_fs.py +++ b/tests/test_fs.py @@ -44,6 +44,9 @@ def test_files_properties(lib_files): assert lib_files.p5js == pyp5_dir.child('static', 'p5', 'p5.min.js') assert lib_files.p5js.exists() + assert lib_files.p5_dom_js == pyp5_dir.child('static', 'p5', 'addons', 'p5.dom.min.js') + assert lib_files.p5_dom_js.exists() + assert lib_files.p5_yml == pyp5_dir.child('assets', 'p5_reference.yml') assert lib_files.p5_yml.exists() @@ -86,6 +89,7 @@ def test_sketch_files(self): self.files.check_sketch_dir = False assert Path(self.sketch_name).child('index.html') == self.files.index_html assert Path(self.sketch_name).child('static', 'p5.js') == self.files.p5js + assert Path(self.sketch_name).child('static', 'p5.dom.js') == self.files.p5_dom_js assert Path(self.sketch_name).child('foo.py') == self.files.sketch_py assert Path(self.sketch_name).child('target_sketch.py') == self.files.target_sketch From 2aff3d22b270d4faa2e660630eac91cc4771f9db Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sun, 2 Jun 2019 15:41:46 -0300 Subject: [PATCH 26/32] Implement function to dynamically load p5.dom.js when called --- pyp5js/pytop5js.py | 22 +++++++++++++++++++++- pyp5js/templates/pytop5js.py.template | 20 ++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/pyp5js/pytop5js.py b/pyp5js/pytop5js.py index fbabc1ee..22af949d 100644 --- a/pyp5js/pytop5js.py +++ b/pyp5js/pytop5js.py @@ -1115,4 +1115,24 @@ def sketch_setup(p5_sketch): for f_name in [f for f in event_function_names if event_functions.get(f, None)]: func = event_functions[f_name] event_func = global_p5_injection(instance)(func) - setattr(instance, f_name, event_func) \ No newline at end of file + setattr(instance, f_name, event_func) + + +def logOnloaded(): + console.log("Lib loaded!") + + +def add_library(lib_name): + src = '' + + if lib_name == 'p5.dom.js': + src = "static/p5.dom.js" + else: + console.log("Lib name is not valid: " + lib_name) + return + + console.log("Importing: " + src) + script = document.createElement("script") + script.onload = logOnloaded + script.src = src + document.head.appendChild(script) \ No newline at end of file diff --git a/pyp5js/templates/pytop5js.py.template b/pyp5js/templates/pytop5js.py.template index 5c2d1494..b2686f0b 100644 --- a/pyp5js/templates/pytop5js.py.template +++ b/pyp5js/templates/pytop5js.py.template @@ -73,3 +73,23 @@ def start_p5(setup_func, draw_func, event_functions): func = event_functions[f_name] event_func = global_p5_injection(instance)(func) setattr(instance, f_name, event_func) + + +def logOnloaded(): + console.log("Lib loaded!") + + +def add_library(lib_name): + src = '' + + if lib_name == 'p5.dom.js': + src = "static/p5.dom.js" + else: + console.log("Lib name is not valid: " + lib_name) + return + + console.log("Importing: " + src) + script = document.createElement("script") + script.onload = logOnloaded + script.src = src + document.head.appendChild(script) From 259e0837eb603e8ad9eabc06844a09214e017158 Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sun, 2 Jun 2019 15:49:32 -0300 Subject: [PATCH 27/32] Display the index.html path after creating new sketch too --- pyp5js/cli.py | 4 +++- pyp5js/commands.py | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/pyp5js/cli.py b/pyp5js/cli.py index b7957a31..acad6799 100755 --- a/pyp5js/cli.py +++ b/pyp5js/cli.py @@ -29,7 +29,7 @@ def configure_new_sketch(sketch_name, sketch_dir, monitor): Example: $ pyp5js new my_sketch """ - sketch_py = commands.new_sketch(sketch_name, sketch_dir) + sketch_py, index_html = commands.new_sketch(sketch_name, sketch_dir) cprint.ok(f"Your sketch was created!") @@ -39,8 +39,10 @@ def configure_new_sketch(sketch_name, sketch_dir, monitor): if sketch_dir: cmd += f" --sketch-dir {sketch_dir}" cprint.ok(cmd) + cprint.ok(f"And open {index_html.absolute()} on your browser to see yor results!") else: cprint.ok(f"Please, open and edit the file {sketch_py} to draw.") + cprint.ok(f"And open {index_html.absolute()} on your browser to see yor results!") commands.monitor_sketch(sketch_name, sketch_dir) diff --git a/pyp5js/commands.py b/pyp5js/commands.py index 6933c1ef..3a1fbfd0 100644 --- a/pyp5js/commands.py +++ b/pyp5js/commands.py @@ -44,7 +44,7 @@ def new_sketch(sketch_name, sketch_dir): with open(sketch_files.index_html, "w") as fd: fd.write(index_contet) - return sketch_files.sketch_py + return sketch_files.sketch_py, sketch_files.index_html def transcrypt_sketch(sketch_name, sketch_dir): From f6e370abfcf5a9ef5221485608a7e41340bf897e Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sun, 2 Jun 2019 16:12:39 -0300 Subject: [PATCH 28/32] Add example --- docs/examples/index.md | 6 +- docs/examples/sketch_008/index.html | 97 + docs/examples/sketch_008/sketch_008.py | 42 + docs/examples/sketch_008/static/p5.dom.js | 3 + docs/examples/sketch_008/static/p5.js | 3 + .../target/org.transcrypt.__runtime__.js | 2122 +++++++++++++++++ .../target/org.transcrypt.__runtime__.py | 285 +++ docs/examples/sketch_008/target/pytop5js.js | 1365 +++++++++++ docs/examples/sketch_008/target/pytop5js.py | 1138 +++++++++ docs/examples/sketch_008/target/sketch_008.js | 34 + docs/examples/sketch_008/target/sketch_008.py | 42 + .../sketch_008/target/target_sketch.js | 9 + .../sketch_008/target/target_sketch.options | Bin 0 -> 607 bytes .../sketch_008/target/target_sketch.py | 24 + 14 files changed, 5168 insertions(+), 2 deletions(-) create mode 100644 docs/examples/sketch_008/index.html create mode 100644 docs/examples/sketch_008/sketch_008.py create mode 100644 docs/examples/sketch_008/static/p5.dom.js create mode 100644 docs/examples/sketch_008/static/p5.js create mode 100644 docs/examples/sketch_008/target/org.transcrypt.__runtime__.js create mode 100644 docs/examples/sketch_008/target/org.transcrypt.__runtime__.py create mode 100644 docs/examples/sketch_008/target/pytop5js.js create mode 100644 docs/examples/sketch_008/target/pytop5js.py create mode 100644 docs/examples/sketch_008/target/sketch_008.js create mode 100644 docs/examples/sketch_008/target/sketch_008.py create mode 100644 docs/examples/sketch_008/target/target_sketch.js create mode 100644 docs/examples/sketch_008/target/target_sketch.options create mode 100644 docs/examples/sketch_008/target/target_sketch.py diff --git a/docs/examples/index.md b/docs/examples/index.md index f884553a..f4c3347c 100644 --- a/docs/examples/index.md +++ b/docs/examples/index.md @@ -1,16 +1,18 @@ ### Examples list -- [sketch_001](https://github.com/berinhard/pyp5js/tree/develop/docs/examples/sketch_001): [**Angles and mouse coordinates**](sketch_001/index.html) +- [sketch_001](https://github.com/berinhard/pyp5js/tree/develop/docs/examples/sketch_001): [**Angles and mouse coordinates**](sketch_001/index.html) - [sketch_002](https://github.com/berinhard/pyp5js/tree/develop/docs/examples/sketch_002): [**Move Eye**](sketch_002/index.html), an example by Simon Greenwold, ported by [@villares](https://github.com/villares) - [sketch_004](https://github.com/berinhard/pyp5js/tree/develop/docs/examples/sketch_004): [**Rotating 3D box**](sketch_003/index.html) - [sketch_004](https://github.com/berinhard/pyp5js/tree/develop/docs/examples/sketch_004): [**Boids**](sketch_004/index.html) -, from [@esperanc](https://github.com/esperanc) [BrythonIDE examples](https://github.com/esperanc/brythonide/blob/master/demoSketches/boids.py) +, from [@esperanc](https://github.com/esperanc) [BrythonIDE examples](https://github.com/esperanc/brythonide/blob/master/demoSketches/boids.py) - [sketch_005](https://github.com/berinhard/pyp5js/tree/develop/docs/examples/sketch_005): [**Globals variables (HSB and CENTER)**](sketch_005/index.html) - [sketch_006](https://github.com/berinhard/pyp5js/tree/develop/docs/examples/sketch_006): [**Registering event functions such as keyPressed**](sketch_006/index.html) - [sketch_007](https://github.com/berinhard/pyp5js/tree/develop/docs/examples/sketch_007): [**p5.Vector static methods**](sketch_007/index.html) + +- [sketch_008](https://github.com/berinhard/pyp5js/tree/develop/docs/examples/sketch_008): [**p5.dom.js usage**](sketch_008/index.html) diff --git a/docs/examples/sketch_008/index.html b/docs/examples/sketch_008/index.html new file mode 100644 index 00000000..06cc2dac --- /dev/null +++ b/docs/examples/sketch_008/index.html @@ -0,0 +1,97 @@ + + + + + + + + + sketch_008 - pyp5js + + + + + + + + + + + + + +

+ Python code here. +

+ + +
+
+ +
+ +
+           
+from pytop5js import *
+
+
+add_library("p5.dom.js")
+
+
+rect_base_size = 30
+positions = []
+rect_offset = None
+
+def setup():
+    global rect_offset
+
+    createP("Hi! This is an example of how to use p5.dom.js with pyp5js")
+
+    # creates a container div
+    slider_div = createDiv()
+    slider_div.style("display", "block")
+
+    # creates the slider
+    rect_offset = createSlider(0, 600, 100)
+    rect_offset.style('width', '50%')
+
+    # adds the slider to the container div
+    slider_div.child(rect_offset)
+
+    createCanvas(600, 600)
+
+    for x in range(-rect_base_size, width + rect_base_size, rect_base_size):
+        for y in range(-rect_base_size, height + rect_base_size, rect_base_size):
+            positions.append((x, y))
+
+    noFill()
+    strokeWeight(2)
+    rectMode(CENTER)
+
+
+def draw():
+    background(255)
+    size = rect_offset.value()
+    for x, y in positions:
+        rect(x, y, size, size)
+           
+        
+ +
+ + + diff --git a/docs/examples/sketch_008/sketch_008.py b/docs/examples/sketch_008/sketch_008.py new file mode 100644 index 00000000..032bbefc --- /dev/null +++ b/docs/examples/sketch_008/sketch_008.py @@ -0,0 +1,42 @@ +from pytop5js import * + + +add_library("p5.dom.js") + + +rect_base_size = 30 +positions = [] +rect_offset = None + +def setup(): + global rect_offset + + createP("Hi! This is an example of how to use p5.dom.js with pyp5js") + + # creates a container div + slider_div = createDiv() + slider_div.style("display", "block") + + # creates the slider + rect_offset = createSlider(0, 600, 100) + rect_offset.style('width', '50%') + + # adds the slider to the container div + slider_div.child(rect_offset) + + createCanvas(600, 600) + + for x in range(-rect_base_size, width + rect_base_size, rect_base_size): + for y in range(-rect_base_size, height + rect_base_size, rect_base_size): + positions.append((x, y)) + + noFill() + strokeWeight(2) + rectMode(CENTER) + + +def draw(): + background(255) + size = rect_offset.value() + for x, y in positions: + rect(x, y, size, size) diff --git a/docs/examples/sketch_008/static/p5.dom.js b/docs/examples/sketch_008/static/p5.dom.js new file mode 100644 index 00000000..385b2ea4 --- /dev/null +++ b/docs/examples/sketch_008/static/p5.dom.js @@ -0,0 +1,3 @@ +/*! p5.js v0.8.0 April 08, 2019 */ + +!function(t,e){"function"==typeof define&&define.amd?define("p5.dom",["p5"],function(t){e(t)}):"object"==typeof exports?e(require("../p5")):e(t.p5)}(this,function(d){function l(t){var e=document;return"string"==typeof t&&"#"===t[0]?(t=t.slice(1),e=document.getElementById(t)||document):t instanceof d.Element?e=t.elt:t instanceof HTMLElement&&(e=t),e}function c(t,e,i){(e._userNode?e._userNode:document.body).appendChild(t);var n=i?new d.MediaElement(t,e):new d.Element(t,e);return e._elements.push(n),n}d.prototype.select=function(t,e){d._validateParameters("select",arguments);var i=null,n=l(e);return(i="."===t[0]?(t=t.slice(1),(i=n.getElementsByClassName(t)).length?i[0]:null):"#"===t[0]?(t=t.slice(1),n.getElementById(t)):(i=n.getElementsByTagName(t)).length?i[0]:null)?this._wrapElement(i):null},d.prototype.selectAll=function(t,e){d._validateParameters("selectAll",arguments);var i,n=[],r=l(e);if(i="."===t[0]?(t=t.slice(1),r.getElementsByClassName(t)):r.getElementsByTagName(t))for(var o=0;o>16&255,o[a++]=t>>8&255,o[a++]=255&t;var l,u;2===n&&(t=c[e.charCodeAt(h)]<<2|c[e.charCodeAt(h+1)]>>4,o[a++]=255&t);1===n&&(t=c[e.charCodeAt(h)]<<10|c[e.charCodeAt(h+1)]<<4|c[e.charCodeAt(h+2)]>>2,o[a++]=t>>8&255,o[a++]=255&t);return o},r.fromByteArray=function(e){for(var t,r=e.length,i=r%3,n=[],o=0,a=r-i;o>2]+s[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],n.push(s[t>>10]+s[t>>4&63]+s[t<<2&63]+"="));return n.join("")};for(var s=[],c=[],p="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=0,o=i.length;n>18&63]+s[n>>12&63]+s[n>>6&63]+s[63&n]);return o.join("")}c["-".charCodeAt(0)]=62,c["_".charCodeAt(0)]=63},{}],2:[function(e,t,r){},{}],3:[function(e,t,r){"use strict";var i=e("base64-js"),o=e("ieee754");r.Buffer=c,r.SlowBuffer=function(e){+e!=e&&(e=0);return c.alloc(+e)},r.INSPECT_MAX_BYTES=50;var n=2147483647;function a(e){if(n>>1;case"base64":return I(e).length;default:if(n)return i?-1:k(e).length;t=(""+t).toLowerCase(),n=!0}}function f(e,t,r){var i=e[t];e[t]=e[r],e[r]=i}function m(e,t,r,i,n){if(0===e.length)return-1;if("string"==typeof r?(i=r,r=0):2147483647=e.length){if(n)return-1;r=e.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof t&&(t=c.from(t,i)),c.isBuffer(t))return 0===t.length?-1:v(e,t,r,i,n);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):v(e,[t],r,i,n);throw new TypeError("val must be string, number or Buffer")}function v(e,t,r,i,n){var o,a=1,s=e.length,h=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;s/=a=2,h/=2,r/=2}function l(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(n){var u=-1;for(o=r;o>>10&1023|55296),u=56320|1023&u),i.push(u),n+=c}return function(e){var t=e.length;if(t<=x)return String.fromCharCode.apply(String,e);var r="",i=0;for(;ithis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return T(this,t,r);case"utf8":case"utf-8":return _(this,t,r);case"ascii":return w(this,t,r);case"latin1":case"binary":return S(this,t,r);case"base64":return b(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,t,r);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}.apply(this,arguments)},c.prototype.equals=function(e){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===c.compare(this,e)},c.prototype.inspect=function(){var e="",t=r.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),""},c.prototype.compare=function(e,t,r,i,n){if(O(e,Uint8Array)&&(e=c.from(e,e.offset,e.byteLength)),!c.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===i&&(i=0),void 0===n&&(n=this.length),t<0||r>e.length||i<0||n>this.length)throw new RangeError("out of range index");if(n<=i&&r<=t)return 0;if(n<=i)return-1;if(r<=t)return 1;if(this===e)return 0;for(var o=(n>>>=0)-(i>>>=0),a=(r>>>=0)-(t>>>=0),s=Math.min(o,a),h=this.slice(i,n),l=e.slice(t,r),u=0;u>>=0,isFinite(r)?(r>>>=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}var n=this.length-t;if((void 0===r||nthis.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o,a,s,h,l,u,c,p,d,f=!1;;)switch(i){case"hex":return g(this,e,t,r);case"utf8":case"utf-8":return p=t,d=r,U(k(e,(c=this).length-p),c,p,d);case"ascii":return y(this,e,t,r);case"latin1":case"binary":return y(this,e,t,r);case"base64":return h=this,l=t,u=r,U(I(e),h,l,u);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return a=t,s=r,U(function(e,t){for(var r,i,n,o=[],a=0;a>8,n=r%256,o.push(n),o.push(i);return o}(e,(o=this).length-a),o,a,s);default:if(f)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),f=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var x=4096;function w(e,t,r){var i="";r=Math.min(e.length,r);for(var n=t;ne.length)throw new RangeError("Index out of range")}function R(e,t,r,i,n,o){if(r+i>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function L(e,t,r,i,n){return t=+t,r>>>=0,n||R(e,0,r,4),o.write(e,t,r,i,23,4),r+4}function P(e,t,r,i,n){return t=+t,r>>>=0,n||R(e,0,r,8),o.write(e,t,r,i,52,8),r+8}c.prototype.slice=function(e,t){var r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):r>>=0,t>>>=0,r||E(e,t,this.length);for(var i=this[e],n=1,o=0;++o>>=0,t>>>=0,r||E(e,t,this.length);for(var i=this[e+--t],n=1;0>>=0,t||E(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return e>>>=0,t||E(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return e>>>=0,t||E(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return e>>>=0,t||E(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return e>>>=0,t||E(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||E(e,t,this.length);for(var i=this[e],n=1,o=0;++o>>=0,t>>>=0,r||E(e,t,this.length);for(var i=t,n=1,o=this[e+--i];0>>=0,t||E(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){e>>>=0,t||E(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt16BE=function(e,t){e>>>=0,t||E(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt32LE=function(e,t){return e>>>=0,t||E(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return e>>>=0,t||E(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return e>>>=0,t||E(e,4,this.length),o.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return e>>>=0,t||E(e,4,this.length),o.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return e>>>=0,t||E(e,8,this.length),o.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return e>>>=0,t||E(e,8,this.length),o.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,r,i){(e=+e,t>>>=0,r>>>=0,i)||C(this,e,t,r,Math.pow(2,8*r)-1,0);var n=1,o=0;for(this[t]=255&e;++o>>=0,r>>>=0,i)||C(this,e,t,r,Math.pow(2,8*r)-1,0);var n=r-1,o=1;for(this[t+n]=255&e;0<=--n&&(o*=256);)this[t+n]=e/o&255;return t+r},c.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,1,255,0),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},c.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeIntLE=function(e,t,r,i){if(e=+e,t>>>=0,!i){var n=Math.pow(2,8*r-1);C(this,e,t,r,n-1,-n)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+r},c.prototype.writeIntBE=function(e,t,r,i){if(e=+e,t>>>=0,!i){var n=Math.pow(2,8*r-1);C(this,e,t,r,n-1,-n)}var o=r-1,a=1,s=0;for(this[t+o]=255&e;0<=--o&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+r},c.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},c.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeFloatLE=function(e,t,r){return L(this,e,t,!0,r)},c.prototype.writeFloatBE=function(e,t,r){return L(this,e,t,!1,r)},c.prototype.writeDoubleLE=function(e,t,r){return P(this,e,t,!0,r)},c.prototype.writeDoubleBE=function(e,t,r){return P(this,e,t,!1,r)},c.prototype.copy=function(e,t,r,i){if(!c.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),0=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function I(e){return i.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(D,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function U(e,t,r,i){for(var n=0;n=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function O(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function B(e){return e!=e}},{"base64-js":1,ieee754:7}],4:[function(z,r,i){(function(G,V){var e,t;e=this,t=function(){"use strict";function l(e){return"function"==typeof e}var r=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},i=0,t=void 0,n=void 0,s=function(e,t){p[i]=e,p[i+1]=t,2===(i+=2)&&(n?n(d):y())};var e="undefined"!=typeof window?window:void 0,o=e||{},a=o.MutationObserver||o.WebKitMutationObserver,h="undefined"==typeof self&&void 0!==G&&"[object process]"==={}.toString.call(G),u="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel;function c(){var e=setTimeout;return function(){return e(d,1)}}var p=new Array(1e3);function d(){for(var e=0;e>1,u=-7,c=r?n-1:0,p=r?-1:1,d=e[t+c];for(c+=p,o=d&(1<<-u)-1,d>>=-u,u+=s;0>=-u,u+=i;0>1,p=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:o-1,f=i?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=u):(a=Math.floor(Math.log(t)/Math.LN2),t*(h=Math.pow(2,-a))<1&&(a--,h*=2),2<=(t+=1<=a+c?p/h:p*Math.pow(2,1-c))*h&&(a++,h/=2),u<=a+c?(s=0,a=u):1<=a+c?(s=(t*h-1)*Math.pow(2,n),a+=c):(s=t*Math.pow(2,c-1)*Math.pow(2,n),a=0));8<=n;e[r+d]=255&s,d+=f,s/=256,n-=8);for(a=a<Math.abs(e[0])&&(t=1),Math.abs(e[2])>Math.abs(e[t])&&(t=2),t}var C=4e150;function R(e,t){e.f+=t.f,e.b.f+=t.b.f}function l(e,t,r){return e=e.a,t=t.a,r=r.a,t.b.a===e?r.b.a===e?g(t.a,r.a)?b(r.b.a,t.a,r.a)<=0:0<=b(t.b.a,r.a,t.a):b(r.b.a,e,r.a)<=0:r.b.a===e?0<=b(t.b.a,e,t.a):(t=y(t.b.a,e,t.a),(e=y(r.b.a,e,r.a))<=t)}function L(e){e.a.i=null;var t=e.e;t.a.c=t.c,t.c.a=t.a,e.e=null}function u(e,t){c(e.a),e.c=!1,(e.a=t).i=e}function P(e){for(var t=e.a.a;(e=pe(e)).a.a===t;);return e.c&&(u(e,t=p(ce(e).a.b,e.a.e)),e=pe(e)),e}function D(e,t,r){var i=new ue;return i.a=r,i.e=W(e.f,t.e,i),r.i=i}function A(e,t){switch(e.s){case 100130:return 0!=(1&t);case 100131:return 0!==t;case 100132:return 0>1]],s[a[l]])?he(r,l):le(r,l)),s[o]=null,h[o]=r.b,r.b=o}else for(r.c[-(o+1)]=null;0Math.max(a.a,h.a))return!1;if(g(o,a)){if(0i.f&&(i.f*=2,i.c=oe(i.c,i.f+1)),0===i.b?r=n:(r=i.b,i.b=i.c[i.b]),i.e[r]=t,i.c[r]=n,i.d[n]=r,i.h&&le(i,n),r}return i=e.a++,e.c[i]=t,-(i+1)}function ie(e){if(0===e.a)return se(e.b);var t=e.c[e.d[e.a-1]];if(0!==e.b.a&&g(ae(e.b),t))return se(e.b);for(;--e.a,0e.a||g(i[a],i[h])){n[r[o]=a]=o;break}n[r[o]=h]=o,o=s}}function le(e,t){for(var r=e.d,i=e.e,n=e.c,o=t,a=r[o];;){var s=o>>1,h=r[s];if(0===s||g(i[h],i[a])){n[r[o]=a]=o;break}n[r[o]=h]=o,o=s}}function ue(){this.e=this.a=null,this.f=0,this.c=this.b=this.h=this.d=!1}function ce(e){return e.e.c.b}function pe(e){return e.e.a.b}(i=q.prototype).x=function(){Y(this,0)},i.B=function(e,t){switch(e){case 100142:return;case 100140:switch(t){case 100130:case 100131:case 100132:case 100133:case 100134:return void(this.s=t)}break;case 100141:return void(this.m=!!t);default:return void Z(this,100900)}Z(this,100901)},i.y=function(e){switch(e){case 100142:return 0;case 100140:return this.s;case 100141:return this.m;default:Z(this,100900)}return!1},i.A=function(e,t,r){this.j[0]=e,this.j[1]=t,this.j[2]=r},i.z=function(e,t){var r=t||null;switch(e){case 100100:case 100106:this.h=r;break;case 100104:case 100110:this.l=r;break;case 100101:case 100107:this.k=r;break;case 100102:case 100108:this.i=r;break;case 100103:case 100109:this.p=r;break;case 100105:case 100111:this.o=r;break;case 100112:this.r=r;break;default:Z(this,100900)}},i.C=function(e,t){var r=!1,i=[0,0,0];Y(this,2);for(var n=0;n<3;++n){var o=e[n];o<-1e150&&(o=-1e150,r=!0),1e150n[l]&&(n[l]=u,a[l]=h)}if(h=0,n[1]-o[1]>n[0]-o[0]&&(h=1),n[2]-o[2]>n[h]-o[h]&&(h=2),o[h]>=n[h])i[0]=0,i[1]=0,i[2]=1;else{for(n=0,o=s[h],a=a[h],s=[0,0,0],o=[o.g[0]-a.g[0],o.g[1]-a.g[1],o.g[2]-a.g[2]],l=[0,0,0],h=r.e;h!==r;h=h.e)l[0]=h.g[0]-a.g[0],l[1]=h.g[1]-a.g[1],l[2]=h.g[2]-a.g[2],s[0]=o[1]*l[2]-o[2]*l[1],s[1]=o[2]*l[0]-o[0]*l[2],s[2]=o[0]*l[1]-o[1]*l[0],n<(u=s[0]*s[0]+s[1]*s[1]+s[2]*s[2])&&(n=u,i[0]=s[0],i[1]=s[1],i[2]=s[2]);n<=0&&(i[0]=i[1]=i[2]=0,i[E(o)]=1)}r=!0}for(s=E(i),h=this.b.c,n=(s+1)%3,a=(s+2)%3,s=0>>=1,t}function _(e,t,r){if(!t)return r;for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>16-t;return e.tag>>>=t,e.bitcount-=t,i+r}function x(e,t){for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>=1,++n,r+=t.table[n],0<=(i-=t.table[n]););return e.tag=o,e.bitcount-=n,t.trans[r+i]}function w(e,t,r){var i,n,o,a,s,h;for(i=_(e,5,257),n=_(e,5,1),o=_(e,4,4),a=0;a<19;++a)v[a]=0;for(a=0;athis.x2&&(this.x2=e)),"number"==typeof t&&((isNaN(this.y1)||isNaN(this.y2))&&(this.y1=t,this.y2=t),tthis.y2&&(this.y2=t))},C.prototype.addX=function(e){this.addPoint(e,null)},C.prototype.addY=function(e){this.addPoint(null,e)},C.prototype.addBezier=function(e,t,r,i,n,o,a,s){var h=this,l=[e,t],u=[r,i],c=[n,o],p=[a,s];this.addPoint(e,t),this.addPoint(a,s);for(var d=0;d<=1;d++){var f=6*l[d]-12*u[d]+6*c[d],m=-3*l[d]+9*u[d]-9*c[d]+3*p[d],v=3*u[d]-3*l[d];if(0!==m){var g=Math.pow(f,2)-4*v*m;if(!(g<0)){var y=(-f+Math.sqrt(g))/(2*m);0>8&255,255&e]},I.USHORT=O(2),k.SHORT=function(e){return 32768<=e&&(e=-(65536-e)),[e>>8&255,255&e]},I.SHORT=O(2),k.UINT24=function(e){return[e>>16&255,e>>8&255,255&e]},I.UINT24=O(3),k.ULONG=function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]},I.ULONG=O(4),k.LONG=function(e){return D<=e&&(e=-(2*D-e)),[e>>24&255,e>>16&255,e>>8&255,255&e]},I.LONG=O(4),k.FIXED=k.ULONG,I.FIXED=I.ULONG,k.FWORD=k.SHORT,I.FWORD=I.SHORT,k.UFWORD=k.USHORT,I.UFWORD=I.USHORT,k.LONGDATETIME=function(e){return[0,0,0,0,e>>24&255,e>>16&255,e>>8&255,255&e]},I.LONGDATETIME=O(8),k.TAG=function(e){return P.argument(4===e.length,"Tag should be exactly 4 ASCII characters."),[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]},I.TAG=O(4),k.Card8=k.BYTE,I.Card8=I.BYTE,k.Card16=k.USHORT,I.Card16=I.USHORT,k.OffSize=k.BYTE,I.OffSize=I.BYTE,k.SID=k.USHORT,I.SID=I.USHORT,k.NUMBER=function(e){return-107<=e&&e<=107?[e+139]:108<=e&&e<=1131?[247+((e-=108)>>8),255&e]:-1131<=e&&e<=-108?[251+((e=-e-108)>>8),255&e]:-32768<=e&&e<=32767?k.NUMBER16(e):k.NUMBER32(e)},I.NUMBER=function(e){return k.NUMBER(e).length},k.NUMBER16=function(e){return[28,e>>8&255,255&e]},I.NUMBER16=O(3),k.NUMBER32=function(e){return[29,e>>24&255,e>>16&255,e>>8&255,255&e]},I.NUMBER32=O(5),k.REAL=function(e){var t=e.toString(),r=/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(t);if(r){var i=parseFloat("1e"+((r[2]?+r[2]:0)+r[1].length));t=(Math.round(e*i)/i).toString()}for(var n="",o=0,a=t.length;o>8&255,t[t.length]=255&i}return t},I.UTF16=function(e){return 2*e.length};var B={"x-mac-croatian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ","x-mac-cyrillic":"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю","x-mac-gaelic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæøṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ","x-mac-greek":"Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­","x-mac-icelandic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-inuit":"ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł","x-mac-ce":"ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ",macintosh:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-romanian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-turkish":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ"};A.MACSTRING=function(e,t,r,i){var n=B[i];if(void 0!==n){for(var o="",a=0;a>8&255,h+256&255)}return o}k.MACSTRING=function(e,t){var r=function(e){if(!N)for(var t in N={},B)N[t]=new String(t);var r=N[e];if(void 0!==r){if(F){var i=F.get(r);if(void 0!==i)return i}var n=B[e];if(void 0!==n){for(var o={},a=0;a>8,t[c+1]=255&p,t=t.concat(i[u])}return t},I.TABLE=function(e){for(var t=0,r=e.fields.length,i=0;i>1,t.skip("uShort",3),e.glyphIndexMap={};for(var a=new se.Parser(r,i+n+14),s=new se.Parser(r,i+n+16+2*o),h=new se.Parser(r,i+n+16+4*o),l=new se.Parser(r,i+n+16+6*o),u=i+n+16+8*o,c=0;c>4,o=15&i;if(15===n)break;if(t+=r[n],15===o)break;t+=r[o]}return parseFloat(t)}(e);if(32<=t&&t<=246)return t-139;if(247<=t&&t<=250)return 256*(t-247)+e.parseByte()+108;if(251<=t&&t<=254)return 256*-(t-251)-e.parseByte()-108;throw new Error("Invalid b0 "+t)}function Ee(e,t,r){t=void 0!==t?t:0;var i=new se.Parser(e,t),n=[],o=[];for(r=void 0!==r?r:e.length;i.relativeOffset>1,E.length=0,R=!0}return function e(t){for(var r,i,n,o,a,s,h,l,u,c,p,d,f=0;fMath.abs(d-D)?P=p+E.shift():D=d+E.shift(),M.curveTo(y,b,_,x,h,l),M.curveTo(u,c,p,d,P,D);break;default:console.log("Glyph "+g.index+": unknown operator 1200"+m),E.length=0}break;case 14:0>3;break;case 21:2>16),f+=2;break;case 29:a=E.pop()+v.gsubrsBias,(s=v.gsubrs[a])&&e(s);break;case 30:for(;0=r.begin&&e=pe.length){var a=i.parseChar();r.names.push(i.parseString(a))}break;case 2.5:r.numberOfGlyphs=i.parseUShort(),r.offset=new Array(r.numberOfGlyphs);for(var s=0;st.value.tag?1:-1}),t.fields=t.fields.concat(i),t.fields=t.fields.concat(n),t}function vt(e,t,r){for(var i=0;i 123 are reserved for internal usage");d|=1<>>1,o=e[n].tag;if(o===t)return n;o>>1,o=e[n];if(o===t)return n;o>>1,a=(r=e[o]).start;if(a===t)return r;a(r=e[i-1]).end?0:r}function xt(e,t){this.font=e,this.tableName=t}function wt(e){xt.call(this,e,"gpos")}function St(e){xt.call(this,e,"gsub")}function Tt(e,t){var r=e.length;if(r!==t.length)return!1;for(var i=0;it.points.length-1||i.matchedPoints[1]>n.points.length-1)throw Error("Matched points out of range in "+t.name);var a=t.points[i.matchedPoints[0]],s=n.points[i.matchedPoints[1]],h={xScale:i.xScale,scale01:i.scale01,scale10:i.scale10,yScale:i.yScale,dx:0,dy:0};s=Pt([s],h)[0],h.dx=a.x-s.x,h.dy=a.y-s.y,o=Pt(n.points,h)}t.points=t.points.concat(o)}}return Dt(t.points)}(wt.prototype=xt.prototype={searchTag:yt,binSearch:bt,getTable:function(e){var t=this.font.tables[this.tableName];return!t&&e&&(t=this.font.tables[this.tableName]=this.createDefaultTable()),t},getScriptNames:function(){var e=this.getTable();return e?e.scripts.map(function(e){return e.tag}):[]},getDefaultScriptName:function(){var e=this.getTable();if(e){for(var t=!1,r=0;r=s[l-1].tag,"Features must be added in alphabetical order."),o={tag:r,feature:{params:0,lookupListIndexes:[]}},s.push(o),a.push(l),o.feature}}},getLookupTables:function(e,t,r,i,n){var o=this.getFeatureTable(e,t,r,n),a=[];if(o){for(var s,h=o.lookupListIndexes,l=this.font.tables[this.tableName].lookups,u=0;u",s),t.stack.push(Math.round(64*s))}function gr(e,t){var r=t.stack,i=r.pop(),n=t.fv,o=t.pv,a=t.ppem,s=t.deltaBase+16*(e-1),h=t.deltaShift,l=t.z0;M.DEBUG&&console.log(t.step,"DELTAP["+e+"]",i,r);for(var u=0;u>4)===a){var d=(15&p)-8;0<=d&&d++,M.DEBUG&&console.log(t.step,"DELTAPFIX",c,"by",d*h);var f=l[c];n.setRelative(f,f,d*h,o)}}}function yr(e,t){var r=t.stack,i=r.pop();M.DEBUG&&console.log(t.step,"ROUND[]"),r.push(64*t.round(i/64))}function br(e,t){var r=t.stack,i=r.pop(),n=t.ppem,o=t.deltaBase+16*(e-1),a=t.deltaShift;M.DEBUG&&console.log(t.step,"DELTAC["+e+"]",i,r);for(var s=0;s>4)===n){var u=(15&l)-8;0<=u&&u++;var c=u*a;M.DEBUG&&console.log(t.step,"DELTACFIX",h,"by",c),t.cvt[h]+=c}}}function _r(e,t){var r,i,n=t.stack,o=n.pop(),a=n.pop(),s=t.z2[o],h=t.z1[a];M.DEBUG&&console.log(t.step,"SDPVTL["+e+"]",o,a),i=e?(r=s.y-h.y,h.x-s.x):(r=h.x-s.x,h.y-s.y),t.dpv=Zt(r,i)}function xr(e,t){var r=t.stack,i=t.prog,n=t.ip;M.DEBUG&&console.log(t.step,"PUSHB["+e+"]");for(var o=0;o":"_")+(i?"R":"_")+(0===n?"Gr":1===n?"Bl":2===n?"Wh":"")+"]",e?c+"("+o.cvt[c]+","+l+")":"",p,"(d =",a,"->",h*s,")"),o.rp1=o.rp0,o.rp2=p,t&&(o.rp0=p)}Nt.prototype.exec=function(e,t){if("number"!=typeof t)throw new Error("Point size is not a number!");if(!(2",i),s.interpolate(c,o,a,h),s.touch(c)}e.loop=1},dr.bind(void 0,0),dr.bind(void 0,1),function(e){for(var t=e.stack,r=e.rp0,i=e.z0[r],n=e.loop,o=e.fv,a=e.pv,s=e.z1;n--;){var h=t.pop(),l=s[h];M.DEBUG&&console.log(e.step,(1=a.width||t>=a.height?[0,0,0,0]:this._getPixel(e,t);var s=new h.Image(r,i);return s.canvas.getContext("2d").drawImage(a,e,t,r*o,i*o,0,0,r,i),s},h.Renderer.prototype.textLeading=function(e){return"number"==typeof e?(this._setProperty("_textLeading",e),this._pInst):this._textLeading},h.Renderer.prototype.textSize=function(e){return"number"==typeof e?(this._setProperty("_textSize",e),this._setProperty("_textLeading",e*y._DEFAULT_LEADMULT),this._applyTextProperties()):this._textSize},h.Renderer.prototype.textStyle=function(e){return e?(e!==y.NORMAL&&e!==y.ITALIC&&e!==y.BOLD&&e!==y.BOLDITALIC||this._setProperty("_textStyle",e),this._applyTextProperties()):this._textStyle},h.Renderer.prototype.textAscent=function(){return null===this._textAscent&&this._updateTextMetrics(),this._textAscent},h.Renderer.prototype.textDescent=function(){return null===this._textDescent&&this._updateTextMetrics(),this._textDescent},h.Renderer.prototype.textAlign=function(e,t){return void 0!==e?(this._setProperty("_textAlign",e),void 0!==t&&this._setProperty("_textBaseline",t),this._applyTextProperties()):{horizontal:this._textAlign,vertical:this._textBaseline}},h.Renderer.prototype.text=function(e,t,r,i,n){var o,a,s,h,l,u,c,p,d=this._pInst,f=Number.MAX_VALUE;if((this._doFill||this._doStroke)&&void 0!==e){if("string"!=typeof e&&(e=e.toString()),o=(e=e.replace(/(\t)/g," ")).split("\n"),void 0!==i){for(s=p=0;sa.HALF_PI&&e<=3*a.HALF_PI?Math.atan(r/i*Math.tan(e))+a.PI:Math.atan(r/i*Math.tan(e))+a.TWO_PI,t=t<=a.HALF_PI?Math.atan(r/i*Math.tan(t)):t>a.HALF_PI&&t<=3*a.HALF_PI?Math.atan(r/i*Math.tan(t))+a.PI:Math.atan(r/i*Math.tan(t))+a.TWO_PI),t_||Math.abs(this.accelerationY-this.pAccelerationY)>_||Math.abs(this.accelerationZ-this.pAccelerationZ)>_)&&e();var t=this.deviceTurned||window.deviceTurned;if("function"==typeof t){var r=this.rotationX+180,i=this.pRotationX+180,n=f+180;0>>24],i+=x[(16711680&C)>>16],n+=x[(65280&C)>>8],o+=x[255&C],r+=P[_],s++}w[h=E+y]=a/r,S[h]=i/r,T[h]=n/r,M[h]=o/r}E+=d}for(u=(l=-R)*d,b=E=0;b>>16,e[r+1]=(65280&t[i])>>>8,e[r+2]=255&t[i],e[r+3]=(4278190080&t[i])>>>24},A._toImageData=function(e){return e instanceof ImageData?e:e.getContext("2d").getImageData(0,0,e.width,e.height)},A._createImageData=function(e,t){return A._tmpCanvas=document.createElement("canvas"),A._tmpCtx=A._tmpCanvas.getContext("2d"),this._tmpCtx.createImageData(e,t)},A.apply=function(e,t,r){var i=e.getContext("2d"),n=i.getImageData(0,0,e.width,e.height),o=t(n,r);o instanceof ImageData?i.putImageData(o,0,0,0,0,e.width,e.height):i.putImageData(n,0,0,0,0,e.width,e.height)},A.threshold=function(e,t){var r=A._toPixels(e);void 0===t&&(t=.5);for(var i=Math.floor(255*t),n=0;n>8)/i,r[n+1]=255*(a*t>>8)/i,r[n+2]=255*(s*t>>8)/i}},A.dilate=function(e){for(var t,r,i,n,o,a,s,h,l,u,c,p,d,f,m,v,g,y=A._toPixels(e),b=0,_=y.length?y.length/4:0,x=new Int32Array(_);b<_;)for(r=(t=b)+e.width;b>16&255)+151*(i>>8&255)+28*(255&i))<(m=77*(c>>16&255)+151*(c>>8&255)+28*(255&c))&&(n=c,o=m),o<(f=77*((u=A._getARGB(y,a))>>16&255)+151*(u>>8&255)+28*(255&u))&&(n=u,o=f),o<(v=77*(p>>16&255)+151*(p>>8&255)+28*(255&p))&&(n=p,o=v),o<(g=77*(d>>16&255)+151*(d>>8&255)+28*(255&d))&&(n=d,o=g),x[b++]=n;A._setPixels(y,x)},A.erode=function(e){for(var t,r,i,n,o,a,s,h,l,u,c,p,d,f,m,v,g,y=A._toPixels(e),b=0,_=y.length?y.length/4:0,x=new Int32Array(_);b<_;)for(r=(t=b)+e.width;b>16&255)+151*(c>>8&255)+28*(255&c))<(o=77*(i>>16&255)+151*(i>>8&255)+28*(255&i))&&(n=c,o=m),(f=77*((u=A._getARGB(y,a))>>16&255)+151*(u>>8&255)+28*(255&u))>16&255)+151*(p>>8&255)+28*(255&p))>16&255)+151*(d>>8&255)+28*(255&d))/g,">").replace(/"/g,""").replace(/'/g,"'")}function h(e,t){t&&!0!==t&&"true"!==t||(t=""),e||(e="untitled");var r="";return e&&-1"),n.print("");if('="text/html;charset=utf-8" />',n.print(' '),n.print(""),n.print(""),n.print(" "),"0"!==o[0]){n.print(" ");for(var u=0;u"+c),n.print(" ")}n.print(" ")}for(var p=0;p");for(var d=0;d"+f),n.print(" ")}n.print(" ")}n.print("
"),n.print(""),n.print("")}n.close(),n.clear()},v.prototype.writeFile=function(e,t,r){var i="application/octet-stream";v.prototype._isSafari()&&(i="text/plain");var n=new Blob(e,{type:i});v.prototype.downloadFile(n,t,r)},v.prototype.downloadFile=function(e,t,r){var i=h(t,r),n=i[0];if(e instanceof Blob){s("file-saver").saveAs(e,n)}else{var o=document.createElement("a");if(o.href=e,o.download=n,o.onclick=function(e){var t;t=e,document.body.removeChild(t.target),e.stopPropagation()},o.style.display="none",document.body.appendChild(o),v.prototype._isSafari()){var a="Hello, Safari user! To download this file...\n";a+="1. Go to File --\x3e Save As.\n",a+='2. Choose "Page Source" as the Format.\n',a+='3. Name it with this extension: ."'+i[1]+'"',alert(a)}o.click()}},v.prototype._checkFileExtension=h,v.prototype._isSafari=function(){return 0>>0},getSeed:function(){return t},rand:function(){return(r=(1664525*r+1013904223)%i)/i}});n.setSeed(e),b=new Array(4096);for(var o=0;o<4096;o++)b[o]=n.rand()},t.exports=i},{"../core/main":23}],53:[function(e,t,r){"use strict";var s=e("../core/main"),o=e("../core/constants");s.Vector=function(){var e,t,r;r=arguments[0]instanceof s?(this.p5=arguments[0],e=arguments[1][0]||0,t=arguments[1][1]||0,arguments[1][2]||0):(e=arguments[0]||0,t=arguments[1]||0,arguments[2]||0),this.x=e,this.y=t,this.z=r},s.Vector.prototype.toString=function(){return"p5.Vector Object : ["+this.x+", "+this.y+", "+this.z+"]"},s.Vector.prototype.set=function(e,t,r){return e instanceof s.Vector?(this.x=e.x||0,this.y=e.y||0,this.z=e.z||0):e instanceof Array?(this.x=e[0]||0,this.y=e[1]||0,this.z=e[2]||0):(this.x=e||0,this.y=t||0,this.z=r||0),this},s.Vector.prototype.copy=function(){return this.p5?new s.Vector(this.p5,[this.x,this.y,this.z]):new s.Vector(this.x,this.y,this.z)},s.Vector.prototype.add=function(e,t,r){return e instanceof s.Vector?(this.x+=e.x||0,this.y+=e.y||0,this.z+=e.z||0):e instanceof Array?(this.x+=e[0]||0,this.y+=e[1]||0,this.z+=e[2]||0):(this.x+=e||0,this.y+=t||0,this.z+=r||0),this},s.Vector.prototype.sub=function(e,t,r){return e instanceof s.Vector?(this.x-=e.x||0,this.y-=e.y||0,this.z-=e.z||0):e instanceof Array?(this.x-=e[0]||0,this.y-=e[1]||0,this.z-=e[2]||0):(this.x-=e||0,this.y-=t||0,this.z-=r||0),this},s.Vector.prototype.mult=function(e){return"number"==typeof e&&isFinite(e)?(this.x*=e,this.y*=e,this.z*=e):console.warn("p5.Vector.prototype.mult:","n is undefined or not a finite number"),this},s.Vector.prototype.div=function(e){return"number"==typeof e&&isFinite(e)?0===e?console.warn("p5.Vector.prototype.div:","divide by 0"):(this.x/=e,this.y/=e,this.z/=e):console.warn("p5.Vector.prototype.div:","n is undefined or not a finite number"),this},s.Vector.prototype.mag=function(){return Math.sqrt(this.magSq())},s.Vector.prototype.magSq=function(){var e=this.x,t=this.y,r=this.z;return e*e+t*t+r*r},s.Vector.prototype.dot=function(e,t,r){return e instanceof s.Vector?this.dot(e.x,e.y,e.z):this.x*(e||0)+this.y*(t||0)+this.z*(r||0)},s.Vector.prototype.cross=function(e){var t=this.y*e.z-this.z*e.y,r=this.z*e.x-this.x*e.z,i=this.x*e.y-this.y*e.x;return this.p5?new s.Vector(this.p5,[t,r,i]):new s.Vector(t,r,i)},s.Vector.prototype.dist=function(e){return e.copy().sub(this).mag()},s.Vector.prototype.normalize=function(){var e=this.mag();return 0!==e&&this.mult(1/e),this},s.Vector.prototype.limit=function(e){var t=this.magSq();return e*e>>0},getSeed:function(){return i},rand:function(){return(n=(1664525*n+1013904223)%o)/o}});a.prototype.randomSeed=function(e){u.setSeed(e),h=!(s=!0)},a.prototype.random=function(e,t){var r;if(r=s?u.rand():Math.random(),void 0===e)return r;if(void 0===t)return e instanceof Array?e[Math.floor(r*e.length)]:r*e;if(tg){var R=p,L=h,P=l;p=c+g*(s&&c=t&&(r=r.substring(r.length-t,r.length)),r}},i.prototype.unhex=function(e){return e instanceof Array?e.map(i.prototype.unhex):parseInt("0x"+e,16)},t.exports=i},{"../core/main":23}],61:[function(e,t,r){"use strict";var a=e("../core/main");function i(e,t,r){var i=e<0,n=i?e.toString().substring(1):e.toString(),o=n.indexOf("."),a=-1!==o?n.substring(0,o):n,s=-1!==o?n.substring(o+1):"",h=i?"-":"";if(void 0!==r){var l="";(-1!==o||0r&&(s=s.substring(0,r));for(var u=0;ui.length)for(var o=t-(i+=-1===r?".":"").length+1,a=0;a=d.TWO_PI?(t="ellipse")+"|"+u+"|":(t="arc")+"|"+s+"|"+h+"|"+l+"|"+u+"|",!this.geometryInHash(r)){var c=new E.Geometry(u,1,function(){if(this.strokeIndices=[],s.toFixed(10)!==h.toFixed(10)){l!==d.PIE&&void 0!==l||(this.vertices.push(new E.Vector(.5,.5,0)),this.uvs.push([.5,.5]));for(var e=0;e<=u;e++){var t=e/u*(h-s)+s,r=.5+Math.cos(t)/2,i=.5+Math.sin(t)/2;this.vertices.push(new E.Vector(r,i,0)),this.uvs.push([r,i]),eMath.PI?h=Math.PI:h<=0&&(h=.001);var l=Math.sin(h)*a*Math.sin(s),u=Math.cos(h)*a,c=Math.sin(h)*a*Math.cos(s);this.camera(l+this.centerX,u+this.centerY,c+this.centerZ,this.centerX,this.centerY,this.centerZ,0,1,0)},m.Camera.prototype._isActive=function(){return this===this._renderer._curCamera},m.prototype.setCamera=function(e){this._renderer._curCamera=e,this._renderer.uPMatrix.set(e.projMatrix.mat4[0],e.projMatrix.mat4[1],e.projMatrix.mat4[2],e.projMatrix.mat4[3],e.projMatrix.mat4[4],e.projMatrix.mat4[5],e.projMatrix.mat4[6],e.projMatrix.mat4[7],e.projMatrix.mat4[8],e.projMatrix.mat4[9],e.projMatrix.mat4[10],e.projMatrix.mat4[11],e.projMatrix.mat4[12],e.projMatrix.mat4[13],e.projMatrix.mat4[14],e.projMatrix.mat4[15])},t.exports=m.Camera},{"../core/main":23}],69:[function(e,t,r){"use strict";var u=e("../core/main");u.Geometry=function(e,t,r){return this.vertices=[],this.lineVertices=[],this.lineNormals=[],this.vertexNormals=[],this.faces=[],this.uvs=[],this.edges=[],this.detailX=void 0!==e?e:1,this.detailY=void 0!==t?t:1,r instanceof Function&&r.call(this),this},u.Geometry.prototype.computeFaces=function(){this.faces.length=0;for(var e,t,r,i,n=this.detailX+1,o=0;othis.vertices.length-1-this.detailX;t--)e.add(this.vertexNormals[t]);for(e=u.Vector.div(e,this.detailX),t=this.vertices.length-1;t>this.vertices.length-1-this.detailX;t--)this.vertexNormals[t]=e;return this},u.Geometry.prototype._makeTriangleEdges=function(){if(this.edges.length=0,Array.isArray(this.strokeIndices))for(var e=0,t=this.strokeIndices.length;e>7,127&p,c>>7,127&c);for(var d=0;d>7,127&f,0,0)}}return{cellImageInfo:h,dimOffset:o,dimImageInfo:n}}return(t=this.glyphInfos[e.index]={glyph:e,uGlyphRect:[i.x1,-i.y1,i.x2,-i.y2],strokeImageInfo:A,strokes:d,colInfo:O(m,this.colDimImageInfos,this.colCellImageInfos),rowInfo:O(f,this.rowDimImageInfos,this.rowCellImageInfos)}).uGridOffset=[t.colInfo.dimOffset,t.rowInfo.dimOffset],t}};B.RendererGL.prototype._renderText=function(e,t,r,i,n){if(!(n<=i)&&this._doFill){if(!this._isOpenType())return console.log("WEBGL: only opentype fonts are supported"),e;e.push();var o=this._doStroke,a=this.drawMode;this._doStroke=!1,this.drawMode=M.TEXTURE;var s=this._textFont.font,h=this._textFont._fontInfo;h||(h=this._textFont._fontInfo=new E(s));var l=this._textFont._handleAlignment(this,t,r,i),u=this._textSize/s.unitsPerEm;this.translate(l.x,l.y,0),this.scale(u,u,1);var c=this.GL,p=!this._defaultFontShader,d=this._getFontShader();d.init(),p&&(d.setUniform("uGridImageSize",[64,64]),d.setUniform("uCellsImageSize",[64,64]),d.setUniform("uStrokeImageSize",[64,64]),d.setUniform("uGridSize",[9,9])),this._applyColorBlend(this.curFillColor);var f=this.gHash.glyph;if(!f){var m=this._textGeom=new B.Geometry(1,1,function(){for(var e=0;e<=1;e++)for(var t=0;t<=1;t++)this.vertices.push(new B.Vector(t,e,0)),this.uvs.push(t,e)});m.computeFaces().computeNormals(),f=this.createBuffers("glyph",m)}this._bindBuffer(f.vertexBuffer,c.ARRAY_BUFFER),d.enableAttrib(d.attributes.aPosition.location,3,c.FLOAT,!1,0,0),this._bindBuffer(f.indexBuffer,c.ELEMENT_ARRAY_BUFFER),this._bindBuffer(f.uvBuffer,c.ARRAY_BUFFER),d.enableAttrib(d.attributes.aTexCoord.location,2,c.FLOAT,!1,0,0),d.setUniform("uMaterialColor",this.curFillColor);try{for(var v=0,g=null,y=!1,b=s.stringToGlyphs(t),_=0;_= 0; index--) { + var base = bases [index]; + for (var attrib in base) { + var descrip = Object.getOwnPropertyDescriptor (base, attrib); + Object.defineProperty (cls, attrib, descrip); + } + for (let symbol of Object.getOwnPropertySymbols (base)) { + let descrip = Object.getOwnPropertyDescriptor (base, symbol); + Object.defineProperty (cls, symbol, descrip); + } + } + cls.__metaclass__ = meta; + cls.__name__ = name.startsWith ('py_') ? name.slice (3) : name; + cls.__bases__ = bases; + for (var attrib in attribs) { + var descrip = Object.getOwnPropertyDescriptor (attribs, attrib); + Object.defineProperty (cls, attrib, descrip); + } + for (let symbol of Object.getOwnPropertySymbols (attribs)) { + let descrip = Object.getOwnPropertyDescriptor (attribs, symbol); + Object.defineProperty (cls, symbol, descrip); + } + return cls; + } +}; +py_metatype.__metaclass__ = py_metatype; +export var object = { + __init__: function (self) {}, + __metaclass__: py_metatype, + __name__: 'object', + __bases__: [], + __new__: function (args) { + var instance = Object.create (this, {__class__: {value: this, enumerable: true}}); + if ('__getattr__' in this || '__setattr__' in this) { + instance = new Proxy (instance, { + get: function (target, name) { + let result = target [name]; + if (result == undefined) { + return target.__getattr__ (name); + } + else { + return result; + } + }, + set: function (target, name, value) { + try { + target.__setattr__ (name, value); + } + catch (exception) { + target [name] = value; + } + return true; + } + }) + } + this.__init__.apply (null, [instance] .concat (args)); + return instance; + } +}; +export function __class__ (name, bases, attribs, meta) { + if (meta === undefined) { + meta = bases [0] .__metaclass__; + } + return meta.__new__ (meta, name, bases, attribs); +}; +export function __pragma__ () {}; +export function __call__ (/* , , * */) { + var args = [] .slice.apply (arguments); + if (typeof args [0] == 'object' && '__call__' in args [0]) { + return args [0] .__call__ .apply (args [1], args.slice (2)); + } + else { + return args [0] .apply (args [1], args.slice (2)); + } +}; +__envir__.executor_name = __envir__.transpiler_name; +var __main__ = {__file__: ''}; +var __except__ = null; +export function __kwargtrans__ (anObject) { + anObject.__kwargtrans__ = null; + anObject.constructor = Object; + return anObject; +} +export function __super__ (aClass, methodName) { + for (let base of aClass.__bases__) { + if (methodName in base) { + return base [methodName]; + } + } + throw new Exception ('Superclass method not found'); +} +export function property (getter, setter) { + if (!setter) { + setter = function () {}; + } + return {get: function () {return getter (this)}, set: function (value) {setter (this, value)}, enumerable: true}; +} +export function __setproperty__ (anObject, name, descriptor) { + if (!anObject.hasOwnProperty (name)) { + Object.defineProperty (anObject, name, descriptor); + } +} +export function assert (condition, message) { + if (!condition) { + throw AssertionError (message, new Error ()); + } +} +export function __mergekwargtrans__ (object0, object1) { + var result = {}; + for (var attrib in object0) { + result [attrib] = object0 [attrib]; + } + for (var attrib in object1) { + result [attrib] = object1 [attrib]; + } + return result; +}; +export function __mergefields__ (targetClass, sourceClass) { + let fieldNames = ['__reprfields__', '__comparefields__', '__initfields__'] + if (sourceClass [fieldNames [0]]) { + if (targetClass [fieldNames [0]]) { + for (let fieldName of fieldNames) { + targetClass [fieldName] = new Set ([...targetClass [fieldName], ...sourceClass [fieldName]]); + } + } + else { + for (let fieldName of fieldNames) { + targetClass [fieldName] = new Set (sourceClass [fieldName]); + } + } + } +} +export function __withblock__ (manager, statements) { + if (hasattr (manager, '__enter__')) { + try { + manager.__enter__ (); + statements (); + manager.__exit__ (); + } + catch (exception) { + if (! (manager.__exit__ (exception.name, exception, exception.stack))) { + throw exception; + } + } + } + else { + statements (); + manager.close (); + } +}; +export function dir (obj) { + var aList = []; + for (var aKey in obj) { + aList.push (aKey.startsWith ('py_') ? aKey.slice (3) : aKey); + } + aList.sort (); + return aList; +}; +export function setattr (obj, name, value) { + obj [name] = value; +}; +export function getattr (obj, name) { + return name in obj ? obj [name] : obj ['py_' + name]; +}; +export function hasattr (obj, name) { + try { + return name in obj || 'py_' + name in obj; + } + catch (exception) { + return false; + } +}; +export function delattr (obj, name) { + if (name in obj) { + delete obj [name]; + } + else { + delete obj ['py_' + name]; + } +}; +export function __in__ (element, container) { + if (container === undefined || container === null) { + return false; + } + if (container.__contains__ instanceof Function) { + return container.__contains__ (element); + } + else { + return ( + container.indexOf ? + container.indexOf (element) > -1 : + container.hasOwnProperty (element) + ); + } +}; +export function __specialattrib__ (attrib) { + return (attrib.startswith ('__') && attrib.endswith ('__')) || attrib == 'constructor' || attrib.startswith ('py_'); +}; +export function len (anObject) { + if (anObject === undefined || anObject === null) { + return 0; + } + if (anObject.__len__ instanceof Function) { + return anObject.__len__ (); + } + if (anObject.length !== undefined) { + return anObject.length; + } + var length = 0; + for (var attr in anObject) { + if (!__specialattrib__ (attr)) { + length++; + } + } + return length; +}; +export function __i__ (any) { + return py_typeof (any) == dict ? any.py_keys () : any; +} +export function __k__ (keyed, key) { + var result = keyed [key]; + if (typeof result == 'undefined') { + if (keyed instanceof Array) + if (key == +key && key >= 0 && keyed.length > key) + return result; + else + throw IndexError (key, new Error()); + else + throw KeyError (key, new Error()); + } + return result; +} +export function __t__ (target) { + return ( + target === undefined || target === null ? false : + ['boolean', 'number'] .indexOf (typeof target) >= 0 ? target : + target.__bool__ instanceof Function ? (target.__bool__ () ? target : false) : + target.__len__ instanceof Function ? (target.__len__ () !== 0 ? target : false) : + target instanceof Function ? target : + len (target) !== 0 ? target : + false + ); +} +export function float (any) { + if (any == 'inf') { + return Infinity; + } + else if (any == '-inf') { + return -Infinity; + } + else if (any == 'nan') { + return NaN; + } + else if (isNaN (parseFloat (any))) { + if (any === false) { + return 0; + } + else if (any === true) { + return 1; + } + else { + throw ValueError ("could not convert string to float: '" + str(any) + "'", new Error ()); + } + } + else { + return +any; + } +}; +float.__name__ = 'float'; +float.__bases__ = [object]; +export function int (any) { + return float (any) | 0 +}; +int.__name__ = 'int'; +int.__bases__ = [object]; +export function bool (any) { + return !!__t__ (any); +}; +bool.__name__ = 'bool'; +bool.__bases__ = [int]; +export function py_typeof (anObject) { + var aType = typeof anObject; + if (aType == 'object') { + try { + return '__class__' in anObject ? anObject.__class__ : object; + } + catch (exception) { + return aType; + } + } + else { + return ( + aType == 'boolean' ? bool : + aType == 'string' ? str : + aType == 'number' ? (anObject % 1 == 0 ? int : float) : + null + ); + } +}; +export function issubclass (aClass, classinfo) { + if (classinfo instanceof Array) { + for (let aClass2 of classinfo) { + if (issubclass (aClass, aClass2)) { + return true; + } + } + return false; + } + try { + var aClass2 = aClass; + if (aClass2 == classinfo) { + return true; + } + else { + var bases = [].slice.call (aClass2.__bases__); + while (bases.length) { + aClass2 = bases.shift (); + if (aClass2 == classinfo) { + return true; + } + if (aClass2.__bases__.length) { + bases = [].slice.call (aClass2.__bases__).concat (bases); + } + } + return false; + } + } + catch (exception) { + return aClass == classinfo || classinfo == object; + } +}; +export function isinstance (anObject, classinfo) { + try { + return '__class__' in anObject ? issubclass (anObject.__class__, classinfo) : issubclass (py_typeof (anObject), classinfo); + } + catch (exception) { + return issubclass (py_typeof (anObject), classinfo); + } +}; +export function callable (anObject) { + return anObject && typeof anObject == 'object' && '__call__' in anObject ? true : typeof anObject === 'function'; +}; +export function repr (anObject) { + try { + return anObject.__repr__ (); + } + catch (exception) { + try { + return anObject.__str__ (); + } + catch (exception) { + try { + if (anObject == null) { + return 'None'; + } + else if (anObject.constructor == Object) { + var result = '{'; + var comma = false; + for (var attrib in anObject) { + if (!__specialattrib__ (attrib)) { + if (attrib.isnumeric ()) { + var attribRepr = attrib; + } + else { + var attribRepr = '\'' + attrib + '\''; + } + if (comma) { + result += ', '; + } + else { + comma = true; + } + result += attribRepr + ': ' + repr (anObject [attrib]); + } + } + result += '}'; + return result; + } + else { + return typeof anObject == 'boolean' ? anObject.toString () .capitalize () : anObject.toString (); + } + } + catch (exception) { + return ''; + } + } + } +}; +export function chr (charCode) { + return String.fromCharCode (charCode); +}; +export function ord (aChar) { + return aChar.charCodeAt (0); +}; +export function max (nrOrSeq) { + return arguments.length == 1 ? Math.max (...nrOrSeq) : Math.max (...arguments); +}; +export function min (nrOrSeq) { + return arguments.length == 1 ? Math.min (...nrOrSeq) : Math.min (...arguments); +}; +export var abs = Math.abs; +export function round (number, ndigits) { + if (ndigits) { + var scale = Math.pow (10, ndigits); + number *= scale; + } + var rounded = Math.round (number); + if (rounded - number == 0.5 && rounded % 2) { + rounded -= 1; + } + if (ndigits) { + rounded /= scale; + } + return rounded; +}; +export function __jsUsePyNext__ () { + try { + var result = this.__next__ (); + return {value: result, done: false}; + } + catch (exception) { + return {value: undefined, done: true}; + } +} +export function __pyUseJsNext__ () { + var result = this.next (); + if (result.done) { + throw StopIteration (new Error ()); + } + else { + return result.value; + } +} +export function py_iter (iterable) { + if (typeof iterable == 'string' || '__iter__' in iterable) { + var result = iterable.__iter__ (); + result.next = __jsUsePyNext__; + } + else if ('selector' in iterable) { + var result = list (iterable) .__iter__ (); + result.next = __jsUsePyNext__; + } + else if ('next' in iterable) { + var result = iterable + if (! ('__next__' in result)) { + result.__next__ = __pyUseJsNext__; + } + } + else if (Symbol.iterator in iterable) { + var result = iterable [Symbol.iterator] (); + result.__next__ = __pyUseJsNext__; + } + else { + throw IterableError (new Error ()); + } + result [Symbol.iterator] = function () {return result;}; + return result; +} +export function py_next (iterator) { + try { + var result = iterator.__next__ (); + } + catch (exception) { + var result = iterator.next (); + if (result.done) { + throw StopIteration (new Error ()); + } + else { + return result.value; + } + } + if (result == undefined) { + throw StopIteration (new Error ()); + } + else { + return result; + } +} +export function __PyIterator__ (iterable) { + this.iterable = iterable; + this.index = 0; +} +__PyIterator__.prototype.__next__ = function() { + if (this.index < this.iterable.length) { + return this.iterable [this.index++]; + } + else { + throw StopIteration (new Error ()); + } +}; +export function __JsIterator__ (iterable) { + this.iterable = iterable; + this.index = 0; +} +__JsIterator__.prototype.next = function () { + if (this.index < this.iterable.py_keys.length) { + return {value: this.index++, done: false}; + } + else { + return {value: undefined, done: true}; + } +}; +export function py_reversed (iterable) { + iterable = iterable.slice (); + iterable.reverse (); + return iterable; +}; +export function zip () { + var args = [] .slice.call (arguments); + for (var i = 0; i < args.length; i++) { + if (typeof args [i] == 'string') { + args [i] = args [i] .split (''); + } + else if (!Array.isArray (args [i])) { + args [i] = Array.from (args [i]); + } + } + var shortest = args.length == 0 ? [] : args.reduce ( + function (array0, array1) { + return array0.length < array1.length ? array0 : array1; + } + ); + return shortest.map ( + function (current, index) { + return args.map ( + function (current) { + return current [index]; + } + ); + } + ); +}; +export function range (start, stop, step) { + if (stop == undefined) { + stop = start; + start = 0; + } + if (step == undefined) { + step = 1; + } + if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) { + return []; + } + var result = []; + for (var i = start; step > 0 ? i < stop : i > stop; i += step) { + result.push(i); + } + return result; +}; +export function any (iterable) { + for (let item of iterable) { + if (bool (item)) { + return true; + } + } + return false; +} +export function all (iterable) { + for (let item of iterable) { + if (! bool (item)) { + return false; + } + } + return true; +} +export function sum (iterable) { + let result = 0; + for (let item of iterable) { + result += item; + } + return result; +} +export function enumerate (iterable) { + return zip (range (len (iterable)), iterable); +} +export function copy (anObject) { + if (anObject == null || typeof anObject == "object") { + return anObject; + } + else { + var result = {}; + for (var attrib in obj) { + if (anObject.hasOwnProperty (attrib)) { + result [attrib] = anObject [attrib]; + } + } + return result; + } +} +export function deepcopy (anObject) { + if (anObject == null || typeof anObject == "object") { + return anObject; + } + else { + var result = {}; + for (var attrib in obj) { + if (anObject.hasOwnProperty (attrib)) { + result [attrib] = deepcopy (anObject [attrib]); + } + } + return result; + } +} +export function list (iterable) { + let instance = iterable ? Array.from (iterable) : []; + return instance; +} +Array.prototype.__class__ = list; +list.__name__ = 'list'; +list.__bases__ = [object]; +Array.prototype.__iter__ = function () {return new __PyIterator__ (this);}; +Array.prototype.__getslice__ = function (start, stop, step) { + if (start < 0) { + start = this.length + start; + } + if (stop == null) { + stop = this.length; + } + else if (stop < 0) { + stop = this.length + stop; + } + else if (stop > this.length) { + stop = this.length; + } + if (step == 1) { + return Array.prototype.slice.call(this, start, stop); + } + let result = list ([]); + for (let index = start; index < stop; index += step) { + result.push (this [index]); + } + return result; +}; +Array.prototype.__setslice__ = function (start, stop, step, source) { + if (start < 0) { + start = this.length + start; + } + if (stop == null) { + stop = this.length; + } + else if (stop < 0) { + stop = this.length + stop; + } + if (step == null) { + Array.prototype.splice.apply (this, [start, stop - start] .concat (source)); + } + else { + let sourceIndex = 0; + for (let targetIndex = start; targetIndex < stop; targetIndex += step) { + this [targetIndex] = source [sourceIndex++]; + } + } +}; +Array.prototype.__repr__ = function () { + if (this.__class__ == set && !this.length) { + return 'set()'; + } + let result = !this.__class__ || this.__class__ == list ? '[' : this.__class__ == tuple ? '(' : '{'; + for (let index = 0; index < this.length; index++) { + if (index) { + result += ', '; + } + result += repr (this [index]); + } + if (this.__class__ == tuple && this.length == 1) { + result += ','; + } + result += !this.__class__ || this.__class__ == list ? ']' : this.__class__ == tuple ? ')' : '}';; + return result; +}; +Array.prototype.__str__ = Array.prototype.__repr__; +Array.prototype.append = function (element) { + this.push (element); +}; +Array.prototype.py_clear = function () { + this.length = 0; +}; +Array.prototype.extend = function (aList) { + this.push.apply (this, aList); +}; +Array.prototype.insert = function (index, element) { + this.splice (index, 0, element); +}; +Array.prototype.remove = function (element) { + let index = this.indexOf (element); + if (index == -1) { + throw ValueError ("list.remove(x): x not in list", new Error ()); + } + this.splice (index, 1); +}; +Array.prototype.index = function (element) { + return this.indexOf (element); +}; +Array.prototype.py_pop = function (index) { + if (index == undefined) { + return this.pop (); + } + else { + return this.splice (index, 1) [0]; + } +}; +Array.prototype.py_sort = function () { + __sort__.apply (null, [this].concat ([] .slice.apply (arguments))); +}; +Array.prototype.__add__ = function (aList) { + return list (this.concat (aList)); +}; +Array.prototype.__mul__ = function (scalar) { + let result = this; + for (let i = 1; i < scalar; i++) { + result = result.concat (this); + } + return result; +}; +Array.prototype.__rmul__ = Array.prototype.__mul__; +export function tuple (iterable) { + let instance = iterable ? [] .slice.apply (iterable) : []; + instance.__class__ = tuple; + return instance; +} +tuple.__name__ = 'tuple'; +tuple.__bases__ = [object]; +export function set (iterable) { + let instance = []; + if (iterable) { + for (let index = 0; index < iterable.length; index++) { + instance.add (iterable [index]); + } + } + instance.__class__ = set; + return instance; +} +set.__name__ = 'set'; +set.__bases__ = [object]; +Array.prototype.__bindexOf__ = function (element) { + element += ''; + let mindex = 0; + let maxdex = this.length - 1; + while (mindex <= maxdex) { + let index = (mindex + maxdex) / 2 | 0; + let middle = this [index] + ''; + if (middle < element) { + mindex = index + 1; + } + else if (middle > element) { + maxdex = index - 1; + } + else { + return index; + } + } + return -1; +}; +Array.prototype.add = function (element) { + if (this.indexOf (element) == -1) { + this.push (element); + } +}; +Array.prototype.discard = function (element) { + var index = this.indexOf (element); + if (index != -1) { + this.splice (index, 1); + } +}; +Array.prototype.isdisjoint = function (other) { + this.sort (); + for (let i = 0; i < other.length; i++) { + if (this.__bindexOf__ (other [i]) != -1) { + return false; + } + } + return true; +}; +Array.prototype.issuperset = function (other) { + this.sort (); + for (let i = 0; i < other.length; i++) { + if (this.__bindexOf__ (other [i]) == -1) { + return false; + } + } + return true; +}; +Array.prototype.issubset = function (other) { + return set (other.slice ()) .issuperset (this); +}; +Array.prototype.union = function (other) { + let result = set (this.slice () .sort ()); + for (let i = 0; i < other.length; i++) { + if (result.__bindexOf__ (other [i]) == -1) { + result.push (other [i]); + } + } + return result; +}; +Array.prototype.intersection = function (other) { + this.sort (); + let result = set (); + for (let i = 0; i < other.length; i++) { + if (this.__bindexOf__ (other [i]) != -1) { + result.push (other [i]); + } + } + return result; +}; +Array.prototype.difference = function (other) { + let sother = set (other.slice () .sort ()); + let result = set (); + for (let i = 0; i < this.length; i++) { + if (sother.__bindexOf__ (this [i]) == -1) { + result.push (this [i]); + } + } + return result; +}; +Array.prototype.symmetric_difference = function (other) { + return this.union (other) .difference (this.intersection (other)); +}; +Array.prototype.py_update = function () { + let updated = [] .concat.apply (this.slice (), arguments) .sort (); + this.py_clear (); + for (let i = 0; i < updated.length; i++) { + if (updated [i] != updated [i - 1]) { + this.push (updated [i]); + } + } +}; +Array.prototype.__eq__ = function (other) { + if (this.length != other.length) { + return false; + } + if (this.__class__ == set) { + this.sort (); + other.sort (); + } + for (let i = 0; i < this.length; i++) { + if (this [i] != other [i]) { + return false; + } + } + return true; +}; +Array.prototype.__ne__ = function (other) { + return !this.__eq__ (other); +}; +Array.prototype.__le__ = function (other) { + if (this.__class__ == set) { + return this.issubset (other); + } + else { + for (let i = 0; i < this.length; i++) { + if (this [i] > other [i]) { + return false; + } + else if (this [i] < other [i]) { + return true; + } + } + return true; + } +}; +Array.prototype.__ge__ = function (other) { + if (this.__class__ == set) { + return this.issuperset (other); + } + else { + for (let i = 0; i < this.length; i++) { + if (this [i] < other [i]) { + return false; + } + else if (this [i] > other [i]) { + return true; + } + } + return true; + } +}; +Array.prototype.__lt__ = function (other) { + return ( + this.__class__ == set ? + this.issubset (other) && !this.issuperset (other) : + !this.__ge__ (other) + ); +}; +Array.prototype.__gt__ = function (other) { + return ( + this.__class__ == set ? + this.issuperset (other) && !this.issubset (other) : + !this.__le__ (other) + ); +}; +export function bytearray (bytable, encoding) { + if (bytable == undefined) { + return new Uint8Array (0); + } + else { + let aType = py_typeof (bytable); + if (aType == int) { + return new Uint8Array (bytable); + } + else if (aType == str) { + let aBytes = new Uint8Array (len (bytable)); + for (let i = 0; i < len (bytable); i++) { + aBytes [i] = bytable.charCodeAt (i); + } + return aBytes; + } + else if (aType == list || aType == tuple) { + return new Uint8Array (bytable); + } + else { + throw py_TypeError; + } + } +} +export var bytes = bytearray; +Uint8Array.prototype.__add__ = function (aBytes) { + let result = new Uint8Array (this.length + aBytes.length); + result.set (this); + result.set (aBytes, this.length); + return result; +}; +Uint8Array.prototype.__mul__ = function (scalar) { + let result = new Uint8Array (scalar * this.length); + for (let i = 0; i < scalar; i++) { + result.set (this, i * this.length); + } + return result; +}; +Uint8Array.prototype.__rmul__ = Uint8Array.prototype.__mul__; +export function str (stringable) { + if (typeof stringable === 'number') + return stringable.toString(); + else { + try { + return stringable.__str__ (); + } + catch (exception) { + try { + return repr (stringable); + } + catch (exception) { + return String (stringable); + } + } + } +}; +String.prototype.__class__ = str; +str.__name__ = 'str'; +str.__bases__ = [object]; +String.prototype.__iter__ = function () {new __PyIterator__ (this);}; +String.prototype.__repr__ = function () { + return (this.indexOf ('\'') == -1 ? '\'' + this + '\'' : '"' + this + '"') .py_replace ('\t', '\\t') .py_replace ('\n', '\\n'); +}; +String.prototype.__str__ = function () { + return this; +}; +String.prototype.capitalize = function () { + return this.charAt (0).toUpperCase () + this.slice (1); +}; +String.prototype.endswith = function (suffix) { + if (suffix instanceof Array) { + for (var i=0;i> b; + } +}; +export function __or__ (a, b) { + if (typeof a == 'object' && '__or__' in a) { + return a.__or__ (b); + } + else if (typeof b == 'object' && '__ror__' in b) { + return b.__ror__ (a); + } + else { + return a | b; + } +}; +export function __xor__ (a, b) { + if (typeof a == 'object' && '__xor__' in a) { + return a.__xor__ (b); + } + else if (typeof b == 'object' && '__rxor__' in b) { + return b.__rxor__ (a); + } + else { + return a ^ b; + } +}; +export function __and__ (a, b) { + if (typeof a == 'object' && '__and__' in a) { + return a.__and__ (b); + } + else if (typeof b == 'object' && '__rand__' in b) { + return b.__rand__ (a); + } + else { + return a & b; + } +}; +export function __eq__ (a, b) { + if (typeof a == 'object' && '__eq__' in a) { + return a.__eq__ (b); + } + else { + return a == b; + } +}; +export function __ne__ (a, b) { + if (typeof a == 'object' && '__ne__' in a) { + return a.__ne__ (b); + } + else { + return a != b + } +}; +export function __lt__ (a, b) { + if (typeof a == 'object' && '__lt__' in a) { + return a.__lt__ (b); + } + else { + return a < b; + } +}; +export function __le__ (a, b) { + if (typeof a == 'object' && '__le__' in a) { + return a.__le__ (b); + } + else { + return a <= b; + } +}; +export function __gt__ (a, b) { + if (typeof a == 'object' && '__gt__' in a) { + return a.__gt__ (b); + } + else { + return a > b; + } +}; +export function __ge__ (a, b) { + if (typeof a == 'object' && '__ge__' in a) { + return a.__ge__ (b); + } + else { + return a >= b; + } +}; +export function __imatmul__ (a, b) { + if ('__imatmul__' in a) { + return a.__imatmul__ (b); + } + else { + return a.__matmul__ (b); + } +}; +export function __ipow__ (a, b) { + if (typeof a == 'object' && '__pow__' in a) { + return a.__ipow__ (b); + } + else if (typeof a == 'object' && '__ipow__' in a) { + return a.__pow__ (b); + } + else if (typeof b == 'object' && '__rpow__' in b) { + return b.__rpow__ (a); + } + else { + return Math.pow (a, b); + } +}; +export function __ijsmod__ (a, b) { + if (typeof a == 'object' && '__imod__' in a) { + return a.__ismod__ (b); + } + else if (typeof a == 'object' && '__mod__' in a) { + return a.__mod__ (b); + } + else if (typeof b == 'object' && '__rpow__' in b) { + return b.__rmod__ (a); + } + else { + return a % b; + } +}; +export function __imod__ (a, b) { + if (typeof a == 'object' && '__imod__' in a) { + return a.__imod__ (b); + } + else if (typeof a == 'object' && '__mod__' in a) { + return a.__mod__ (b); + } + else if (typeof b == 'object' && '__rmod__' in b) { + return b.__rmod__ (a); + } + else { + return ((a % b) + b) % b; + } +}; +export function __imul__ (a, b) { + if (typeof a == 'object' && '__imul__' in a) { + return a.__imul__ (b); + } + else if (typeof a == 'object' && '__mul__' in a) { + return a = a.__mul__ (b); + } + else if (typeof b == 'object' && '__rmul__' in b) { + return a = b.__rmul__ (a); + } + else if (typeof a == 'string') { + return a = a.__mul__ (b); + } + else if (typeof b == 'string') { + return a = b.__rmul__ (a); + } + else { + return a *= b; + } +}; +export function __idiv__ (a, b) { + if (typeof a == 'object' && '__idiv__' in a) { + return a.__idiv__ (b); + } + else if (typeof a == 'object' && '__div__' in a) { + return a = a.__div__ (b); + } + else if (typeof b == 'object' && '__rdiv__' in b) { + return a = b.__rdiv__ (a); + } + else { + return a /= b; + } +}; +export function __iadd__ (a, b) { + if (typeof a == 'object' && '__iadd__' in a) { + return a.__iadd__ (b); + } + else if (typeof a == 'object' && '__add__' in a) { + return a = a.__add__ (b); + } + else if (typeof b == 'object' && '__radd__' in b) { + return a = b.__radd__ (a); + } + else { + return a += b; + } +}; +export function __isub__ (a, b) { + if (typeof a == 'object' && '__isub__' in a) { + return a.__isub__ (b); + } + else if (typeof a == 'object' && '__sub__' in a) { + return a = a.__sub__ (b); + } + else if (typeof b == 'object' && '__rsub__' in b) { + return a = b.__rsub__ (a); + } + else { + return a -= b; + } +}; +export function __ilshift__ (a, b) { + if (typeof a == 'object' && '__ilshift__' in a) { + return a.__ilshift__ (b); + } + else if (typeof a == 'object' && '__lshift__' in a) { + return a = a.__lshift__ (b); + } + else if (typeof b == 'object' && '__rlshift__' in b) { + return a = b.__rlshift__ (a); + } + else { + return a <<= b; + } +}; +export function __irshift__ (a, b) { + if (typeof a == 'object' && '__irshift__' in a) { + return a.__irshift__ (b); + } + else if (typeof a == 'object' && '__rshift__' in a) { + return a = a.__rshift__ (b); + } + else if (typeof b == 'object' && '__rrshift__' in b) { + return a = b.__rrshift__ (a); + } + else { + return a >>= b; + } +}; +export function __ior__ (a, b) { + if (typeof a == 'object' && '__ior__' in a) { + return a.__ior__ (b); + } + else if (typeof a == 'object' && '__or__' in a) { + return a = a.__or__ (b); + } + else if (typeof b == 'object' && '__ror__' in b) { + return a = b.__ror__ (a); + } + else { + return a |= b; + } +}; +export function __ixor__ (a, b) { + if (typeof a == 'object' && '__ixor__' in a) { + return a.__ixor__ (b); + } + else if (typeof a == 'object' && '__xor__' in a) { + return a = a.__xor__ (b); + } + else if (typeof b == 'object' && '__rxor__' in b) { + return a = b.__rxor__ (a); + } + else { + return a ^= b; + } +}; +export function __iand__ (a, b) { + if (typeof a == 'object' && '__iand__' in a) { + return a.__iand__ (b); + } + else if (typeof a == 'object' && '__and__' in a) { + return a = a.__and__ (b); + } + else if (typeof b == 'object' && '__rand__' in b) { + return a = b.__rand__ (a); + } + else { + return a &= b; + } +}; +export function __getitem__ (container, key) { + if (typeof container == 'object' && '__getitem__' in container) { + return container.__getitem__ (key); + } + else if ((typeof container == 'string' || container instanceof Array) && key < 0) { + return container [container.length + key]; + } + else { + return container [key]; + } +}; +export function __setitem__ (container, key, value) { + if (typeof container == 'object' && '__setitem__' in container) { + container.__setitem__ (key, value); + } + else if ((typeof container == 'string' || container instanceof Array) && key < 0) { + container [container.length + key] = value; + } + else { + container [key] = value; + } +}; +export function __getslice__ (container, lower, upper, step) { + if (typeof container == 'object' && '__getitem__' in container) { + return container.__getitem__ ([lower, upper, step]); + } + else { + return container.__getslice__ (lower, upper, step); + } +}; +export function __setslice__ (container, lower, upper, step, value) { + if (typeof container == 'object' && '__setitem__' in container) { + container.__setitem__ ([lower, upper, step], value); + } + else { + container.__setslice__ (lower, upper, step, value); + } +}; +export var BaseException = __class__ ('BaseException', [object], { + __module__: __name__, +}); +export var Exception = __class__ ('Exception', [BaseException], { + __module__: __name__, + get __init__ () {return __get__ (this, function (self) { + var kwargs = dict (); + if (arguments.length) { + var __ilastarg0__ = arguments.length - 1; + if (arguments [__ilastarg0__] && arguments [__ilastarg0__].hasOwnProperty ("__kwargtrans__")) { + var __allkwargs0__ = arguments [__ilastarg0__--]; + for (var __attrib0__ in __allkwargs0__) { + switch (__attrib0__) { + case 'self': var self = __allkwargs0__ [__attrib0__]; break; + default: kwargs [__attrib0__] = __allkwargs0__ [__attrib0__]; + } + } + delete kwargs.__kwargtrans__; + } + var args = tuple ([].slice.apply (arguments).slice (1, __ilastarg0__ + 1)); + } + else { + var args = tuple (); + } + self.__args__ = args; + try { + self.stack = kwargs.error.stack; + } + catch (__except0__) { + self.stack = 'No stack trace available'; + } + });}, + get __repr__ () {return __get__ (this, function (self) { + if (len (self.__args__) > 1) { + return '{}{}'.format (self.__class__.__name__, repr (tuple (self.__args__))); + } + else if (len (self.__args__)) { + return '{}({})'.format (self.__class__.__name__, repr (self.__args__ [0])); + } + else { + return '{}()'.format (self.__class__.__name__); + } + });}, + get __str__ () {return __get__ (this, function (self) { + if (len (self.__args__) > 1) { + return str (tuple (self.__args__)); + } + else if (len (self.__args__)) { + return str (self.__args__ [0]); + } + else { + return ''; + } + });} +}); +export var IterableError = __class__ ('IterableError', [Exception], { + __module__: __name__, + get __init__ () {return __get__ (this, function (self, error) { + Exception.__init__ (self, "Can't iterate over non-iterable", __kwargtrans__ ({error: error})); + });} +}); +export var StopIteration = __class__ ('StopIteration', [Exception], { + __module__: __name__, + get __init__ () {return __get__ (this, function (self, error) { + Exception.__init__ (self, 'Iterator exhausted', __kwargtrans__ ({error: error})); + });} +}); +export var ValueError = __class__ ('ValueError', [Exception], { + __module__: __name__, + get __init__ () {return __get__ (this, function (self, message, error) { + Exception.__init__ (self, message, __kwargtrans__ ({error: error})); + });} +}); +export var KeyError = __class__ ('KeyError', [Exception], { + __module__: __name__, + get __init__ () {return __get__ (this, function (self, message, error) { + Exception.__init__ (self, message, __kwargtrans__ ({error: error})); + });} +}); +export var AssertionError = __class__ ('AssertionError', [Exception], { + __module__: __name__, + get __init__ () {return __get__ (this, function (self, message, error) { + if (message) { + Exception.__init__ (self, message, __kwargtrans__ ({error: error})); + } + else { + Exception.__init__ (self, __kwargtrans__ ({error: error})); + } + });} +}); +export var NotImplementedError = __class__ ('NotImplementedError', [Exception], { + __module__: __name__, + get __init__ () {return __get__ (this, function (self, message, error) { + Exception.__init__ (self, message, __kwargtrans__ ({error: error})); + });} +}); +export var IndexError = __class__ ('IndexError', [Exception], { + __module__: __name__, + get __init__ () {return __get__ (this, function (self, message, error) { + Exception.__init__ (self, message, __kwargtrans__ ({error: error})); + });} +}); +export var AttributeError = __class__ ('AttributeError', [Exception], { + __module__: __name__, + get __init__ () {return __get__ (this, function (self, message, error) { + Exception.__init__ (self, message, __kwargtrans__ ({error: error})); + });} +}); +export var py_TypeError = __class__ ('py_TypeError', [Exception], { + __module__: __name__, + get __init__ () {return __get__ (this, function (self, message, error) { + Exception.__init__ (self, message, __kwargtrans__ ({error: error})); + });} +}); +export var Warning = __class__ ('Warning', [Exception], { + __module__: __name__, +}); +export var UserWarning = __class__ ('UserWarning', [Warning], { + __module__: __name__, +}); +export var DeprecationWarning = __class__ ('DeprecationWarning', [Warning], { + __module__: __name__, +}); +export var RuntimeWarning = __class__ ('RuntimeWarning', [Warning], { + __module__: __name__, +}); +export var __sort__ = function (iterable, key, reverse) { + if (typeof key == 'undefined' || (key != null && key.hasOwnProperty ("__kwargtrans__"))) {; + var key = null; + }; + if (typeof reverse == 'undefined' || (reverse != null && reverse.hasOwnProperty ("__kwargtrans__"))) {; + var reverse = false; + }; + if (arguments.length) { + var __ilastarg0__ = arguments.length - 1; + if (arguments [__ilastarg0__] && arguments [__ilastarg0__].hasOwnProperty ("__kwargtrans__")) { + var __allkwargs0__ = arguments [__ilastarg0__--]; + for (var __attrib0__ in __allkwargs0__) { + switch (__attrib0__) { + case 'iterable': var iterable = __allkwargs0__ [__attrib0__]; break; + case 'key': var key = __allkwargs0__ [__attrib0__]; break; + case 'reverse': var reverse = __allkwargs0__ [__attrib0__]; break; + } + } + } + } + else { + } + if (key) { + iterable.sort ((function __lambda__ (a, b) { + if (arguments.length) { + var __ilastarg0__ = arguments.length - 1; + if (arguments [__ilastarg0__] && arguments [__ilastarg0__].hasOwnProperty ("__kwargtrans__")) { + var __allkwargs0__ = arguments [__ilastarg0__--]; + for (var __attrib0__ in __allkwargs0__) { + switch (__attrib0__) { + case 'a': var a = __allkwargs0__ [__attrib0__]; break; + case 'b': var b = __allkwargs0__ [__attrib0__]; break; + } + } + } + } + else { + } + return (key (a) > key (b) ? 1 : -(1)); + })); + } + else { + iterable.sort (); + } + if (reverse) { + iterable.reverse (); + } +}; +export var sorted = function (iterable, key, reverse) { + if (typeof key == 'undefined' || (key != null && key.hasOwnProperty ("__kwargtrans__"))) {; + var key = null; + }; + if (typeof reverse == 'undefined' || (reverse != null && reverse.hasOwnProperty ("__kwargtrans__"))) {; + var reverse = false; + }; + if (arguments.length) { + var __ilastarg0__ = arguments.length - 1; + if (arguments [__ilastarg0__] && arguments [__ilastarg0__].hasOwnProperty ("__kwargtrans__")) { + var __allkwargs0__ = arguments [__ilastarg0__--]; + for (var __attrib0__ in __allkwargs0__) { + switch (__attrib0__) { + case 'iterable': var iterable = __allkwargs0__ [__attrib0__]; break; + case 'key': var key = __allkwargs0__ [__attrib0__]; break; + case 'reverse': var reverse = __allkwargs0__ [__attrib0__]; break; + } + } + } + } + else { + } + if (py_typeof (iterable) == dict) { + var result = copy (iterable.py_keys ()); + } + else { + var result = copy (iterable); + } + __sort__ (result, key, reverse); + return result; +}; +export var map = function (func, iterable) { + return (function () { + var __accu0__ = []; + for (var item of iterable) { + __accu0__.append (func (item)); + } + return __accu0__; + }) (); +}; +export var filter = function (func, iterable) { + if (func == null) { + var func = bool; + } + return (function () { + var __accu0__ = []; + for (var item of iterable) { + if (func (item)) { + __accu0__.append (item); + } + } + return __accu0__; + }) (); +}; +export var divmod = function (n, d) { + return tuple ([Math.floor (n / d), __mod__ (n, d)]); +}; +export var __Terminal__ = __class__ ('__Terminal__', [object], { + __module__: __name__, + get __init__ () {return __get__ (this, function (self) { + self.buffer = ''; + try { + self.element = document.getElementById ('__terminal__'); + } + catch (__except0__) { + self.element = null; + } + if (self.element) { + self.element.style.overflowX = 'auto'; + self.element.style.boxSizing = 'border-box'; + self.element.style.padding = '5px'; + self.element.innerHTML = '_'; + } + });}, + get print () {return __get__ (this, function (self) { + var sep = ' '; + var end = '\n'; + if (arguments.length) { + var __ilastarg0__ = arguments.length - 1; + if (arguments [__ilastarg0__] && arguments [__ilastarg0__].hasOwnProperty ("__kwargtrans__")) { + var __allkwargs0__ = arguments [__ilastarg0__--]; + for (var __attrib0__ in __allkwargs0__) { + switch (__attrib0__) { + case 'self': var self = __allkwargs0__ [__attrib0__]; break; + case 'sep': var sep = __allkwargs0__ [__attrib0__]; break; + case 'end': var end = __allkwargs0__ [__attrib0__]; break; + } + } + } + var args = tuple ([].slice.apply (arguments).slice (1, __ilastarg0__ + 1)); + } + else { + var args = tuple (); + } + self.buffer = '{}{}{}'.format (self.buffer, sep.join ((function () { + var __accu0__ = []; + for (var arg of args) { + __accu0__.append (str (arg)); + } + return __accu0__; + }) ()), end).__getslice__ (-(4096), null, 1); + if (self.element) { + self.element.innerHTML = self.buffer.py_replace ('\n', '
').py_replace (' ', ' '); + self.element.scrollTop = self.element.scrollHeight; + } + else { + console.log (sep.join ((function () { + var __accu0__ = []; + for (var arg of args) { + __accu0__.append (str (arg)); + } + return __accu0__; + }) ())); + } + });}, + get input () {return __get__ (this, function (self, question) { + if (arguments.length) { + var __ilastarg0__ = arguments.length - 1; + if (arguments [__ilastarg0__] && arguments [__ilastarg0__].hasOwnProperty ("__kwargtrans__")) { + var __allkwargs0__ = arguments [__ilastarg0__--]; + for (var __attrib0__ in __allkwargs0__) { + switch (__attrib0__) { + case 'self': var self = __allkwargs0__ [__attrib0__]; break; + case 'question': var question = __allkwargs0__ [__attrib0__]; break; + } + } + } + } + else { + } + self.print ('{}'.format (question), __kwargtrans__ ({end: ''})); + var answer = window.prompt ('\n'.join (self.buffer.py_split ('\n').__getslice__ (-(8), null, 1))); + self.print (answer); + return answer; + });} +}); +export var __terminal__ = __Terminal__ (); +export var print = __terminal__.print; +export var input = __terminal__.input; + +//# sourceMappingURL=org.transcrypt.__runtime__.map \ No newline at end of file diff --git a/docs/examples/sketch_008/target/org.transcrypt.__runtime__.py b/docs/examples/sketch_008/target/org.transcrypt.__runtime__.py new file mode 100644 index 00000000..87834491 --- /dev/null +++ b/docs/examples/sketch_008/target/org.transcrypt.__runtime__.py @@ -0,0 +1,285 @@ +# Transcrypt runtime module + +#__pragma__ ('js', 'export var __envir__ = {{}};\n{}', __include__ ('org/transcrypt/__envir__.js')) +#__pragma__ ('js', '{}', __include__ ('org/transcrypt/__core__.js')) +#__pragma__ ('js', '{}', __include__ ('org/transcrypt/__builtin__.js')) + +#__pragma__ ('skip') +copy = Math = __typeof__ = __repr__ = document = console = window = 0 +#__pragma__ ('noskip') + +#__pragma__ ('notconv') # !!! tconv gives a problem with __terminal__, needs investigation +#__pragma__ ('nokwargs') +#__pragma__ ('noalias', 'sort') + +class BaseException: + pass + +class Exception (BaseException): + #__pragma__ ('kwargs') + def __init__ (self, *args, **kwargs): + self.__args__ = args + try: + self.stack = kwargs.error.stack # Integrate with JavaScript Error object + except: + self.stack = 'No stack trace available' + #__pragma__ ('nokwargs') + + def __repr__ (self): + if len (self.__args__) > 1: + return '{}{}'.format (self.__class__.__name__, repr (tuple (self.__args__))) + elif len (self.__args__): + return '{}({})'.format (self.__class__.__name__, repr (self.__args__ [0])) + else: + return '{}()'.format (self.__class__.__name__) + + def __str__ (self): + if len (self.__args__) > 1: + return str (tuple (self.__args__)) + elif len (self.__args__): + return str (self.__args__ [0]) + else: + return '' + +class IterableError (Exception): + def __init__ (self, error): + Exception.__init__ (self, 'Can\'t iterate over non-iterable', error = error) + +class StopIteration (Exception): + def __init__ (self, error): + Exception.__init__ (self, 'Iterator exhausted', error = error) + +class ValueError (Exception): + def __init__ (self, message, error): + Exception.__init__ (self, message, error = error) + +class KeyError (Exception): + def __init__ (self, message, error): + Exception.__init__ (self, message, error = error) + +class AssertionError (Exception): + def __init__ (self, message, error): + if message: + Exception.__init__ (self, message, error = error) + else: + Exception.__init__ (self, error = error) + +class NotImplementedError (Exception): + def __init__(self, message, error): + Exception.__init__(self, message, error = error) + +class IndexError (Exception): + def __init__(self, message, error): + Exception.__init__(self, message, error = error) + +class AttributeError (Exception): + def __init__(self, message, error): + Exception.__init__(self, message, error = error) + +class TypeError (Exception): + def __init__(self, message, error): + Exception.__init__(self, message, error = error) + +# Warnings Exceptions +# N.B. This is a limited subset of the warnings defined in +# the cpython implementation to keep things small for now. + +class Warning (Exception): + ''' Warning Base Class + ''' + pass + +class UserWarning (Warning): + pass + +class DeprecationWarning (Warning): + pass + +class RuntimeWarning (Warning): + pass + +#__pragma__ ('kwargs') + +def __sort__ (iterable, key = None, reverse = False): # Used by py_sort, can deal with kwargs + if key: + iterable.sort (lambda a, b: 1 if key (a) > key (b) else -1) # JavaScript sort, case '==' is irrelevant for sorting + else: + iterable.sort () # JavaScript sort + + if reverse: + iterable.reverse () + +def sorted (iterable, key = None, reverse = False): + if type (iterable) == dict: + result = copy (iterable.keys ()) + else: + result = copy (iterable) + + __sort__ (result, key, reverse) + return result + +#__pragma__ ('nokwargs') + +def map (func, iterable): + return [func (item) for item in iterable] + + +def filter (func, iterable): + if func == None: + func = bool + return [item for item in iterable if func (item)] + +def divmod (n, d): + return n // d, n % d + +#__pragma__ ('ifdef', '__complex__') + +class complex: + def __init__ (self, real, imag = None): + if imag == None: + if type (real) == complex: + self.real = real.real + self.imag = real.imag + else: + self.real = real + self.imag = 0 + else: + self.real = real + self.imag = imag + + def __neg__ (self): + return complex (-self.real, -self.imag) + + def __exp__ (self): + modulus = Math.exp (self.real) + return complex (modulus * Math.cos (self.imag), modulus * Math.sin (self.imag)) + + def __log__ (self): + return complex (Math.log (Math.sqrt (self.real * self.real + self.imag * self.imag)), Math.atan2 (self.imag, self.real)) + + def __pow__ (self, other): # a ** b = exp (b log a) + return (self.__log__ () .__mul__ (other)) .__exp__ () + + def __rpow__ (self, real): # real ** comp -> comp.__rpow__ (real) + return self.__mul__ (Math.log (real)) .__exp__ () + + def __mul__ (self, other): + if __typeof__ (other) is 'number': + return complex (self.real * other, self.imag * other) + else: + return complex (self.real * other.real - self.imag * other.imag, self.real * other.imag + self.imag * other.real) + + def __rmul__ (self, real): # real + comp -> comp.__rmul__ (real) + return complex (self.real * real, self.imag * real) + + def __div__ (self, other): + if __typeof__ (other) is 'number': + return complex (self.real / other, self.imag / other) + else: + denom = other.real * other.real + other.imag * other.imag + return complex ( + (self.real * other.real + self.imag * other.imag) / denom, + (self.imag * other.real - self.real * other.imag) / denom + ) + + def __rdiv__ (self, real): # real / comp -> comp.__rdiv__ (real) + denom = self.real * self.real + return complex ( + (real * self.real) / denom, + (real * self.imag) / denom + ) + + def __add__ (self, other): + if __typeof__ (other) is 'number': + return complex (self.real + other, self.imag) + else: # Assume other is complex + return complex (self.real + other.real, self.imag + other.imag) + + def __radd__ (self, real): # real + comp -> comp.__radd__ (real) + return complex (self.real + real, self.imag) + + def __sub__ (self, other): + if __typeof__ (other) is 'number': + return complex (self.real - other, self.imag) + else: + return complex (self.real - other.real, self.imag - other.imag) + + def __rsub__ (self, real): # real - comp -> comp.__rsub__ (real) + return complex (real - self.real, -self.imag) + + def __repr__ (self): + return '({}{}{}j)'.format (self.real, '+' if self.imag >= 0 else '', self.imag) + + def __str__ (self): + return __repr__ (self) [1 : -1] + + def __eq__ (self, other): + if __typeof__ (other) is 'number': + return self.real == other + else: + return self.real == other.real and self.imag == other.imag + + def __ne__ (self, other): + if __typeof__ (other) is 'number': + return self.real != other + else: + return self.real != other.real or self.imag != other.imag + + def conjugate (self): + return complex (self.real, -self.imag) + +def __conj__ (aNumber): + if isinstance (aNumber, complex): + return complex (aNumber.real, -aNumber.imag) + else: + return complex (aNumber, 0) + +#__pragma__ ('endif') + +class __Terminal__: + ''' + Printing to either the console or to html happens async, but is blocked by calling window.prompt. + So while all input and print statements are encountered in normal order, the print's exit immediately without yet having actually printed + This means the next input takes control, blocking actual printing and so on indefinitely + The effect is that everything's only printed after all inputs are done + To prevent that, what's needed is to only execute the next window.prompt after actual printing has been done + Since we've no way to find out when that is, a timeout is used. + ''' + + def __init__ (self): + self.buffer = '' + + try: + self.element = document.getElementById ('__terminal__') + except: + self.element = None + + if self.element: + self.element.style.overflowX = 'auto' + self.element.style.boxSizing = 'border-box' + self.element.style.padding = '5px' + self.element.innerHTML = '_' + + #__pragma__ ('kwargs') + + def print (self, *args, sep = ' ', end = '\n'): + self.buffer = '{}{}{}'.format (self.buffer, sep.join ([str (arg) for arg in args]), end) [-4096 : ] + + if self.element: + self.element.innerHTML = self.buffer.replace ('\n', '
') .replace (' ', ' ') + self.element.scrollTop = self.element.scrollHeight + else: + console.log (sep.join ([str (arg) for arg in args])) + + def input (self, question): + self.print ('{}'.format (question), end = '') + answer = window.prompt ('\n'.join (self.buffer.split ('\n') [-8:])) + self.print (answer) + return answer + + #__pragma__ ('nokwargs') + +__terminal__ = __Terminal__ () + +print = __terminal__.print +input = __terminal__.input diff --git a/docs/examples/sketch_008/target/pytop5js.js b/docs/examples/sketch_008/target/pytop5js.js new file mode 100644 index 00000000..1ada93e1 --- /dev/null +++ b/docs/examples/sketch_008/target/pytop5js.js @@ -0,0 +1,1365 @@ +// Transcrypt'ed from Python, 2019-06-02 16:11:11 +import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, isinstance, issubclass, len, list, object, ord, print, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; +var __name__ = 'pytop5js'; +export var _P5_INSTANCE = null; +export var _CTX_MIDDLE = null; +export var _DEFAULT_FILL = null; +export var _DEFAULT_LEADMULT = null; +export var _DEFAULT_STROKE = null; +export var _DEFAULT_TEXT_FILL = null; +export var ADD = null; +export var ALT = null; +export var ARROW = null; +export var AUTO = null; +export var AXES = null; +export var BACKSPACE = null; +export var BASELINE = null; +export var BEVEL = null; +export var BEZIER = null; +export var BLEND = null; +export var BLUR = null; +export var BOLD = null; +export var BOLDITALIC = null; +export var BOTTOM = null; +export var BURN = null; +export var CENTER = null; +export var CHORD = null; +export var CLAMP = null; +export var CLOSE = null; +export var CONTROL = null; +export var CORNER = null; +export var CORNERS = null; +export var CROSS = null; +export var CURVE = null; +export var DARKEST = null; +export var DEG_TO_RAD = null; +export var DEGREES = null; +export var DELETE = null; +export var DIFFERENCE = null; +export var DILATE = null; +export var DODGE = null; +export var DOWN_ARROW = null; +export var ENTER = null; +export var ERODE = null; +export var ESCAPE = null; +export var EXCLUSION = null; +export var FILL = null; +export var GRAY = null; +export var GRID = null; +export var HALF_PI = null; +export var HAND = null; +export var HARD_LIGHT = null; +export var HSB = null; +export var HSL = null; +export var IMAGE = null; +export var IMMEDIATE = null; +export var INVERT = null; +export var ITALIC = null; +export var LANDSCAPE = null; +export var LEFT = null; +export var LEFT_ARROW = null; +export var LIGHTEST = null; +export var LINE_LOOP = null; +export var LINE_STRIP = null; +export var LINEAR = null; +export var LINES = null; +export var MIRROR = null; +export var MITER = null; +export var MOVE = null; +export var MULTIPLY = null; +export var NEAREST = null; +export var NORMAL = null; +export var OPAQUE = null; +export var OPEN = null; +export var OPTION = null; +export var OVERLAY = null; +export var PI = null; +export var PIE = null; +export var POINTS = null; +export var PORTRAIT = null; +export var POSTERIZE = null; +export var PROJECT = null; +export var QUAD_STRIP = null; +export var QUADRATIC = null; +export var QUADS = null; +export var QUARTER_PI = null; +export var RAD_TO_DEG = null; +export var RADIANS = null; +export var RADIUS = null; +export var REPEAT = null; +export var REPLACE = null; +export var RETURN = null; +export var RGB = null; +export var RIGHT = null; +export var RIGHT_ARROW = null; +export var ROUND = null; +export var SCREEN = null; +export var SHIFT = null; +export var SOFT_LIGHT = null; +export var SQUARE = null; +export var STROKE = null; +export var SUBTRACT = null; +export var TAB = null; +export var TAU = null; +export var TEXT = null; +export var TEXTURE = null; +export var THRESHOLD = null; +export var TOP = null; +export var TRIANGLE_FAN = null; +export var TRIANGLE_STRIP = null; +export var TRIANGLES = null; +export var TWO_PI = null; +export var UP_ARROW = null; +export var WAIT = null; +export var WEBGL = null; +export var P2D = null; +var PI = null; +export var frameCount = null; +export var focused = null; +export var displayWidth = null; +export var displayHeight = null; +export var windowWidth = null; +export var windowHeight = null; +export var width = null; +export var height = null; +export var disableFriendlyErrors = null; +export var deviceOrientation = null; +export var accelerationX = null; +export var accelerationY = null; +export var accelerationZ = null; +export var pAccelerationX = null; +export var pAccelerationY = null; +export var pAccelerationZ = null; +export var rotationX = null; +export var rotationY = null; +export var rotationZ = null; +export var pRotationX = null; +export var pRotationY = null; +export var pRotationZ = null; +export var turnAxis = null; +export var keyIsPressed = null; +export var key = null; +export var keyCode = null; +export var mouseX = null; +export var mouseY = null; +export var pmouseX = null; +export var pmouseY = null; +export var winMouseX = null; +export var winMouseY = null; +export var pwinMouseX = null; +export var pwinMouseY = null; +export var mouseButton = null; +export var mouseIsPressed = null; +export var touches = null; +export var pixels = null; +export var VIDEO = null; +export var AUDIO = null; +export var alpha = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.alpha (...args); +}; +export var blue = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.blue (...args); +}; +export var brightness = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.brightness (...args); +}; +export var color = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.color (...args); +}; +export var green = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.green (...args); +}; +export var hue = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.hue (...args); +}; +export var lerpColor = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.lerpColor (...args); +}; +export var lightness = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.lightness (...args); +}; +export var red = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.red (...args); +}; +export var saturation = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.saturation (...args); +}; +export var background = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.background (...args); +}; +export var py_clear = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.py_clear (...args); +}; +export var colorMode = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.colorMode (...args); +}; +export var fill = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.fill (...args); +}; +export var noFill = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.noFill (...args); +}; +export var noStroke = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.noStroke (...args); +}; +export var stroke = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.stroke (...args); +}; +export var arc = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.arc (...args); +}; +export var ellipse = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.ellipse (...args); +}; +export var circle = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.circle (...args); +}; +export var line = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.line (...args); +}; +export var point = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.point (...args); +}; +export var quad = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.quad (...args); +}; +export var rect = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.rect (...args); +}; +export var square = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.square (...args); +}; +export var triangle = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.triangle (...args); +}; +export var plane = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.plane (...args); +}; +export var box = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.box (...args); +}; +export var sphere = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.sphere (...args); +}; +export var cylinder = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.cylinder (...args); +}; +export var cone = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.cone (...args); +}; +export var ellipsoid = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.ellipsoid (...args); +}; +export var torus = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.torus (...args); +}; +export var loadModel = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.loadModel (...args); +}; +export var model = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.model (...args); +}; +export var ellipseMode = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.ellipseMode (...args); +}; +export var noSmooth = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.noSmooth (...args); +}; +export var rectMode = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.rectMode (...args); +}; +export var smooth = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.smooth (...args); +}; +export var strokeCap = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.strokeCap (...args); +}; +export var strokeJoin = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.strokeJoin (...args); +}; +export var strokeWeight = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.strokeWeight (...args); +}; +export var bezier = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.bezier (...args); +}; +export var bezierDetail = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.bezierDetail (...args); +}; +export var bezierPoint = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.bezierPoint (...args); +}; +export var bezierTangent = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.bezierTangent (...args); +}; +export var curve = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.curve (...args); +}; +export var curveDetail = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.curveDetail (...args); +}; +export var curveTightness = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.curveTightness (...args); +}; +export var curvePoint = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.curvePoint (...args); +}; +export var curveTangent = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.curveTangent (...args); +}; +export var beginContour = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.beginContour (...args); +}; +export var beginShape = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.beginShape (...args); +}; +export var bezierVertex = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.bezierVertex (...args); +}; +export var curveVertex = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.curveVertex (...args); +}; +export var endContour = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.endContour (...args); +}; +export var endShape = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.endShape (...args); +}; +export var quadraticVertex = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.quadraticVertex (...args); +}; +export var vertex = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.vertex (...args); +}; +export var cursor = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.cursor (...args); +}; +export var frameRate = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.frameRate (...args); +}; +export var noCursor = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.noCursor (...args); +}; +export var fullscreen = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.fullscreen (...args); +}; +export var pixelDensity = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.pixelDensity (...args); +}; +export var displayDensity = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.displayDensity (...args); +}; +export var getURL = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.getURL (...args); +}; +export var getURLPath = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.getURLPath (...args); +}; +export var getURLParams = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.getURLParams (...args); +}; +export var preload = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.preload (...args); +}; +export var setup = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.setup (...args); +}; +export var draw = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.draw (...args); +}; +export var remove = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.remove (...args); +}; +export var noLoop = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.noLoop (...args); +}; +export var loop = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.loop (...args); +}; +export var push = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.push (...args); +}; +export var redraw = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.redraw (...args); +}; +export var resizeCanvas = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.resizeCanvas (...args); +}; +export var noCanvas = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.noCanvas (...args); +}; +export var createGraphics = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createGraphics (...args); +}; +export var blendMode = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.blendMode (...args); +}; +export var setAttributes = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.setAttributes (...args); +}; +export var applyMatrix = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.applyMatrix (...args); +}; +export var resetMatrix = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.resetMatrix (...args); +}; +export var rotate = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.rotate (...args); +}; +export var rotateX = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.rotateX (...args); +}; +export var rotateY = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.rotateY (...args); +}; +export var rotateZ = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.rotateZ (...args); +}; +export var scale = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.scale (...args); +}; +export var shearX = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.shearX (...args); +}; +export var shearY = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.shearY (...args); +}; +export var translate = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.translate (...args); +}; +export var createStringDict = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createStringDict (...args); +}; +export var createNumberDict = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createNumberDict (...args); +}; +export var append = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.append (...args); +}; +export var arrayCopy = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.arrayCopy (...args); +}; +export var concat = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.concat (...args); +}; +export var reverse = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.reverse (...args); +}; +export var shorten = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.shorten (...args); +}; +export var shuffle = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.shuffle (...args); +}; +export var py_sort = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.py_sort (...args); +}; +export var splice = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.splice (...args); +}; +export var subset = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.subset (...args); +}; +export var float = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.float (...args); +}; +export var int = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.int (...args); +}; +export var str = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.str (...args); +}; +export var boolean = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.boolean (...args); +}; +export var byte = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.byte (...args); +}; +export var char = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.char (...args); +}; +export var unchar = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.unchar (...args); +}; +export var hex = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.hex (...args); +}; +export var unhex = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.unhex (...args); +}; +export var join = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.join (...args); +}; +export var match = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.match (...args); +}; +export var matchAll = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.matchAll (...args); +}; +export var nf = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.nf (...args); +}; +export var nfc = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.nfc (...args); +}; +export var nfp = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.nfp (...args); +}; +export var nfs = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.nfs (...args); +}; +export var py_split = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.py_split (...args); +}; +export var splitTokens = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.splitTokens (...args); +}; +export var trim = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.trim (...args); +}; +export var setMoveThreshold = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.setMoveThreshold (...args); +}; +export var setShakeThreshold = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.setShakeThreshold (...args); +}; +export var keyIsDown = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.keyIsDown (...args); +}; +export var createImage = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createImage (...args); +}; +export var saveCanvas = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.saveCanvas (...args); +}; +export var saveFrames = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.saveFrames (...args); +}; +export var loadImage = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.loadImage (...args); +}; +export var image = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.image (...args); +}; +export var tint = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.tint (...args); +}; +export var noTint = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.noTint (...args); +}; +export var imageMode = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.imageMode (...args); +}; +export var blend = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.blend (...args); +}; +export var copy = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.copy (...args); +}; +export var filter = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.filter (...args); +}; +export var py_get = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.py_get (...args); +}; +export var loadPixels = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.loadPixels (...args); +}; +export var set = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.set (...args); +}; +export var updatePixels = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.updatePixels (...args); +}; +export var loadJSON = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.loadJSON (...args); +}; +export var loadStrings = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.loadStrings (...args); +}; +export var loadTable = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.loadTable (...args); +}; +export var loadXML = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.loadXML (...args); +}; +export var loadBytes = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.loadBytes (...args); +}; +export var httpGet = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.httpGet (...args); +}; +export var httpPost = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.httpPost (...args); +}; +export var httpDo = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.httpDo (...args); +}; +export var createWriter = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createWriter (...args); +}; +export var save = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.save (...args); +}; +export var saveJSON = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.saveJSON (...args); +}; +export var saveStrings = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.saveStrings (...args); +}; +export var saveTable = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.saveTable (...args); +}; +export var day = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.day (...args); +}; +export var hour = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.hour (...args); +}; +export var minute = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.minute (...args); +}; +export var millis = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.millis (...args); +}; +export var month = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.month (...args); +}; +export var second = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.second (...args); +}; +export var year = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.year (...args); +}; +export var createVector = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createVector (...args); +}; +export var abs = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.abs (...args); +}; +export var ceil = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.ceil (...args); +}; +export var constrain = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.constrain (...args); +}; +export var dist = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.dist (...args); +}; +export var exp = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.exp (...args); +}; +export var floor = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.floor (...args); +}; +export var lerp = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.lerp (...args); +}; +export var log = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.log (...args); +}; +export var mag = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.mag (...args); +}; +export var map = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.map (...args); +}; +export var max = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.max (...args); +}; +export var min = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.min (...args); +}; +export var norm = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.norm (...args); +}; +export var pow = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.pow (...args); +}; +export var round = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.round (...args); +}; +export var sq = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.sq (...args); +}; +export var sqrt = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.sqrt (...args); +}; +export var noise = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.noise (...args); +}; +export var noiseDetail = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.noiseDetail (...args); +}; +export var noiseSeed = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.noiseSeed (...args); +}; +export var randomSeed = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.randomSeed (...args); +}; +export var random = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.random (...args); +}; +export var randomGaussian = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.randomGaussian (...args); +}; +export var acos = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.acos (...args); +}; +export var asin = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.asin (...args); +}; +export var atan = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.atan (...args); +}; +export var atan2 = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.atan2 (...args); +}; +export var cos = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.cos (...args); +}; +export var sin = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.sin (...args); +}; +export var tan = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.tan (...args); +}; +export var degrees = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.degrees (...args); +}; +export var radians = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.radians (...args); +}; +export var angleMode = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.angleMode (...args); +}; +export var textAlign = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.textAlign (...args); +}; +export var textLeading = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.textLeading (...args); +}; +export var textSize = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.textSize (...args); +}; +export var textStyle = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.textStyle (...args); +}; +export var textWidth = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.textWidth (...args); +}; +export var textAscent = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.textAscent (...args); +}; +export var textDescent = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.textDescent (...args); +}; +export var loadFont = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.loadFont (...args); +}; +export var text = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.text (...args); +}; +export var textFont = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.textFont (...args); +}; +export var orbitControl = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.orbitControl (...args); +}; +export var debugMode = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.debugMode (...args); +}; +export var noDebugMode = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.noDebugMode (...args); +}; +export var ambientLight = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.ambientLight (...args); +}; +export var directionalLight = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.directionalLight (...args); +}; +export var pointLight = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.pointLight (...args); +}; +export var lights = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.lights (...args); +}; +export var loadShader = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.loadShader (...args); +}; +export var createShader = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createShader (...args); +}; +export var shader = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.shader (...args); +}; +export var resetShader = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.resetShader (...args); +}; +export var normalMaterial = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.normalMaterial (...args); +}; +export var texture = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.texture (...args); +}; +export var textureMode = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.textureMode (...args); +}; +export var textureWrap = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.textureWrap (...args); +}; +export var ambientMaterial = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.ambientMaterial (...args); +}; +export var specularMaterial = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.specularMaterial (...args); +}; +export var shininess = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.shininess (...args); +}; +export var camera = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.camera (...args); +}; +export var perspective = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.perspective (...args); +}; +export var ortho = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.ortho (...args); +}; +export var createCamera = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createCamera (...args); +}; +export var setCamera = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.setCamera (...args); +}; +export var select = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.select (...args); +}; +export var selectAll = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.selectAll (...args); +}; +export var removeElements = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.removeElements (...args); +}; +export var changed = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.changed (...args); +}; +export var input = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.input (...args); +}; +export var createDiv = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createDiv (...args); +}; +export var createP = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createP (...args); +}; +export var createSpan = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createSpan (...args); +}; +export var createImg = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createImg (...args); +}; +export var createA = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createA (...args); +}; +export var createSlider = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createSlider (...args); +}; +export var createButton = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createButton (...args); +}; +export var createCheckbox = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createCheckbox (...args); +}; +export var createSelect = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createSelect (...args); +}; +export var createRadio = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createRadio (...args); +}; +export var createColorPicker = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createColorPicker (...args); +}; +export var createInput = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createInput (...args); +}; +export var createFileInput = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createFileInput (...args); +}; +export var createVideo = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createVideo (...args); +}; +export var createAudio = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createAudio (...args); +}; +export var createCapture = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createCapture (...args); +}; +export var createElement = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + return _P5_INSTANCE.createElement (...args); +}; +export var createCanvas = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + var result = _P5_INSTANCE.createCanvas (...args); + width = _P5_INSTANCE.width; + height = _P5_INSTANCE.height; +}; +export var py_pop = function () { + var args = tuple ([].slice.apply (arguments).slice (0)); + var p5_pop = _P5_INSTANCE.pop (...args); + return p5_pop; +}; +export var pre_draw = function (p5_instance, draw_func) { + _CTX_MIDDLE = p5_instance._CTX_MIDDLE; + _DEFAULT_FILL = p5_instance._DEFAULT_FILL; + _DEFAULT_LEADMULT = p5_instance._DEFAULT_LEADMULT; + _DEFAULT_STROKE = p5_instance._DEFAULT_STROKE; + _DEFAULT_TEXT_FILL = p5_instance._DEFAULT_TEXT_FILL; + ADD = p5_instance.ADD; + ALT = p5_instance.ALT; + ARROW = p5_instance.ARROW; + AUTO = p5_instance.AUTO; + AXES = p5_instance.AXES; + BACKSPACE = p5_instance.BACKSPACE; + BASELINE = p5_instance.BASELINE; + BEVEL = p5_instance.BEVEL; + BEZIER = p5_instance.BEZIER; + BLEND = p5_instance.BLEND; + BLUR = p5_instance.BLUR; + BOLD = p5_instance.BOLD; + BOLDITALIC = p5_instance.BOLDITALIC; + BOTTOM = p5_instance.BOTTOM; + BURN = p5_instance.BURN; + CENTER = p5_instance.CENTER; + CHORD = p5_instance.CHORD; + CLAMP = p5_instance.CLAMP; + CLOSE = p5_instance.CLOSE; + CONTROL = p5_instance.CONTROL; + CORNER = p5_instance.CORNER; + CORNERS = p5_instance.CORNERS; + CROSS = p5_instance.CROSS; + CURVE = p5_instance.CURVE; + DARKEST = p5_instance.DARKEST; + DEG_TO_RAD = p5_instance.DEG_TO_RAD; + DEGREES = p5_instance.DEGREES; + DELETE = p5_instance.DELETE; + DIFFERENCE = p5_instance.DIFFERENCE; + DILATE = p5_instance.DILATE; + DODGE = p5_instance.DODGE; + DOWN_ARROW = p5_instance.DOWN_ARROW; + ENTER = p5_instance.ENTER; + ERODE = p5_instance.ERODE; + ESCAPE = p5_instance.ESCAPE; + EXCLUSION = p5_instance.EXCLUSION; + FILL = p5_instance.FILL; + GRAY = p5_instance.GRAY; + GRID = p5_instance.GRID; + HALF_PI = p5_instance.HALF_PI; + HAND = p5_instance.HAND; + HARD_LIGHT = p5_instance.HARD_LIGHT; + HSB = p5_instance.HSB; + HSL = p5_instance.HSL; + IMAGE = p5_instance.IMAGE; + IMMEDIATE = p5_instance.IMMEDIATE; + INVERT = p5_instance.INVERT; + ITALIC = p5_instance.ITALIC; + LANDSCAPE = p5_instance.LANDSCAPE; + LEFT = p5_instance.LEFT; + LEFT_ARROW = p5_instance.LEFT_ARROW; + LIGHTEST = p5_instance.LIGHTEST; + LINE_LOOP = p5_instance.LINE_LOOP; + LINE_STRIP = p5_instance.LINE_STRIP; + LINEAR = p5_instance.LINEAR; + LINES = p5_instance.LINES; + MIRROR = p5_instance.MIRROR; + MITER = p5_instance.MITER; + MOVE = p5_instance.MOVE; + MULTIPLY = p5_instance.MULTIPLY; + NEAREST = p5_instance.NEAREST; + NORMAL = p5_instance.NORMAL; + OPAQUE = p5_instance.OPAQUE; + OPEN = p5_instance.OPEN; + OPTION = p5_instance.OPTION; + OVERLAY = p5_instance.OVERLAY; + PI = p5_instance.PI; + PIE = p5_instance.PIE; + POINTS = p5_instance.POINTS; + PORTRAIT = p5_instance.PORTRAIT; + POSTERIZE = p5_instance.POSTERIZE; + PROJECT = p5_instance.PROJECT; + QUAD_STRIP = p5_instance.QUAD_STRIP; + QUADRATIC = p5_instance.QUADRATIC; + QUADS = p5_instance.QUADS; + QUARTER_PI = p5_instance.QUARTER_PI; + RAD_TO_DEG = p5_instance.RAD_TO_DEG; + RADIANS = p5_instance.RADIANS; + RADIUS = p5_instance.RADIUS; + REPEAT = p5_instance.REPEAT; + REPLACE = p5_instance.REPLACE; + RETURN = p5_instance.RETURN; + RGB = p5_instance.RGB; + RIGHT = p5_instance.RIGHT; + RIGHT_ARROW = p5_instance.RIGHT_ARROW; + ROUND = p5_instance.ROUND; + SCREEN = p5_instance.SCREEN; + SHIFT = p5_instance.SHIFT; + SOFT_LIGHT = p5_instance.SOFT_LIGHT; + SQUARE = p5_instance.SQUARE; + STROKE = p5_instance.STROKE; + SUBTRACT = p5_instance.SUBTRACT; + TAB = p5_instance.TAB; + TAU = p5_instance.TAU; + TEXT = p5_instance.TEXT; + TEXTURE = p5_instance.TEXTURE; + THRESHOLD = p5_instance.THRESHOLD; + TOP = p5_instance.TOP; + TRIANGLE_FAN = p5_instance.TRIANGLE_FAN; + TRIANGLE_STRIP = p5_instance.TRIANGLE_STRIP; + TRIANGLES = p5_instance.TRIANGLES; + TWO_PI = p5_instance.TWO_PI; + UP_ARROW = p5_instance.UP_ARROW; + WAIT = p5_instance.WAIT; + WEBGL = p5_instance.WEBGL; + P2D = p5_instance.P2D; + PI = p5_instance.PI; + frameCount = p5_instance.frameCount; + focused = p5_instance.focused; + displayWidth = p5_instance.displayWidth; + displayHeight = p5_instance.displayHeight; + windowWidth = p5_instance.windowWidth; + windowHeight = p5_instance.windowHeight; + width = p5_instance.width; + height = p5_instance.height; + disableFriendlyErrors = p5_instance.disableFriendlyErrors; + deviceOrientation = p5_instance.deviceOrientation; + accelerationX = p5_instance.accelerationX; + accelerationY = p5_instance.accelerationY; + accelerationZ = p5_instance.accelerationZ; + pAccelerationX = p5_instance.pAccelerationX; + pAccelerationY = p5_instance.pAccelerationY; + pAccelerationZ = p5_instance.pAccelerationZ; + rotationX = p5_instance.rotationX; + rotationY = p5_instance.rotationY; + rotationZ = p5_instance.rotationZ; + pRotationX = p5_instance.pRotationX; + pRotationY = p5_instance.pRotationY; + pRotationZ = p5_instance.pRotationZ; + turnAxis = p5_instance.turnAxis; + keyIsPressed = p5_instance.keyIsPressed; + key = p5_instance.key; + keyCode = p5_instance.keyCode; + mouseX = p5_instance.mouseX; + mouseY = p5_instance.mouseY; + pmouseX = p5_instance.pmouseX; + pmouseY = p5_instance.pmouseY; + winMouseX = p5_instance.winMouseX; + winMouseY = p5_instance.winMouseY; + pwinMouseX = p5_instance.pwinMouseX; + pwinMouseY = p5_instance.pwinMouseY; + mouseButton = p5_instance.mouseButton; + mouseIsPressed = p5_instance.mouseIsPressed; + touches = p5_instance.touches; + pixels = p5_instance.pixels; + VIDEO = p5_instance.VIDEO; + AUDIO = p5_instance.AUDIO; + return draw_func (); +}; +export var global_p5_injection = function (p5_sketch) { + var decorator = function (f) { + var wrapper = function () { + _P5_INSTANCE = p5_sketch; + return pre_draw (_P5_INSTANCE, f); + }; + return wrapper; + }; + return decorator; +}; +export var start_p5 = function (setup_func, draw_func, event_functions) { + var sketch_setup = function (p5_sketch) { + p5_sketch.setup = global_p5_injection (p5_sketch) (setup_func); + p5_sketch.draw = global_p5_injection (p5_sketch) (draw_func); + }; + var instance = new p5 (sketch_setup, 'sketch-holder'); + var event_function_names = list (['deviceMoved', 'deviceTurned', 'deviceShaken', 'keyPressed', 'keyReleased', 'keyTyped', 'mouseMoved', 'mouseDragged', 'mousePressed', 'mouseReleased', 'mouseClicked', 'doubleClicked', 'mouseWheel', 'touchStarted', 'touchMoved', 'touchEnded', 'windowResized']); + for (var f_name of (function () { + var __accu0__ = []; + for (var f of event_function_names) { + if (event_functions.py_get (f, null)) { + __accu0__.append (f); + } + } + return __accu0__; + }) ()) { + var func = event_functions [f_name]; + var event_func = global_p5_injection (instance) (func); + setattr (instance, f_name, event_func); + } +}; +export var logOnloaded = function () { + console.log ('Lib loaded!'); +}; +export var add_library = function (lib_name) { + var src = ''; + if (lib_name == 'p5.dom.js') { + var src = 'static/p5.dom.js'; + } + else { + console.log ('Lib name is not valid: ' + lib_name); + return ; + } + console.log ('Importing: ' + src); + var script = document.createElement ('script'); + script.onload = logOnloaded; + script.src = src; + document.head.appendChild (script); +}; + +//# sourceMappingURL=pytop5js.map \ No newline at end of file diff --git a/docs/examples/sketch_008/target/pytop5js.py b/docs/examples/sketch_008/target/pytop5js.py new file mode 100644 index 00000000..22af949d --- /dev/null +++ b/docs/examples/sketch_008/target/pytop5js.py @@ -0,0 +1,1138 @@ +_P5_INSTANCE = None +_CTX_MIDDLE = None +_DEFAULT_FILL = None +_DEFAULT_LEADMULT = None +_DEFAULT_STROKE = None +_DEFAULT_TEXT_FILL = None +ADD = None +ALT = None +ARROW = None +AUTO = None +AXES = None +BACKSPACE = None +BASELINE = None +BEVEL = None +BEZIER = None +BLEND = None +BLUR = None +BOLD = None +BOLDITALIC = None +BOTTOM = None +BURN = None +CENTER = None +CHORD = None +CLAMP = None +CLOSE = None +CONTROL = None +CORNER = None +CORNERS = None +CROSS = None +CURVE = None +DARKEST = None +DEG_TO_RAD = None +DEGREES = None +DELETE = None +DIFFERENCE = None +DILATE = None +DODGE = None +DOWN_ARROW = None +ENTER = None +ERODE = None +ESCAPE = None +EXCLUSION = None +FILL = None +GRAY = None +GRID = None +HALF_PI = None +HAND = None +HARD_LIGHT = None +HSB = None +HSL = None +IMAGE = None +IMMEDIATE = None +INVERT = None +ITALIC = None +LANDSCAPE = None +LEFT = None +LEFT_ARROW = None +LIGHTEST = None +LINE_LOOP = None +LINE_STRIP = None +LINEAR = None +LINES = None +MIRROR = None +MITER = None +MOVE = None +MULTIPLY = None +NEAREST = None +NORMAL = None +OPAQUE = None +OPEN = None +OPTION = None +OVERLAY = None +PI = None +PIE = None +POINTS = None +PORTRAIT = None +POSTERIZE = None +PROJECT = None +QUAD_STRIP = None +QUADRATIC = None +QUADS = None +QUARTER_PI = None +RAD_TO_DEG = None +RADIANS = None +RADIUS = None +REPEAT = None +REPLACE = None +RETURN = None +RGB = None +RIGHT = None +RIGHT_ARROW = None +ROUND = None +SCREEN = None +SHIFT = None +SOFT_LIGHT = None +SQUARE = None +STROKE = None +SUBTRACT = None +TAB = None +TAU = None +TEXT = None +TEXTURE = None +THRESHOLD = None +TOP = None +TRIANGLE_FAN = None +TRIANGLE_STRIP = None +TRIANGLES = None +TWO_PI = None +UP_ARROW = None +WAIT = None +WEBGL = None +P2D = None +PI = None +frameCount = None +focused = None +displayWidth = None +displayHeight = None +windowWidth = None +windowHeight = None +width = None +height = None +disableFriendlyErrors = None +deviceOrientation = None +accelerationX = None +accelerationY = None +accelerationZ = None +pAccelerationX = None +pAccelerationY = None +pAccelerationZ = None +rotationX = None +rotationY = None +rotationZ = None +pRotationX = None +pRotationY = None +pRotationZ = None +turnAxis = None +keyIsPressed = None +key = None +keyCode = None +mouseX = None +mouseY = None +pmouseX = None +pmouseY = None +winMouseX = None +winMouseY = None +pwinMouseX = None +pwinMouseY = None +mouseButton = None +mouseIsPressed = None +touches = None +pixels = None +VIDEO = None +AUDIO = None + + + +def alpha(*args): + return _P5_INSTANCE.alpha(*args) + +def blue(*args): + return _P5_INSTANCE.blue(*args) + +def brightness(*args): + return _P5_INSTANCE.brightness(*args) + +def color(*args): + return _P5_INSTANCE.color(*args) + +def green(*args): + return _P5_INSTANCE.green(*args) + +def hue(*args): + return _P5_INSTANCE.hue(*args) + +def lerpColor(*args): + return _P5_INSTANCE.lerpColor(*args) + +def lightness(*args): + return _P5_INSTANCE.lightness(*args) + +def red(*args): + return _P5_INSTANCE.red(*args) + +def saturation(*args): + return _P5_INSTANCE.saturation(*args) + +def background(*args): + return _P5_INSTANCE.background(*args) + +def clear(*args): + return _P5_INSTANCE.clear(*args) + +def colorMode(*args): + return _P5_INSTANCE.colorMode(*args) + +def fill(*args): + return _P5_INSTANCE.fill(*args) + +def noFill(*args): + return _P5_INSTANCE.noFill(*args) + +def noStroke(*args): + return _P5_INSTANCE.noStroke(*args) + +def stroke(*args): + return _P5_INSTANCE.stroke(*args) + +def arc(*args): + return _P5_INSTANCE.arc(*args) + +def ellipse(*args): + return _P5_INSTANCE.ellipse(*args) + +def circle(*args): + return _P5_INSTANCE.circle(*args) + +def line(*args): + return _P5_INSTANCE.line(*args) + +def point(*args): + return _P5_INSTANCE.point(*args) + +def quad(*args): + return _P5_INSTANCE.quad(*args) + +def rect(*args): + return _P5_INSTANCE.rect(*args) + +def square(*args): + return _P5_INSTANCE.square(*args) + +def triangle(*args): + return _P5_INSTANCE.triangle(*args) + +def plane(*args): + return _P5_INSTANCE.plane(*args) + +def box(*args): + return _P5_INSTANCE.box(*args) + +def sphere(*args): + return _P5_INSTANCE.sphere(*args) + +def cylinder(*args): + return _P5_INSTANCE.cylinder(*args) + +def cone(*args): + return _P5_INSTANCE.cone(*args) + +def ellipsoid(*args): + return _P5_INSTANCE.ellipsoid(*args) + +def torus(*args): + return _P5_INSTANCE.torus(*args) + +def loadModel(*args): + return _P5_INSTANCE.loadModel(*args) + +def model(*args): + return _P5_INSTANCE.model(*args) + +def ellipseMode(*args): + return _P5_INSTANCE.ellipseMode(*args) + +def noSmooth(*args): + return _P5_INSTANCE.noSmooth(*args) + +def rectMode(*args): + return _P5_INSTANCE.rectMode(*args) + +def smooth(*args): + return _P5_INSTANCE.smooth(*args) + +def strokeCap(*args): + return _P5_INSTANCE.strokeCap(*args) + +def strokeJoin(*args): + return _P5_INSTANCE.strokeJoin(*args) + +def strokeWeight(*args): + return _P5_INSTANCE.strokeWeight(*args) + +def bezier(*args): + return _P5_INSTANCE.bezier(*args) + +def bezierDetail(*args): + return _P5_INSTANCE.bezierDetail(*args) + +def bezierPoint(*args): + return _P5_INSTANCE.bezierPoint(*args) + +def bezierTangent(*args): + return _P5_INSTANCE.bezierTangent(*args) + +def curve(*args): + return _P5_INSTANCE.curve(*args) + +def curveDetail(*args): + return _P5_INSTANCE.curveDetail(*args) + +def curveTightness(*args): + return _P5_INSTANCE.curveTightness(*args) + +def curvePoint(*args): + return _P5_INSTANCE.curvePoint(*args) + +def curveTangent(*args): + return _P5_INSTANCE.curveTangent(*args) + +def beginContour(*args): + return _P5_INSTANCE.beginContour(*args) + +def beginShape(*args): + return _P5_INSTANCE.beginShape(*args) + +def bezierVertex(*args): + return _P5_INSTANCE.bezierVertex(*args) + +def curveVertex(*args): + return _P5_INSTANCE.curveVertex(*args) + +def endContour(*args): + return _P5_INSTANCE.endContour(*args) + +def endShape(*args): + return _P5_INSTANCE.endShape(*args) + +def quadraticVertex(*args): + return _P5_INSTANCE.quadraticVertex(*args) + +def vertex(*args): + return _P5_INSTANCE.vertex(*args) + +def cursor(*args): + return _P5_INSTANCE.cursor(*args) + +def frameRate(*args): + return _P5_INSTANCE.frameRate(*args) + +def noCursor(*args): + return _P5_INSTANCE.noCursor(*args) + +def fullscreen(*args): + return _P5_INSTANCE.fullscreen(*args) + +def pixelDensity(*args): + return _P5_INSTANCE.pixelDensity(*args) + +def displayDensity(*args): + return _P5_INSTANCE.displayDensity(*args) + +def getURL(*args): + return _P5_INSTANCE.getURL(*args) + +def getURLPath(*args): + return _P5_INSTANCE.getURLPath(*args) + +def getURLParams(*args): + return _P5_INSTANCE.getURLParams(*args) + +def preload(*args): + return _P5_INSTANCE.preload(*args) + +def setup(*args): + return _P5_INSTANCE.setup(*args) + +def draw(*args): + return _P5_INSTANCE.draw(*args) + +def remove(*args): + return _P5_INSTANCE.remove(*args) + +def noLoop(*args): + return _P5_INSTANCE.noLoop(*args) + +def loop(*args): + return _P5_INSTANCE.loop(*args) + +def push(*args): + return _P5_INSTANCE.push(*args) + +def redraw(*args): + return _P5_INSTANCE.redraw(*args) + +def resizeCanvas(*args): + return _P5_INSTANCE.resizeCanvas(*args) + +def noCanvas(*args): + return _P5_INSTANCE.noCanvas(*args) + +def createGraphics(*args): + return _P5_INSTANCE.createGraphics(*args) + +def blendMode(*args): + return _P5_INSTANCE.blendMode(*args) + +def setAttributes(*args): + return _P5_INSTANCE.setAttributes(*args) + +def applyMatrix(*args): + return _P5_INSTANCE.applyMatrix(*args) + +def resetMatrix(*args): + return _P5_INSTANCE.resetMatrix(*args) + +def rotate(*args): + return _P5_INSTANCE.rotate(*args) + +def rotateX(*args): + return _P5_INSTANCE.rotateX(*args) + +def rotateY(*args): + return _P5_INSTANCE.rotateY(*args) + +def rotateZ(*args): + return _P5_INSTANCE.rotateZ(*args) + +def scale(*args): + return _P5_INSTANCE.scale(*args) + +def shearX(*args): + return _P5_INSTANCE.shearX(*args) + +def shearY(*args): + return _P5_INSTANCE.shearY(*args) + +def translate(*args): + return _P5_INSTANCE.translate(*args) + +def createStringDict(*args): + return _P5_INSTANCE.createStringDict(*args) + +def createNumberDict(*args): + return _P5_INSTANCE.createNumberDict(*args) + +def append(*args): + return _P5_INSTANCE.append(*args) + +def arrayCopy(*args): + return _P5_INSTANCE.arrayCopy(*args) + +def concat(*args): + return _P5_INSTANCE.concat(*args) + +def reverse(*args): + return _P5_INSTANCE.reverse(*args) + +def shorten(*args): + return _P5_INSTANCE.shorten(*args) + +def shuffle(*args): + return _P5_INSTANCE.shuffle(*args) + +def sort(*args): + return _P5_INSTANCE.sort(*args) + +def splice(*args): + return _P5_INSTANCE.splice(*args) + +def subset(*args): + return _P5_INSTANCE.subset(*args) + +def float(*args): + return _P5_INSTANCE.float(*args) + +def int(*args): + return _P5_INSTANCE.int(*args) + +def str(*args): + return _P5_INSTANCE.str(*args) + +def boolean(*args): + return _P5_INSTANCE.boolean(*args) + +def byte(*args): + return _P5_INSTANCE.byte(*args) + +def char(*args): + return _P5_INSTANCE.char(*args) + +def unchar(*args): + return _P5_INSTANCE.unchar(*args) + +def hex(*args): + return _P5_INSTANCE.hex(*args) + +def unhex(*args): + return _P5_INSTANCE.unhex(*args) + +def join(*args): + return _P5_INSTANCE.join(*args) + +def match(*args): + return _P5_INSTANCE.match(*args) + +def matchAll(*args): + return _P5_INSTANCE.matchAll(*args) + +def nf(*args): + return _P5_INSTANCE.nf(*args) + +def nfc(*args): + return _P5_INSTANCE.nfc(*args) + +def nfp(*args): + return _P5_INSTANCE.nfp(*args) + +def nfs(*args): + return _P5_INSTANCE.nfs(*args) + +def split(*args): + return _P5_INSTANCE.split(*args) + +def splitTokens(*args): + return _P5_INSTANCE.splitTokens(*args) + +def trim(*args): + return _P5_INSTANCE.trim(*args) + +def setMoveThreshold(*args): + return _P5_INSTANCE.setMoveThreshold(*args) + +def setShakeThreshold(*args): + return _P5_INSTANCE.setShakeThreshold(*args) + +def keyIsDown(*args): + return _P5_INSTANCE.keyIsDown(*args) + +def createImage(*args): + return _P5_INSTANCE.createImage(*args) + +def saveCanvas(*args): + return _P5_INSTANCE.saveCanvas(*args) + +def saveFrames(*args): + return _P5_INSTANCE.saveFrames(*args) + +def loadImage(*args): + return _P5_INSTANCE.loadImage(*args) + +def image(*args): + return _P5_INSTANCE.image(*args) + +def tint(*args): + return _P5_INSTANCE.tint(*args) + +def noTint(*args): + return _P5_INSTANCE.noTint(*args) + +def imageMode(*args): + return _P5_INSTANCE.imageMode(*args) + +def blend(*args): + return _P5_INSTANCE.blend(*args) + +def copy(*args): + return _P5_INSTANCE.copy(*args) + +def filter(*args): + return _P5_INSTANCE.filter(*args) + +def get(*args): + return _P5_INSTANCE.get(*args) + +def loadPixels(*args): + return _P5_INSTANCE.loadPixels(*args) + +def set(*args): + return _P5_INSTANCE.set(*args) + +def updatePixels(*args): + return _P5_INSTANCE.updatePixels(*args) + +def loadJSON(*args): + return _P5_INSTANCE.loadJSON(*args) + +def loadStrings(*args): + return _P5_INSTANCE.loadStrings(*args) + +def loadTable(*args): + return _P5_INSTANCE.loadTable(*args) + +def loadXML(*args): + return _P5_INSTANCE.loadXML(*args) + +def loadBytes(*args): + return _P5_INSTANCE.loadBytes(*args) + +def httpGet(*args): + return _P5_INSTANCE.httpGet(*args) + +def httpPost(*args): + return _P5_INSTANCE.httpPost(*args) + +def httpDo(*args): + return _P5_INSTANCE.httpDo(*args) + +def createWriter(*args): + return _P5_INSTANCE.createWriter(*args) + +def save(*args): + return _P5_INSTANCE.save(*args) + +def saveJSON(*args): + return _P5_INSTANCE.saveJSON(*args) + +def saveStrings(*args): + return _P5_INSTANCE.saveStrings(*args) + +def saveTable(*args): + return _P5_INSTANCE.saveTable(*args) + +def day(*args): + return _P5_INSTANCE.day(*args) + +def hour(*args): + return _P5_INSTANCE.hour(*args) + +def minute(*args): + return _P5_INSTANCE.minute(*args) + +def millis(*args): + return _P5_INSTANCE.millis(*args) + +def month(*args): + return _P5_INSTANCE.month(*args) + +def second(*args): + return _P5_INSTANCE.second(*args) + +def year(*args): + return _P5_INSTANCE.year(*args) + +def createVector(*args): + return _P5_INSTANCE.createVector(*args) + +def abs(*args): + return _P5_INSTANCE.abs(*args) + +def ceil(*args): + return _P5_INSTANCE.ceil(*args) + +def constrain(*args): + return _P5_INSTANCE.constrain(*args) + +def dist(*args): + return _P5_INSTANCE.dist(*args) + +def exp(*args): + return _P5_INSTANCE.exp(*args) + +def floor(*args): + return _P5_INSTANCE.floor(*args) + +def lerp(*args): + return _P5_INSTANCE.lerp(*args) + +def log(*args): + return _P5_INSTANCE.log(*args) + +def mag(*args): + return _P5_INSTANCE.mag(*args) + +def map(*args): + return _P5_INSTANCE.map(*args) + +def max(*args): + return _P5_INSTANCE.max(*args) + +def min(*args): + return _P5_INSTANCE.min(*args) + +def norm(*args): + return _P5_INSTANCE.norm(*args) + +def pow(*args): + return _P5_INSTANCE.pow(*args) + +def round(*args): + return _P5_INSTANCE.round(*args) + +def sq(*args): + return _P5_INSTANCE.sq(*args) + +def sqrt(*args): + return _P5_INSTANCE.sqrt(*args) + +def noise(*args): + return _P5_INSTANCE.noise(*args) + +def noiseDetail(*args): + return _P5_INSTANCE.noiseDetail(*args) + +def noiseSeed(*args): + return _P5_INSTANCE.noiseSeed(*args) + +def randomSeed(*args): + return _P5_INSTANCE.randomSeed(*args) + +def random(*args): + return _P5_INSTANCE.random(*args) + +def randomGaussian(*args): + return _P5_INSTANCE.randomGaussian(*args) + +def acos(*args): + return _P5_INSTANCE.acos(*args) + +def asin(*args): + return _P5_INSTANCE.asin(*args) + +def atan(*args): + return _P5_INSTANCE.atan(*args) + +def atan2(*args): + return _P5_INSTANCE.atan2(*args) + +def cos(*args): + return _P5_INSTANCE.cos(*args) + +def sin(*args): + return _P5_INSTANCE.sin(*args) + +def tan(*args): + return _P5_INSTANCE.tan(*args) + +def degrees(*args): + return _P5_INSTANCE.degrees(*args) + +def radians(*args): + return _P5_INSTANCE.radians(*args) + +def angleMode(*args): + return _P5_INSTANCE.angleMode(*args) + +def textAlign(*args): + return _P5_INSTANCE.textAlign(*args) + +def textLeading(*args): + return _P5_INSTANCE.textLeading(*args) + +def textSize(*args): + return _P5_INSTANCE.textSize(*args) + +def textStyle(*args): + return _P5_INSTANCE.textStyle(*args) + +def textWidth(*args): + return _P5_INSTANCE.textWidth(*args) + +def textAscent(*args): + return _P5_INSTANCE.textAscent(*args) + +def textDescent(*args): + return _P5_INSTANCE.textDescent(*args) + +def loadFont(*args): + return _P5_INSTANCE.loadFont(*args) + +def text(*args): + return _P5_INSTANCE.text(*args) + +def textFont(*args): + return _P5_INSTANCE.textFont(*args) + +def orbitControl(*args): + return _P5_INSTANCE.orbitControl(*args) + +def debugMode(*args): + return _P5_INSTANCE.debugMode(*args) + +def noDebugMode(*args): + return _P5_INSTANCE.noDebugMode(*args) + +def ambientLight(*args): + return _P5_INSTANCE.ambientLight(*args) + +def directionalLight(*args): + return _P5_INSTANCE.directionalLight(*args) + +def pointLight(*args): + return _P5_INSTANCE.pointLight(*args) + +def lights(*args): + return _P5_INSTANCE.lights(*args) + +def loadShader(*args): + return _P5_INSTANCE.loadShader(*args) + +def createShader(*args): + return _P5_INSTANCE.createShader(*args) + +def shader(*args): + return _P5_INSTANCE.shader(*args) + +def resetShader(*args): + return _P5_INSTANCE.resetShader(*args) + +def normalMaterial(*args): + return _P5_INSTANCE.normalMaterial(*args) + +def texture(*args): + return _P5_INSTANCE.texture(*args) + +def textureMode(*args): + return _P5_INSTANCE.textureMode(*args) + +def textureWrap(*args): + return _P5_INSTANCE.textureWrap(*args) + +def ambientMaterial(*args): + return _P5_INSTANCE.ambientMaterial(*args) + +def specularMaterial(*args): + return _P5_INSTANCE.specularMaterial(*args) + +def shininess(*args): + return _P5_INSTANCE.shininess(*args) + +def camera(*args): + return _P5_INSTANCE.camera(*args) + +def perspective(*args): + return _P5_INSTANCE.perspective(*args) + +def ortho(*args): + return _P5_INSTANCE.ortho(*args) + +def createCamera(*args): + return _P5_INSTANCE.createCamera(*args) + +def setCamera(*args): + return _P5_INSTANCE.setCamera(*args) + +def select(*args): + return _P5_INSTANCE.select(*args) + +def selectAll(*args): + return _P5_INSTANCE.selectAll(*args) + +def removeElements(*args): + return _P5_INSTANCE.removeElements(*args) + +def changed(*args): + return _P5_INSTANCE.changed(*args) + +def input(*args): + return _P5_INSTANCE.input(*args) + +def createDiv(*args): + return _P5_INSTANCE.createDiv(*args) + +def createP(*args): + return _P5_INSTANCE.createP(*args) + +def createSpan(*args): + return _P5_INSTANCE.createSpan(*args) + +def createImg(*args): + return _P5_INSTANCE.createImg(*args) + +def createA(*args): + return _P5_INSTANCE.createA(*args) + +def createSlider(*args): + return _P5_INSTANCE.createSlider(*args) + +def createButton(*args): + return _P5_INSTANCE.createButton(*args) + +def createCheckbox(*args): + return _P5_INSTANCE.createCheckbox(*args) + +def createSelect(*args): + return _P5_INSTANCE.createSelect(*args) + +def createRadio(*args): + return _P5_INSTANCE.createRadio(*args) + +def createColorPicker(*args): + return _P5_INSTANCE.createColorPicker(*args) + +def createInput(*args): + return _P5_INSTANCE.createInput(*args) + +def createFileInput(*args): + return _P5_INSTANCE.createFileInput(*args) + +def createVideo(*args): + return _P5_INSTANCE.createVideo(*args) + +def createAudio(*args): + return _P5_INSTANCE.createAudio(*args) + +def createCapture(*args): + return _P5_INSTANCE.createCapture(*args) + +def createElement(*args): + return _P5_INSTANCE.createElement(*args) + + +def createCanvas(*args): + result = _P5_INSTANCE.createCanvas(*args) + + global width, height + width = _P5_INSTANCE.width + height = _P5_INSTANCE.height + + +def pop(*args): + __pragma__('noalias', 'pop') + p5_pop = _P5_INSTANCE.pop(*args) + __pragma__('alias', 'pop', 'py_pop') + return p5_pop + +def pre_draw(p5_instance, draw_func): + """ + We need to run this before the actual draw to insert and update p5 env variables + """ + global _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, ADD, ALT, ARROW, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEG_TO_RAD, DEGREES, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINE_LOOP, LINE_STRIP, LINEAR, LINES, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUAD_STRIP, QUADRATIC, QUADS, QUARTER_PI, RAD_TO_DEG, RADIANS, RADIUS, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLE_FAN, TRIANGLE_STRIP, TRIANGLES, TWO_PI, UP_ARROW, WAIT, WEBGL, P2D, PI, frameCount, focused, displayWidth, displayHeight, windowWidth, windowHeight, width, height, disableFriendlyErrors, deviceOrientation, accelerationX, accelerationY, accelerationZ, pAccelerationX, pAccelerationY, pAccelerationZ, rotationX, rotationY, rotationZ, pRotationX, pRotationY, pRotationZ, turnAxis, keyIsPressed, key, keyCode, mouseX, mouseY, pmouseX, pmouseY, winMouseX, winMouseY, pwinMouseX, pwinMouseY, mouseButton, mouseIsPressed, touches, pixels, VIDEO, AUDIO + + _CTX_MIDDLE = p5_instance._CTX_MIDDLE + _DEFAULT_FILL = p5_instance._DEFAULT_FILL + _DEFAULT_LEADMULT = p5_instance._DEFAULT_LEADMULT + _DEFAULT_STROKE = p5_instance._DEFAULT_STROKE + _DEFAULT_TEXT_FILL = p5_instance._DEFAULT_TEXT_FILL + ADD = p5_instance.ADD + ALT = p5_instance.ALT + ARROW = p5_instance.ARROW + AUTO = p5_instance.AUTO + AXES = p5_instance.AXES + BACKSPACE = p5_instance.BACKSPACE + BASELINE = p5_instance.BASELINE + BEVEL = p5_instance.BEVEL + BEZIER = p5_instance.BEZIER + BLEND = p5_instance.BLEND + BLUR = p5_instance.BLUR + BOLD = p5_instance.BOLD + BOLDITALIC = p5_instance.BOLDITALIC + BOTTOM = p5_instance.BOTTOM + BURN = p5_instance.BURN + CENTER = p5_instance.CENTER + CHORD = p5_instance.CHORD + CLAMP = p5_instance.CLAMP + CLOSE = p5_instance.CLOSE + CONTROL = p5_instance.CONTROL + CORNER = p5_instance.CORNER + CORNERS = p5_instance.CORNERS + CROSS = p5_instance.CROSS + CURVE = p5_instance.CURVE + DARKEST = p5_instance.DARKEST + DEG_TO_RAD = p5_instance.DEG_TO_RAD + DEGREES = p5_instance.DEGREES + DELETE = p5_instance.DELETE + DIFFERENCE = p5_instance.DIFFERENCE + DILATE = p5_instance.DILATE + DODGE = p5_instance.DODGE + DOWN_ARROW = p5_instance.DOWN_ARROW + ENTER = p5_instance.ENTER + ERODE = p5_instance.ERODE + ESCAPE = p5_instance.ESCAPE + EXCLUSION = p5_instance.EXCLUSION + FILL = p5_instance.FILL + GRAY = p5_instance.GRAY + GRID = p5_instance.GRID + HALF_PI = p5_instance.HALF_PI + HAND = p5_instance.HAND + HARD_LIGHT = p5_instance.HARD_LIGHT + HSB = p5_instance.HSB + HSL = p5_instance.HSL + IMAGE = p5_instance.IMAGE + IMMEDIATE = p5_instance.IMMEDIATE + INVERT = p5_instance.INVERT + ITALIC = p5_instance.ITALIC + LANDSCAPE = p5_instance.LANDSCAPE + LEFT = p5_instance.LEFT + LEFT_ARROW = p5_instance.LEFT_ARROW + LIGHTEST = p5_instance.LIGHTEST + LINE_LOOP = p5_instance.LINE_LOOP + LINE_STRIP = p5_instance.LINE_STRIP + LINEAR = p5_instance.LINEAR + LINES = p5_instance.LINES + MIRROR = p5_instance.MIRROR + MITER = p5_instance.MITER + MOVE = p5_instance.MOVE + MULTIPLY = p5_instance.MULTIPLY + NEAREST = p5_instance.NEAREST + NORMAL = p5_instance.NORMAL + OPAQUE = p5_instance.OPAQUE + OPEN = p5_instance.OPEN + OPTION = p5_instance.OPTION + OVERLAY = p5_instance.OVERLAY + PI = p5_instance.PI + PIE = p5_instance.PIE + POINTS = p5_instance.POINTS + PORTRAIT = p5_instance.PORTRAIT + POSTERIZE = p5_instance.POSTERIZE + PROJECT = p5_instance.PROJECT + QUAD_STRIP = p5_instance.QUAD_STRIP + QUADRATIC = p5_instance.QUADRATIC + QUADS = p5_instance.QUADS + QUARTER_PI = p5_instance.QUARTER_PI + RAD_TO_DEG = p5_instance.RAD_TO_DEG + RADIANS = p5_instance.RADIANS + RADIUS = p5_instance.RADIUS + REPEAT = p5_instance.REPEAT + REPLACE = p5_instance.REPLACE + RETURN = p5_instance.RETURN + RGB = p5_instance.RGB + RIGHT = p5_instance.RIGHT + RIGHT_ARROW = p5_instance.RIGHT_ARROW + ROUND = p5_instance.ROUND + SCREEN = p5_instance.SCREEN + SHIFT = p5_instance.SHIFT + SOFT_LIGHT = p5_instance.SOFT_LIGHT + SQUARE = p5_instance.SQUARE + STROKE = p5_instance.STROKE + SUBTRACT = p5_instance.SUBTRACT + TAB = p5_instance.TAB + TAU = p5_instance.TAU + TEXT = p5_instance.TEXT + TEXTURE = p5_instance.TEXTURE + THRESHOLD = p5_instance.THRESHOLD + TOP = p5_instance.TOP + TRIANGLE_FAN = p5_instance.TRIANGLE_FAN + TRIANGLE_STRIP = p5_instance.TRIANGLE_STRIP + TRIANGLES = p5_instance.TRIANGLES + TWO_PI = p5_instance.TWO_PI + UP_ARROW = p5_instance.UP_ARROW + WAIT = p5_instance.WAIT + WEBGL = p5_instance.WEBGL + P2D = p5_instance.P2D + PI = p5_instance.PI + frameCount = p5_instance.frameCount + focused = p5_instance.focused + displayWidth = p5_instance.displayWidth + displayHeight = p5_instance.displayHeight + windowWidth = p5_instance.windowWidth + windowHeight = p5_instance.windowHeight + width = p5_instance.width + height = p5_instance.height + disableFriendlyErrors = p5_instance.disableFriendlyErrors + deviceOrientation = p5_instance.deviceOrientation + accelerationX = p5_instance.accelerationX + accelerationY = p5_instance.accelerationY + accelerationZ = p5_instance.accelerationZ + pAccelerationX = p5_instance.pAccelerationX + pAccelerationY = p5_instance.pAccelerationY + pAccelerationZ = p5_instance.pAccelerationZ + rotationX = p5_instance.rotationX + rotationY = p5_instance.rotationY + rotationZ = p5_instance.rotationZ + pRotationX = p5_instance.pRotationX + pRotationY = p5_instance.pRotationY + pRotationZ = p5_instance.pRotationZ + turnAxis = p5_instance.turnAxis + keyIsPressed = p5_instance.keyIsPressed + key = p5_instance.key + keyCode = p5_instance.keyCode + mouseX = p5_instance.mouseX + mouseY = p5_instance.mouseY + pmouseX = p5_instance.pmouseX + pmouseY = p5_instance.pmouseY + winMouseX = p5_instance.winMouseX + winMouseY = p5_instance.winMouseY + pwinMouseX = p5_instance.pwinMouseX + pwinMouseY = p5_instance.pwinMouseY + mouseButton = p5_instance.mouseButton + mouseIsPressed = p5_instance.mouseIsPressed + touches = p5_instance.touches + pixels = p5_instance.pixels + VIDEO = p5_instance.VIDEO + AUDIO = p5_instance.AUDIO + + return draw_func() + + +def global_p5_injection(p5_sketch): + """ + Injects the p5js's skecth instance as a global variable to setup and draw functions + """ + + def decorator(f): + + def wrapper(): + global _P5_INSTANCE + _P5_INSTANCE = p5_sketch + return pre_draw(_P5_INSTANCE, f) + return wrapper + + return decorator + + +def start_p5(setup_func, draw_func, event_functions): + """ + This is the entrypoint function. It accepts 2 parameters: + + - setup_func: a Python setup callable + - draw_func: a Python draw callable + - event_functions: a config dict for the event functions in the format: + {"eventFunctionName": python_event_function} + + This method gets the p5js's sketch instance and injects them + """ + + def sketch_setup(p5_sketch): + p5_sketch.setup = global_p5_injection(p5_sketch)(setup_func) + p5_sketch.draw = global_p5_injection(p5_sketch)(draw_func) + + instance = __new__ (p5(sketch_setup, 'sketch-holder')) + + # inject event functions into p5 + event_function_names = ["deviceMoved", "deviceTurned", "deviceShaken", "keyPressed", "keyReleased", "keyTyped", "mouseMoved", "mouseDragged", "mousePressed", "mouseReleased", "mouseClicked", "doubleClicked", "mouseWheel", "touchStarted", "touchMoved", "touchEnded", "windowResized", ] + + for f_name in [f for f in event_function_names if event_functions.get(f, None)]: + func = event_functions[f_name] + event_func = global_p5_injection(instance)(func) + setattr(instance, f_name, event_func) + + +def logOnloaded(): + console.log("Lib loaded!") + + +def add_library(lib_name): + src = '' + + if lib_name == 'p5.dom.js': + src = "static/p5.dom.js" + else: + console.log("Lib name is not valid: " + lib_name) + return + + console.log("Importing: " + src) + script = document.createElement("script") + script.onload = logOnloaded + script.src = src + document.head.appendChild(script) \ No newline at end of file diff --git a/docs/examples/sketch_008/target/sketch_008.js b/docs/examples/sketch_008/target/sketch_008.js new file mode 100644 index 00000000..0787da48 --- /dev/null +++ b/docs/examples/sketch_008/target/sketch_008.js @@ -0,0 +1,34 @@ +// Transcrypt'ed from Python, 2019-06-02 16:11:12 +import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, isinstance, issubclass, len, list, object, ord, print, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; +import {ADD, ALT, ARROW, AUDIO, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEGREES, DEG_TO_RAD, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINEAR, LINES, LINE_LOOP, LINE_STRIP, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, P2D, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUADRATIC, QUADS, QUAD_STRIP, QUARTER_PI, RADIANS, RADIUS, RAD_TO_DEG, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, TWO_PI, UP_ARROW, VIDEO, WAIT, WEBGL, _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, _P5_INSTANCE, abs, accelerationX, accelerationY, accelerationZ, acos, add_library, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, changed, char, circle, color, colorMode, concat, cone, constrain, copy, cos, createA, createAudio, createButton, createCamera, createCanvas, createCapture, createCheckbox, createColorPicker, createDiv, createElement, createFileInput, createGraphics, createImage, createImg, createInput, createNumberDict, createP, createRadio, createSelect, createShader, createSlider, createSpan, createStringDict, createVector, createVideo, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, deviceOrientation, directionalLight, disableFriendlyErrors, displayDensity, displayHeight, displayWidth, dist, ellipse, ellipseMode, ellipsoid, endContour, endShape, exp, fill, filter, float, floor, focused, frameCount, frameRate, fullscreen, getURL, getURLParams, getURLPath, global_p5_injection, green, height, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, input, int, join, key, keyCode, keyIsDown, keyIsPressed, lerp, lerpColor, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, logOnloaded, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, mouseButton, mouseIsPressed, mouseX, mouseY, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noFill, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normalMaterial, orbitControl, ortho, pAccelerationX, pAccelerationY, pAccelerationZ, pRotationX, pRotationY, pRotationZ, perspective, pixelDensity, pixels, plane, pmouseX, pmouseY, point, pointLight, pow, pre_draw, preload, push, pwinMouseX, pwinMouseY, py_clear, py_get, py_pop, py_sort, py_split, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, remove, removeElements, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, rotationX, rotationY, rotationZ, round, saturation, save, saveCanvas, saveFrames, saveJSON, saveStrings, saveTable, scale, second, select, selectAll, set, setAttributes, setCamera, setMoveThreshold, setShakeThreshold, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, specularMaterial, sphere, splice, splitTokens, sq, sqrt, square, start_p5, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, touches, translate, triangle, trim, turnAxis, unchar, unhex, updatePixels, vertex, width, winMouseX, winMouseY, windowHeight, windowWidth, year} from './pytop5js.js'; +var __name__ = 'sketch_008'; +add_library ('p5.dom.js'); +export var rect_base_size = 30; +export var positions = list ([]); +export var rect_offset = null; +export var setup = function () { + createP ('Hi! This is an example of how to use p5.dom.js with pyp5js'); + var slider_div = createDiv (); + slider_div.style ('display', 'block'); + rect_offset = createSlider (0, 600, 100); + rect_offset.style ('width', '50%'); + slider_div.child (rect_offset); + createCanvas (600, 600); + for (var x of range (-(rect_base_size), width + rect_base_size, rect_base_size)) { + for (var y of range (-(rect_base_size), height + rect_base_size, rect_base_size)) { + positions.append (tuple ([x, y])); + } + } + noFill (); + strokeWeight (2); + rectMode (CENTER); +}; +export var draw = function () { + background (255); + var size = rect_offset.value (); + for (var [x, y] of positions) { + rect (x, y, size, size); + } +}; + +//# sourceMappingURL=sketch_008.map \ No newline at end of file diff --git a/docs/examples/sketch_008/target/sketch_008.py b/docs/examples/sketch_008/target/sketch_008.py new file mode 100644 index 00000000..032bbefc --- /dev/null +++ b/docs/examples/sketch_008/target/sketch_008.py @@ -0,0 +1,42 @@ +from pytop5js import * + + +add_library("p5.dom.js") + + +rect_base_size = 30 +positions = [] +rect_offset = None + +def setup(): + global rect_offset + + createP("Hi! This is an example of how to use p5.dom.js with pyp5js") + + # creates a container div + slider_div = createDiv() + slider_div.style("display", "block") + + # creates the slider + rect_offset = createSlider(0, 600, 100) + rect_offset.style('width', '50%') + + # adds the slider to the container div + slider_div.child(rect_offset) + + createCanvas(600, 600) + + for x in range(-rect_base_size, width + rect_base_size, rect_base_size): + for y in range(-rect_base_size, height + rect_base_size, rect_base_size): + positions.append((x, y)) + + noFill() + strokeWeight(2) + rectMode(CENTER) + + +def draw(): + background(255) + size = rect_offset.value() + for x, y in positions: + rect(x, y, size, size) diff --git a/docs/examples/sketch_008/target/target_sketch.js b/docs/examples/sketch_008/target/target_sketch.js new file mode 100644 index 00000000..81f5561c --- /dev/null +++ b/docs/examples/sketch_008/target/target_sketch.js @@ -0,0 +1,9 @@ +// Transcrypt'ed from Python, 2019-06-02 16:11:11 +import {AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError, NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning, __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__, __call__, __class__, __envir__, __eq__, __floordiv__, __ge__, __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__, __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__, __imatmul__, __imod__, __imul__, __in__, __init__, __ior__, __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__, __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__, __matmul__, __mergefields__, __mergekwargtrans__, __mod__, __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__, __proxy__, __pyUseJsNext__, __rshift__, __setitem__, __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__, __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__, all, any, assert, bool, bytearray, bytes, callable, chr, deepcopy, delattr, dict, dir, divmod, enumerate, getattr, hasattr, isinstance, issubclass, len, list, object, ord, print, property, py_TypeError, py_iter, py_metatype, py_next, py_reversed, py_typeof, range, repr, setattr, sorted, sum, tuple, zip} from './org.transcrypt.__runtime__.js'; +import {ADD, ALT, ARROW, AUDIO, AUTO, AXES, BACKSPACE, BASELINE, BEVEL, BEZIER, BLEND, BLUR, BOLD, BOLDITALIC, BOTTOM, BURN, CENTER, CHORD, CLAMP, CLOSE, CONTROL, CORNER, CORNERS, CROSS, CURVE, DARKEST, DEGREES, DEG_TO_RAD, DELETE, DIFFERENCE, DILATE, DODGE, DOWN_ARROW, ENTER, ERODE, ESCAPE, EXCLUSION, FILL, GRAY, GRID, HALF_PI, HAND, HARD_LIGHT, HSB, HSL, IMAGE, IMMEDIATE, INVERT, ITALIC, LANDSCAPE, LEFT, LEFT_ARROW, LIGHTEST, LINEAR, LINES, LINE_LOOP, LINE_STRIP, MIRROR, MITER, MOVE, MULTIPLY, NEAREST, NORMAL, OPAQUE, OPEN, OPTION, OVERLAY, P2D, PI, PIE, POINTS, PORTRAIT, POSTERIZE, PROJECT, QUADRATIC, QUADS, QUAD_STRIP, QUARTER_PI, RADIANS, RADIUS, RAD_TO_DEG, REPEAT, REPLACE, RETURN, RGB, RIGHT, RIGHT_ARROW, ROUND, SCREEN, SHIFT, SOFT_LIGHT, SQUARE, STROKE, SUBTRACT, TAB, TAU, TEXT, TEXTURE, THRESHOLD, TOP, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, TWO_PI, UP_ARROW, VIDEO, WAIT, WEBGL, _CTX_MIDDLE, _DEFAULT_FILL, _DEFAULT_LEADMULT, _DEFAULT_STROKE, _DEFAULT_TEXT_FILL, _P5_INSTANCE, abs, accelerationX, accelerationY, accelerationZ, acos, add_library, alpha, ambientLight, ambientMaterial, angleMode, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginContour, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, blend, blendMode, blue, boolean, box, brightness, byte, camera, ceil, changed, char, circle, color, colorMode, concat, cone, constrain, copy, cos, createA, createAudio, createButton, createCamera, createCanvas, createCapture, createCheckbox, createColorPicker, createDiv, createElement, createFileInput, createGraphics, createImage, createImg, createInput, createNumberDict, createP, createRadio, createSelect, createShader, createSlider, createSpan, createStringDict, createVector, createVideo, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, cylinder, day, debugMode, degrees, deviceOrientation, directionalLight, disableFriendlyErrors, displayDensity, displayHeight, displayWidth, dist, draw, ellipse, ellipseMode, ellipsoid, endContour, endShape, exp, fill, filter, float, floor, focused, frameCount, frameRate, fullscreen, getURL, getURLParams, getURLPath, global_p5_injection, green, height, hex, hour, httpDo, httpGet, httpPost, hue, image, imageMode, input, int, join, key, keyCode, keyIsDown, keyIsPressed, lerp, lerpColor, lightness, lights, line, loadBytes, loadFont, loadImage, loadJSON, loadModel, loadPixels, loadShader, loadStrings, loadTable, loadXML, log, logOnloaded, loop, mag, map, match, matchAll, max, millis, min, minute, model, month, mouseButton, mouseIsPressed, mouseX, mouseY, nf, nfc, nfp, nfs, noCanvas, noCursor, noDebugMode, noFill, noLoop, noSmooth, noStroke, noTint, noise, noiseDetail, noiseSeed, norm, normalMaterial, orbitControl, ortho, pAccelerationX, pAccelerationY, pAccelerationZ, pRotationX, pRotationY, pRotationZ, perspective, pixelDensity, pixels, plane, pmouseX, pmouseY, point, pointLight, pow, pre_draw, preload, push, pwinMouseX, pwinMouseY, py_clear, py_get, py_pop, py_sort, py_split, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, remove, removeElements, resetMatrix, resetShader, resizeCanvas, reverse, rotate, rotateX, rotateY, rotateZ, rotationX, rotationY, rotationZ, round, saturation, save, saveCanvas, saveFrames, saveJSON, saveStrings, saveTable, scale, second, select, selectAll, set, setAttributes, setCamera, setMoveThreshold, setShakeThreshold, setup, shader, shearX, shearY, shininess, shorten, shuffle, sin, smooth, specularMaterial, sphere, splice, splitTokens, sq, sqrt, square, start_p5, str, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textSize, textStyle, textWidth, texture, textureMode, textureWrap, tint, torus, touches, translate, triangle, trim, turnAxis, unchar, unhex, updatePixels, vertex, width, winMouseX, winMouseY, windowHeight, windowWidth, year} from './pytop5js.js'; +import * as source_sketch from './sketch_008.js'; +var __name__ = '__main__'; +export var event_functions = dict ({'deviceMoved': source_sketch.deviceMoved, 'deviceTurned': source_sketch.deviceTurned, 'deviceShaken': source_sketch.deviceShaken, 'keyPressed': source_sketch.keyPressed, 'keyReleased': source_sketch.keyReleased, 'keyTyped': source_sketch.keyTyped, 'mouseMoved': source_sketch.mouseMoved, 'mouseDragged': source_sketch.mouseDragged, 'mousePressed': source_sketch.mousePressed, 'mouseReleased': source_sketch.mouseReleased, 'mouseClicked': source_sketch.mouseClicked, 'doubleClicked': source_sketch.doubleClicked, 'mouseWheel': source_sketch.mouseWheel, 'touchStarted': source_sketch.touchStarted, 'touchMoved': source_sketch.touchMoved, 'touchEnded': source_sketch.touchEnded, 'windowResized': source_sketch.windowResized}); +start_p5 (source_sketch.setup, source_sketch.draw, event_functions); + +//# sourceMappingURL=target_sketch.map \ No newline at end of file diff --git a/docs/examples/sketch_008/target/target_sketch.options b/docs/examples/sketch_008/target/target_sketch.options new file mode 100644 index 0000000000000000000000000000000000000000..fce84d73a5cb8eb50cab883c0009d315fefc0f19 GIT binary patch literal 607 zcmXw0xpLbu5S1fexf46Lb2)KhJB8^cGx-YD=sX~}mMDP$9sts0k(rd@UkAd<6|mU1 z?^yhs{>9`%>`x|>U|X*UJK|(htSG9*&Gq%4B1%7}c*8GOZomVvn-J0%i|Lq0rLG%W zVRsaJsZ+MKuCTWj2dPlDahiJUbFZ>WMjVW}SIH2_M;tOsr52=Cc(|>ok7@4FnAIw6 z=XkumH`3wBC=L^SWo(GPc6hqw4>9pS+ZNFi;rS@02}z;Di&-{!tEAR=$?tPAIAVOQ ztm$yf`pb|}ukNcA4FRtixD1=PZ@9I(OA88k%Z3t+W4z;xx>jTY;XSKutbbT%7sfWV z!O1%3v(9$-$b?RMG7+C<*|%>EJ~LMsn$qfkFB~J>THoL+TZ-BHDQ~DXb;P$>UUEmi zw8_BtQS78O^f=?`KJBK*50>ob+Li%7nX7j)E^sbR6TVp3hKiEBk-oA8nJyG=aKD%L W2QG4&KGtTyCF`e8@c1>hSN{Q-SE(NW literal 0 HcmV?d00001 diff --git a/docs/examples/sketch_008/target/target_sketch.py b/docs/examples/sketch_008/target/target_sketch.py new file mode 100644 index 00000000..866e5007 --- /dev/null +++ b/docs/examples/sketch_008/target/target_sketch.py @@ -0,0 +1,24 @@ +import sketch_008 as source_sketch +from pytop5js import * + +event_functions = { + "deviceMoved": source_sketch.deviceMoved, + "deviceTurned": source_sketch.deviceTurned, + "deviceShaken": source_sketch.deviceShaken, + "keyPressed": source_sketch.keyPressed, + "keyReleased": source_sketch.keyReleased, + "keyTyped": source_sketch.keyTyped, + "mouseMoved": source_sketch.mouseMoved, + "mouseDragged": source_sketch.mouseDragged, + "mousePressed": source_sketch.mousePressed, + "mouseReleased": source_sketch.mouseReleased, + "mouseClicked": source_sketch.mouseClicked, + "doubleClicked": source_sketch.doubleClicked, + "mouseWheel": source_sketch.mouseWheel, + "touchStarted": source_sketch.touchStarted, + "touchMoved": source_sketch.touchMoved, + "touchEnded": source_sketch.touchEnded, + "windowResized": source_sketch.windowResized, +} + +start_p5(source_sketch.setup, source_sketch.draw, event_functions) \ No newline at end of file From b540b4031f21d125becc1df46977c57dd3a5d654 Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sun, 2 Jun 2019 16:19:16 -0300 Subject: [PATCH 29/32] Update the docs hierarchy --- docs/index.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/index.md b/docs/index.md index 879c4f57..a52d0d0c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,4 +1,4 @@ -## pyp5js: Python to P5.js Transcriptor +# pyp5js: Python to P5.js Transcriptor > [Processing](https://processing.org) ideas and Python 3 together with [P5.js](https://p5js.org) in the browser, using [Transcrypt](https://transcrypt.org/). @@ -22,11 +22,11 @@ def draw(): r = sin(frameCount / 60) * 50 + 50 ellipse(100, 100, r, r) ``` -### More Examples +## Examples [Click here](https://berinhard.github.io/pyp5js/examples/) to see a list of examples generated with `pyp5js`. -### Installation +## Installation This project requires Python 3 and is now on PyPI, so you can install it with `pip` or `pip3`, depending on your environment: @@ -35,7 +35,7 @@ $ pip install pyp5js ``` (You might have to install `setuptools` first, if it's not already installed) -### Usage +## Usage Since you'll be writting Python code and then generating the correspondent P5.js code from it, pyp5js provides a simple command line API to help you to generate the files. @@ -93,17 +93,17 @@ $ pyp5js --help - At this point, it is a known limitation that you have to "declare" global variables before `setup()` and `draw()`, maybe using `name = None`, as they can't be created inside methods. -### How can I contribute? +## How can I contribute? -#### Testing, testing and testing +### Testing, testing and testing Since pyp5js have a lot of moving parts, it would be great to have the p5.js API fully covered and tested. So, use your imagination, code your sketches and, if pyp5js breaks or starts to annoy you with something, you're very welcome to [open an issue](https://github.com/berinhard/pyp5js/issues/new) documenting your thoughts. Test it and let me know how can I improve it. -#### What about these shinning examples? +### What about these shinning examples? If you fell confortable with that, I'd be happy to add some of your pyp5js sketches to our [examples list](https://berinhard.github.io/pyp5js/examples/)! To do so, you'll have [to fork this repository](https://help.github.com/en/articles/fork-a-repo) and add your new sketch example in the `docs/examples` directory. Once you've your sketch ready, you can [open a pull request](https://help.github.com/en/articles/about-pull-requests) and I'll take a look at it. -#### I want to hack! +### I want to hack! Okay, if you want to contribute with pyp5js's code, let's go! I really advise you to use [virtualenv with virtualenvwrapper](http://www.indjango.com/python-install-virtualenv-and-virtualenvwrapper/) or [pyenv](https://amaral.northwestern.edu/resources/guides/pyenv-tutorial) to isolate your pyp5js fork from your the rest of your system. Once you have everything ready, you can run: From 9b74aeef83ace5064c2e7d51ff6c7f87e940ce59 Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sun, 2 Jun 2019 16:19:25 -0300 Subject: [PATCH 30/32] add example on p5.dom.js --- docs/index.md | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/docs/index.md b/docs/index.md index a52d0d0c..6b36efad 100644 --- a/docs/index.md +++ b/docs/index.md @@ -81,12 +81,28 @@ All of the command-line interface methods have a few optional arguments, such as $ pyp5js --help ``` +### p5.dom.js + +To use [p5.dom.js functions](https://p5js.org/reference/#/libraries/p5.dom) such as `createDiv` or `createSlider` you'll have to call `add_library('p5.dom.js')`, like the following example: + +```python +from pytop5js import * + +add_library("p5.dom.js") # this will import p5.dom.js and make all functions available + +def setup(): + createP("Hello world!") + + +def draw(): + pass +``` + + ### Known [issues](https://github.com/berinhard/pyp5js/issues) and differences to the Processing.Py and P5.js ways of doing things - Remember to use **P5.js** method names & conventions for most things. -- The `p5.dom.js` library can be used, but you'll have to add it to the `index.html` yourself, and then it's methods and objects will be available with the `p5.` prefix. - - There are no Py.Processing `with` context facilities for `push/pop` or `beginShape/endShape`. - There are no `PVector` objects, with their nice syntatic operator overloaded sugar - use `p5.Vector` with `createVector()` and P5.js conventions ... for now... From 069c758e161b5488431c9453b2dd39dceb361172 Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sun, 2 Jun 2019 16:24:15 -0300 Subject: [PATCH 31/32] Update changelog --- Changelog.txt | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/Changelog.txt b/Changelog.txt index 17775768..cc93df29 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,5 +1,8 @@ Development ----------- +- Simplification of pytop5js usage +- Support p5.dom.js library +- Fixes on monitor observer 0.0.7 ----- @@ -13,17 +16,17 @@ Development 0.0.5 ----- -- Adds all p5's missing global variables +- Add all p5's missing global variables 0.0.4.1 ------- -- Supports event functions such as `keyPressed` +- Support event functions such as `keyPressed` 0.0.4 ----- -- Supports p5.js pop function -- Adds `monitor` command to the CLI -- Allows to run `pyp5js` commands specifying a directory +- Support p5.js pop function +- Add `monitor` command to the CLI +- Allow to run `pyp5js` commands specifying a directory - First try on organizing the docs 0.0.3 @@ -32,7 +35,7 @@ Development 0.0.2 ----- -- Supports more of P5's variable +- Support more of P5's variable 0.0.1 From 8888f913fe7c0e161bc5c5ef28823b69aaca0d4c Mon Sep 17 00:00:00 2001 From: Bernardo Fontes Date: Sun, 2 Jun 2019 16:30:03 -0300 Subject: [PATCH 32/32] Update version --- Changelog.txt | 3 +++ setup.py | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/Changelog.txt b/Changelog.txt index cc93df29..65470531 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,5 +1,8 @@ Development ----------- + +0.1.0 +----- - Simplification of pytop5js usage - Support p5.dom.js library - Fixes on monitor observer diff --git a/setup.py b/setup.py index 689c6418..5d31e6a2 100644 --- a/setup.py +++ b/setup.py @@ -23,7 +23,7 @@ setup( name="pyp5js", - version="0.0.7", + version="0.1.0", description='Simple tool to allow to transcrypt Python code that uses P5.js', long_description=long_description, long_description_content_type='text/markdown',